Newer
Older
adaptive-nback / generators / nb_gm_003.py
import random
import scipy.stats


class SequenceGenerator:
    """nb_gm_003
        Generates a sequence of trials with even distribution of stimuli.
    """

    def __init__(self, choices, trials, n=3, targets_ratio=0.33):
        self.trials, self.choices, self.n, self.targets_ratio = trials, choices, n, targets_ratio
        self.seq = []
        self.norm_even_dist = scipy.stats.norm(0, trials/2)
        self.norm_targets_ratio_dist = scipy.stats.norm(targets_ratio, 0.1)

    def generate(self):
        print('next')
        while not self.seq or len(self.seq) < self.trials:
            self.seq = self.__find_best_next_sequence(self.seq, self.choices)
        return self.seq

    def __find_best_next_sequence(self, seq: list, choices: list) -> list:
        import sys
        min_cost = sys.float_info.max
        best_seq = seq
        random.shuffle(choices)  # to avoid ordering effect
        for choice in choices:
            tmp_seq = seq + list(choice)
            cost = self.__cost(tmp_seq)
            if cost < min_cost:
                min_cost = cost
                best_seq = tmp_seq
        return best_seq

    def __cost(self, seq):
        return self.__even_dist_cost(seq) + self.__target_ratio_cost(seq)


    def __even_dist_cost(self, seq):
        costs = {c: 0.0 for c in self.choices}
        for c in list(seq):
            costs[c] += (1.0 if costs.__contains__(c) else 0.0)
        even_ratio = self.trials / len(self.choices)
        costs = {k: abs(v - even_ratio)/self.trials for k, v in costs.items()}
        max_cost = max(list(costs.values()))
        return 1.0 - self.norm_even_dist.pdf(max_cost)

    def __target_ratio_cost(self, seq):
        targets, _ = self.count_targets_and_lures(seq)
        return 1.0 - self.norm_targets_ratio_dist.pdf(targets/self.trials)

    def count_targets_and_lures(self, seq):
        n = self.n
        targets = 0.0
        lures = 0.0
        for index in range(n, len(seq)):
            if seq[index] == seq[index - n]:
                targets += 1.0
            elif seq[index] == seq[index - (n-1)] or seq[index] == seq[index - (n+1)]:
                lures += 1.0
        return targets, lures

    def calc_tl_ratio(self, seq):
        """Calculates the T/L ratio in a block of trials."""
        targets, lures = self.count_targets_and_lures(seq)
        if lures < 0.01:  # avoid division by zero
            lures = 0.01
        return targets/lures


def __generate_stat_csv(filename):
    alphabetic_choices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
    trials = 24
    n = 2
    import csv
    import heapq
    with open(filename, mode='w') as stat_dist_file:
        writer = csv.writer(stat_dist_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['index'] + alphabetic_choices + ['ralph_skewed'])
        for i in range(100):
            generator = SequenceGenerator(alphabetic_choices, n=n, trials=trials)
            seq = generator.generate()
            dist = [float(seq.count(c)) for c in alphabetic_choices]
            ralph_skewed = sum(heapq.nlargest(int(len(alphabetic_choices)/2), dist)) > (trials*2/3)
            writer.writerow([str(i)] + dist + [str(ralph_skewed)])


if __name__ == '__main__':
    __generate_stat_csv('../stat/nb_gm_003_2back_24trials.csv')