def calculate_total_RainIrrigation(crop_season, field, date, water_history_query): """ Calculate total rain/irrigations. Values are added over all records for that day. Two queries are required, since rain/irrigation can now come from the probe readings as well. Calculate min/max temps for the day as well. """ if isinstance(date, datetime): date = date.date() rainfall = Decimal(0.0) irrigation = Decimal(0.0) min_temp = None max_temp = None # Now add the values coming from the water history (soon to be renamed manual reading) wh_list = water_history_query.filter(datetime__range=d2dt_range(date)).all() if wh_list: rainfall = rainfall + sum( map( lambda wh: wh.rain if wh.rain else 0, wh_list ) ) irrigation = irrigation + sum( map( lambda wh: wh.irrigation if wh.irrigation else 0, wh_list) ) min_temp = minNone(min_temp, minNone(*map( lambda wh: wh.min_temp_24_hours, wh_list))) max_temp = max(max_temp, max(map( lambda wh: wh.max_temp_24_hours, wh_list))) ## Really need min_temp? #if DEBUG: print "Min temp, max temp for: ", date, min_temp, max_temp return ( rainfall, irrigation, min_temp, max_temp )
def earliest_register_to_update(report_date, crop_season, field): # Start by getting the dependency modification date stored in the field object dependency_mdate = field.earliest_changed_dependency_date ## if DEBUG: print "Crop Season %s, Field %s, Earliest changed date %s" % (crop_season, field, dependency_mdate) # Get the modification time of the latest water register latest_water_register = WaterRegister.objects.filter(crop_season=crop_season, field=field ).order_by('-datetime').first() if latest_water_register is None: ##if DEBUG: print 'No water register yet' return crop_season.season_start_date #if DEBUG: print 'Date of latest wr: ', latest_water_register.datetime.date() # Get the earliest water history that has been modified after the latest # water register has been modified earliest_wh_update = WaterHistory.objects.filter(crop_season=crop_season, field=field).filter( Q(mdate__gte = latest_water_register.mdate)).order_by('datetime').first() earliest_to_update = latest_water_register.datetime.date() + timedelta(days=1) if earliest_wh_update is None: # if DEBUG: print 'No WH will cause update to water register' pass else: earliest_to_update = earliest_wh_update.datetime.date() # if DEBUG: print "Caclulated dependency dates:" # if DEBUG: print "field.earliest_changed_dependency_date:", dependency_mdate # if DEBUG: print "earliest changed water history:", earliest_to_update # if DEBUG: print "latest_water_register.date + 1:", latest_water_register.datetime.date() + timedelta(1) retval = minNone(dependency_mdate, earliest_to_update, latest_water_register.datetime.date() + timedelta(1)) if DEBUG: print "Returning earliest_date: %s" % retval return retval