def get_cumulative_report(farm, field, crop_season, user, start_date, end_date):

    generate_water_register(crop_season,
                            field,
                            user,
                            None,
                            end_date)

                
    # Will add an entry for this field and farm
            
    crf = CumulativeReportFields()
    crf.field = field
    crf.farm = farm
    crf.crop = crop_season.crop
    crf.start_date = crop_season.season_start_date
    crf.end_date = crop_season.season_end_date

    # Get the water registry for the crop season / field
    wr_list = WaterRegister.objects.filter(crop_season = crop_season, 
                                           field = field).order_by('-datetime').filter(Q(datetime__gte = d2dt_min(start_date), \
                                                                                         datetime__lte = d2dt_max(end_date)
                                                                                         )
                                                                                       )
                                                                                         
                
    if len(wr_list) == 0: return None
    wr = wr_list[0]
    if (wr is not None):
        (crf.cumulative_rain, 
         crf.cumulative_irrigation_vol, 
         crf.cumulative_water_use,
         crf.days_of_irrigation) = cumulative_water(wr_list)
         
        # Add link to water register
        crf.water_register_url = reverse('unified_water_season_field_date',
                                          kwargs={'season':crop_season.pk,
                                                  'field':field.pk,
						  'date':end_date }
                                          )

    return crf
예제 #2
0
crop_season = CropSeason.objects.get(name='Corn 2015', description='mine')  # need one with probes.
field = Field.objects.get(name='North')


print 'Performing query'
earliest_date = earliest_register_to_update(date(2015,07,03),
                                            crop_season,
                                            field)

print '############### Earliest to update', earliest_date


print '############### Generating register'

generate_water_register(crop_season,
                        field,
                        User.objects.get(email='*****@*****.**'))


print '############### Testing calculateAWC_RainIrrigation'


probe_readings = get_probe_readings_dict(field, crop_season)
water_history_query = WaterHistory.objects.filter(crop_season=crop_season,
                                                  field=field).all()

(rain, irrigation) = calculateAWC_RainIrrigation(crop_season,
                                                 field,
                                                 date(2015, 06, 30), 
                                                 water_history_query,
                                                 probe_readings)
예제 #3
0
def get_daily_report(farm, field, crop_season, user, report_date):

    generate_water_register(crop_season,
                            field,
                            user,
                            None,
                            report_date)

    # Will add an entry for this field and farm
            
    srf = SummaryReportFields()
    srf.field = field
    srf.farm = farm
    srf.crop = crop_season.crop
    srf.water_register_url = reverse('unified_water_season_field_date',
                                     kwargs={'season': crop_season.pk,
                                             'field':  field.pk,
                                             'date':   report_date}
                                     )

    # Get the water registry for the crop season / field

    wr_list = WaterRegister.objects.filter(crop_season = crop_season, 
                                           field = field).order_by('-datetime').filter(Q(datetime__lte =  d2dt_max(report_date)))

    if len(wr_list) == 0: return None
    wr = wr_list[0]
    if (wr is not None):
        srf.growth_stage    = wr.crop_stage
        srf.message         = wr.message
        (srf.cumulative_rain, srf.cumulative_irrigation_vol) = cumulative_water(wr_list)
        srf.days_to_irrigation = wr.days_to_irrigation

        # Get the last event for the field. It will be either rain, irrigation,
        # manual reading or automated reading.
        
        # First get the latest water event from water history
        # The water history contains a field list (although right now it
        # may be limited to one field.) Still, assume there could be more
        # than one.

        whList = WaterHistory.objects.filter(crop_season = crop_season)
        # Just keep the ones with one of the fields equal to current field.
                    
        latest_water_record = None
        if len(whList) > 0:
            latestWH = whList.filter(field = field) 
            latest_water_record = whList.latest('datetime')

            # Now get the latest measurement record from the probes.
            # First all the probes for a given pair (field, crop season)

            probe_list = Probe.objects.filter(field = field, crop_season = crop_season)
            latest_probe_reading = None
            if (len(probe_list) > 0):
                radio_id = probe_list[0].radio_id
                probe_readings = ProbeReading.objects.filter(radio_id = radio_id)
                # Same radio id can be used across seasons. Filter based on (Start, end) of 
                # crop season
                probe_readings = probe_readings.filter(datetime__gte = crop_season.season_start_date,
                                                       datetime__lte = crop_season.season_end_date)
                if (probe_readings is not None and len(probe_readings) > 0):
                    latest_probe_reading = probe_readings.latest('datetime')
                    
                        

            # Compare both records, keep most recent.
            # Probably easier way in python to do this. Can worry later.
            latest_is_wr = None
            if (latest_water_record is None and latest_probe_reading is None): pass
            elif  (latest_water_record is not None and latest_probe_reading is not None):
                latest_is_wr = (latest_water_record.datetime.date() > latest_probe_reading.datetime.date()) 
            else:
                if (latest_water_record is not None):
                    latest_is_wr = True
                else:
                    latest_is_wr = False
            if (latest_is_wr is not None):
                if (latest_is_wr):
                    srf.last_data_entry_type = "Rain or irrigation"
                    srf.time_last_data_entry = latest_water_record.datetime
                else:
                    srf.last_data_entry_type = "Probe reading"
                    srf.time_last_data_entry = latest_probe_reading.datetime
            
                    # Add link to water register
            
            # Add the water register object to get next irrigation date, or status.
            # Only add if planting season is not over.
            if (crop_season.season_end_date >= report_date):
                srf.water_register_object = wr

    return srf
예제 #4
0
def generate_objects(wh_formset, crop_season, field, user,  report_date):

    """
    Returns the list of object for display in the template.
    Each object is an instance of the class UnifiedReport,
    defined below.

    We assume that the wh_formset is sorted by date, but not necessarily
    by source. In this implementation there are two possible sources for 
    the WaterHistory objects for one date: at most one UGA and any number
    of User.
    """

    if crop_season.season_start_date > report_date:
        return None
    
    if crop_season.season_end_date < report_date:
        report_date = crop_season.season_end_date

    generate_water_register(crop_season, field, user, None, report_date)

    water_register_query = WaterRegister.objects.filter(crop_season = crop_season, field = field)
    water_register_query = water_register_query.order_by('-datetime')
    water_register_query = water_register_query.filter(
                               Q(datetime__lte =  d2dt_min(report_date + timedelta(WATER_REGISTER_DELTA))) 
                               )

    if len(water_register_query) == 0:
        return None

    ### Get all the forms defined by the formset created from the water history objects
    form_index = 0
    current_form = None
    all_forms = wh_formset.forms
    ret = []

    if all_forms is not None and len(all_forms) > 0:
        current_form = all_forms[form_index]
        form_index = form_index + 1

        ## Point to the first form in the current crop season
        while current_form is not None and \
              getDateObject(current_form['datetime'].value()) is not None and \
              getDateObject(current_form['datetime'].value()) < crop_season.season_start_date:
            if form_index == len(all_forms):
                current_form = None
            else:
                print "IF WE SEE THIS THEN THIS LOOP IS NECESSARY"
                current_form = all_forms[form_index]
                form_index = form_index + 1
                

    for day in daterange(crop_season.season_start_date, report_date + timedelta(days=1)):
        try:
            water_register = water_register_query.get(datetime__range = d2dt_range(day))
        except:
            print "Some date in crop season does not have a water register. Return nothing."
            return None

        day_record = UnifiedReport(day, water_register)

        while current_form is not None and getDateObject(current_form['datetime'].value()) == day:
            if current_form['source'].value() == "UGA":
                if day_record.uga_form is not None:
                    message = "There is more than one UGA probe defined for %s on %s " % \
                              (crop_season, day)
                    #raise RuntimeError(message)
                    print message
                day_record.add_uga(current_form)

            elif current_form['source'].value() == "User":
                day_record.all_forms.append(current_form)
            else:
                # raise RuntimeError("Unrecogized source type: " + current_form['source'].value())
                print "Have a WaterHistory of 'Unknown' type: ", current_form
                day_record.all_forms.append(current_form)

            if form_index == len(all_forms):
                current_form = None
            else:
                current_form = all_forms[form_index]
                form_index = form_index + 1

        ret.append(day_record)

    # Add records for days in the future
    
    ### Might want days=WATER_REGISTER_DELTA+1 below, but we don't do it
    ### in generate_water_register

    ### Also this loop could be merged with above. But this is easier to see
    ### what happens
    report_plus_delta = min(report_date + timedelta(days=WATER_REGISTER_DELTA), crop_season.season_end_date)
    
    for day in daterange(report_date + timedelta(days=1), report_plus_delta):
        water_register = water_register_query.filter(datetime__range = d2dt_range(day))
        if len(water_register) == 1:
            day_record = UnifiedReport(day, water_register[0])
            ret.append(day_record)
        else:
            print "Found %d WaterRegister entries on %s for %s " % ( len(water_register),
                                                                     day,
                                                                     crop_season )
    return  ret
예제 #5
0
 def update_water_register(self, crop_season, field, today):
     generate_water_register(crop_season, field, self.request.user, None, today)
예제 #6
0
    ## Update ProbeSync record
    ps.nrecords = nRecords
    ps.save()


## Finalize ProbeSync record
if store_log:
    ps.success = True
    ps.message = "Successful sync for cropseasons active between %s and %s" % (date_start, date_end)
    ps.nfiles = 0
    ps.nrecords = nRecords
    ps.filenames = ""
    ps.muser = user
    ps.mdate = timezone.now()
    ps.save()

print "%d WaterRegister records created/updated in %f seconds." % (nRecords, elapsed.total_seconds())
sys.stderr.write("\n\n")

print
print "Updating water register records..."
print
nChanged = 0
for crop_season in CropSeason.objects.all():
    for field in crop_season.field_list.all():
        nChanged += generate_water_register(crop_season, field, User.objects.get(email="*****@*****.**"))
print
print "%d water register records updated." % nChanged
print
print