# ! /usr/bin/env python
# coding=utf-8
import math
import os
import time
import pandas as pd
# day of year
def doy(dt):
sec = time.mktime(dt.timetuple())
t = time.localtime(sec)
return t.tm_yday
# day of year
def date2doy(year, month, day):
month_leapyear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month_notleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
doy = 0
if month == 1:
pass
elif year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
for i in range(month - 1):
doy += month_leapyear[i]
else:
for i in range(month - 1):
doy += month_notleap[i]
doy += day
return doy
# earth-sun distance
def dr(doy):
return 1 + 0.033 * math.cos(2 * math.pi * doy / 365)
# declination
def dec(doy):
return 0.409 * math.sin(2 * math.pi * doy / 365 - 1.39)
# sunset hour angle
def ws(lat, dec):
x = 1 - math.pow(math.tan(lat), 2) * math.pow(math.tan(dec), 2)
if x < 0:
x = 0.00001
# print x
return 0.5 * math.pi - math.atan(-math.tan(lat) * math.tan(dec) / math.sqrt(x))
def Rs(doy, n, lat):
"""n is sunshine duration"""
lat = lat * math.pi / 180.
a = 0.25
b = 0.5
d = dec(doy)
w = ws(lat, d)
N = 24 * w / math.pi
# Extraterrestrial radiation for daily periods
ra = (24 * 60 * 0.082 * dr(doy) / math.pi) * (
w * math.sin(lat) * math.sin(d) + math.cos(lat) * math.cos(d) * math.sin(w))
return (a + b * n / N) * ra
def writeToTxt(list_name, file_path):
try:
fp = open(file_path, "w+")
for item in list_name:
fp.write(str(item) + "\n")
fp.close()
except IOError:
print("fail to open file")
if __name__ == "__main__":
list_dir = r"C:\Users\wq\Desktop\ssd_data\ssd_data"
for filename in os.listdir(list_dir):
file_path = os.path.join(list_dir, filename)
print(file_path)
df = pd.read_csv(file_path, encoding='utf-8')
df['doy'] = 0
df['sr'] = 0.0
for i in range(0, len(df)):
year = df.iloc[i, 4]
month = df.iloc[i, 5]
day = df.iloc[i, 6]
doy = date2doy(year, month, day)
df.iloc[i, 8] = doy
lat = df.iloc[i, 1]
ssd = df.iloc[i, 7]
sr = round(Rs(float(doy), float(ssd), lat * math.pi / 180.), 1)
print(sr)
df.iloc[i, 9] = sr
df.to_csv(r"C:\Users\wq\Desktop\ssd_data\sr_data\%s" % (filename,))
- 1
- 2
前往页