Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mass balance error if fertiliser entered after test #64

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions SVSModel/Models/SoilNitrogen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,6 @@ public static void UpdateBalance(DateTime updateDate, double dResetN, double pre
if (IsSet == false)
{
thisSim.SoilN[d] += thisSim.NSoilOM[d]; //add Som mineralisation
if (nAapplied.ContainsKey(d))
{
thisSim.NFertiliser[d] = nAapplied[d];
thisSim.SoilN[d] += nAapplied[d]; //add fertiliser
}
double availableN = thisSim.SoilN[d] * 0.2; //20% of soil N can be used in a day
double potentialImobilisation = Math.Max(0, thisSim.NResidues[d] * -1); //if NResidues is negative imobilisatin is happening
if (potentialImobilisation == 0)
Expand Down Expand Up @@ -104,13 +99,26 @@ public static void UpdateBalance(DateTime updateDate, double dResetN, double pre
/// </summary>
/// <param name="testResults">date indexed series of test results</param>
/// <param name="soilN">date indexed series of soil mineral N estimates to be corrected with measurements. Passed in as ref so
/// <param name="nApplied">nitrogen fertiliser already applied</param>
/// the corrections are applied to the property passed in</param>
public static void TestCorrection(Dictionary<DateTime, double> testResults, ref SimulationType thisSim)
public static void TestsAndActualFertiliser(Dictionary<DateTime, double> testResults, ref SimulationType thisSim, Dictionary<DateTime, double> nApplied)
{
foreach (DateTime d in testResults.Keys)
List<DateTime> UpdateDates = testResults.Keys.ToList();
UpdateDates.AddRange(nApplied.Keys.ToList());
UpdateDates.Sort((a, b) => a.CompareTo(b));

foreach (DateTime d in UpdateDates)
{
double dCorrection = testResults[d] - thisSim.SoilN[d];
SoilNitrogen.UpdateBalance(d, dCorrection, thisSim.SoilN[d] - thisSim.NFertiliser[d], thisSim.NLost[d], ref thisSim, true, new Dictionary<DateTime, double>(), true); //need to take out fertiliser if fert applied on same day as test so it doesn't break balance check test
if (nApplied.ContainsKey(d))
{
SoilNitrogen.UpdateBalance(d, nApplied[d], thisSim.SoilN[d], thisSim.NLost[d], ref thisSim, true, nApplied, true);
thisSim.NFertiliser[d] = nApplied[d];
}
if (testResults.ContainsKey(d))
{
double dCorrection = testResults[d] - thisSim.SoilN[d];
SoilNitrogen.UpdateBalance(d, dCorrection, thisSim.SoilN[d], thisSim.NLost[d], ref thisSim, true, nApplied, true);
}
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions SVSModel/Simulation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ public class Simulation
// Calculate soil OM mineralisation
SoilOrganic.Mineralisation(ref thisSim);

//Do initial nitorgen balance with no fertiliser or resets
SoilNitrogen.UpdateBalance(config.StartDate, initialN, 0, 0, ref thisSim, false, nAapplied, ScheduleFert);
//Do initial nitorgen balance with actual fertiliser but no scheduled fertiliser or resets
SoilNitrogen.UpdateBalance(config.StartDate, initialN, 0, 0, ref thisSim, false, new Dictionary<DateTime, double>(), ScheduleFert);

//Reset soil N with test valaues
SoilNitrogen.TestCorrection(testResults, ref thisSim);
SoilNitrogen.TestsAndActualFertiliser(testResults, ref thisSim, nAapplied);

//Calculate Fertiliser requirements and add into soil N
DateTime StartSchedullingDate = Fertiliser.startSchedullingDate(nAapplied, testResults, config);
Expand Down
20 changes: 12 additions & 8 deletions TestComponents/Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
}
else
{
root = Environment.GetEnvironmentVariable("GITHUB_WORKSPACE");

Check warning on line 45 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

Check warning on line 45 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.
path = Path.Join(root, "TestComponents", "TestSets");
}

Expand All @@ -63,7 +63,7 @@
foreach (string s in sets)
{
//Make config file in format that .NET DataTable is able to import
runPythonScript(root, Path.Join("TestGraphs", "MakeConfigs", $"{s}.py"));

Check warning on line 66 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'path' in 'void Test.runPythonScript(string path, string pyProg)'.

Check warning on line 66 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'path' in 'void Test.runPythonScript(string path, string pyProg)'.
//Run each test
runTestSet(path, s);
//Make graphs associated with each test
Expand All @@ -85,11 +85,11 @@

var assembly = Assembly.GetExecutingAssembly();
string testConfig = "TestComponents.TestSets." + set + ".FieldConfigs.csv";
Stream configcsv = assembly.GetManifestResourceStream(testConfig);

Check warning on line 88 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

Check warning on line 88 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.
DataFrame allTests = DataFrame.LoadCsv(configcsv);

string fertData = "TestComponents.TestSets." + set + ".FertiliserData.csv";
Stream fertcsv = assembly.GetManifestResourceStream(fertData);

Check warning on line 92 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

Check warning on line 92 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.
DataFrame allFert = new DataFrame();
if (fertcsv != null)
{
Expand All @@ -100,7 +100,7 @@

foreach (DataFrameRow row in allTests.Rows)
{
Tests.Add(row[0].ToString());

Check warning on line 103 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'item' in 'void List<string>.Add(string item)'.

Check warning on line 103 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'item' in 'void List<string>.Add(string item)'.
}
//Tests.Add("8-1Wheat");

Expand All @@ -115,11 +115,11 @@
double initialN = _testData.Item2;

Dictionary<System.DateTime, double> testResults = new Dictionary<System.DateTime, double>();
Dictionary<System.DateTime, double> nApplied = fertDict(test, allFert);
Dictionary<System.DateTime, double> nApplied = fertDict(test, allFert, _config);

string weatherStation = allTests["WeatherStation"][testRow].ToString();

Check warning on line 120 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

Check warning on line 120 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

bool actualWeather = weatherStation.Contains("Actual");

Check warning on line 122 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 122 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

MetDataDictionaries metData = ModelInterface.BuildMetDataDictionaries(_config.Prior.EstablishDate, _config.Following.HarvestDate.AddDays(1), weatherStation, actualWeather);

Expand All @@ -129,7 +129,7 @@
List<string> OutPutHeaders = new List<string>();
for (int i = 0; i < output.GetLength(1); i += 1)
{
OutPutHeaders.Add(output[0, i].ToString());

Check warning on line 132 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'item' in 'void List<string>.Add(string item)'.

Check warning on line 132 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'item' in 'void List<string>.Add(string item)'.
if (i == 0)
{
columns[i] = new PrimitiveDataFrameColumn<System.DateTime>(output[0, i].ToString());
Expand Down Expand Up @@ -272,7 +272,7 @@
return testRow;
}

private static Dictionary<System.DateTime, double> fertDict(string test, DataFrame allFert)
private static Dictionary<System.DateTime, double> fertDict(string test, DataFrame allFert, Config _config)
{
Dictionary<System.DateTime, double> fert = new Dictionary<System.DateTime, double>();
foreach (DataFrameRow row in allFert.Rows)
Expand All @@ -284,7 +284,7 @@
if (Environment.GetEnvironmentVariable("GITHUB_WORKSPACE") != null)
{
//Need to parse date like this in GitHub
date = DateTime.ParseExact(row[1].ToString(), "d/MM/yyyy", CultureInfo.InvariantCulture);

Check warning on line 287 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 's' in 'DateTime DateTime.ParseExact(string s, string format, IFormatProvider? provider)'.

Check warning on line 287 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 's' in 'DateTime DateTime.ParseExact(string s, string format, IFormatProvider? provider)'.
}
else
{
Expand All @@ -292,18 +292,22 @@
date = (DateTime)row[1];
}


DateTime last = new DateTime();
if (fert.Keys.Count > 0)
{
last = fert.Keys.Last();
}
if (date == last) //If alread fertiliser added for that date add it to existing total
{
fert[last] += Double.Parse(row[2].ToString());
}
else //add it to a new date
if ((date >= _config.StartDate) && (date <= _config.StartDate))
{
fert.Add(date, Double.Parse(row[2].ToString()));
if (date == last) //If alread fertiliser added for that date add it to existing total
{
fert[last] += Double.Parse(row[2].ToString());

Check warning on line 305 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 's' in 'double double.Parse(string s)'.

Check warning on line 305 in TestComponents/Test.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 's' in 'double double.Parse(string s)'.
}
else //add it to a new date
{
fert.Add(date, Double.Parse(row[2].ToString()));
}
}
}
}
Expand Down
Loading
Loading