FarmMapsApiClient_KB34_MAST/FarmmapsApiSamples/NitrogenService.cs

263 lines
14 KiB
C#
Raw Normal View History

2020-03-25 16:49:00 +00:00
using System;
using System.Collections.Generic;
2020-03-25 16:49:00 +00:00
using System.Globalization;
using System.IO;
2020-03-25 16:49:00 +00:00
using System.Linq;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
2020-03-25 16:49:00 +00:00
using static FarmmapsApi.Extensions;
using static FarmmapsApiSamples.Constants;
namespace FarmmapsApiSamples
{
public class NitrogenService : ITestFlow
2020-03-25 16:49:00 +00:00
{
private readonly ILogger<NitrogenService> _logger;
private readonly FarmmapsApiService _farmmapsApiService;
private readonly GeneralService _generalService;
2020-03-25 16:49:00 +00:00
public NitrogenService(ILogger<NitrogenService> logger, FarmmapsApiService farmmapsApiService,
GeneralService generalService)
2020-03-25 16:49:00 +00:00
{
_logger = logger;
_farmmapsApiService = farmmapsApiService;
_generalService = generalService;
2020-03-25 16:49:00 +00:00
}
public async Task TestFlow(List<UserRoot> roots)
{
var downloadFolder = "Downloads";
if (!Directory.Exists(downloadFolder))
Directory.CreateDirectory(downloadFolder);
var plantingDate = new DateTime(DateTime.UtcNow.Year, 2, 1);
var measurementDate = plantingDate.AddMonths(5);
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "Uploaded");
if (uploadedRoot == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
var myDriveRoot = roots.SingleOrDefault(r => r.Name == "My drive");
if (myDriveRoot == null)
{
_logger.LogError("Could not find a needed root item");
return;
}
2020-04-08 17:28:30 +00:00
var cropfieldItem = await CreateCropfieldItemAsync(myDriveRoot.Code, "VRA NBS cropfield", 2020,
@"{ ""type"": ""Polygon"", ""coordinates"": [ [ [ 3.40843828875524, 50.638966444680605 ], [ 3.408953272886064, 50.639197789621612 ], [ 3.409242951459603, 50.639469958681836 ], [ 3.409328782148028, 50.639612846807708 ], [ 3.409457528180712, 50.639789755314411 ], [ 3.409639918393741, 50.640014292074966 ], [ 3.409833037442765, 50.640211611372706 ], [ 3.410069071836049, 50.640395321698435 ], [ 3.410380208081761, 50.640572227259661 ], [ 3.410605513638958, 50.640715112034222 ], [ 3.411925160474145, 50.641177783561204 ], [ 3.411935889310142, 50.640728720085136 ], [ 3.412590348309737, 50.63948356709389 ], [ 3.413244807309242, 50.638224772339846 ], [ 3.413400375432099, 50.637901562841307 ], [ 3.413539850300779, 50.637449065809889 ], [ 3.413475477284437, 50.637418445552932 ], [ 3.40999396998362, 50.637449065810451 ], [ 3.409940325803365, 50.638102293212661 ], [ 3.409575545377398, 50.638483338338325 ], [ 3.409060561246574, 50.638707881340494 ], [ 3.40843828875524, 50.638966444680605 ] ] ] }");
var dataPath = Path.Combine("Data", "Nbs", "Scan_1_20190605.zip");
var isariaShapeItem = await _generalService.UploadZipWithShapeAsync(uploadedRoot, dataPath, "Scan_1_20190605");
if (isariaShapeItem == null)
{
_logger.LogError("Could not find isaria shape item");
return;
}
2020-04-08 17:28:30 +00:00
_logger.LogInformation($"Converting shape to geotiff");
var isariaGeotiffItem = await _generalService.ShapeToGeotiff(isariaShapeItem);
if (isariaGeotiffItem == null)
{
_logger.LogError("Something went wrong with isaria shape to geotiff transformation");
return;
}
_logger.LogInformation($"Calculating targetN with targetYield: {60}");
2020-04-08 17:28:30 +00:00
var targetNItem = await CreateTargetNItem(cropfieldItem);
var targetN = await CalculateTargetN(cropfieldItem, targetNItem, plantingDate, measurementDate, "consumption", "irmi", 60);
_logger.LogInformation($"TargetN: {targetN}");
2020-04-06 12:45:28 +00:00
_logger.LogInformation("Calculating uptake map");
var uptakeMapItem =
await CalculateUptakeMap(cropfieldItem, isariaGeotiffItem, plantingDate, measurementDate);
2020-04-06 12:45:28 +00:00
_logger.LogInformation("Downloading uptake map");
await _farmmapsApiService.DownloadItemAsync(uptakeMapItem.Code, Path.Combine(downloadFolder, $"{uptakeMapItem.Name}.zip"));
2020-04-06 12:45:28 +00:00
_logger.LogInformation("Calculating appliance map");
var applianceMapItem =
2020-04-08 17:28:30 +00:00
await CalculateApplicationMap(cropfieldItem, isariaGeotiffItem, plantingDate, measurementDate, "irmi", targetN);
2020-04-06 12:45:28 +00:00
_logger.LogInformation("Downloading appliance map");
await _farmmapsApiService.DownloadItemAsync(applianceMapItem.Code, Path.Combine(downloadFolder, $"{applianceMapItem.Name}.zip"));
}
2020-04-08 17:28:30 +00:00
private async Task<Item> CreateCropfieldItemAsync(string parentItemCode, string name, int year, string fieldGeomJson)
{
2020-04-08 17:28:30 +00:00
var currentYear = new DateTime(year, 1, 1);
var cropfieldItemRequest = new ItemRequest()
{
ParentCode = parentItemCode,
ItemType = CROPFIELD_ITEMTYPE,
2020-04-08 17:28:30 +00:00
Name = name,
DataDate = currentYear,
DataEndDate = currentYear.AddYears(1).AddDays(-1),
Data = JObject.Parse("{}"),
2020-04-08 17:28:30 +00:00
Geometry = JObject.Parse(fieldGeomJson)
};
return await _farmmapsApiService.CreateItemAsync(cropfieldItemRequest);
}
2020-04-08 17:28:30 +00:00
public async Task<Item> CreateTargetNItem(Item cropfieldItem)
{
var itemRequest = new ItemRequest()
{
ParentCode = cropfieldItem.ParentCode,
ItemType = USERINPUT_ITEMTYPE,
Name = "TargetN"
};
return await _farmmapsApiService.CreateItemAsync(itemRequest);
}
2020-03-25 16:49:00 +00:00
/// <summary>
/// Calculates TargetN, makes the assumption the cropfield and user.input(targetn) item have the same parent
/// </summary>
/// <param name="cropfieldItem">The cropfield to base the calculations on</param>
/// <param name="targetYield">The target yield input for the TargetN calculation</param>
/// <param name="plantingDate">The date the crop is planted</param>
/// <param name="measurementDate">The date the measurements are taken</param>
2020-03-25 16:49:00 +00:00
/// <returns>The TargetN</returns>
2020-04-08 17:28:30 +00:00
public async Task<double> CalculateTargetN(Item cropfieldItem, Item targetNItem, DateTime plantingDate,
DateTime measurementDate, string inputType, string purposeType, int targetYield)
2020-03-25 16:49:00 +00:00
{
var nbsTargetNRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsTargetNRequest.attributes["operation"] = "targetn";
nbsTargetNRequest.attributes["inputCode"] = targetNItem.Code;
nbsTargetNRequest.attributes["plantingDate"] = plantingDate.ToString();
nbsTargetNRequest.attributes["measurementDate"] = measurementDate.ToString();
2020-04-08 17:28:30 +00:00
nbsTargetNRequest.attributes["inputType"] = inputType;
nbsTargetNRequest.attributes["purposeType"] = purposeType.ToLower();
2020-03-25 16:49:00 +00:00
nbsTargetNRequest.attributes["targetYield"] = targetYield.ToString();
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsTargetNRequest);
await PollTask(TimeSpan.FromSeconds(3), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTaskStatus.IsFinished)
2020-03-25 16:49:00 +00:00
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if(itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return 0;
}
var item = await _farmmapsApiService.GetItemAsync(targetNItem.Code);
if (item.Data.ContainsKey("TargetN"))
return item.Data.Value<double>("TargetN");
return 0;
}
2020-04-06 12:45:28 +00:00
/// <summary>
/// Calculates the uptake map based on the given inputs
/// </summary>
/// <param name="cropfieldItem">The cropfield to base the calculations on</param>
/// <param name="inputItem"></param>
/// <param name="plantingDate">The date the crop is planted</param>
/// <param name="measurementDate">The date the measurements are taken</param>
/// <returns></returns>
public async Task<Item> CalculateUptakeMap(Item cropfieldItem, Item inputItem, DateTime plantingDate,
2020-04-08 17:28:30 +00:00
DateTime measurementDate, string inputType = "irmi")
2020-04-06 12:45:28 +00:00
{
var nbsUptakeMapRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsUptakeMapRequest.attributes["operation"] = "uptake";
nbsUptakeMapRequest.attributes["inputCode"] = inputItem.Code;
nbsUptakeMapRequest.attributes["plantingDate"] = plantingDate.ToString();
nbsUptakeMapRequest.attributes["measurementDate"] = measurementDate.ToString();
2020-04-08 17:28:30 +00:00
nbsUptakeMapRequest.attributes["inputType"] = inputType.ToLower();
2020-04-06 12:45:28 +00:00
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsUptakeMapRequest);
2020-04-06 12:45:28 +00:00
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTaskStatus.IsFinished)
2020-04-06 12:45:28 +00:00
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if(itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
2020-04-08 17:28:30 +00:00
var itemName = "VRANbs uptake";
var uptakeMapItem = await _generalService.FindChildItemAsync(cropfieldItem.Code,
GEOTIFF_PROCESSED_ITEMTYPE, itemName,
i => i.Updated >= itemTask.Finished.GetValueOrDefault(DateTime.UtcNow) &&
i.Name.ToLower().Contains(itemName.ToLower()));
if (uptakeMapItem == null)
2020-04-06 12:45:28 +00:00
{
_logger.LogError("Could not find the uptake geotiff child item under cropfield");
return null;
}
2020-04-08 17:28:30 +00:00
return uptakeMapItem;
2020-04-06 12:45:28 +00:00
}
2020-03-25 16:49:00 +00:00
/// <summary>
/// Creates the nitrogen appliance map based on given input data
/// </summary>
/// <param name="cropfieldItem">The cropfield to base the calculations on</param>
/// <param name="inputItem">The farmmaps item containing the geotiff data</param>
/// <param name="plantingDate">The date the crop is planted</param>
/// <param name="measurementDate">The date the measurements are taken</param>
2020-04-08 17:28:30 +00:00
/// <param name="inputType">The inputtype to use</param>
/// <param name="targetN">The target nitrogen to use for the calculations</param>
/// <returns></returns>
public async Task<Item> CalculateApplicationMap(Item cropfieldItem, Item inputItem, DateTime plantingDate,
2020-04-08 17:28:30 +00:00
DateTime measurementDate, string inputType = "irmi", double targetN = 60.0)
2020-03-25 16:49:00 +00:00
{
var nbsApplianceMapRequest = new TaskRequest {TaskType = VRANBS_TASK};
nbsApplianceMapRequest.attributes["operation"] = "application";
nbsApplianceMapRequest.attributes["inputCode"] = inputItem.Code;
nbsApplianceMapRequest.attributes["plantingDate"] = plantingDate.ToString();
nbsApplianceMapRequest.attributes["measurementDate"] = measurementDate.ToString();
nbsApplianceMapRequest.attributes["inputCode"] = inputItem.Code;
2020-04-08 17:28:30 +00:00
nbsApplianceMapRequest.attributes["inputType"] = inputType.ToLower();
nbsApplianceMapRequest.attributes["targetN"] = targetN.ToString(CultureInfo.InvariantCulture);
2020-03-25 16:49:00 +00:00
string itemTaskCode = await _farmmapsApiService.QueueTaskAsync(cropfieldItem.Code, nbsApplianceMapRequest);
2020-03-25 16:49:00 +00:00
await PollTask(TimeSpan.FromSeconds(5), async (tokenSource) =>
{
var itemTaskStatus = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if (itemTaskStatus.IsFinished)
2020-03-25 16:49:00 +00:00
tokenSource.Cancel();
});
var itemTask = await _farmmapsApiService.GetTaskStatusAsync(cropfieldItem.Code, itemTaskCode);
if(itemTask.State == ItemTaskState.Error)
{
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null;
}
2020-04-08 17:28:30 +00:00
var itemName = $"VRANbs application";
var applianceMapItem = await _generalService.FindChildItemAsync(cropfieldItem.Code,
GEOTIFF_PROCESSED_ITEMTYPE, itemName,
i => i.Updated >= itemTask.Finished.GetValueOrDefault(DateTime.UtcNow) &&
i.Name.ToLower().Contains(itemName.ToLower()));
2020-04-06 12:45:28 +00:00
if (applianceMapItem == null)
2020-03-25 16:49:00 +00:00
{
_logger.LogError("Could not find the application map geotiff child item under cropfield");
2020-03-25 16:49:00 +00:00
return null;
}
2020-04-06 12:45:28 +00:00
return applianceMapItem;
2020-03-25 16:49:00 +00:00
}
}
}