Example #1
0
 def get_wilting_point(self):
     if self.use_custom_parameters:
         if self.custom_wilting_point in [None, ""]:
             return extract_point_from_raster(
                 self.location,
                 gdal.Open(
                     os.path.join(settings.AIRA_COEFFS_RASTERS_DIR,
                                  "pwp.tif")),
             )
         return self.custom_wilting_point
     else:
         return extract_point_from_raster(
             self.location,
             gdal.Open(
                 os.path.join(settings.AIRA_COEFFS_RASTERS_DIR, "pwp.tif")),
         )
Example #2
0
 def test_bottom_left_point(self):
     # Use almost exactly same point as test_middle_point(), only slightly altered
     # so that we get bottom left point instead.
     point = hspatial.coordinates2point(22.00999, 37.97999)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            3.1,
                            places=2)
Example #3
0
 def test_middle_point(self):
     # We use co-ordinates almost to the common corner of the four lower left points,
     # only a little bit towards the center.
     point = hspatial.coordinates2point(22.01001, 37.98001)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            2.2,
                            places=2)
Example #4
0
 def in_covered_area(self):
     mask = os.path.join(settings.AIRA_DATA_SOIL, "fc.tif")
     try:
         tmp_check = extract_point_from_raster(self.location,
                                               gdal.Open(mask))
     except (RuntimeError, ValueError):
         tmp_check = float("nan")
     return not math.isnan(tmp_check)
Example #5
0
 def test_bottom_left_point_with_GRS80(self):
     # Same as test_bottom_left_point(), but with a different reference system,
     # GRS80; the result should be the same.
     point = hspatial.coordinates2point(324076, 4205176, srid=2100)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            3.1,
                            places=2)
Example #6
0
 def test_middle_point_with_GRS80(self):
     # Same as test_middle_point(), but with a different reference system, GRS80; the
     # result should be the same.
     point = hspatial.coordinates2point(325077, 4205177, srid=2100)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            2.2,
                            places=2)
Example #7
0
 def default_field_capacity(self):
     if not self.in_covered_area:
         return None
     else:
         return extract_point_from_raster(
             self.location,
             gdal.Open(os.path.join(settings.AIRA_DATA_SOIL, "fc.tif")),
         )
Example #8
0
def get_parameters(afield_obj):
    """
        For url:advice, populate  afield_obj
        information table
    """
    # For url 'advice' templates use
    fc = afield_obj.get_field_capacity
    wp = afield_obj.get_wilting_point
    rd = (float(afield_obj.get_root_depth_min) +
          float(afield_obj.get_root_depth_max)) / 2
    # FAO table 22 , page 163
    p = float(afield_obj.get_mad)
    peff = 0.8  # Effective rainfall coeff 0.8 * Precip
    irr_eff = float(afield_obj.get_efficiency)
    theta_s = afield_obj.get_thetaS
    rd_factor = 1000  # Static for mm
    IRT = afield_obj.get_irrigation_optimizer
    custom_parameters = afield_obj.use_custom_parameters
    last_irrigate = None
    if afield_obj.irrigationlog_set.exists():
        last_irrigate = afield_obj.irrigationlog_set.latest()
        if last_irrigate.applied_water is None:
            rd_factor = 1000
            if not custom_parameters:
                fc = extract_point_from_raster(
                    afield_obj.location,
                    gdal.Open(
                        os.path.join(settings.AIRA_COEFFS_RASTERS_DIR,
                                     "fc.tif")),
                )
                wp = extract_point_from_raster(
                    afield_obj.location,
                    gdal.Open(
                        os.path.join(settings.AIRA_COEFFS_RASTERS_DIR,
                                     "pwp.tif")),
                )
            fc_mm = fc * rd * rd_factor
            wp_mm = wp * rd * rd_factor
            taw_mm = fc_mm - wp_mm
            p = float(afield_obj.get_mad)
            raw_mm = p * taw_mm
            last_irrigate.applied_water = (raw_mm * afield_obj.area) / 1000
            last_irrigate.message = _("Irrigation water is estimated using "
                                      "system's default parameters.")
    return locals()
Example #9
0
 def get_field_capacity(self):
     if self.use_custom_parameters and self.custom_field_capacity:
         return self.custom_field_capacity
     else:
         return extract_point_from_raster(
             self.location,
             gdal.Open(
                 os.path.join(settings.AIRA_COEFFS_RASTERS_DIR, "fc.tif")),
         )
Example #10
0
def agripoint_in_raster(obj, mask=None):
    """
        Check if a afield_obj location is
            within 'mask' raster file
    """
    if mask is None:
        mask = os.path.join(settings.AIRA_COEFFS_RASTERS_DIR, "fc.tif")
    try:
        tmp_check = extract_point_from_raster(obj.location, gdal.Open(mask))
    except (RuntimeError, ValueError):
        tmp_check = float("nan")
    return not math.isnan(tmp_check)
Example #11
0
def get_default_db_value(afield_obj):
    """
       doc str is missing
    """
    irr_eff = afield_obj.irrigation_type.efficiency
    mad = afield_obj.crop_type.max_allow_depletion
    rd_max = afield_obj.crop_type.root_depth_max
    rd_min = afield_obj.crop_type.root_depth_min
    IRT = afield_obj.irrigation_optimizer
    fc = extract_point_from_raster(
        afield_obj.location,
        gdal.Open(os.path.join(settings.AIRA_COEFFS_RASTERS_DIR, "fc.tif")),
    )
    wp = extract_point_from_raster(
        afield_obj.location,
        gdal.Open(os.path.join(settings.AIRA_COEFFS_RASTERS_DIR, "pwp.tif")),
    )
    thetaS = extract_point_from_raster(
        afield_obj.location,
        gdal.Open(os.path.join(settings.AIRA_COEFFS_RASTERS_DIR,
                               "theta_s.tif")),
    )
    return locals()
Example #12
0
 def test_does_not_modify_srid_of_point(self):
     point = hspatial.coordinates2point(325077, 4205177, srid=2100)
     original_spatial_reference = point.GetSpatialReference().ExportToWkt()
     hspatial.extract_point_from_raster(point, self.fp)
     self.assertEqual(point.GetSpatialReference().ExportToWkt(),
                      original_spatial_reference)
Example #13
0
def extractSWBTimeseries(agrifield):
    """
        Given a Agrifield extract Timeseries from raster files and
        convert to pd.DataFrame.
    """
    EFFECTIVE_PRECIP_FACTOR = 0.8

    current_year = dt.date.today().year
    start_of_season = dt.datetime(current_year, 3, 15, 0, 0)

    _r = _point_timeseries(agrifield, "HISTORICAL", "rain", start_of_season)
    _e = _point_timeseries(agrifield, "HISTORICAL", "evaporation",
                           start_of_season)
    _rf = _point_timeseries(agrifield, "FORECAST", "rain", start_of_season)
    _ef = _point_timeseries(agrifield, "FORECAST", "evaporation",
                            start_of_season)

    start, end = common_period_dates(_r, _e)
    fstart, fend = common_period_dates(_rf, _ef)

    dateIndexH = pd.date_range(start=start.date(), end=end.date(), freq="D")
    dateIndex = pd.date_range(start=start.date(), end=fend.date(), freq="D")

    _rfdatapart = _rf.data.loc[fstart:fend]
    _efdatapart = _ef.data.loc[fstart:fend]
    data = {
        "effective_precipitation":
        ((_r.data.loc[start:end, "value"] * EFFECTIVE_PRECIP_FACTOR).tolist() +
         (_rfdatapart[~_rfdatapart.index.isin(dateIndexH)]["value"] *
          EFFECTIVE_PRECIP_FACTOR).tolist()),
        "actual_net_irrigation":
        0,  # Zero is the default
        "ref_evapotranspiration":
        ((_e.data.loc[start:end, "value"] * EFFECTIVE_PRECIP_FACTOR).tolist() +
         (_efdatapart[~_efdatapart.index.isin(dateIndexH)]["value"] *
          EFFECTIVE_PRECIP_FACTOR).tolist()),
    }
    df = pd.DataFrame(data, index=dateIndex)
    calculate_crop_evapotranspiration(
        timeseries=df,
        planting_date=agrifield.crop_type.most_recent_planting_date,
        kc_unplanted=agrifield.crop_type.kc_init,
        kc_ini=agrifield.crop_type.kc_init,
        kc_mid=agrifield.crop_type.kc_mid,
        kc_end=agrifield.crop_type.kc_end,
        init=agrifield.crop_type.days_kc_init,
        dev=agrifield.crop_type.days_kc_dev,
        mid=agrifield.crop_type.days_kc_mid,
        late=agrifield.crop_type.days_kc_late,
    )

    # Update dates with irrigations events
    logs = agrifield.irrigationlog_set.filter(time__range=(start, end))
    for log in logs:
        try:
            date = log.time.date()
            if log.applied_water is None:
                # When an irrigation event has been logged but we don't know how
                # much, we assume we reached field capacity. At that point we use
                # "True" instead of a number, which signals to
                # swb.calculate_soil_water() to assume we irrigated with the recommended
                # amount.
                df.at[date, "actual_net_irrigation"] = True
            else:
                applied_water = float(log.applied_water / agrifield.area *
                                      1000)
                df.at[date, "actual_net_irrigation"] = applied_water
        except Exception:
            # Insanity check, date does not exist in our original date
            pass

    return {
        "timeseries":
        df,
        "start":
        start,
        "end":
        end,
        "fstart":
        fstart,
        "fend":
        fend,
        "draintime_A":
        extract_point_from_raster(
            agrifield.location,
            gdal.Open(os.path.join(settings.AIRA_DRAINTIME_DIR, "a_1d.tif")),
        ),
        "draintime_B":
        extract_point_from_raster(
            agrifield.location,
            gdal.Open(os.path.join(settings.AIRA_DRAINTIME_DIR, "b.tif")),
        ),
    }
Example #14
0
 def test_top_left_point(self):
     point = hspatial.coordinates2point(22.005, 37.995)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            1.1,
                            places=2)
Example #15
0
 def draintime(self):
     raster_a = os.path.join(settings.AIRA_DATA_SOIL, "a_1d.tif")
     a = extract_point_from_raster(self.location, gdal.Open(raster_a))
     raster_b = os.path.join(settings.AIRA_DATA_SOIL, "b.tif")
     b = extract_point_from_raster(self.location, gdal.Open(raster_b))
     return round(a * self.root_depth**b)
Example #16
0
 def test_fails_gracefully_when_geos_point_is_really_outside_crs_limits(
         self):
     point = GeoDjangoPoint(125.0, 85.0)
     with self.assertRaises(RuntimeError):
         hspatial.extract_point_from_raster(point, self.fp)
Example #17
0
 def test_fails_gracefully_when_osr_point_is_really_outside_crs_limits(
         self):
     point = hspatial.coordinates2point(125.0, 85.0)
     with self.assertRaises(RuntimeError):
         hspatial.extract_point_from_raster(point, self.fp)
Example #18
0
 def test_point_outside_raster(self):
     point = hspatial.coordinates2point(21.0, 38.0)
     with self.assertRaises(RuntimeError):
         hspatial.extract_point_from_raster(point, self.fp)
Example #19
0
 def test_top_left_point_as_geodjango(self):
     point = GeoDjangoPoint(22.005, 37.995)
     self.assertAlmostEqual(hspatial.extract_point_from_raster(
         point, self.fp),
                            1.1,
                            places=2)
Example #20
0
 def test_top_middle_point(self):
     point = hspatial.coordinates2point(22.015, 37.995)
     self.assertTrue(
         math.isnan(hspatial.extract_point_from_raster(point, self.fp)))