use python itertools.groupby for memory efficient nested iteration over the sampled tree histories in the sqlite3 database