E. Water Balance

本文解析了Codeforces比赛中的E-WaterBalance问题,提供了详细的解题思路和实现代码。通过贪心算法,对连续数字取平均值以达到整体平均值最小化的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

E - Water Balance

input

4
7 5 5 7

output

5.666666667
5.666666667
5.666666667
7.000000000

input

5
7 8 8 10 12

output

7.000000000
8.000000000
8.000000000
10.000000000
12.000000000

input

10
3 9 5 5 1 7 5 3 8 7

output

3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000

Note
In the first sample, you can get the sequence by applying the operation for subsegment [1,3].
In the second sample, you can’t get any lexicographically smaller sequence.

题目大意

给你一串数字,你可以对连续的数字取平均值,然后保证取完之后这一串数字的平均值最小;

解题思路

假设说现在有两个数字,x1,x2;如果x2小于x1;那么我们是不是就让x1和 x2取平均值,如果不是那么就不管对吧?,然后我们将x1,x2想成两个区间,只是这个区间的数值都是一样的,那么我还可以根据这个策略进行贪心,一旦发现后面的前面的数值小,就把他们合成一块,然后继续向下走;

代码

#include<bits/stdc++.h>
using namespace std;
const int mx=1000100;

double a[mx];
double len[mx],st[mx];//分别存这一块的长度和平均值 
int p;//记录有几块 
int main()
{
	int n;scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%lf",&a[i]);
	}
	for(int i=1;i<=n;i++){
		st[++p]=a[i];//记录这一块的平均值 
		len[p]=1;//其长度开始时唯一 
		while(p>1&&st[p]<st[p-1]){//去更新前面的数值,如果比前面的小就进行 合并 
			st[p-1]=(st[p]*len[p]+st[p-1]*len[p-1])/(len[p]+len[p-1]);//将两块区间合并 
			len[p-1]=len[p-1]+len[p];//更新长度 
			p--;//块数也相应的减一 
		}
	}
	for(int i=1;i<=p;i++)//输出 
	{
		for(int j=1;j<=len[i];j++)
		{
			printf("%.9lf\n",st[i]);
		}
	}
	return 0;
} 
% Supplemental program 13.1 (完整修复版) % ------------------------------------------------------------------------- % Calculate leaf gas exchange coupled with the leaf energy budget for C3 % and C4 plants. Leaf temperature is calculated from the energy balance. % Stomatal conductance is calculated from water-use efficiency optimization % within the constraints imposed by plant hydraulics. % ------------------------------------------------------------------------- % --- Waveband indices for visible and near-infrared params.vis = 1; params.nir = 2; % --- Physical constants physcon.grav = 9.80665; % Gravitational acceleration (m/s2) physcon.tfrz = 273.15; % Freezing point of water (K) physcon.sigma = 5.67e-08; % Stefan-Boltzmann constant (W/m2/K4) physcon.mmdry = 28.97 / 1000; % Molecular mass of dry air (kg/mol) physcon.mmh2o = 18.02 / 1000; % Molecular mass of water (kg/mol) physcon.cpd = 1005; % Specific heat of dry air at constant pressure (J/kg/K) physcon.cpw = 1846; % Specific heat of water vapor at constant pressure (J/kg/K) physcon.rgas = 8.31446; % Universal gas constant (J/K/mol) physcon.visc0 = 13.3e-06; % Kinematic viscosity at 0C and 1013.25 hPa (m2/s) physcon.Dh0 = 18.9e-06; % Molecular diffusivity (heat) at 0C and 1013.25 hPa (m2/s) physcon.Dv0 = 21.8e-06; % Molecular diffusivity (H2O) at 0C and 1013.25 hPa (m2/s) physcon.Dc0 = 13.8e-06; % Molecular diffusivity (CO2) at 0C and 1013.25 hPa (m2/s) physcon.denh2o = 1000; % Density of liquid water (kg/m3) % --- Set leaf physiology variables % Photosynthetic pathway: 1 = C3. 0 = C4 leaf.c3psn = 1; % Photosynthesis co-limitation: 0 = no. 1 = yes leaf.colim = 1; % Leaf physiological parameters [leaf] = LeafPhysiologyParams (params, physcon, leaf); % --- Set root parameters (修复缺失字段) rootvar.biomass = 500; % Fine root biomass (g biomass / m2) rootvar.radius = 0.5e-3; % Fine root radius (m) [0.5 mm] rootvar.density = 0.25e6; % Fine root density (g biomass / m3 root) [0.25 g/cm³] rootvar.resist = 0.5; % Hydraulic resistivity of root tissue (MPa.s.g/mmol H2O) % --- Set site variables % Leaf height (m) flux.height = 15; % Canopy leaf area index (m2/m2) flux.lai = 5; % Soil texture classes % 1: sand % 2: loamy sand % 3: sandy loam % 4: silt loam % 5: loam % 6: sandy clay loam % 7 silty clay loam % 8: clay loam % 9: sandy clay % 10: silty clay % 11: clay soil.texture = 3; % --- Set soil hydraulic parameters, soil depth, and rooting fraction [soil] = SoilParams (soil); % --- Set soil moisture for j = 1:soil.nlevsoi soil.h2osoi_vol(j) = 0.5 * soil.watsat(j); soil.psi(j) = soil.psisat(j) * (soil.h2osoi_vol(j) / soil.watsat(j))^-soil.bsw(j); end % --- Hydraulic conductances % Aboveground plant stem resistance for xylem-to-leaf (MPa.s.m2/mmol H2O) flux.rplant = 1 / leaf.gplant; % Calculate soil hydraulic resistance, weighted soil water potential and % water uptake from each soil layer [flux] = SoilResistance (physcon, leaf, rootvar, soil, flux); % Leaf-specific conductance for soil-to-leaf (mmol H2O/m2 laef/s/MPa) flux.lsc = 1 / (flux.rsoil + flux.rplant); fprintf('rplant = %15.5f\n',flux.rplant) fprintf('rsoil = %15.5f\n',flux.rsoil) fprintf('lsc = %15.5f\n',flux.lsc) % --- Atmospheric forcing % Process sunlit or shaded leaf leaftype = 'sun'; % leaftype = 'shade'; % Atmospheric CO2 (umol/mol) and O2 (mmol/mol) atmos.co2air = 380; atmos.o2air = 0.209 * 1000; % Air temperature (K) and relative humidity (%) atmos.tair = physcon.tfrz + 30; atmos.relhum = 60; % Wind (m/s) atmos.wind = 1; % Atmospheric pressure (Pa) atmos.patm = 101325; % Vapor pressure (Pa) and specific humidity (kg/kg) [esat, desat] = satvap ((atmos.tair-physcon.tfrz)); atmos.eair = esat * (atmos.relhum / 100); atmos.qair = physcon.mmh2o / physcon.mmdry * atmos.eair / (atmos.patm - (1 - physcon.mmh2o/physcon.mmdry) * atmos.eair); % Molar density (mol/m3) atmos.rhomol = atmos.patm / (physcon.rgas * atmos.tair); % Air density (kg/m3) atmos.rhoair = atmos.rhomol * physcon.mmdry * (1 - (1 - physcon.mmh2o/physcon.mmdry) * atmos.eair / atmos.patm); % Molecular mass of air (kg/mol) atmos.mmair = atmos.rhoair / atmos.rhomol; % Specific heat of air at constant pressure (J/mol/K) atmos.cpair = physcon.cpd * (1 + (physcon.cpw/physcon.cpd - 1) * atmos.qair) * atmos.mmair; % Atmospheric longwave radiation (W/m2) atmos.irsky = 400; % Solar radiation (W/m2) switch leaftype case 'sun' fsds = 800; % Sun leaf case 'shade' fsds = 300; % Shade leaf end atmos.swsky(params.vis) = 0.5 * fsds; atmos.swsky(params.nir) = 0.5 * fsds; % --- Ground variables ground.albsoi(params.vis) = 0.1; % Soil albedo (visible waveband) ground.albsoi(params.nir) = 0.2; % Soil albedo (near-infrared waveband) tg = atmos.tair; ground.irgrd = physcon.sigma * tg^4; % --- Radiation absorbed by leaf % Solar radiation incident on leaf flux.swinc(params.vis) = atmos.swsky(params.vis) * (1 + ground.albsoi(params.vis)); flux.swinc(params.nir) = atmos.swsky(params.nir) * (1 + ground.albsoi(params.nir)); % Solar radiation absorbed by leaf flux.swflx(params.vis) = flux.swinc(params.vis) * (1 - leaf.rho(params.vis) - leaf.tau(params.vis)); flux.swflx(params.nir) = flux.swinc(params.nir) * (1 - leaf.rho(params.nir) - leaf.tau(params.nir)); flux.apar = flux.swflx(params.vis) * 4.6; % Radiative forcing for leaf temperature calculation flux.qa = flux.swflx(params.vis) + flux.swflx(params.nir) + leaf.emiss * (atmos.irsky + ground.irgrd); % --- Leaf temperature, energy fluxes, photosynthesis, and stomatal conductance % Initial estimate for leaf temperature flux.tleaf = atmos.tair; % Leaf water potential at beginning of time step (MPa) flux.psi_leaf = -0.1; % Time step (s) for change in leaf water potential flux.dt = 30 * 60; % Flux calculations [flux] = LeafFluxes (physcon, atmos, leaf, flux); % Print flux output fprintf('dleaf = %15.5f\n',leaf.dleaf*100) % m -> cm fprintf('apar = %15.5f\n',flux.apar) fprintf('tleaf = %15.5f\n',flux.tleaf-physcon.tfrz) % K -> oC fprintf('qa = %15.5f\n',flux.qa) fprintf('lhflx = %15.5f\n',flux.lhflx) fprintf('etflx = %15.5f\n',flux.etflx*1000) % mol H2O/m2/s -> mmol H2O/m2/s fprintf('an = %15.5f\n',flux.an) fprintf('gbh = %15.5f\n',flux.gbh) fprintf('gs = %15.5f\n',flux.gs) fprintf('psi_leaf = %15.5f\n',flux.psi_leaf) % --- 参数敏感性分析 % 测试参数变化 factors = [0.5, 0.75, 1.0, 1.25, 1.5]; params_test = {'capac', 'minlwp', 'gplant'}; base_values = [leaf.capac, leaf.minlwp, leaf.gplant]; % 原始参数值 results = struct(); for p = 1:length(params_test) gs_vals = zeros(size(factors)); for f = 1:length(factors) leaf_temp = leaf; flux_temp = flux; % 修改当前参数 param_name = params_test{p}; leaf_temp.(param_name) = base_values(p) * factors(f); % 更新导水率相关变量 if strcmp(param_name, 'gplant') flux_temp.rplant = 1 / leaf_temp.gplant; flux_temp.lsc = 1 / (flux_temp.rsoil + flux_temp.rplant); end % 重置叶温和叶水势 flux_temp.tleaf = atmos.tair; flux_temp.psi_leaf = -0.1; % 运行模型 flux_temp = LeafFluxes(physcon, atmos, leaf_temp, flux_temp); gs_vals(f) = flux_temp.gs; end results.(param_name) = gs_vals; end % --- 绘制结果 figure; hold on; markers = {'o-', 's-', 'd-'}; colors = [0.2, 0.6, 0.8; 0.8, 0.2, 0.2; 0.2, 0.8, 0.4]; % 蓝、红、绿 for p = 1:length(params_test) param_name = params_test{p}; plot(factors, results.(param_name), markers{p}, ... 'Color', colors(p,:), ... 'MarkerFaceColor', colors(p,:), ... 'LineWidth', 1.5, ... 'MarkerSize', 8); end hold off; % 设置图形属性 xlabel('Parameter scaling factor'); ylabel('Stomatal conductance, g_s (mol m^{-2} s^{-1})'); legend('Plant capacitance (c_{apac})', ... 'Minimum leaf water potential (\psi_{min})', ... 'Stem hydraulic conductance (g_{plant})', ... 'Location', 'best'); grid on; title('Effect of plant hydraulic parameters on stomatal conductance'); set(gca, 'FontSize', 12); box on; % 保存结果 save('sensitivity_results.mat', 'factors', 'params_test', 'results'); 再在这张图给定的x轴范围内多加几个点绘图
06-21
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import time # ====================== 模型参数设置 ====================== class ModelParams: """水文模型参数容器类""" def __init__(self): self.Kc = 1.20 # 蒸发系数 self.c = 0.16 # 深层蒸发系数 self.Im = 0.003 # 不透水面积比例 self.WM = 140.0 # 流域蓄水容量 self.WUM = 20.0 # 上层蓄水容量 self.WLM = 60.0 # 中层蓄水容量 self.WDM = 60.0 # 深层蓄水容量 self.b = 0.3 # 蓄水容量曲线指数 self.init_WU = 10.0 # 初始上层含水量 self.init_WL = 40.0 # 初始中层含水量 self.init_WD = 60.0 # 初始深层含水量 # ====================== 核心功能函数 ====================== def calculate_evapotranspiration(P, E0, WU, WL, WD, params): """ 三层蒸发模型计算 返回: (总蒸发, 上层蒸发, 中层蒸发, 深层蒸发, 上层新含水量, 中层新含水量, 深层新含水量) """ # 计算实际蒸散发能力 Ep = E0 * params.Kc # 1. 上层蒸发计算 if WU + P >= Ep: EU = Ep new_WU = WU + P - EU else: EU = WU + P new_WU = 0 remaining_ep = Ep - EU # 2. 中层蒸发计算 if WL >= params.c * params.WLM: # 中层水量充足 EL = min(remaining_ep, WL) new_WL = WL - EL remaining_ep -= EL else: # 中层水量不足 EL = min(params.c * remaining_ep, WL) new_WL = WL - EL remaining_ep -= EL # 3. 深层蒸发计算 ED = min(params.c * remaining_ep, WD) new_WD = WD - ED remaining_ep -= ED # 计算总蒸发量 total_E = EU + EL + ED # 确保含水量非负 new_WU = max(new_WU, 0) new_WL = max(new_WL, 0) new_WD = max(new_WD, 0) return total_E, EU, EL, ED, new_WU, new_WL, new_WD def calculate_runoff(PE, WU, WL, WD, params): """ 蓄满产流计算 返回: (产流量, 上层新含水量, 中层新含水量, 深层新含水量) """ # 当前土壤总含水量 W = WU + WL + WD # 无有效降雨时返回零产流 if PE <= 0: return 0.0, WU, WL, WD # 完全饱和情况 if W >= params.WM: return PE, WU, WL, WD # 计算张力水蓄水容量曲线参数 WMM = params.WM * (1 + params.b) # 最大蓄水容量 ratio = min(W / params.WM, 1.0) # 防止超过100% A = WMM * (1 - (1 - ratio) ** (1 / (1 + params.b))) # 产流量计算 if PE + A < WMM: term = max(0, 1 - (PE + A) / WMM) # 防止负值 R = PE + W - params.WM + params.WM * (term ** (1 + params.b)) else: R = PE + W - params.WM # 确保产流在合理范围内 R = max(min(R, PE), 0) # 计算净入渗量 net_infiltration = PE - R # 更新土壤含水量 (分层补充) # 1. 上层补充 add_WU = min(params.WUM - WU, net_infiltration) new_WU = WU + add_WU net_infiltration -= add_WU # 2. 中层补充 add_WL = min(params.WLM - WL, net_infiltration) new_WL = WL + add_WL net_infiltration -= add_WL # 3. 深层补充 add_WD = min(params.WDM - WD, net_infiltration) new_WD = WD + add_WD return R, new_WU, new_WL, new_WD # ====================== 数据准备 ====================== def load_data(file_path): """加载输入数据""" data = pd.read_excel(file_path) P = data['P'].values E0 = data['E0'].values return P, E0 # ====================== 模拟计算主函数 ====================== def run_hydrological_model(params, P, E0): """运行水文模型""" # 预处理:划分不透水面积和透水面积 P_im = P * params.Im P_soil = P * (1 - params.Im) # 初始化状态变量 WU, WL, WD = params.init_WU, params.init_WL, params.init_WD # 存储结果 results = [] total_runoff = 0 total_evap = 0 for i in range(len(P)): # 当前时段数据 current_P_total = P[i] current_E0 = E0[i] current_P_im = P_im[i] current_P_soil = P_soil[i] try: # 三层蒸散发计算 total_E, EU, EL, ED, new_WU, new_WL, new_WD = calculate_evapotranspiration( current_P_soil, current_E0, WU, WL, WD, params ) # 计算净雨量 PE = current_P_soil - total_E # 产流计算 R_soil, updated_WU, updated_WL, updated_WD = calculate_runoff( PE, new_WU, new_WL, new_WD, params ) # 总产流 = 透水面积产流 + 不透水面积直接径流 R_total = R_soil + current_P_im total_runoff += R_total total_evap += total_E # 记录结果 result = { 'Period': i + 1, 'P_total': current_P_total, 'P_im': current_P_im, 'P_soil': current_P_soil, 'E0': current_E0, 'Ep': current_E0 * params.Kc, 'EU': EU, 'EL': EL, 'ED': ED, 'E': total_E, 'PE': PE, 'R_soil': R_soil, 'R_im': current_P_im, 'R_total': R_total, 'WU': updated_WU, 'WL': updated_WL, 'WD': updated_WD, 'Total_W': updated_WU + updated_WL + updated_WD } results.append(result) # 更新状态变量 WU, WL, WD = updated_WU, updated_WL, updated_WD except Exception as e: print(f"错误发生在第 {i+1} 时段: {str(e)}") print(f"当前参数: WU={WU}, WL={WL}, WD={WD}, P={current_P_total}, E0={current_E0}") break # 转换为DataFrame results_df = pd.DataFrame(results) # 添加累计量 results_df['累计产流'] = results_df['R_total'].cumsum() results_df['累计蒸发'] = results_df['E'].cumsum() return results_df, total_runoff, total_evap # ====================== 结果分析与可视化 ====================== def analyze_and_visualize(results_df, params, output_dir): """分析结果并生成可视化图表""" # 创建输出目录 os.makedirs(output_dir, exist_ok=True) # 保存结果到Excel output_path = os.path.join(output_dir, '水文模型模拟结果.xlsx') results_df.to_excel(output_path, index=False) print(f"模拟结果已保存到: {output_path}") # 水量平衡验证 initial_water = params.init_WU + params.init_WL + params.init_WD final_water = results_df.iloc[-1]['Total_W'] total_rain = results_df['P_total'].sum() total_evap = results_df['E'].sum() total_runoff = results_df['R_total'].sum() balance = total_rain - (final_water - initial_water) - total_evap - total_runoff print("\n水量平衡验证:") print(f"总降雨量: {total_rain:.2f} mm") print(f"总蒸发量: {total_evap:.2f} mm") print(f"总径流量: {total_runoff:.2f} mm") print(f"土壤蓄水变化: {final_water - initial_water:.2f} mm") print(f"水量平衡误差: {balance:.6f} mm (应接近0)") # 可视化 plt.figure(figsize=(15, 10)) # 1. 降雨-径流过程 plt.subplot(2, 2, 1) plt.plot(results_df['Period'], results_df['P_total'], 'b-', label='降雨量') plt.plot(results_df['Period'], results_df['R_total'], 'r-', label='径流量') plt.xlabel('时段') plt.ylabel('水量 (mm)') plt.title('降雨-径流过程线') plt.legend() plt.grid(True) # 2. 土壤含水量变化 plt.subplot(2, 2, 2) plt.plot(results_df['Period'], results_df['WU'], 'g-', label='上层土壤水') plt.plot(results_df['Period'], results_df['WL'], 'b-', label='中层土壤水') plt.plot(results_df['Period'], results_df['WD'], 'r-', label='深层土壤水') plt.xlabel('时段') plt.ylabel('土壤含水量 (mm)') plt.title('土壤含水量变化过程') plt.legend() plt.grid(True) # 3. 累计水量变化 plt.subplot(2, 2, 3) plt.plot(results_df['Period'], results_df['累计产流'], 'r-', label='累计径流') plt.plot(results_df['Period'], results_df['累计蒸发'], 'b-', label='累计蒸发') plt.xlabel('时段') plt.ylabel('累计水量 (mm)') plt.title('累计水量变化过程') plt.legend() plt.grid(True) # 4. 蒸发分量构成 plt.subplot(2, 2, 4) plt.stackplot( results_df['Period'], results_df['EU'], results_df['EL'], results_df['ED'], labels=['上层蒸发', '中层蒸发', '深层蒸发'] ) plt.xlabel('时段') plt.ylabel('蒸发量 (mm)') plt.title('蒸发分量构成') plt.legend(loc='upper left') plt.grid(True) plt.tight_layout() # 保存图表 plot_path = os.path.join(output_dir, '水文模型结果可视化.png') plt.savefig(plot_path) print(f"可视化结果已保存到: {plot_path}") plt.close() # ====================== 主程序 ====================== if __name__ == "__main__": # 记录开始时间 start_time = time.time() # 初始化模型参数 params = ModelParams() # 加载数据 data_file = r"C:\Users\80401\Desktop\SHUJU2.xlsx" P, E0 = load_data(data_file) # 运行模型 results_df, total_runoff, total_evap = run_hydrological_model(params, P, E0) # 分析结果并可视化 output_dir = os.path.join(os.path.expanduser('~'), 'Desktop', '水文模型结果') analyze_and_visualize(results_df, params, output_dir) # 计算执行时间 end_time = time.time() print(f"\n模型执行完成,耗时: {end_time - start_time:.2f}秒") print(f"总径流量: {total_runoff:.2f} mm") print(f"总蒸发量: {total_evap:.2f} mm") 修正下列错误:D:\Python\python.exe D:\Python\PythonProject\EPW\a.py Traceback (most recent call last): File "D:\Python\PythonProject\EPW\a.py", line 122, in <module> R_soil, updated_WU, updated_WL, updated_WD = calculate_runoff( ~~~~~~~~~~~~~~~~^ PE, new_WU, new_WL, new_WD ^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "D:\Python\PythonProject\EPW\a.py", line 55, in calculate_runoff if PE <= 0: ^^^^^^^ ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 进程已结束,退出代码为 1
最新发布
06-26
参考该代码:# 水量平衡验证 water_balance, total_rain, total_evap, total_runoff, delta_W = check_water_balance(results) print("\n模型运行汇总:") print(f"总时段数: {len(results)}") print(f"初始总水量: {initial_water:.3f} mm") print(f"最终总水量: {results_df.iloc[-1]['总含水量']:.3f} mm") print(f"总降雨量: {total_rain:.3f} mm") print(f"总蒸发量: {total_evap:.3f} mm") print(f"总径流量: {total_runoff:.3f} mm") print(f"土壤蓄水变化: {delta_W:.3f} mm") print(f"水量平衡误差: {water_balance:.6f} mm (应接近0)") 完成对下列代码的水量平衡分析:import pandas as pd import numpy as np import os import time #1.参数设置与数据输入 data = pd.read_excel(r"C:\Users\80401\Desktop\SHUJU2.xlsx") P = data['P'].values # 转换为 NumPy 数组 E0 = data['E0'].values # 参数初始化 K = float(1.20) C = float(0.16) Im = float(0.003) WM = float(140) WUM = float(20) WLM = float(60) WDM = float(60) b = float(0.3) WU = float(10.0) WL = float(40.0) WD = float(60.0) # 预处理:划分不透水面积和透水面积 P_im = P * Im # 不透水面积降雨 P_soil = P * (1 - Im) # 透水面积降雨 # 结果存储列表 results = [] #2.三层蒸发计算模块 def evp(WU, WL, WD, Ep, P): """三层蒸发计算模块""" # 初始化所有变量 EU = EL = ED = 0.0 if P == 0 and WU == 0: # 上层无水时,考虑下层蒸发 if WL >= C * WLM: EL = min(Ep, WL) # 限制蒸发量不超过可用水量 elif WL >= C * Ep: EL = C * Ep else: EL = WL remaining_ep = max(Ep - EL, 0) # 确保蒸发需求非负 ED = min(C * remaining_ep, WD) elif WU + P >= Ep: # 三层蒸散发 EU = Ep else: EU = WU + P remaining_ep = Ep - EU if WL >= C * WLM: EL = min(remaining_ep * WL / WLM, WL) elif WL >= C * remaining_ep: EL = C * remaining_ep else: EL = WL ED = min(C * (remaining_ep - EL), WD) E = EU + EL + ED PE = P - E return EU, EL, ED, E, PE #3.蓄满产流计算模块 def runoff(PE,W,WM,b): """蓄满产流计算""" if PE <= 0: return 0.0 # 完全饱和时所有净雨转化为径流 if W >= WM: return PE WMM = WM * (1 + b) a = WMM * (1 - (1 -W / WM) ** (1 / (1 + b))) if a + PE <= WMM: R = PE + W - WM + WM * (1 - (PE + a) / WMM) ** (1 + b) else: R = PE + W - WM return max(R, 0) # 确保产流不为负 #4.土壤蓄水量更新模块 def update(WU, WL, WD, EU, EL, ED, PE, R): """更新土壤含水量""" # 1. 计算实际入渗量(净雨量扣除产流) net_water = PE - R # 2. 分层补充水量 (先补充上层,再下层,最后深层) # 上层 add_WU = min(WUM - WU, max(0, net_water)) new_WU = max(0, min(WU + add_WU, WUM)) net_water -= add_WU #下渗量 # 下层 add_WL = min(WLM - WL, max(0, net_water)) new_WL = max(0, min(WL + add_WL, WLM)) net_water -= add_WL #下渗量 # 深层 add_WD = min(WDM - WD, max(0, net_water)) new_WD = max(0, min(WD + add_WD, WDM)) # 3. 水量平衡检查 (使用透水面积部分) total_change = (new_WU - WU) + (new_WL - WL) + (new_WD - WD) expected_change = PE - R # 净雨量-产流 # 5.调整误差(确保水量平衡) if abs(total_change - expected_change) > 0.001: adjustment = expected_change - total_change # 将调整量加到深层(或按需分配到各层) new_WD = max(0, min(new_WD + adjustment, WDM)) return new_WU, new_WL, new_WD # 主循环 for i in range(len(P)): try: # 获取当前时段的原始降雨和蒸发能力 current_P_total = P[i] # 原始总降雨量 current_E0 = E0[i] # 划分不透水面积和透水面积 current_P_im = P_im[i] # 不透水面积降雨 current_P_soil = P_soil[i] # 透水面积降雨 # 计算实际蒸发能力 current_Ep = current_E0 * K # 三层蒸散发计算 (使用透水面积降雨) EU, EL, ED, E, PE = evp(WU, WL, WD, current_Ep, current_P_soil) # 产流计算 (仅透水面积) W = WU + WL + WD R_soil = runoff(PE, W, WM, b) # 总产流 = 透水面积产流 + 不透水面积直接径流 R_total = R_soil + current_P_im # 更新土壤含水量 (仅透水面积部分) new_WU, new_WL, new_WD = update(WU, WL, WD, EU, EL, ED, PE, R_soil) # 记录结果 results.append({ 'Period': i + 1, 'P_total': round(current_P_total, 3), 'P_im': round(current_P_im, 3), 'P_soil': round(current_P_soil, 3), 'E0': round(current_E0, 2), 'Ep': round(current_Ep, 2), 'EU': round(EU, 3), 'EL': round(EL, 3), 'ED': round(ED, 3), 'E': round(E, 3), 'PE': round(PE, 3), 'R_soil': round(R_soil, 3), 'R_im': round(current_P_im, 3), 'R_total': round(R_total, 3), 'WU': round(new_WU, 3), 'WL': round(new_WL, 3), 'WD': round(new_WD, 3), 'Total_W': round(new_WU + new_WL + new_WD, 3) }) # 更新状态变量 WU, WL, WD = new_WU, new_WL, new_WD except Exception as e: print(f"错误发生在第 {i + 1} 时段: {str(e)}") print(f"当前参数: WU={WU}, WL={WL}, WD={WD}, Ep={Ep[i]}, P={P[i]}") break # 转换为DataFrame并保存结果 results_df = pd.DataFrame(results) print("\n计算结果预览:") print(results_df.head()) # 保存到Excel output_path = os.path.join(os.path.expanduser("~"), "Desktop", "水文模型计算结果KESHE.xlsx") results_df.to_excel(output_path, index=False) print(f"结果已保存到: {output_path}")
06-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值