Skip to content
New issue

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

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

Already on GitHub? # to your account

Add ifs, maxifs, minifs functions to analysis tool pack #448

Merged
merged 3 commits into from
Oct 27, 2020
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
6 changes: 4 additions & 2 deletions main/SS/Formula/Atp/AnalysisToolPak.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private static Dictionary<String, FreeRefFunction> CreateFunctionsMap()
r(m, "BIN2OCT", null);
r(m, "COMPLEX", Complex.Instance);
r(m, "CONVERT", null);
r(m, "COUNTIFS", null);
r(m, "COUNTIFS", Countifs.instance);
r(m, "COUPDAYBS", null);
r(m, "COUPDAYS", null);
r(m, "COUPDAYSNC", null);
Expand Down Expand Up @@ -123,6 +123,7 @@ private static Dictionary<String, FreeRefFunction> CreateFunctionsMap()
r(m, "HEX2DEC", Hex2Dec.instance);
r(m, "HEX2OCT", null);
r(m, "IFERROR", IfError.Instance);
r(m, "IFS", Ifs.Instance);
r(m, "IMABS", null);
r(m, "IMAGINARY", Imaginary.instance);
r(m, "IMARGUMENT", null);
Expand All @@ -145,7 +146,9 @@ private static Dictionary<String, FreeRefFunction> CreateFunctionsMap()
r(m, "ISODD", ParityFunction.IS_ODD);
r(m, "JIS", null);
r(m, "LCM", null);
r(m, "MAXIFS", Maxifs.instance);
r(m, "MDURATION", null);
r(m, "MINIFS", Minifs.instance);
r(m, "MROUND", MRound.Instance);
r(m, "MULTINOMIAL", null);
r(m, "NETWORKDAYS", NetworkdaysFunction.instance);
Expand Down Expand Up @@ -178,7 +181,6 @@ private static Dictionary<String, FreeRefFunction> CreateFunctionsMap()
r(m, "YIELD", null);
r(m, "YIELDDISC", null);
r(m, "YIELDMAT", null);
r(m, "COUNTIFS", Countifs.instance);
return m;
}

Expand Down
53 changes: 53 additions & 0 deletions main/SS/Formula/Atp/Ifs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using System.Collections.Generic;
using System.Text;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.Eval;

namespace NPOI.SS.Formula.Atp
{
class Ifs : FreeRefFunction
{
public static FreeRefFunction Instance = new Ifs();

private Ifs()
{
// enforce singleton
}

public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
if (args.Length % 2 != 0)
{
return ErrorEval.VALUE_INVALID;
}

for (int i = 0; i < args.Length; i = i + 2)
{
BoolEval logicalTest = (BoolEval)args[i];
if ( logicalTest.BooleanValue )
{
return args[i + 1];
}
}

return ErrorEval.NA;
}
}
}
70 changes: 70 additions & 0 deletions main/SS/Formula/Atp/Maxifs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */


namespace NPOI.SS.Formula.Atp
{
using System;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.Eval;

/**
* Implementation for the function MAXIFS
* <p>
* Syntax: MAXIFS(data_range, criteria_range1, criteria1, [criteria_range2, criteria2])
* </p>
*/

public class Maxifs : FreeRefFunction
{
public static FreeRefFunction instance = new Maxifs();

public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
if (args.Length < 3 || args.Length % 2 == 0)
{
return ErrorEval.VALUE_INVALID;
}

try
{
AreaEval dataRange = Sumifs.ConvertRangeArg(args[0]);

// collect pairs of ranges and criteria
AreaEval[] ae = new AreaEval[(args.Length - 1) / 2];
IMatchPredicate[] mp = new IMatchPredicate[ae.Length];
for (int i = 1, k = 0; i < args.Length; i += 2, k++)
{
ae[k] = Sumifs.ConvertRangeArg(args[i]);
mp[k] = Countif.CreateCriteriaPredicate(args[i + 1], ec.RowIndex, ec.ColumnIndex);
}

Sumifs.ValidateCriteriaRanges(ae, dataRange);
Sumifs.ValidateCriteria(mp);

double result = Sumifs.CalcMatchingCells(ae, mp, dataRange, double.NaN, (init, current) => !current.HasValue ? init : double.IsNaN(init) ? current.Value : current.Value > init ? current.Value : init);
return new NumberEval(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
}

}
70 changes: 70 additions & 0 deletions main/SS/Formula/Atp/MinIfs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */


namespace NPOI.SS.Formula.Atp
{
using System;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.Eval;

/**
* Implementation for the function MINIFS
* <p>
* Syntax: MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2])
* </p>
*/

public class Minifs : FreeRefFunction
{
public static FreeRefFunction instance = new Minifs();

public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
if (args.Length < 3 || args.Length % 2 == 0)
{
return ErrorEval.VALUE_INVALID;
}

try
{
AreaEval minRange = Sumifs.ConvertRangeArg(args[0]);

// collect pairs of ranges and criteria
AreaEval[] ae = new AreaEval[(args.Length - 1) / 2];
IMatchPredicate[] mp = new IMatchPredicate[ae.Length];
for (int i = 1, k = 0; i < args.Length; i += 2, k++)
{
ae[k] = Sumifs.ConvertRangeArg(args[i]);
mp[k] = Countif.CreateCriteriaPredicate(args[i + 1], ec.RowIndex, ec.ColumnIndex);
}

Sumifs.ValidateCriteriaRanges(ae, minRange);
Sumifs.ValidateCriteria(mp);

double result = Sumifs.CalcMatchingCells(ae, mp, minRange, double.NaN, (init, current) => !current.HasValue ? init : double.IsNaN(init) ? current.Value : current.Value < init ? current.Value : init);
return new NumberEval(result);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
}

}
1 change: 1 addition & 0 deletions main/SS/Formula/Functions/Averageifs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
}

ValidateCriteriaRanges(ae, avgRange);
Sumifs.ValidateCriteria(mp);

double result = GetAvgFromMatchingCells(ae, mp, avgRange);
return new NumberEval(result);
Expand Down
23 changes: 13 additions & 10 deletions main/SS/Formula/Functions/Sumifs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)

ValidateCriteriaRanges(ae, sumRange);
ValidateCriteria(mp);
double result = SumMatchingCells(ae, mp, sumRange);

double result = CalcMatchingCells(ae, mp, sumRange, 0.0, (init, current) => init + (current.HasValue ? current.Value : 0.0));
return new NumberEval(result);
}
catch (EvaluationException e)
Expand All @@ -82,7 +83,7 @@ public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
*
* @throws EvaluationException if there are criteria which resulted in Errors.
*/
private void ValidateCriteria(IMatchPredicate[] criteria)
internal static void ValidateCriteria(IMatchPredicate[] criteria)
{
foreach (IMatchPredicate predicate in criteria)
{
Expand All @@ -100,7 +101,7 @@ private void ValidateCriteria(IMatchPredicate[] criteria)
*
* @throws EvaluationException if
*/
private void ValidateCriteriaRanges(AreaEval[] criteriaRanges, AreaEval sumRange)
internal static void ValidateCriteriaRanges(AreaEval[] criteriaRanges, AreaEval sumRange)
{
foreach (AreaEval r in criteriaRanges)
{
Expand All @@ -120,12 +121,12 @@ private void ValidateCriteriaRanges(AreaEval[] criteriaRanges, AreaEval sumRange
*
* @return the computed value
*/
private static double SumMatchingCells(AreaEval[] ranges, IMatchPredicate[] predicates, AreaEval aeSum)
internal static double CalcMatchingCells(AreaEval[] ranges, IMatchPredicate[] predicates, AreaEval aeSum, double initialValue, System.Func<double, double?, double> calc)
{
int height = aeSum.Height;
int width = aeSum.Width;

double result = 0.0;
double result = initialValue;
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
Expand All @@ -147,15 +148,17 @@ private static double SumMatchingCells(AreaEval[] ranges, IMatchPredicate[] pred

if (matches)
{ // sum only if all of the corresponding criteria specified are true for that cell.
result += Accumulate(aeSum, r, c);
result = calc(result, ReadValue(aeSum, r, c));
}
}
}
return result;
}

private static double Accumulate(AreaEval aeSum, int relRowIndex,
int relColIndex)
/**
* Reads the numeric values from the row/col of the specified area - other values return the indicated missing value.
*/
private static double? ReadValue(AreaEval aeSum, int relRowIndex, int relColIndex)
{

ValueEval addend = aeSum.GetRelativeValue(relRowIndex, relColIndex);
Expand All @@ -164,10 +167,10 @@ private static double Accumulate(AreaEval aeSum, int relRowIndex,
return ((NumberEval)addend).NumberValue;
}
// everything else (including string and boolean values) counts as zero
return 0.0;
return null;
}

private static AreaEval ConvertRangeArg(ValueEval eval)
internal static AreaEval ConvertRangeArg(ValueEval eval)
{
if (eval is AreaEval)
{
Expand Down
66 changes: 66 additions & 0 deletions testcases/main/SS/Formula/Atp/TestIfs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;

namespace TestCases.SS.Formula.Atp
{
[TestFixture]
public class TestIfs
{
/// <summary>
/// =IFS(A1="A", "Value for A" , A1="B", "Value for B")
/// </summary>
[Test]
public void TestEvaluate()
{
IWorkbook wb = new HSSFWorkbook();
ISheet sh = wb.CreateSheet();
IRow row1 = sh.CreateRow(0);

// Create cells
row1.CreateCell(0, CellType.String);

// Create references
CellReference a1Ref = new CellReference("A1");

// Set values
ICell cellA1 = sh.GetRow(a1Ref.Row).GetCell(a1Ref.Col);

ICell cell1 = row1.CreateCell(1);
cell1.CellFormula = "IFS(A1=\"A\", \"Value for A\", A1=\"B\",\"Value for B\")";

IFormulaEvaluator evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();

cellA1.SetCellValue("A");
Assert.AreEqual(CellType.String, evaluator.Evaluate(cell1).CellType, "Checks that the cell is numeric");
Assert.AreEqual("Value for A", evaluator.Evaluate(cell1).StringValue, "IFS should return 'Value for B'");

cellA1.SetCellValue("B");
evaluator.ClearAllCachedResultValues();

Assert.AreEqual(CellType.String, evaluator.Evaluate(cell1).CellType, "Checks that the cell is numeric");
Assert.AreEqual("Value for B", evaluator.Evaluate(cell1).StringValue, "IFS should return 'Value for B'");
}
}
}
Loading