farmmapsKPI receives minimum necessary input and writes relevant KPI output

This commit is contained in:
Pepijn van Oort 2023-10-13 16:37:50 +02:00
parent 1cc36422a4
commit 4102ed628e
7 changed files with 285 additions and 117 deletions

View File

@ -17,7 +17,7 @@ namespace FarmmapsApiSamples
public const string CROPCHAR_ITEMTYPE = "vnd.farmmaps.itemtype.edicrop.characteristic"; public const string CROPCHAR_ITEMTYPE = "vnd.farmmaps.itemtype.edicrop.characteristic";
public const string CROPSCHEME_ITEMTYPE = "vnd.farmmaps.itemtype.croppingscheme"; // deze toegevoegd, misschien is het type van de KPI task wel een croppingscheme public const string CROPSCHEME_ITEMTYPE = "vnd.farmmaps.itemtype.croppingscheme"; // deze toegevoegd, misschien is het type van de KPI task wel een croppingscheme
//public const string KPI_ITEM = "vnd.farmmaps.itemtype.kpi.data"; //PO20231004: originally with .data //public const string KPI_ITEM = "vnd.farmmaps.itemtype.kpi.data"; //PO20231004: originally with .data
public const string KPI_ITEM = "vnd.farmmaps.itemtype.kpi.data.container"; //PO20231004: originally without .container public const string KPICONTAINER_ITEM = "vnd.farmmaps.itemtype.kpi.data.container"; //PO20231004: originally without .container
public const string VRANBS_TASK = "vnd.farmmaps.task.vranbs"; public const string VRANBS_TASK = "vnd.farmmaps.task.vranbs";
public const string VRAHERBICIDE_TASK = "vnd.farmmaps.task.vraherbicide"; public const string VRAHERBICIDE_TASK = "vnd.farmmaps.task.vraherbicide";

View File

@ -350,9 +350,9 @@ namespace FarmmapsApi.Services
return bofekItem; return bofekItem;
} }
public async Task<List<Item>> GetKpiItemsForCropField(Item cropfieldItem) // dit is dus nieuw om de KPI task te runnen public async Task<List<Item>> GetKpiItemsForCropField(Item cropfieldItem)
{ {
var kpiRequest = new TaskRequest { TaskType = KPI_TASK }; TaskRequest kpiRequest = new TaskRequest { TaskType = KPI_TASK };
kpiRequest.attributes["processAggregateKpi"] = "false"; kpiRequest.attributes["processAggregateKpi"] = "false";
int year = cropfieldItem.DataDate.Value.Year; int year = cropfieldItem.DataDate.Value.Year;
kpiRequest.attributes["year"] = year.ToString(); kpiRequest.attributes["year"] = year.ToString();
@ -372,15 +372,24 @@ namespace FarmmapsApi.Services
_logger.LogError($"Something went wrong with task execution: {itemTask.Message}"); _logger.LogError($"Something went wrong with task execution: {itemTask.Message}");
return null; return null;
} }
await Task.Delay(60000); //wacht hier een minuut tot de KPIs berekend zijn await Task.Delay(6000); // wait 6000 secs for task to be completed
//PO20230627 Je zou hier ook om de 10 sec eens kunnen kijken of we al zo ver zijn? Iets in trant van while KPI_ITEM is null? //After the task is completed we have 1 kpiContainerItem with a code and with no data
//hier nog definieren waar in de hierarchie een KPI item is? //Because the data are in the children of this kpiContainerItem. The container will have a list of children each with an "id" aand data,
var allChildren = await _farmmapsApiService.GetItemChildrenAsync(cropfieldItem.Code); //The ids' are "a1", "b1", "b2", "c1","d1","d3","d5"
var kpiItems = await _farmmapsApiService.GetItemChildrenAsync(cropfieldItem.Code, KPI_ITEM); //with following meanings:
//| A1 | Opbrengst | Yield |
//| B1 | Stikstofoverschot | Nitrogen surplus |
//| B2 | Fosfaatoverschot | Phosphate surplus |
//| C1 | Effectieve Organischestof aanvoer| Effective Organic Matter supply |
//| D1 | Gebruik bestrijdingsmiddelen | Use of pesticides|
//| D3 | Gewasdiversiteit(randdichtheid) | Crop diversity(edge density) |
//| D5 | Percentage rustgewassen | Percentage of rest crops |
List <Item> kpiContainerItem = await _farmmapsApiService.GetItemChildrenAsync(cropfieldItem.Code, KPICONTAINER_ITEM);
string kpiContainerItemCode = kpiContainerItem[0].Code;
List<Item> kpiItems = await _farmmapsApiService.GetItemChildrenAsync(kpiContainerItemCode);
return kpiItems; return kpiItems;
} }
public async Task<Item> RunAhnTask(Item cropfieldItem) { public async Task<Item> RunAhnTask(Item cropfieldItem) {

View File

@ -46,21 +46,45 @@ namespace FarmmapsKPI
await _farmmapsApiService.GetCurrentUserCodeAsync(); await _farmmapsApiService.GetCurrentUserCodeAsync();
var roots = await _farmmapsApiService.GetCurrentUserRootsAsync(); var roots = await _farmmapsApiService.GetCurrentUserRootsAsync();
//Where to write the output
string downloadFolder = fieldsInputs[0].DownloadFolder;
if (string.IsNullOrEmpty(downloadFolder))
{
downloadFolder = "Downloads";
}
if (!Directory.Exists(downloadFolder))
Directory.CreateDirectory(downloadFolder);
//Write the same info to a single csv file. Note this means existing file will be overwritten!
StreamWriter sw; string KPIItemPathCsv = Path.Combine(downloadFolder, "KPIItems.csv");
List<string> headerList = new List<string> { "parentName", "area_ha", "cropTypeCode", "cropTypeName", "KPIid", "KPIvariable", "KPIvalue", "KPIunit", "KPItargetvalue", "KPIthresholdValue" };
//Create a new csv file. Means if existing then overwritten !!!
sw = new StreamWriter(KPIItemPathCsv);
sw.WriteLine(string.Join(",", headerList));
//Now loop through the list of cropfields in KPIinput.json and get the KPI's for each cropfield
foreach (var input in fieldsInputs) foreach (var input in fieldsInputs)
{ {
try try
{ {
await Process(roots, input); await Process(roots, input, sw);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex.Message); _logger.LogError(ex.Message);
} }
} }
//Close the csv file, write message to screen
sw.Close();
_logger.LogInformation($"Done! Written all KPI for all fields in 'KPIinput.json' to output file '{KPIItemPathCsv}'");
} }
private async Task Process(List<UserRoot> roots, KPIInput input) private async Task Process(List<UserRoot> roots, KPIInput input, StreamWriter sw)
{ {
KPIOutput kpio;
KPIOutput kpioPrevious = null;
string downloadFolder = input.DownloadFolder; string downloadFolder = input.DownloadFolder;
if (string.IsNullOrEmpty(downloadFolder)) { if (string.IsNullOrEmpty(downloadFolder)) {
downloadFolder = "Downloads"; downloadFolder = "Downloads";
@ -69,20 +93,13 @@ namespace FarmmapsKPI
Directory.CreateDirectory(downloadFolder); Directory.CreateDirectory(downloadFolder);
// !!specify if you are using an already created cropfield: // !!specify if you are using an already created cropfield:
bool useCreatedCropfield = input.UseCreatedCropfield; bool useExistingCropfieldWithChildren = input.UseExistingCropfieldWithChildren;
bool useCreatedCropRecording = input.UseCreatedCropRecording; int cropYear = input.CropYear;
bool useCreatedOperations = input.UseCreatedOperation; string fieldName = input.fieldName;
bool useCreatedCropfieldCharacteristic = input.UseCreatedCropfieldCharacteristic; string fieldGeom = input.GeometryJson.ToString(Formatting.None);
var cropYear = input.CropYear;
var fieldName = input.fieldName;
//bool storeSatelliteStatistics = input.StoreSatelliteStatisticsSingleImage;
//bool storeSatelliteStatisticsCropYear = input.StoreSatelliteStatisticsCropYear;
//List<string> SatelliteBands = new List<string>(1) { input.SatelliteBand };
//string headerLineStats = $"FieldName,satelliteDate,satelliteBand,max,min,mean,mode,median,stddev,minPlus,curtosis,maxMinus,skewness,variance,populationCount,variationCoefficient,confidenceIntervalLow, confidenceIntervalHigh,confidenceIntervalErrorMargin" + Environment.NewLine;
//Settings
string settingsfile = $"Settings_{fieldName}.json"; string settingsfile = $"Settings_{fieldName}.json";
LoadSettings(settingsfile); LoadSettings(settingsfile);
var uploadedRoot = roots.SingleOrDefault(r => r.Name == "USER_IN"); var uploadedRoot = roots.SingleOrDefault(r => r.Name == "USER_IN");
@ -101,14 +118,14 @@ namespace FarmmapsKPI
// Use already created cropfield or create new one, added a Data input, with field specific data for the KPI calculation // Use already created cropfield or create new one, added a Data input, with field specific data for the KPI calculation
Item cropfieldItem; Item cropfieldItem;
//1 useCreatedCropfield = false -> create new //1 useExistingCropfieldWithChildren = false -> create new
//2 useCreatedCropfield = true && CropfieldItemCode = "" or absent -> read from settings json //2 useExistingCropfieldWithChildren = true && input.CropfieldItemCode = "" or absent -> read from settings json
//3 useCreatedCropfield = true && CropfieldItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one //3 useExistingCropfieldWithChildren = true && input.CropfieldItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if (useCreatedCropfield == false || string.IsNullOrEmpty(_settings.CropfieldItemCode)) if (useExistingCropfieldWithChildren == false)
{ {
_logger.LogInformation("Creating cropfield, writting to settings file"); _logger.LogInformation("Creating cropfield, writting to settings file");
cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code, cropfieldItem = await _generalService.CreateCropfieldItemAsync(myDriveRoot.Code,
$"{input.OutputFileName}", cropYear, input.GeometryJson.ToString(Formatting.None), input.DataCropfield.ToString(Formatting.None)); $"{fieldName}", cropYear, input.GeometryJson.ToString(Formatting.None), input.DataCropfield.ToString(Formatting.None));
_settings.CropfieldItemCode = cropfieldItem.Code; _settings.CropfieldItemCode = cropfieldItem.Code;
SaveSettings(settingsfile); SaveSettings(settingsfile);
} }
@ -121,15 +138,16 @@ namespace FarmmapsKPI
{ {
_logger.LogInformation("reading CropfieldItemCode from KPIinput.json"); _logger.LogInformation("reading CropfieldItemCode from KPIinput.json");
cropfieldItem = await _farmmapsApiService.GetItemAsync(input.CropfieldItemCode); cropfieldItem = await _farmmapsApiService.GetItemAsync(input.CropfieldItemCode);
SaveSettings(settingsfile);
} }
// Use already created croprecording or create new one, added a Data input, with field specific data for the KPI calculation // Use already created croprecording or create new one, added a Data input, with field specific data for the KPI calculation
Item crprecItem; Item crprecItem;
//1 useCreatedCropRecording = false -> create new //1 useExistingCropfieldWithChildren = false -> create new
//2 useCreatedCropRecording = true && CropRecordingItemCode = "" or absent -> read from settings json //2 useExistingCropfieldWithChildren = true && input.CropRecordingItemCode = "" or absent -> read from settings json
//3 useCreatedCropRecording = true && CropRecordingItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one //3 useExistingCropfieldWithChildren = true && input.CropRecordingItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if (useCreatedCropRecording == false || string.IsNullOrEmpty(_settings.CropRecordingItemCode)) if (useExistingCropfieldWithChildren == false)
{ {
_logger.LogInformation("RunCropRecordingTask ..."); _logger.LogInformation("RunCropRecordingTask ...");
crprecItem = await _generalService.RunCropRecordingTask(cropfieldItem); crprecItem = await _generalService.RunCropRecordingTask(cropfieldItem);
@ -145,29 +163,55 @@ namespace FarmmapsKPI
{ {
_logger.LogInformation("reading CropRecordingItemCode from KPIinput.json"); _logger.LogInformation("reading CropRecordingItemCode from KPIinput.json");
crprecItem = await _farmmapsApiService.GetItemAsync(input.CropRecordingItemCode); crprecItem = await _farmmapsApiService.GetItemAsync(input.CropRecordingItemCode);
SaveSettings(settingsfile);
} }
// Use already created operation or create new one, added a Data input, with field specific data for the KPI calculation // Use already created operations or create new one,s added a Data input, with field specific data for the KPI calculation
List<Item> crpOperationItems = new List<Item> { };
List<string> crpOperationItemCodes = new List<string> { };
Item crpOperationItem; Item crpOperationItem;
//1 useCreatedOperation = false -> create new string dataOperation;
//2 useCreatedOperation = true && OperationItemCode = "" or absent -> read from settings json string codeOperation;
//3 useCreatedOperation = true && OperationItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one //1 useExistingCropfieldWithChildren = false -> create new
if (useCreatedOperations == false || string.IsNullOrEmpty(_settings.OperationItemCode)) //2 useExistingCropfieldWithChildren = true && input.OperationItemCode = "" or absent -> read from settings json
//3 useExistingCropfieldWithChildren = true && input.OperationItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if (useExistingCropfieldWithChildren == false)
{ {
_logger.LogInformation("CreateOperationItemAsync ..."); for (int i = 0; i < input.DataOperations.Length; i++)
crpOperationItem = await _generalService.CreateOperationItemAsync(crprecItem.Code, cropYear, input.GeometryJson.ToString(Formatting.None), input.DataOperation.ToString(Formatting.None)); {
_settings.OperationItemCode = crpOperationItem.Code; dataOperation = input.DataOperations[i].ToString(Formatting.None);
dynamic data = JObject.Parse(dataOperation);
_logger.LogInformation($"CreateOperationItemAsync ... for operation {i}: '{data.name}', {data.n} kg N/ha, on date '{data.from}'");
crpOperationItem = await _generalService.CreateOperationItemAsync(crprecItem.Code, cropYear, fieldGeom, dataOperation);
crpOperationItems.Add(crpOperationItem);
crpOperationItemCodes.Add(crpOperationItem.Code);
}
_settings.OperationItemCodes = crpOperationItemCodes.ToArray();
SaveSettings(settingsfile); SaveSettings(settingsfile);
} }
else if (string.IsNullOrEmpty(input.CropfieldItemCode)) else if (string.IsNullOrEmpty(input.CropfieldItemCode))
{ {
_logger.LogInformation("reading OperationItemCode from settings file"); _logger.LogInformation("reading OperationItemCode from settings file");
crpOperationItem = await _farmmapsApiService.GetItemAsync(_settings.OperationItemCode); for (int i = 0; i < _settings.OperationItemCodes.Length; i++)
{
codeOperation = _settings.OperationItemCodes[i];
crpOperationItem = await _farmmapsApiService.GetItemAsync(codeOperation);
crpOperationItems.Add(crpOperationItem);
crpOperationItemCodes.Add(crpOperationItem.Code);
}
} }
else else
{ {
_logger.LogInformation("reading OperationItemCode from KPIinput.json"); _logger.LogInformation("reading OperationItemCodes from KPIinput.json");
crpOperationItem = await _farmmapsApiService.GetItemAsync(input.OperationItemCode); for (int i = 0; i < input.OperationItemCodes.Length; i++)
{
codeOperation = input.OperationItemCodes[i];
crpOperationItem = await _farmmapsApiService.GetItemAsync(codeOperation);
crpOperationItems.Add(crpOperationItem);
crpOperationItemCodes.Add(crpOperationItem.Code);
}
_settings.OperationItemCodes = crpOperationItemCodes.ToArray();
SaveSettings(settingsfile);
} }
// The cropfieldCharacteristicItem is used to enter crop yields // The cropfieldCharacteristicItem is used to enter crop yields
@ -175,17 +219,17 @@ namespace FarmmapsKPI
// Nutrient balance. // Nutrient balance.
// Use already created cropfieldCharacteristicItem or create new one, added a Data input, with field specific data for the KPI calculation // Use already created cropfieldCharacteristicItem or create new one, added a Data input, with field specific data for the KPI calculation
Item cropfieldCharacteristicItem; Item cropfieldCharacteristicItem;
//1 useCreatedCropfieldCharacteristic = false -> create new //1 useExistingCropfieldWithChildren = false -> create new
//2 useCreatedCropfieldCharacteristic = true && CropfieldCharacteristicItemCode = "" or absent -> read from settings json //2 useExistingCropfieldWithChildren = true && input.CropfieldCharacteristicItemCode = "" or absent -> read from settings json
//3 useCreatedCropfieldCharacteristic = true && CropfieldCharacteristicItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one //3 useExistingCropfieldWithChildren = true && input.CropfieldCharacteristicItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> use this one
if (useCreatedCropfieldCharacteristic == false) if (useExistingCropfieldWithChildren == false)
{ {
_logger.LogInformation("CreateCropfieldCharacteristicItemAsync ..."); _logger.LogInformation("CreateCropfieldCharacteristicItemAsync ...");
cropfieldCharacteristicItem = await _generalService.CreateCropfieldCharacteristicItemAsync(cropfieldItem.Code, cropYear, input.GeometryJson.ToString(Formatting.None), input.DataCropfieldCharacteristic.ToString(Formatting.None)); cropfieldCharacteristicItem = await _generalService.CreateCropfieldCharacteristicItemAsync(cropfieldItem.Code, cropYear, fieldGeom, input.DataCropfieldCharacteristic.ToString(Formatting.None));
_settings.CropfieldCharacteristicItemCode = cropfieldCharacteristicItem.Code; _settings.CropfieldCharacteristicItemCode = cropfieldCharacteristicItem.Code;
SaveSettings(settingsfile); SaveSettings(settingsfile);
} }
else if (string.IsNullOrEmpty(input.CropfieldCharacteristicItemCode)) else if (string.IsNullOrEmpty(input.CropfieldItemCode))
{ {
_logger.LogInformation("reading OperationItemCode from settings file"); _logger.LogInformation("reading OperationItemCode from settings file");
cropfieldCharacteristicItem = await _farmmapsApiService.GetItemAsync(_settings.CropfieldCharacteristicItemCode); cropfieldCharacteristicItem = await _farmmapsApiService.GetItemAsync(_settings.CropfieldCharacteristicItemCode);
@ -194,38 +238,77 @@ namespace FarmmapsKPI
{ {
_logger.LogInformation("reading CropfieldCharacteristicItemCode from KPIinput.json"); _logger.LogInformation("reading CropfieldCharacteristicItemCode from KPIinput.json");
cropfieldCharacteristicItem = await _farmmapsApiService.GetItemAsync(input.CropfieldCharacteristicItemCode); cropfieldCharacteristicItem = await _farmmapsApiService.GetItemAsync(input.CropfieldCharacteristicItemCode);
SaveSettings(settingsfile);
} }
// Inspect the children. If all is well, cropfield will have one crprec and one edicrop.characteristic // Inspect the children and grandchildren. If all is well, cropfield will have:
// And the crprec will have 0-many operations as children // one crprec, with 0-many operations as children. And the Data of an operation will have specification of how much fertilizer was applied
// And the Data of an operation will have specification of how much fertilizer was applied // one edicrop.characteristic (with yield in the data)
// And crprec can have multiple operations
// Note existing cropfields and croprecordings keep existing properties you added in previous runs
// (unless you deleted them)
// So ech time you run with "UseCreatedCropfield": true & "UseCreatedCropRecording": false -> a new recording will be added to the existing cropfield
// So ech time you run with "UseCreatedCropfield": true & "useCreatedCropfieldCharacteristic": false -> a new CropfieldCharacteristic will be added to the existing cropfield
// So ech time you run with "UseCreatedCropRecording": true & "UseCreatedOperation": false -> a new operation will be added to the existing crop recording
var cropfieldChildren = await _farmmapsApiService.GetItemChildrenAsync(cropfieldItem.Code); var cropfieldChildren = await _farmmapsApiService.GetItemChildrenAsync(cropfieldItem.Code);
var crprecChildren = await _farmmapsApiService.GetItemChildrenAsync(crprecItem.Code); var crprecChildren = await _farmmapsApiService.GetItemChildrenAsync(crprecItem.Code);
//Now get the KPIs for this cropfield, mounted with operations & cropyield //Now get the KPIs for this cropfield, mounted with operations & cropyield
// Get KPI data for saving it in a file, here the generalsedrvice is called to get the KPI data // Get KPI data for saving it in a file, here the generalsedrvice is called to get the KPI data
_logger.LogInformation($"GetKpiItemsForCropField('{cropfieldItem.Code}')"); _logger.LogInformation($"GetKpiItemsForCropField('{cropfieldItem.Code}')");
var KPIItem = await _generalService.GetKpiItemsForCropField(cropfieldItem); List<Item> KPIItems = await _generalService.GetKpiItemsForCropField(cropfieldItem);
_logger.LogInformation($"Found {KPIItems.Count} KPI items");
//Download KPI's into a json output file for this specific cropfield (with unique cropfieldItem.Code) //Download KPI's into a json output file for this specific cropfield (with unique cropfieldItem.Code)
var KPIItemPath = Path.Combine(downloadFolder, $"KPIItems_{cropfieldItem.Code}.json"); string KPIItemPathJson = Path.Combine(downloadFolder, $"KPIItems_{cropfieldItem.Code}.json");
_logger.LogInformation($"Found {KPIItem.Count} KPI items");
var count = 0; var count = 0;
await Task.Delay(50); foreach (Item item in KPIItems)
foreach (var item in KPIItem)
{ {
Console.WriteLine($"KPI item #{count}: {item.Name}"); //Console.WriteLine($"KPI item #{count}: {item.Name}");
File.AppendAllText(KPIItemPath, item.Data + Environment.NewLine); File.AppendAllText(KPIItemPathJson, item.Data + Environment.NewLine);
count++; count++;
} }
_logger.LogInformation($"Downloaded file {KPIItemPath}"); _logger.LogInformation($"Downloaded file {KPIItemPathJson}");
//Write to the csv file that collects all KPI's for all the crop fields
List<string> dataList;
foreach (Item item in KPIItems)
{
dataList = new List<string> { };
kpio = JsonConvert.DeserializeObject<KPIOutput>(item.Data.ToString());
//Seems sometimes duplicate KPI items are returned. So check that here and only write if this kpio is different from previous
if (kpio != kpioPrevious)
{
dataList.Add(kpio.parentName);
dataList.Add(kpio.data.area);
dataList.Add(kpio.data.cropTypeCode);
dataList.Add(kpio.data.cropTypeName);
dataList.Add(kpio.id);
dataList.Add(kpio.quantity);
dataList.Add(kpio.value);
dataList.Add(kpio.unit);
dataList.Add(kpio.targetValue);
dataList.Add(kpio.thresholdValue);
sw.WriteLine(string.Join(",", dataList));
}
kpioPrevious = kpio;
}
//Clean up. Only newly created fields
//Look up instruction in Swagger / api / v1 / items /{ code}
if (useExistingCropfieldWithChildren == false && input.DeleteNewlyCreatedAfterCalc == true)
{
// Tested and found that if I delete the parent (cropfieldItem) then
// automatically deletes children (crprecItem, cropfieldCharacteristicItem, KPIcontainer)
// and automatically deletes grand children (crprecItem: operations, KPIcontainer: KPI items)
await _farmmapsApiService.DeleteItemAsync(cropfieldItem.Code);
//Do we need to wait here for the task to be completed? Or does it continue in the background?
//await Task.Delay(60000); // wait 60 secs for task to be completed
//Before the GetItem you will see cropfieldItem, crprecItem etc exist (with data).
//After the GetItem these cropfieldItem, crprecItem etc are null which means they have been succesfully deleted.
//// Check if below works, i.e. is item really deleted?
//cropfieldItem = await _farmmapsApiService.GetItemAsync(cropfieldItem.Code);
//// Check if croprecording has also been deleted. If not also delete it
//crprecItem = await _farmmapsApiService.GetItemAsync(crprecItem.Code);
//// Check if 1 operation has also been deleted. If not also delete it
//crpOperationItem = await _farmmapsApiService.GetItemAsync(crpOperationItemCodes[0]);
//// Check if 1 cropfieldCharacteristicItem has also been deleted. If not also delete it
//cropfieldCharacteristicItem = await _farmmapsApiService.GetItemAsync(cropfieldCharacteristicItem.Code);
}
} }
// Functions to save previously created cropfields // Functions to save previously created cropfields

View File

@ -1,53 +1,39 @@
[ [
{ {
"UseCreatedCropfield": false, "useExistingCropfieldWithChildren": false,
"CropfieldItemCode": "", "deleteNewlyCreatedAfterCalc": true,
//Note when you run the FarmmapsKPI project, somewhere to your C:\git\FarmMapsApiClient_KB34_MAST\FarmmapsKPI\bin\Debug\netcoreapp3.1\ directory, files named like this are written:
//'Settings_aardappelveld_test_Potato_ZeroFertilizer.json', where 'aardappelveld_test_Potato_ZeroFertilizer.json' is your fieldName (see below)
//1 useExistingCropfieldWithChildren = false -> create new
//2 useExistingCropfieldWithChildren = true && CropfieldItemCode = "" or absent -> read fieldName (see below) -> read all codes from settings json file
//3 useExistingCropfieldWithChildren = true && CropfieldItemCode like "deb48a74c5b54299bb852f17288010e9" in KPIinput -> if you have in your account already an existing cropfield then use that
"CropfieldItemCode": "", // could contain for example this: "abae97f89f3c4ac08953b1b8bea9f076" if this is an exisiting CropfieldItemCode in your account.
//And then if useExistingCropfieldWithChildren = true, this would be used.
"dataCropfield": { "dataCropfield": {
//"area": 4.22, //"area": 4.22, //not needed for KPI calculation, but shown here to know this is a possible property
"final": true, "final": true, //always true
//"soilCode": "5", //"soilCode": "5", //not needed for KPI calculation, but shown here to know this is a possible property
"soilName": "Loam", //"soilName": "Loam", //not needed for KPI calculation, but shown here to know this is a possible property
"cropTypeCode": "1010101", // make a table/list with possible inputs. "cropTypeCode": "1010101",
"cropTypeName": "Potato", "cropTypeName": "Potato",
//"rootDepthMax": 45, //"rootDepthMax": 45, //not needed for KPI calculation, but shown here to know this is a possible property
//"emergenceDate": "2022-05-16T00:00:00", //"emergenceDate": "2022-05-16T00:00:00", //not needed for KPI calculation, but shown here to know this is a possible property
"productionPurposeCode": "003" "productionPurposeCode": "003"
//"productionPurposeName": "consumption" //"productionPurposeName": "consumption" //not needed for KPI calculation, but shown here to know this is a possible property
}, },
"UseCreatedCropRecording": false, "CropRecordingItemCode": "", // could contain for example this: "314aa1b6480b493ba28a5f55039a01d4" if this is the CropRecordingItemCode of the provided CropfieldItemCode. And then if useExistingCropfieldWithChildren = true, this would be used
"CropRecordingItemCode": "", "OperationItemCodes": [], // could contain for example this: ["4d1a6f28ea3f414180663baa4b08c60f"] or ["4d1a6f28ea3f414180663baa4b08c60f","21e08386f0454ad79acfebf78649d59b"] if these are the operations of the provided CropRecordingItemCode. And then if useExistingCropfieldWithChildren = true, these would be used
"dataCropRecording": {}, //not yet used "dataOperations": [], //leaving the operations empty means no fertilizer is applied
"UseCreatedOperation": false,
"OperationItemCode": "",
"dataOperation": {
"n": "92",
"to": "2022-05-23T12:34:00",
"area": "0.08", //?!
"from": "2022-05-23T11:34:00",
"name": "Kunstmest strooien",
"unit": "kg/ha",
"method": "70400",
"status": "3",
"product": "7360",
"quantity": "200",
"unitCode": "KGMHAR", //?!
"contractor": false,
"designator": "Kunstmest strooien",
"operationCode": "7"
},
"UseCreatedCropfieldCharacteristic": false,
"CropfieldCharacteristicItemCode": "", "CropfieldCharacteristicItemCode": "",
"DataCropfieldCharacteristic": { "DataCropfieldCharacteristic": {
"code": "860619", //PO20231004: so what does this code mean? Can we see the code list somewhere? "code": "860619", //PO20231004: so what does this code mean? Can we see the code list somewhere?
"label": "cropyield", "label": "cropyield",
"value": "48.01" "value": "48.01"
}, },
//"DownloadFolder": "Downloads", //"C:\\workdir\\groenmonitor\\", // "Downloads", -> if you just put "Downloads" the program will download to somewhere in ..\FarmMapsApiClient_WURtest\FarmmapsDataDownload\bin\Debug\netcoreapp3.1\Downloads\ //"DownloadFolder": "Downloads", //"C:\\hugoschrererdir\\kpidir\\", // "Downloads", -> if you just put "Downloads" the program will download to somewhere in ..\FarmMapsApiClient_KB34_MAST\FarmmapsKPI\bin\Debug\netcoreapp3.1\Downloads\
"CropYear": 2022, "CropYear": 2022,
"dataDate": "2022-04-15T00:00:00Z", "fieldName": "aardappelveld_test_Potato_ZeroFertilizer",
"dataEndDate": "2022-09-15T00:00:00Z", //geometryJson = polygon of location of the cropfield, coordinates in LON,LAT (LON: decimal degrees East, LAT: decimal degrees North)
"fieldName": "aardappelveld_test",
//"ProcessAggegrateKpi": "false", // toegevoegd, want alleen veld level KPIs voor nu.
"geometryJson": { "geometryJson": {
"type": "Polygon", "type": "Polygon",
"coordinates": [ "coordinates": [
@ -74,7 +60,97 @@
] ]
] ]
] ]
},
"outputFileName": "TestData"
} }
},
{
"useExistingCropfieldWithChildren": false,
"CropfieldItemCode": "",
"dataCropfield": {
//"area": 4.22, //not needed for KPI calculation, but shown here to know this is a possible property
"final": true, //always true
//"soilCode": "5", //not needed for KPI calculation, but shown here to know this is a possible property
//"soilName": "Loam", //not needed for KPI calculation, but shown here to know this is a possible property
"cropTypeCode": "1010101",
"cropTypeName": "Potato",
//"rootDepthMax": 45, //not needed for KPI calculation, but shown here to know this is a possible property
//"emergenceDate": "2022-05-16T00:00:00", //not needed for KPI calculation, but shown here to know this is a possible property
"productionPurposeCode": "003"
//"productionPurposeName": "consumption" //not needed for KPI calculation, but shown here to know this is a possible property
},
"CropRecordingItemCode": "",
"OperationItemCodes": [],
"dataOperations": [
{
"area": "0.08", //?!
"contractor": false,
"designator": "Kunstmest strooien",
"from": "2022-05-23T11:34:00",
"method": "70400",
"n": "92",
"name": "Kunstmest strooien",
"operationCode": "7",
"product": "7360",
"quantity": "400",
"status": "3",
"to": "2022-05-23T12:34:00",
"unit": "kg/ha",
"unitCode": "KGMHAR"
},
{
"k": "201.6",
"n": "144",
"p": "60.8",
"to": "2022-04-19T09:19:00",
"area": "0.08", //?!,
"from": "2022-04-19T08:19:00",
"name": "Injecteren",
"unit": "kg/ha",
"method": "70700",
"status": "3",
"product": "2329",
"quantity": "32000",
"unitCode": "KGMHAR",
"contractor": false,
"designator": "Injecteren",
"operationCode": "7"
}
],
"CropfieldCharacteristicItemCode": "",
"DataCropfieldCharacteristic": {
"code": "860619", //PO20231004: so what does this code mean? Can we see the code list somewhere?
"label": "cropyield",
"value": "48.01"
},
//"DownloadFolder": "Downloads", //"C:\\hugoschrererdir\\kpidir\\", // "Downloads", -> if you just put "Downloads" the program will download to somewhere in ..\FarmMapsApiClient_WURtest\FarmmapsDataDownload\bin\Debug\netcoreapp3.1\Downloads\
"CropYear": 2022,
"fieldName": "aardappelveld_test_Potato_cattlemanure144kgnha_plusUrea92kgNha",
"geometryJson": {
"type": "Polygon",
"coordinates": [
[
[
5.5945257993548765,
52.57080744107003
],
[
5.598645994070678,
52.571540800206236
],
[
5.599381743127071,
52.57012773140724
],
[
5.595408698222548,
52.56968054825188
],
[
5.5945257993548765,
52.57080744107003
]
]
]
}
}
] ]

View File

@ -0,0 +1,8 @@
KPIid,KPIvariable,Description
A1,yield,observed yield (user input)
B1,nitrogen,Nitrogen surplus = N fertilizer + N atmospheric deposition + N fixation by crop - N removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and fertilizer applications
B2,phosphate,Phosphate surplus = P fertilizer - P removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and fertilizer applications
C1,organic matter supply,Organic matter surplus = Organic matter from manure + Crop residues to soil - organic matter removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and manure applications
D1,pesticides,?
,KPItargetvalue,target value as in benchmark value for same crop in same region
,KPIthresholdValue,threshold from ??? Ask farmmaps. Surplus nitrogen / phosphate / pesticides must not be above threshold. Surplus organic matter supply must be above threshold
1 KPIid KPIvariable Description
2 A1 yield observed yield (user input)
3 B1 nitrogen Nitrogen surplus = N fertilizer + N atmospheric deposition + N fixation by crop - N removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and fertilizer applications
4 B2 phosphate Phosphate surplus = P fertilizer - P removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and fertilizer applications
5 C1 organic matter supply Organic matter surplus = Organic matter from manure + Crop residues to soil - organic matter removal through harvested product. Calculated KPI internal model & parameters and from user input: yield and manure applications
6 D1 pesticides ?
7 KPItargetvalue target value as in benchmark value for same crop in same region
8 KPIthresholdValue threshold from ??? Ask farmmaps. Surplus nitrogen / phosphate / pesticides must not be above threshold. Surplus organic matter supply must be above threshold

View File

@ -5,28 +5,20 @@ namespace FarmmapsKPI.Models
{ {
public class KPIInput public class KPIInput
{ {
public bool UseCreatedCropfield { get; set; } public bool UseExistingCropfieldWithChildren { get; set; }
public bool DeleteNewlyCreatedAfterCalc { get; set; }
public string CropfieldItemCode { get; set; } public string CropfieldItemCode { get; set; }
public JObject DataCropfield { get; set; } public JObject DataCropfield { get; set; }
public bool UseCreatedCropRecording { get; set; }
public string CropRecordingItemCode { get; set; } public string CropRecordingItemCode { get; set; }
public JObject DataCropRecording { get; set; } public JObject DataCropRecording { get; set; }
public bool UseCreatedOperation { get; set; } public string[] OperationItemCodes { get; set; }
public string OperationItemCode { get; set; } public JObject[] DataOperations { get; set; }
public JObject DataOperation { get; set; }
public bool UseCreatedCropfieldCharacteristic { get; set; }
public string CropfieldCharacteristicItemCode { get; set; } public string CropfieldCharacteristicItemCode { get; set; }
public JObject DataCropfieldCharacteristic { get; set; } public JObject DataCropfieldCharacteristic { get; set; }
public string File { get; set; }
public string InputVariable { get; set; }
public string OutputFileName { get; set; }
public string DownloadFolder { get; set; } public string DownloadFolder { get; set; }
public int CropYear { get; set; } public int CropYear { get; set; }
public JObject GeometryJson { get; set; } public JObject GeometryJson { get; set; }
public string InputLayerName { get; set; }
public string fieldName { get; set; } public string fieldName { get; set; }
public bool GetShadowData { get; set; }
} }
} }

View File

@ -4,7 +4,7 @@
{ {
public string CropfieldItemCode { get; set; } public string CropfieldItemCode { get; set; }
public string CropRecordingItemCode { get; set; } public string CropRecordingItemCode { get; set; }
public string OperationItemCode { get; set; } public string[] OperationItemCodes { get; set; }
public string CropfieldCharacteristicItemCode { get; set; } public string CropfieldCharacteristicItemCode { get; set; }
} }