def NASA_weather_data_loader(self, latitude, longitude):
        """
        Download weather from NASA database and fill missing values
        
        Input: latitude,longitude (int)
        
        Output: Weather database for 30-40 last years
        
        """

        weather = NASAPowerWeatherDataProvider(latitude,
                                               longitude,
                                               force_update=True)
        df_weather = pd.DataFrame(weather.export())

        r = pd.date_range(start=df_weather.DAY.min(), end=df_weather.DAY.max())
        full_range_weather = df_weather.set_index('DAY').reindex(
            r).rename_axis('DAY').reset_index()
        filled_weather = full_range_weather.fillna(method='ffill', axis=0)
        weather._make_WeatherDataContainers(
            filled_weather.to_dict(orient="records"))

        self.NASA_start_year = weather.first_date.year + 1
        self.NASA_last_year = weather.last_date.year - 1
        self.weather = weather
Пример #2
0
def get_met(lat, lon, start_date=None, end_date=None):
    """

    :param lat: 
    :param lon: 
    :param start_date: 
    :param end_date: 
    :return: 
    """
    from pcse.db import NASAPowerWeatherDataProvider
    wdp = NASAPowerWeatherDataProvider(lat, lon, True)
    _df = wdp._query_NASAPower_server(lat, lon)

    _df = [x.decode("utf-8") for x in _df]  # Decode from bytes to strings
    _ix = [i for i, s in enumerate(_df)
           if 'END HEADER' in s][0]  # Find end of header
    _header = [x for x in _df[_ix - 1].split()
               ]  # Header is one line before end of header
    _df = _df[_ix + 1:]  # All data (except after END HEADER)

    # Convert data to dataframe
    df = pd.DataFrame(columns=_header, data=[row.split() for row in _df])
    df.replace('-', np.NaN, inplace=True)
    df = pd.to_numeric(df.stack(), 'coerce').unstack()
    df['datetime'] = pd.to_datetime(
        df['YEAR'].astype(int), format='%Y') + pd.to_timedelta(df['DOY'] - 1,
                                                               unit='d')

    # Add datetime column and set it as index
    if 'datetime' in df and not isinstance(df.index, pd.DatetimeIndex):
        df = df.set_index('datetime')

    return df
Пример #3
0
def get_met(lat, lon, start_date=None, end_date=None):
    """

    :param lat: 
    :param lon: 
    :param start_date: 
    :param end_date: 
    :return: 
    """
    from pcse.db import NASAPowerWeatherDataProvider
    wdp = NASAPowerWeatherDataProvider(lat, lon, start_date, end_date)
    _df = wdp._query_NASAPower_server(lat, lon, start_date, end_date)

    _df = [x.decode("utf-8") for x in _df]  # Decode from bytes to strings
    _ix = [i for i, s in enumerate(_df) if 'END HEADER' in s][0]  # Find end of header
    _header = [x for x in _df[_ix - 1].split()]  # Header is one line before end of header
    _df = _df[_ix + 1:]  # All data (except after END HEADER)

    # Convert data to dataframe
    df = pd.DataFrame(columns=_header, data=[row.split() for row in _df])
    df.replace('-', np.NaN, inplace=True)
    df = pd.to_numeric(df.stack(), 'coerce').unstack()
    df['datetime'] = pd.to_datetime(df['YEAR'].astype(int), format='%Y') + pd.to_timedelta(df['DOY'] - 1, unit='d')

    # Add datetime column and set it as index
    if 'datetime' in df and not isinstance(df.index, pd.DatetimeIndex):
        df = df.set_index('datetime')

    return df
Пример #4
0
    def _کوائف_بنانا(خود, سے, تک, چوڑائی, طول, بلندی, خاکے):
        try:
            ذریعہ_ناسا = NASAPowerWeatherDataProvider(latitude=چوڑائی, longitude=طول, force_update=False)
        except (requests.exceptions.ConnectionError, KeyError, JSONDecodeError):
            return

        سے = max(ذریعہ_ناسا.first_date, سے)
        تک = min(ذریعہ_ناسا.last_date, تک)

        اعداد_پاندس = pd.DataFrame(columns=list(متاغیرات), index=pd.period_range(سے, تک), dtype=float)

        ستون = {
            'بارش': 'RAIN',
            'شمسی_تابکاری': 'IRRAD',
            'درجہ_حرارت_زیادہ': 'TMAX',
            'درجہ_حرارت_کم': 'TMIN',
            'درجہ_حرارت_اوسط': 'TEMP'
        }

        for تاریخ in اعداد_پاندس.index:
            for س, س_ناسا in ستون.items():
                اعداد_پاندس.loc[تاریخ][س] = getattr(ذریعہ_ناسا(سے), س_ناسا)

        اعداد_پاندس.شمسی_تابکاری *= 1e-6

        return اعداد_پاندس
Пример #5
0
  def run_simulation(self):
    if not isinstance(self.weather_data, dict):
      print("Fetching NASA weather...")
      self.wdp = NASAPowerWeatherDataProvider(self.location.lat, self.location.lon)
    else:
      print("Weather data is cached...")
      if (self.location.lat != self.weather_data['latitude']) or (self.location.lon != self.weather_data['longitude']):
        print("Location changed, fetching NASA weather again")
        self.wdp = NASAPowerWeatherDataProvider(self.location.lat, self.location.lon)
      else:
        self.wdp = WeatherDataProvider()
        self.wdp.store = self.weather_data['store']
        self.wdp.elevation = self.weather_data['elevation']
        self.wdp.longitude = self.weather_data['longitude']
        self.wdp.latitude = self.weather_data['latitude']
        self.wdp.description = self.weather_data['description']
        self.wdp.ETmodel = self.weather_data['ETmodel']
    print(self.wdp)
    amgt = default_amgt
    soil = default_soil
    site = default_site
    crop = default_crop

    amgt[0][self.start_date] = amgt[0].pop(amgt[0].keys()[0])

    amgt[0][self.start_date]['CropCalendar']['crop_start_date'] = self.sowing_date
    amgt[0][self.start_date]['CropCalendar']['crop_end_date'] = self.end_date

    parvalues = ParameterProvider(sitedata=site, soildata=soil, cropdata=crop)
    crop['TSUM1'] = self.tsum1
    crop['TSUM2'] = self.tsum2
    soil.update(self.soil_attributes)
    wofsim = Wofost71_WLP_FD(parvalues, self.wdp, agromanagement=amgt)
    wofsim.run_till_terminate()
    output = wofsim.get_output()

    results_dict = {}
    for a in output:
        results_dict[a.pop('day').isoformat()] = a
    self.simulation_dict = results_dict
    return results_dict
Пример #6
0
    def init_wofost():
        data_dir = os.path.join(os.getcwd(), '../simulation/default_data')
        crop_file_name = 'crop.cab'
        soil_file_name = 'soil.cab'
        site_file_name = 'site.cab'
        config_file_name = 'WLP_NPK.conf'

        soildata = CABOFileReader(os.path.join(data_dir, soil_file_name))
        sitedata = CABOFileReader(os.path.join(data_dir, site_file_name))
        cropdata = CABOFileReader(os.path.join(data_dir, crop_file_name))
        config = os.path.join(data_dir, config_file_name)

        params = ParameterProvider(cropdata, sitedata, soildata)
        latitude, longitude = 51.97, 5.67
        wdp = NASAPowerWeatherDataProvider(latitude, longitude)

        return params, wdp, config
Пример #7
0
 def test_weather(latitude,longitude):
     n=0
     weather=None
     while n<10:
         n+=1
         try:
             weather = NASAPowerWeatherDataProvider(latitude, longitude, force_update=True)
             info='ok in this region'
             break
         except KeyError as e:
             info = e
             print('В Америке ночь, сервер NASA сладко спит и не хочет отвечать')
             time.sleep(60*5)
         except PCSEError as e:
             print('Погода в этом регионе снова подвела!')
             info = e
             break
     return weather, info
Пример #8
0
def dailyweatherobservations(lat, long):

    wdp = NASAPowerWeatherDataProvider(latitude=lat, longitude=long)
    print(wdp)
    return wdp
#pack the different sets of parameters
from pcse.base_classes import ParameterProvider
parameters = ParameterProvider(cropdata=cropdata,
                               soildata=soildata,
                               sitedata=sitedata)  #cropdata = cropd

#agromanagement control the start date and end date
#there are two files, one is defalut, the other one is for excel weather data
from pcse.fileinput import YAMLAgroManagementReader
agromanagement = YAMLAgroManagementReader("sugarbeet_c.agro")
print(agromanagement)

#using modeul to read weather data
from pcse.db import NASAPowerWeatherDataProvider
wdp = NASAPowerWeatherDataProvider(latitude=52, longitude=5)
print(wdp)

#from pcse.fileinput import ExcelWeatherDataProvider
#wdp = ExcelWeatherDataProvider ("weather04.xlsx")
#print (wdp)

#simulate the crop
from pcse.models import Wofost71_WLP_FD
wofsim = Wofost71_WLP_FD(parameters, wdp, agromanagement)
wofsim.run_till_terminate()
output = wofsim.get_output()
len(output)

varnames = ["day", "DVS", "TAGP", "LAI", "SM"]
tmp = {}
    def update_csv_NASA_weather_database(self, path_CSV_dir, latitude_min,
                                         latitude_max, longitude_min,
                                         longitude_max):
        """
        function for downloading NASA weather and creating csv files in folders for future simulation 

        Input: path, latitude_min, latitude_max, longitude_min, longitude_max
        Output: CSV files in dir 

        """
        #import time
        longitude_array = np.arange(longitude_min, longitude_max, step=1)
        latitude_array = np.arange(latitude_min, latitude_max, step=1)

        col_names = [
            'latitude', 'longitude', 'Num_of_missing_dates', 'start_date',
            'last_date'
        ]
        weather_database = pd.DataFrame(data=np.zeros([
            latitude_array.shape[0] * longitude_array.shape[0],
            len(col_names)
        ]),
                                        columns=col_names)
        weather_database.start_date = pd.to_datetime(
            weather_database.start_date)
        weather_database.last_date = pd.to_datetime(weather_database.last_date)

        #path = '/gdrive/My Drive/NASA_CSV'
        path = path_CSV_dir

        i = 0

        for latitude in latitude_array:
            for longitude in longitude_array:
                start_time = time.time()
                #API request to NASA database
                weather = NASAPowerWeatherDataProvider(latitude,
                                                       longitude,
                                                       force_update=True)

                # Print done if downloaded
                print('____DONE_____', 'latitude', latitude, 'longitude',
                      longitude, '____')

                # export pcse.weather format to pandas df
                df_weather = pd.DataFrame(weather.export())

                #print('initial number of days:', len(df_weather))

                #create full range of dates
                r = pd.date_range(start=df_weather.DAY.min(),
                                  end=df_weather.DAY.max())

                #extend range of dates
                full_range_weather = df_weather.set_index('DAY').reindex(
                    r).rename_axis('DAY').reset_index()
                missing_days = (full_range_weather.isna()).sum().sum()

                print('num_of_missing_days', missing_days)

                #fill weather with fill forward method in pandas
                filled_weather = full_range_weather.fillna(method='ffill',
                                                           axis=0)
                ##save as csv file
                #filled_weather.to_csv(path+f'/NASA_weather_latitude_{latitude}_longitude{longitude}.csv', index=False)

                # filled_weather = pd.read_csv('../NASA_test/NASA_weather_latitude_30_longitude40.csv')
                # filled_weather.DAY = pd.to_datetime(loaded_weather.DAY)
                filled_weather = filled_weather[[
                    'DAY', 'IRRAD', 'TMIN', 'TMAX', 'VAP', 'WIND', 'RAIN'
                ]]
                filled_weather['SNOWDEPTH'] = 'NaN'
                filled_weather[['IRRAD']] = filled_weather[['IRRAD']] / 1000.
                filled_weather[['VAP']] = filled_weather[['VAP']] / 10.
                filled_weather.DAY = filled_weather.DAY.dt.strftime('%Y%m%d')

                text = open(path + "pattern.csv", "r")
                text = ''.join([i for i in text
                                ]).replace("1111", str(weather.longitude))
                text = ''.join([i for i in text
                                ]).replace("2222", str(weather.latitude))
                text = ''.join([i for i in text
                                ]).replace("3333", str(weather.elevation))
                text = ''.join([i for i in text
                                ]).replace("4444", str(weather.angstA))
                text = ''.join([i for i in text
                                ]).replace("5555", str(weather.angstB))
                x = open(
                    path +
                    f'NASA_weather_latitude_{latitude}_longitude_{longitude}_TEST.csv',
                    "w")
                x.writelines(text)
                x.close()

                filled_weather.to_csv(
                    path +
                    f'NASA_weather_latitude_{latitude}_longitude_{longitude}_TEST.csv',
                    mode='a',
                    header=False,
                    index=False)

                #add info to weather database and save it to csv
                list_to_add = [
                    latitude, longitude, missing_days, weather.first_date,
                    weather.last_date
                ]
                weather_database.iloc[i, :] = list_to_add
                i += 1
                weather_database.to_csv(path + 'weather_database.csv',
                                        mode='a')

                print('time in sec', time.time() - start_time)
    def weather_loader(self, path_CSV_dir, latitude, longitude):
        """
        Main fun to load weather 
        
        If we have CSV file - load CSV, 
        
        else: Load from NASA
        
        """

        self.path_to_CSV_database = path_CSV_dir

        # latitude_min = self._csv_weather_database_boarders['latitude_min']
        # latitude_max = self._csv_weather_database_boarders['latitude_max']
        # longitude_min = self._csv_weather_database_boarders['longitude_min']
        # longitude_max = self._csv_weather_database_boarders['longitude_max']
        # if latitude_min <= latitude < latitude_max and longitude_min <= longitude < longitude_max:
        # If in range of our database - load CSV file from database
        path = self.path_to_CSV_database + f'/NASA_weather_latitude_{latitude}_longitude_{longitude}.csv'
        # print('path and file', path)
        if os.path.exists(path):

            print('LOAD FROM LOCAL CSV WEATHER DATABASE')
            # path = self.path_to_CSV_database + f'NASA_weather_latitude_{latitude}_longitude_{longitude}_TEST.csv'
            weather = pcse.fileinput.CSVWeatherDataProvider(path)
            self.weather = weather
            self.NASA_start_year = weather.first_date.year + 1

            ### WEATHER YEAR TEST
            self.NASA_last_year = weather.last_date.year - 1

            #self.NASA_last_year = weather.last_date.year
        else:
            print('No such directory or CSV file')
            print('DOWNLOAD FROM NASA POWER database (1-5 mins)')

            # Test load from NASA POWER and save as  csv and after load
            path = self.path_to_CSV_database
            try:
                start_time = time.time()
                #API request to NASA database
                weather = NASAPowerWeatherDataProvider(latitude,
                                                       longitude,
                                                       force_update=True)

                # Print done if downloaded
                print('____DONE_____', 'latitude', latitude, 'longitude',
                      longitude, '____')

                # export pcse.weather format to pandas df
                df_weather = pd.DataFrame(weather.export())

                #print('initial number of days:', len(df_weather))

                #create full range of dates
                r = pd.date_range(start=df_weather.DAY.min(),
                                  end=df_weather.DAY.max())

                #extend range of dates
                full_range_weather = df_weather.set_index('DAY').reindex(
                    r).rename_axis('DAY').reset_index()
                missing_days = (full_range_weather.isna()).sum().sum()

                print('num_of_missing_days', missing_days)

                #fill weather with fill forward method in pandas
                filled_weather = full_range_weather.fillna(method='ffill',
                                                           axis=0)

                #save as csv file

                filled_weather = filled_weather[[
                    'DAY', 'IRRAD', 'TMIN', 'TMAX', 'VAP', 'WIND', 'RAIN'
                ]]
                filled_weather['SNOWDEPTH'] = 'NaN'
                filled_weather[['IRRAD']] = filled_weather[['IRRAD']] / 1000.
                filled_weather[['VAP']] = filled_weather[['VAP']] / 10.
                filled_weather.DAY = filled_weather.DAY.dt.strftime('%Y%m%d')

                text = open(path + "pattern.csv", "r")
                text = ''.join([i for i in text
                                ]).replace("1111", str(weather.longitude))
                text = ''.join([i for i in text
                                ]).replace("2222", str(weather.latitude))
                text = ''.join([i for i in text
                                ]).replace("3333", str(weather.elevation))
                text = ''.join([i for i in text
                                ]).replace("4444", str(weather.angstA))
                text = ''.join([i for i in text
                                ]).replace("5555", str(weather.angstB))
                x = open(
                    path +
                    f'NASA_weather_latitude_{latitude}_longitude_{longitude}.csv',
                    "w")
                x.writelines(text)
                x.close()

                path_to_save_csv_file = path + f'NASA_weather_latitude_{latitude}_longitude_{longitude}.csv'
                filled_weather.to_csv(path_to_save_csv_file,
                                      mode='a',
                                      header=False,
                                      index=False)

                #add info to weather database and save it to csv

                print('time in sec', time.time() - start_time)

                #LOAD WEATHER as csv file
                weather = pcse.fileinput.CSVWeatherDataProvider(
                    path_to_save_csv_file)
                self.weather = weather
                self.NASA_start_year = weather.first_date.year + 1

                self.NASA_last_year = weather.last_date.year - 1
            except Exception:
                info = traceback.format_exc()
                print(info)
Пример #12
0
def ensemble_wofost(lon=115.55,
                    lat=38.05,
                    start=dt.date(2008, 10, 12),
                    end=None,
                    en_size=3,
                    prior_file=None,
                    weather_type="NASA",
                    weather_path=None,
                    out_en_file=None,
                    data_dir=None):
    """
    This is a function to generate a emsemble of WOFOST paramters and corresponding output.
    you need to specify Longitude (lon), Latitude (lat), 
    start time of crop (start), end time of crop (end, 270 days duration by default),
    emsemble size (en_size), configuration file for prior distributions of pramaters (prior_file), 
    weather driver dataset type (weather_type), it's set to NASA Power dataset "NASA" by default,
    you could use ERA5 "ERA5" or ECMWF TIGGE "ITGEE" instead or use your own CABO file (%your_cabo_files_name%).)
    """
    if data_dir is None:
        #home = os.path.dirname(os.path.realpath("__file__"))
        home = os.path.split(os.path.realpath(__file__))[
            0]  #os.path.dirname(os.path.abspath(__file__))
        data_dir = home + "/data/"
        #print(data_dir)
    if prior_file is None:
        prior_file = data_dir + "par_prior.csv"
    if out_en_file is None:
        out_en_file = "WOFOST_par_ensemble.npy"

    if lat < -90 or lat > 90:
        msg = "Latitude should be between -90 and 90 degrees."
        raise ValueError(msg)
    if lon < -180 or lon > 180:
        msg = "Longitude should be between -180 and 180 degrees."
        raise ValueError(msg)
    if end == None:
        end = start + dt.timedelta(days=270)
    if start >= end:
        msg = "Start time should be earlier than end time."
        raise ValueError(msg)
    if weather_type == "NASA":
        print("Downloading weather driver from NASA Power...")
        weather = NASAPowerWeatherDataProvider(latitude=lat, longitude=lon)
    elif weather_type[:3] == "ERA" or weather_type[:3] == "era":
        print("ERA5 reanalysis dataset used.")
        if weather_path is None or not os.path.isdir(weather_path):
            msg = "Please provide a valid path for weahter driver data."
            raise ValueError(msg)
        gen_era_cabo(lat,
                     lon,
                     start.year,
                     end.year,
                     inputfile=weather_path,
                     data_dir=data_dir)
        size = 0.25
        weather_name = "ERA_%5.2f_%5.2f" % (int(
            (lon + size / 2.) / size) * size, int(
                (lat + size / 2.) / size) * size)
        weather = CABOWeatherDataProvider(weather_name, fpath=weather_path)
    elif weather_type[:5].upper() == "TIGGE":
        print("TIGGE forecast from ECMWF used.")
        if weather_path is None or not os.path.isdir(weather_path):
            msg = "Please provide a valid path for weahter driver data."
            raise ValueError(msg)
        gen_tigge_cabo(lat,
                       lon,
                       start.year,
                       end.year,
                       inputfile=weather_path,
                       data_dir=data_dir)
        size = 0.25
        weather_name = "TIGGE_%5.2f_%5.2f" % (int(
            (lon + size / 2.) / size) * size, int(
                (lat + size / 2.) / size) * size)
        weather = CABOWeatherDataProvider(weather_name, fpath=weather_path)
    else:
        if weather_path == None:
            raise ValueError("Please provide your weather driver path!")
        weather = CABOWeatherDataProvider(weather_type, fpath=weather_path)

    sdoy = retrieve_pixel_value([lon, lat], data_dir +
                                "mean_wheat_sdoy_china_kriging_int.tif")
    tsum1 = retrieve_pixel_value([lon, lat], data_dir +
                                 "mean_wheat_TSUM1_china_kriging.tif")
    tsum2 = retrieve_pixel_value([lon, lat],
                                 data_dir + "TSUM2_aver_0.1deg.tif")

    varnames = ["day", "TAGP", "LAI", "TWSO", "DVS"]
    tmp = {}

    cropfile = os.path.join(data_dir, 'WWH108.CAB')
    crop = CABOFileReader(cropfile)
    soilfile = os.path.join(data_dir, 'Hengshui.soil')
    soil = CABOFileReader(soilfile)
    site = WOFOST71SiteDataProvider(WAV=100, CO2=360)
    parameters = ParameterProvider(soildata=soil, cropdata=crop, sitedata=site)
    agromanagement_file = os.path.join(data_dir, 'shenzhou_wheat.amgt')
    agromanagement = YAMLAgroManagementReader(agromanagement_file)
    (key, value), = agromanagement[0].items()
    agromanagement[0][dt.datetime.strptime(
        "%d%03d" % (start.year, sdoy),
        "%Y%j").date()] = agromanagement[0].pop(key)
    value['CropCalendar']['crop_start_date'] = dt.datetime.strptime(
        "%d%03d" % (start.year, sdoy), "%Y%j").date()
    print("Crop is sowed at %s" % dt.datetime.strftime(
        value['CropCalendar']['crop_start_date'], "%Y-%m-%d"))
    value['CropCalendar']['crop_end_date'] = end

    prior_dist, prior_list, param_xvalue, param_type = define_prior_distributions(
        chunk=prior_file, tsum1=tsum1, tsum2=tsum2)
    z_start = np.empty((len(prior_list), en_size))
    for i, param in enumerate(prior_list):
        z_start[i, :] = prior_dist[param].rvs(en_size)
    outdata = []

    for i in range(en_size):
        theta_dict = dict(zip(prior_list, z_start[:, i]))
        cropdata = copy.deepcopy(crop)
        tb_x = {}
        tb_y = {}
        tb_t = {}
        tmp_dict = {}
        for par in theta_dict.keys():
            try:
                if param_type[par] != 'S':
                    tb_index = par.find("TB")
                    if tb_index < 0:
                        print(param_xvparam_typealue[par])
                        raise Exception("Are you sure %s is a table value?" %
                                        par)
                    tb_name = par[:tb_index + 2]
                    tmp_list = [param_xvalue[par], theta_dict[par]]
                    if not tb_name in tb_x:
                        tb_x[tb_name] = np.array([param_xvalue[par]])
                        tb_y[tb_name] = np.array([theta_dict[par]])
                        tb_t[tb_name] = param_type[par]
                    else:
                        tb_x[tb_name] = np.append(tb_x[tb_name],
                                                  param_xvalue[par])
                        tb_y[tb_name] = np.append(tb_y[tb_name],
                                                  theta_dict[par])
            except KeyError:
                raise Exception(
                    "There's something wrong with %s, please check it." % par)
        tmp_dict = {}
        for par in tb_x.keys():  # Table parameters
            s_i = np.argsort(tb_x[par])
            s_x = tb_x[par][s_i]
            s_v = tb_y[par][s_i]
            par_tb = []
            #         print(par,tb_t[par],cropdata[par],s_x,s_v)
            if tb_t[par][1] == 'P':
                for i in range(len(tb_x[par])):
                    if tb_t[par][0] == 'Y':  # Partly change table Y values
                        if s_x[i] in cropdata[par][::2]:  # change old value
                            c_i = cropdata[par][::2].index(s_x[i])
                            cropdata[par][c_i * 2] = s_v[i]
                        else:  # insert new value
                            array_X = cropdata[par][::2]
                            array_Y = cropdata[par][1:][::2]
                            ins_i = bisect(array_X, s_x[i])
                            cropdata[par].insert(ins_i * 2, s_x[i])
                            cropdata[par].insert(ins_i * 2 + 1, s_v[i])
                        #print(cropdata[par])
                    else:  # Partly change table X values
                        if s_x[i] in cropdata[par][
                                1:][::2]:  # change old value
                            c_i = cropdata[par][1:][::2].index(s_x[i])
                            cropdata[par][c_i * 2] = s_v[i]
                        else:  # insert new value
                            array_X = cropdata[par][::2]
                            array_Y = cropdata[par][1:][::2]
                            ins_i = bisect(array_X, s_x[i])
                            cropdata[par].insert(ins_i * 2, s_x[i])
                            cropdata[par].insert(ins_i * 2 + 1, s_v[i])
                        #print(cropdata[par])
            elif tb_t[par][1] == 'A':
                if tb_t[par][0] == 'Y':  # Totally change table Y values
                    for i in range(len(tb_x[par])):
                        par_tb.append(s_x[i])
                        par_tb.append(s_v[i])
                else:  # Totally change table X values
                    for i in range(len(tb_x[par])):
                        par_tb.append(s_v[i])
                        par_tb.append(s_x[i])
                tmp_dict[par] = par_tb
                #print(tmp_dict[par])
                theta_dict.update(tmp_dict)
            else:
                raise Exception(
                    "There's something wrong with %s, please check it." % par)
        ##########################################################################
        cropdata.update(theta_dict)

        parameters = ParameterProvider(cropdata=cropdata,
                                       soildata=soil,
                                       sitedata=site)
        wofwof = Wofost71_PP(parameters, weather, agromanagement)
        wofwof.run_till_terminate()
        output = wofwof.get_output()
        summary_output = wofwof.get_summary_output()
        msg = "Reached maturity at {DOM} with max LAI of {LAIMAX} "\
    "and a yield of {TWSO} kg/ha."
        print(msg.format(**summary_output[0]))
        for var in varnames:
            tmp[var] = [t[var] for t in output]
        theta_dict["LAI"] = tmp["LAI"][-181:]
        theta_dict["day"] = tmp["day"][-181:]
        theta_dict["Yield"] = tmp["TWSO"][-1]
        outdata.append(theta_dict)
    np.save(out_en_file, outdata)
Пример #13
0
#agromanagement = yaml.safe_load(yaml_agro)
print(yaml_agro)

"""## Daily weather observations
Daily weather variables are needed for running the simulation. There are several data providers in PCSE for reading weather data, see the section on [weather data providers](http://pcse.readthedocs.io/en/stable/reference_guide.html#weather-data-providers) to get an overview.

For this example we will use weather data from an excel file which provides daily weather data for Wageningen for the period 2004 to 2008. We will read the data from the file using the ExcelWeatherDataProvider:

### NASA Weather Data Provider from NASA [DataBase](https://power.larc.nasa.gov/)
"""

#NASA Weather system
from pcse.db import NASAPowerWeatherDataProvider

#export weather to list
moscow_weather = NASAPowerWeatherDataProvider(55.45, 37.36)
print(moscow_weather)

"""Weather loader for __NH__ example"""

from pcse.fileinput import ExcelWeatherDataProvider
weatherfile = os.path.join(data_dir, 'meteo', 'nl1.xlsx')
wdp = ExcelWeatherDataProvider(weatherfile)
print(wdp)

"""## Importing, initializing and running a PCSE model

Internally, PCSE uses a simulation engine to run a crop simulation. This engine takes a configuration file that specifies the components for the crop, the soil and the agromanagement that need to be used for the simulation. So any PCSE model can be started by importing the engine and initializing it with a given configuration file and the corresponding parameters, weather data and agromanagement.

However, as many users of PCSE only need a particular configuration (for example the WOFOST model for potential production), preconfigured Engines are provided in `pcse.models`. For the sugarbeet example we will import the WOFOST model for water-limited simulation under freely draining soil conditions:
"""
Пример #14
0
import unittest
from json import JSONDecodeError

import pandas as pd
import pandas.testing as pdt
import requests
from pcse.db import NASAPowerWeatherDataProvider
from تقدیر.ذرائع import ناسا

جگہ = dict(چوڑائی=11.02, طول=76.96, بلندی=1)
try:
    NASAPowerWeatherDataProvider(latitude=جگہ['چوڑائی'],
                                 longitude=جگہ['طول'],
                                 force_update=False)
    جالبینی_رسائی = True
except (requests.exceptions.ConnectionError, KeyError, JSONDecodeError):
    جالبینی_رسائی = False
وجہ = 'ناسا کا جالبین پنہ اب دستیاب نہیں۔'


class امتحان_ناسا(unittest.TestCase):
    @staticmethod
    def _پورا(سے, تک, اعداد):
        pdt.assert_index_equal(اعداد.روزانہ().dropna(how='all').index,
                               pd.period_range(سے, تک, freq='D'))

    @unittest.skipUnless(جالبینی_رسائی, وجہ)
    def test_کوائف_پانا(خود):
        سے, تک = '۲۰۱۷۱۲۱۵', '۲۰۱۸۰۱۱۵'
        اعداد = ناسا().کوائف_پانا(سے, تک, **جگہ, خاکے='۴۔۵')
        خود._پورا(سے, تک, اعداد)