Skip to content

DnD Character: Added tests for randomness and distribution of abilities - #1623

Closed
jippiee wants to merge 5 commits into
exercism:mainfrom
jippiee:testRandomness
Closed

jippiee wants to merge 5 commits into
exercism:mainfrom
jippiee:testRandomness

Conversation

@jippiee

@jippiee jippiee commented Jan 24, 2019

Copy link
Copy Markdown

The idea for these tests is that currently you can simply return a constant value within range of 3 to 18 in the ability method and all test will still pass. (See my solution)

The first test testRandomAbilityIsRandom asserts that within 100 calls to ability() there are at leased 2 different values returned.

The second test testDistributionMatchesReference asserts that the resulting distribution matches the reference distribution. This reference is simply the count of all distinct abilities for all possible dice rolls. I generated this with:

int[] distribution = new int[20];
for (int i = 1; i <= 6; i++) {
    for (int j = 1; j <= 6; j++) {
        for (int k = 1; k <= 6; k++) {
            for (int l = 1; l <= 6; l++) {
                int min = Math.min(i, Math.min(j, Math.min(k, l)));
                int sum = i + j + k + l - min;
                distribution[sum]++;
                // System.out.format("%d %d %d %d (min=%d) (sum=%d)%n", i, j, k, l, min, sum);
            }
        }
    }
}
System.out.println(Arrays.toString(distribution));
// [0, 0, 0, 1, 4, 10, 21, 38, 62, 91, 122, 148, 167, 172, 160, 131, 94, 54, 21, 0]

To be considered as matching, a distribution populated by 10000 random values must differ less than 2% from the reference. These two values (cycles=10000, threshold=0.02) were determined by experimentation. The larger this first value (cycles) is, the more precise the second value (threshold) can be. To determine the threshold I let the entire test loop 1000000 times and keep track of the max difference. It was 0.0166. I created this test to catch the implementations that only return the sum of 3 dice rolls or (even wore) return a random number between 3 and 18.


Reviewer Resources:

Track Policies

@sshine

sshine commented Feb 5, 2020

Copy link
Copy Markdown
Contributor

Hi @jippiee, and thanks for your PR!

Here comes a very delayed response, but better late than never I hope!

With this response I hope that @exercism/java will find interest in eventually approving it.

I came up with this exercise (in exercism/problem-specifications#1397) and @lemoncurry created the exercise on the Java track (in #1621). One of my motivations behind this exercise was that I was working with random numbers at work and had to test that some function returned random data according to the proper probability distribution.

Testing that a solution doesn't use rand(3, 18) but uses rand(1,6) + rand(1,6) + rand(1,6) was also brought up here where some maintainers (myself included) deferred from testing this extensively. But since my original motivation was to stir conversation that could guide me towards a good solution to testing randomness (using declarative and/or probabilistic approaches), I still think this is a subject worth spreading learning material on.

Let us know what @lemoncurry thinks also.

As for your two proposed properties, here is some feedback for them:

  • testRandomAbilityIsRandom: We should justify this test by saying that the probability of false negatives is astronomically small (exactly how small takes a bit of figuring out), and that the cost of the test is relatively small (100 random calls). But we should also be honest and say that we don't actually test that ability() is random. We test that it returns more than one thing over a few amount of calls. So perhaps rename this to something like testAbilityIsNotConstant? Or maybe to humor the student, testAbilityIsProbablyNotConstant. ;-)

  • testDistributionMatchesReference: I am very impressed with this approach. We should justify this test by saying that it overcomes coriolinus'es warning (quoted below) by reducing computational complexity on each run;

    [...] Doing this the mathematically rigorous way would involve a few million iterations; at that scale, the mathematical properties of the generated numbers will be reliably measurably different from the mathematical properties of rand(3, 18). That's too big for a unit test, though. [...]

    We can then similarly reason about the probability of false negatives during tests, and we can lower this probability by either increasing the number of cycles or the threshold for the difference between the reference distribution and the tested distribution.

    But perhaps it would comfort the reviewer to give a ballpark estimate of how often this test would produce a false negative given some parameters such as the ones submitted.

In summary,

  • The implementation strategy of these probabilistic tests seems sound to me.
  • The probability of false negatives can in both cases be calculated, experimentally or theoretically, for fun or for moral justification.
  • We should clarify if the purpose of a probabilistic test (in particular the one that tests the distribution) is only to catch the rand(3, 18) vs. rand(1, 6) + rand(1, 6) + rand(1, 6) bug, or if we also aim to teach how to test something like this. If the latter is the case, perhaps the probabilistic tests should carry some of the justifications in this pull request with them? In particular, I don't believe that being able to justify that false negatives that occur with astronomical frequency is something that everyone will immediately derive from looking at the test code.

@jmrunkle

Copy link
Copy Markdown
Contributor

@jippiee - are you still actively working on this PR? If not, we might close it to clean up our backlog. It can always be reopened if needed.

@jippiee

jippiee commented Apr 15, 2020

Copy link
Copy Markdown
Author

Ok, I've updated the test and also included comments describing how the test with the distribution works. I've also included a Note on why rand(1,6) + rand(1,6) + rand(1,6) also gives a wrong distribution, but I'm not quite sure if that should belong in the test source.

Here I've also plotted the distributions. The green is the correct one.

exercism_dnd_character_distributions

@jmrunkle

Copy link
Copy Markdown
Contributor

Closing and reopening to trigger travis CI to retry this...

@jmrunkle jmrunkle closed this Apr 16, 2020
@jmrunkle jmrunkle reopened this Apr 16, 2020
@jmrunkle

Copy link
Copy Markdown
Contributor

Looks like there is a slight style violation at line 189:

Task :dnd-character:checkstyleTest FAILED
[ant:checkstyle] [ERROR] /home/travis/build/exercism/java/exercises/dnd-character/src/test/java/DnDCharacterTest.java:189: 'array initialization' child has incorrect indentation level 16, expected level should be 12. [Indentation]

So just reduce the indentation there to 12 (ie. delete 4 spaces). Other than that, I will try to take a look at this tomorrow morning.

@jmrunkle jmrunkle left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this. We are getting pretty close now.

}

/*
* Extra Notes:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a very interesting statistical commentary, but I'm not sure it belongs here. Perhaps this sort of thing should go in the mentoring notes for this exercise?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this really remains to be decided.

The purpose of the exercise (I can say because I came up with it) is to explore probabilistic property testing.

But any maintainer is fit to choose how to make any exercise fit some track-specific goal.

I think this stuff is ingenious -- and it is, it seems, one of the things people do wrong: Not understanding that just because the range is correct, the distribution isn't necessarily.

Alternative suggestions for placements:

  • In a hint: Would increase exposure.
  • In a git commit message: Would remove exposure.
  • In a blog post linked to from a hint: Would require someone to want to write a blog post.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea for this comment was, that if a student has a wrong solution which fails the testAbilityIsDistributedAccordingToRules test, but they don't jet know why it is failing, they might want to check out the source of the tests and thus stumble on this note. I admit that probably not every student will find it, but for some it might help them solve the exercise.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally, I am leaning towards having a hints.md file that includes this extra information about this test. If it makes you feel better, put a Javadoc comment on the test method telling them to check the hints.

@sshine

sshine commented Apr 17, 2020

Copy link
Copy Markdown
Contributor

@jmrunkle wrote:

are you still actively working on this PR? If not, we might close it

Ever since reviewing this, my impression has been that the solution is sufficient, but that it lacks explanation for maintainers to want to touch it. So my review was an encouragement to convince those less statistics savvy (myself included) that it won't, in practice, fail, without resorting to "trust me, I know math", because I think such an argument is extremely fragile in the context of Exercism, where we rely heavily on commit history.

Added comment explaining methodology
Added inRange and testDistribution helper methods
Updated reference solution

@jippiee jippiee left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the updated test and reference solution.

Comment on lines +237 to +246
* The parameters (10000, 0.1, 0.01) were chosen based on the results
* of the table above, and were tested further in the test setup with a
* loop of 1000000, which passed.
*
* Further following should hold true:
* relativeError <= 0.2
* constantError <= 0.02
* Otherwise it becomes increasingly likely that an 'ability' method
* which gives "Throw three dice and sum them" would wrongly pass the
* test.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is a chart of what I am talking about:

exercism_dnd_character_distributions_2

The yellow and green graphs are the distributions of two wrong implementations mentioned at the beginning.
The red graph is the reference distribution.
The pink graph represents the error bounds for the parameters currently in use: Any distribution that we create by repeatedly calling ability, which falls completely within these bounds is accepted, otherwise rejected.
The blue graph represents the error bounds for the two maximum parameters mentioned. Should the parameters be even larger, it will become increasingly likely that we accept a solution which actually conforms to the green graph ("Throw three dice. Sum them.") than the red one ("Throw four dice. Sum the largest three.").

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is missing the graph showing the error bounds for the green graph. This only shows an idealized distribution for the green case (roll 3, sum them). I'm curious that there is even more overlap if you consider the error bounds for the green distribution. With that said, I think this is probably sufficient to get us close enough as-is.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE: If you move the long comments to a hints.md file, you could also put the graphic into the markdown. Just a thought.

Comment on lines +282 to +288
/* This distribution was generated by going through all possible
* combinations for throwing four dice, computing the ability for that
* combination, and incrementing the array at that index.
*/
int[] referenceDist = new int[] {
0, 0, 0, 1, 4, 10, 21, 38, 62, 91, 122, 148, 167, 172, 160, 131, 94, 54, 21
};

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead use actual generation code? Or maybe put the code in a comment?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm debating the merits. I assume the generation is time-prohibitive to just generate it in the test. We could leave it in an unused method just for documentation purposes?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment bad?

If you ask me the ingenious part of this PR is that @jippiee precomputes the heavy parts and remains confident to any chosen probability that there isn't false negatives. But this array is certainly magical and deserves an explanation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, while some comments can be moved to the hint file, this one is overly specific about some magical constants. So I might be inclined to keep it local, since you really don't care about what the numbers are until you read them, but they also really need an explanation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be nice to have an unused method that computes this array which can have some nice Javadoc and the actual precomputed array can say it was generated by method X.

So something like this:

/* Built by {@link generateReferenceDistribution} */
int[] referenceDist = new int[] ...

/**
   * Generates a distribution by going through all possible
   * combinations for throwing four dice, computing the ability for that
   * combination, and incrementing the array at that index.
   */
private static int[] generateReferenceDistribution() { ... }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not a bad idea, but not an entirely uncontentious one either.

Dead code vs. looking up commits for explanations.

I would be happy with either.

@sshine sshine Apr 21, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not saying we should go with the following, but it made me think of golden tests, i.e. unit tests stored in files: "When you add a new test, your testing framework can generate the missing golden file from the current output of the function."

return;
}
}
fail();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably include an error message saying what happened so that the student could debug the test failure: "ability appears to always return the same value"

@jmrunkle

Copy link
Copy Markdown
Contributor

@jippiee - any more updates on this PR?

Base automatically changed from master to main January 28, 2021 19:15
@sshine

sshine commented Feb 15, 2021

Copy link
Copy Markdown
Contributor

To get this PR merged, I see some points that were raised:

  1. DnD Character: Added tests for randomness and distribution of abilities #1623 (comment): Move "Extra Notes" into .meta/hints.md, or not.
  2. DnD Character: Added tests for randomness and distribution of abilities #1623 (comment): Put distribution generator into dead function, create golden test, or keep as-is.
  3. DnD Character: Added tests for randomness and distribution of abilities #1623 (comment): Add meaningful error message when ability is probably constant.

The comment links refer to the discussion on each of these.

It would be a pity to not have this included because of minor, unresolved ideas about where to place comments. :-)

Also, this PR probably needs rebasing after v3 has moved practice exercises to a sub-directory.

@jmrunkle

Copy link
Copy Markdown
Contributor

If there are no further updates or comments on this PR, I will probably close it in one week. Otherwise, please comment and then synchronize the files and we can continue the review.

@jmrunkle

Copy link
Copy Markdown
Contributor

If there are no further updates or comments on this PR, I will probably close it in one week. Otherwise, please comment and then synchronize the files and we can continue the review.

Closing as there has been no followup on this. Feel free to reopen if / when you are willing to address the merge conflicts, etc and continue the review.

@jmrunkle jmrunkle closed this Sep 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants