I can dump the SetAnalysis value in a chart, but if I tried to do the following code, it gives me null or the entire set of IDs. For example, the Dimension in the chart is KeyValue, and an Expression in the chart is:
Dollar sign expansion is done up front, outside of the context of your chart dimensions. At that time, unless you've selected a single KeyValue, SetAnalysis has multiple values, and therefore returns null. So then you probably just count the distinct PatientIDs, ignoring the set you wanted.
If you avoid the dollar sign expansion by just sticking the field in there directly, it will have a unique value for SetAnalysis. However, at that point, it will be a string, not something actually inserted into the code to be evaluated. In other words, I think it would be the equivalent of this:
Where the single quotes make this a completely invalid expression, and so I would expect it to return null. You just can't use field values this way.
The evaluate() function would be perfect, except that it's explicitly disallowed in expressions.
The best way I've found to get around these limitations (and I'm not saying it's a good way) is to generate a pick() expression that can then choose the correct expression to apply. See attached example. Script for the expression part and variable generation below.