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

Summary stat #803

Merged
merged 26 commits into from
Jun 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
7886cbc
First implementation of the summary stat.
ASmirnov-HORIS Jun 16, 2023
d95a062
Update API for the stat_summary() function.
ASmirnov-HORIS Jun 20, 2023
b28bf7f
Small refactor in SummaryStat.
ASmirnov-HORIS Jun 21, 2023
6ce963b
Remove extra enum class from the SummaryStatUtil.
ASmirnov-HORIS Jun 21, 2023
b7a8f33
Remove SummaryStatUtil.
ASmirnov-HORIS Jun 21, 2023
05345ee
Use references instead of lambdas for the SummaryCalculator.
ASmirnov-HORIS Jun 21, 2023
756b626
Replace SummaryCalculator by the SummaryStatUtil.
ASmirnov-HORIS Jun 21, 2023
3b2bca7
Refactor functions in SummaryStatUtil.
ASmirnov-HORIS Jun 22, 2023
1f03da4
Refactor summary stat options in StatProto.
ASmirnov-HORIS Jun 22, 2023
baccb49
Fix statData emptiness case in the SummaryStat.
ASmirnov-HORIS Jun 22, 2023
c9e154c
Further code refactoring.
ASmirnov-HORIS Jun 22, 2023
0082f74
Small fixes.
ASmirnov-HORIS Jun 22, 2023
cbabbe3
Add new stat variables and use them in the SummaryStat.
ASmirnov-HORIS Jun 23, 2023
7fea03b
Add prefix to min/max stats in stat_summary().
ASmirnov-HORIS Jun 23, 2023
0ecc6ec
Change API of the summary_stat() - add 'quantiles' parameter.
ASmirnov-HORIS Jun 26, 2023
722b43a
Tiny refactor in SummaryStat and AggregateFunctions.
ASmirnov-HORIS Jun 27, 2023
e30b93b
Use AggregateFunctions in the FiveNumberSummary.
ASmirnov-HORIS Jun 27, 2023
f076938
Add tests for AggregateFunctions.
ASmirnov-HORIS Jun 27, 2023
2313872
Replace parameter fun_map by usual aesthetics list for the stat_summa…
ASmirnov-HORIS Jun 29, 2023
4bba413
Small fixes in code for summary stat.
ASmirnov-HORIS Jun 29, 2023
9cfeea5
Merge branch 'master' into summary-stats
ASmirnov-HORIS Jun 29, 2023
4586451
Add getMapping() method to the Flipped stat context.
ASmirnov-HORIS Jun 29, 2023
9dcdd79
Add docstrings to the stat_summary() function.
ASmirnov-HORIS Jun 29, 2023
37526eb
Add demo notebook for stat_summary().
ASmirnov-HORIS Jun 29, 2023
0a1d636
Mention stat_summary() in the future_changes.
ASmirnov-HORIS Jun 29, 2023
a392ba1
Refactor StatContext.
ASmirnov-HORIS Jun 30, 2023
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
Prev Previous commit
Next Next commit
Change API of the summary_stat() - add 'quantiles' parameter.
  • Loading branch information
ASmirnov-HORIS committed Jun 26, 2023
commit 0ecc6ec92301f69d40a281316016aa991d353a17
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ object Stats {
val MEAN = DataFrame.Variable("..mean..", STAT, "mean")
val MEDIAN = DataFrame.Variable("..median..", STAT, "median")
val QUANTILE = DataFrame.Variable("..quantile..", STAT, "quantile")
val QUANTILE_A = DataFrame.Variable("..qa..", STAT, "quantile a")
val QUANTILE_B = DataFrame.Variable("..qb..", STAT, "quantile b")
val QUANTILE_C = DataFrame.Variable("..qc..", STAT, "quantile c")
val LOWER_QUANTILE = DataFrame.Variable("..lq..", STAT, "lower quantile")
val MIDDLE_QUANTILE = DataFrame.Variable("..mq..", STAT, "middle quantile")
val UPPER_QUANTILE = DataFrame.Variable("..uq..", STAT, "upper quantile")
val LOWER = DataFrame.Variable("..lower..", STAT, "lower")
val MIDDLE = DataFrame.Variable("..middle..", STAT, "middle")
val UPPER = DataFrame.Variable("..upper..", STAT, "upper")
Expand Down Expand Up @@ -61,9 +61,9 @@ object Stats {
MEAN,
MEDIAN,
QUANTILE,
QUANTILE_A,
QUANTILE_B,
QUANTILE_C,
LOWER_QUANTILE,
MIDDLE_QUANTILE,
UPPER_QUANTILE,
LOWER,
MIDDLE,
UPPER,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ class SummaryStat(
}

companion object {
val DEF_QUANTILES = Triple(0.25, 0.5, 0.75)

private val DEF_MAPPING: Map<Aes<*>, DataFrame.Variable> = mapOf(
Aes.X to Stats.X,
Aes.Y to Stats.Y,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,6 @@ object SummaryUtil {

fun max(sortedValues: List<Double>): Double = sortedValues.lastOrNull() ?: Double.NaN

fun firstQuartile(sortedValues: List<Double>): Double = quantile(sortedValues, 0.25)

fun thirdQuartile(sortedValues: List<Double>): Double = quantile(sortedValues, 0.75)

fun quantile(sortedValues: List<Double>, p: Double): Double {
if (sortedValues.isEmpty()) {
return Double.NaN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@ object Option {
}

object Summary {
const val QUANTILES = "quantiles"
const val FUN = "fun"
const val FUN_MIN = "fun_min"
const val FUN_MAX = "fun_max"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ open class OptionsAccessor(
return options[option] != null
}

fun isNumber(option: String): Boolean {
val v = get(option) ?: return false
return v is Number
}

operator fun get(option: String): Any? {
return if (hasOwn(option)) {
options[option]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,53 +407,63 @@ object StatProto {
}

private fun configureSummaryStat(options: OptionsAccessor): SummaryStat {
val sortedQuantiles: Triple<Double, Double, Double> = if (options.hasOwn(Summary.QUANTILES)) {
options.getBoundedDoubleList(Summary.QUANTILES, 0.0, 1.0).let { quantiles ->
if (quantiles.size != 3) error("Parameter 'quantiles' should contains 3 values")
quantiles.sorted().let { Triple(it[0], it[1], it[2]) }
}
} else {
SummaryStat.DEF_QUANTILES
}

val defaultAggFunctions = mapOf(
Stats.Y to (getAggFunction(options, Summary.FUN) ?: SummaryUtil::mean),
Stats.Y_MIN to (getAggFunction(options, Summary.FUN_MIN) ?: SummaryUtil::min),
Stats.Y_MAX to (getAggFunction(options, Summary.FUN_MAX) ?: SummaryUtil::max)
Stats.Y to (options.getString(Summary.FUN)?.lowercase()?.let { getAggFunction(it, sortedQuantiles) } ?: SummaryUtil::mean),
Stats.Y_MIN to (options.getString(Summary.FUN_MIN)?.lowercase()?.let { getAggFunction(it, sortedQuantiles) } ?: SummaryUtil::min),
Stats.Y_MAX to (options.getString(Summary.FUN_MAX)?.lowercase()?.let { getAggFunction(it, sortedQuantiles) } ?: SummaryUtil::max)
)

val additionalAggFunctions = configureAggFunMap(options.getMap(Summary.FUN_MAP))
val additionalAggFunctions = configureAggFunMap(options.getMap(Summary.FUN_MAP), sortedQuantiles)

return SummaryStat(defaultAggFunctions + additionalAggFunctions)
}

private fun configureAggFunMap(aggFunMap: Map<String, Any>): Map<DataFrame.Variable, (List<Double>) -> Double> {
private fun configureAggFunMap(
aggFunMap: Map<String, Any>,
sortedQuantiles: Triple<Double, Double, Double>
): Map<DataFrame.Variable, (List<Double>) -> Double> {
val aggFunOptions = OptionsAccessor(aggFunMap)
return aggFunMap.keys.associate { statVarName ->
Pair(
Stats.statVar("..$statVarName.."),
getAggFunction(aggFunOptions, statVarName) ?: SummaryUtil::nan
)
}
return aggFunMap.keys.mapNotNull { option ->
aggFunOptions.getString(option)?.lowercase()?.let { aggFunName ->
val statVar = when (aggFunName) {
"min", "max" -> "..y$aggFunName.."
else -> "..$aggFunName.."
}.let { Stats.statVar(it) }
Pair(statVar, getAggFunction(aggFunName, sortedQuantiles))
}
}.toMap()
}

private fun getAggFunction(
options: OptionsAccessor,
option: String
): ((List<Double>) -> Double)? {
if (options.isNumber(option)) {
return options.getDouble(option)?.let { p: Double ->
{ values: List<Double> -> SummaryUtil.quantile(values, p) }
}
aggFunName: String,
sortedQuantiles: Triple<Double, Double, Double>
): ((List<Double>) -> Double) {
val quantileAggFunction: (Double) -> (List<Double>) -> Double = { p ->
{ values: List<Double> -> SummaryUtil.quantile(values, p) }
}
return options.getString(option)?.let {
when (it.lowercase()) {
"nan" -> SummaryUtil::nan
"count" -> SummaryUtil::count
"sum" -> SummaryUtil::sum
"mean" -> SummaryUtil::mean
"median" -> SummaryUtil::median
"min" -> SummaryUtil::min
"max" -> SummaryUtil::max
"q1" -> SummaryUtil::firstQuartile
"q2" -> SummaryUtil::median
"q3" -> SummaryUtil::thirdQuartile
else -> throw IllegalArgumentException(
"Unsupported function name: '$it'\n" +
"Use one of: nan, count, sum, mean, median, min, max, q1, q2, q3."
)
}
return when (aggFunName) {
"count" -> SummaryUtil::count
"sum" -> SummaryUtil::sum
"mean" -> SummaryUtil::mean
"median" -> SummaryUtil::median
"min" -> SummaryUtil::min
"max" -> SummaryUtil::max
"lq" -> quantileAggFunction(sortedQuantiles.first)
"mq" -> quantileAggFunction(sortedQuantiles.second)
"uq" -> quantileAggFunction(sortedQuantiles.third)
else -> throw IllegalArgumentException(
"Unsupported function name: '$aggFunName'\n" +
"Use one of: count, sum, mean, median, min, max, lq, mq, uq."
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ class Summary {
'geom': 'pointrange',
'stat': 'summary',
'fun': 'median',
'fun_min': 'q1',
'fun_max': 0.75,
'fun_min': 'lq',
'fun_max': 'uq',
'color': 'red'
}
]
Expand Down Expand Up @@ -92,7 +92,9 @@ class Summary {
'geom': 'crossbar',
'mapping': {'middle': '..median..'},
'stat': 'summary',
'fun_map': {'median': 'median'}
'fun_min': 'lq',
'fun_map': {'middle': 'median'},
'quantiles': [0.45, 0.5, 0.55]
}
]
}
Expand Down
29 changes: 8 additions & 21 deletions python-package/lets_plot/plot/stat.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,15 @@ def stat_summary(mapping=None, *, data=None, geom='pointrange',
position=None, show_legend=None, sampling=None, tooltips=None,
orientation=None,
fun=None, fun_min=None, fun_max=None, fun_map=None,
quantiles=None,
color_by=None, fill_by=None,
**other_args):
mapping_dict = mapping.as_dict() if mapping is not None else {}

quantile_agg_functions = {"qa": None, "qb": None, "qc": None}
def fun_to_stat(fun_name):
prefix = "y" if fun_name in ["min", "max"] else ""
return "..{0}{1}..".format(prefix, fun_name)

def get_stat_name(agg_fun):
if isinstance(agg_fun, str) and agg_fun not in ["q1", "q2", "q3"]:
prefix = "" if agg_fun not in ["min", "max"] else "y"
return prefix + agg_fun
else:
name = next((q for (q, f) in quantile_agg_functions.items() if f is None or f == agg_fun), None)
if name is None:
raise Exception("No more than three different quantiles can be used in fun_map parameter")
quantile_agg_functions[name] = agg_fun
return name

inner_fun_map = {}
fun_mapping_dict = {}
for aes_name, fun_name in (fun_map or {}).items():
stat_name = get_stat_name(fun_name)
inner_fun_map[stat_name] = fun_name
fun_mapping_dict[aes_name] = "..{0}..".format(stat_name)
mapping_dict = mapping.as_dict() if mapping is not None else {}
fun_mapping_dict = {aes_name: fun_to_stat(fun_name) for aes_name, fun_name in (fun_map or {}).items()}
inner_mapping_dict = {**fun_mapping_dict, **mapping_dict}
inner_mapping = aes(**inner_mapping_dict) if len(inner_mapping_dict.keys()) > 0 else None

Expand All @@ -48,6 +34,7 @@ def get_stat_name(agg_fun):
sampling=sampling,
tooltips=tooltips,
orientation=orientation,
fun=fun, fun_min=fun_min, fun_max=fun_max, fun_map=inner_fun_map,
fun=fun, fun_min=fun_min, fun_max=fun_max, fun_map=fun_map,
quantiles=quantiles,
color_by=color_by, fill_by=fill_by,
**other_args)