Exemplo n.º 1
0
    def error(self):
        """Introduce a random error."""

        #count = math.floor(pow(random.randint(1, 11), 2) / 50) + 1
        # count = npchoice([0,1,2,3,4],p=[0.05,0.07,0.25,0.35,0.28]) #original (a1)
        #count = npchoice([0,1,2,3,4],p=[0.1,0.1,0.2,0.3,0.3]) # (a2)
        #count = npchoice([0,1,2,3,4,5],p=[0.1,0.1,0.2,0.2,0.2,0.2]) # (a3)
        #count = npchoice([0,1,2,3,4,5],p=[0.1,0.1,0.2,0.2,0.2,0.2]) # (a4)
        #count = npchoice([0,1,2,3,4,5],p=[0.0,0.0,0.25,0.25,0.25,0.25]) # (a5)
        count = npchoice([0, 1, 2, 3, 4], p=[0.5, 0.125, 0.125, 0.125,
                                             0.125])  # custom

        for x in range(count):
            # Note: verb_error redirects to replace_error and vice versa if nothing happened
            # error_probs = [.30,.25,.25,.20] #original (a1)
            #error_probs = [.25,.30,.30,.15] # (a2)
            #error_probs = [.40,.25,.25,.10] #(a3)
            #error_probs = [.30,.30,.30,.10] #(a4)
            #error_probs = [.35,.25,.25,.15] #(a5)
            error_probs = [0.0, 0.0, 1.0, 0.0]  # custom

            error_fun = npchoice([
                self.insert_error, self.verb_error, self.replace_error,
                self.delete_error
            ],
                                 p=error_probs)
            self.sentence = error_fun()
            self.tokenize()

        return self.sentence
Exemplo n.º 2
0
def get_random_regions(chrom_sizes, ref_fname, jitter_size, sample_size,
                       out_fname):

    print("Getting reference length and chromosome distributions ... "),
    sys.stdout.flush()

    chrom_counts = {}
    ref_lengths = []
    with open(ref_fname, 'r') as f:
        for line in f:
            line_list = line.strip().split()
            try:
                chrom_counts[line_list[0]] += 1
            except KeyError:
                chrom_counts[line_list[0]] = 1
            ref_lengths.append(int(line_list[2]) - int(line_list[1]))

    ref_total = sum(chrom_counts.values())
    chrom_props = {
        chrom: float(count) / ref_total
        for chrom, count in chrom_counts.iteritems()
    }

    chroms = sorted(chrom_props.keys())
    probs = [chrom_props[c] for c in chroms]

    print("Done")

    print("Generating random chromosomes and lengths ... "),
    sys.stdout.flush()

    sample_chroms = npchoice(chroms, size=sample_size, p=probs)
    sample_lengths = map(lambda x: jitter(x, jitter_size),
                         npchoice(ref_lengths, size=sample_size).tolist())

    print("Done")
    print("Writing random regions to file ... "),
    sys.stdout.flush()

    with open(out_fname, 'wa') as out:
        for i, (chrom, length) in enumerate(zip(sample_chroms,
                                                sample_lengths)):
            chrom_size = chrom_sizes[chrom]
            start = random.randint(1, chrom_size - length)
            end = start + length
            name = "RAND" + str(i)
            score = "1"
            strand = "+"
            out.write("\t".join(
                [chrom, str(start),
                 str(end), name, score, strand]) + "\n")

    print("Done")
Exemplo n.º 3
0
    def replace_error(self, redir=True):
        """Add a common replace error."""
        if len(self.tokenized) > 0:
            deletable = [
                i for i, w in enumerate(self.tokenized) if w in COMMON_REPLACES
            ]
            if not deletable:
                if redir:
                    return self.verb_error(redir=False)
                return self.sentence

            index = random.choice(deletable)
            word = self.tokenized[index]
            if not COMMON_REPLACES[word]:
                return self.sentence

            # Normalize probabilities
            plist = list(COMMON_REPLACES[word].values())
            plistsum = sum(plist)
            plist = [x / plistsum for x in plist]

            # Choose a bad word
            repl = npchoice(list(COMMON_REPLACES[word].keys()), p=plist)
            self.tokenized[index] = repl

        return ' '.join(self.tokenized)
Exemplo n.º 4
0
 def getPlayers(self):
     # returns two randomly chosen agents. If there are no such
     # agents remaining, simply return None.
     if len(self.agents) < 2:
         # only 0 or 1 agents -- that agent is, sadly, doomed to die
         # with no fitness.
         return None
     while True:
         rem_both = True
         if not len(self.agents_to_play):
             return None
         if len(self.agents_to_play) == 1:
             agent_a = self.agents_to_play[0]
             agent_b = choice(self.agents)
             rem_both = False
         else:
             agent_a, agent_b = npchoice(self.agents_to_play, 2, False)
         if agent_a.available_moves >= 1 or agent_b.available_moves >= 1:
             # i.e., if either have something left that they
             # can gain.
             break
         self.agents_to_play.remove(agent_a)
         if rem_both:
             self.agents_to_play.remove(agent_b)
     if agent_a.available_moves < 1:
         self.agents_to_play.remove(agent_a)
     if agent_b.available_moves < 1 and rem_both:
         self.agents_to_play.remove(agent_b)
     return (agent_a, agent_b)
def sample_new_words(bag_of_words: set, number_of_words: int):
    new_words = sample(bag_of_words, number_of_words)
    for word in new_words:
        if npchoice([True, False],
                    p=[uppercase_probability, 1 - uppercase_probability]):
            new_words.remove(word)
            new_words.append(word.capitalize())
    return new_words
Exemplo n.º 6
0
 def choose_resource_card(self, n):
     m = self.number_resources(n)
     resources = self.dir_resources[n]
     if m == 0:
         return None
     p = [(resources[resource] / m) for resource in resources]
     #return np.random.choice(list(resources.keys()), p=p)
     return npchoice(list(resources.keys()), p=p)
def mutation(individuals: list, bag_of_words: set, mean_words_length: float):
    ret = []
    for ind in individuals:
        if npchoice([True, False],
                    p=[mutation_probability, 1 - mutation_probability]):
            ret.append(single_mutation(ind, bag_of_words, mean_words_length))
        else:
            ret.append(ind)
    return ret
Exemplo n.º 8
0
 def set_gender(self, gender=None):
     """This model recognizes that sex chromosomes don't always line up with
     gender. Assign M, F, or NB according to the probabilities in p_gender.
     """
     if gender and gender in genders:
         self.gender = gender
     else:
         if not self.chromosomes: self.set_chromosomes()
         self.gender = npchoice(genders, 1, p=p_gender[self.chromosomes])[0]
Exemplo n.º 9
0
    def generate_gamete(self, egg_or_sperm_word):
        """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens
        by searching the list of tokens for words that are related to the given
        egg_or_sperm_word.
        """
        p_rate_of_mutation = [0.9, 0.1]
        should_use_mutant_pool = (npchoice([0,1], 1, p=p_rate_of_mutation)[0] == 1)
        if should_use_mutant_pool:
            pool = tokens.secondary_tokens
        else:
            pool = tokens.primary_tokens

        return get_matches(egg_or_sperm_word, pool, 23)
Exemplo n.º 10
0
    def error(self):
        """Introduce a random error."""

        #count = math.floor(pow(random.randint(1, 11), 2) / 50) + 1
        count = npchoice([0,1,2,3,4],p=[0.05,0.07,0.25,0.35,0.28]) #original (a1)  # 从0到5里面按照概率抽出来一个数字.表示 给句子弄几个错误,从概率上看推荐是2,3,4
        #count = npchoice([0,1,2,3,4],p=[0.1,0.1,0.2,0.3,0.3]) # (a2)
        #count = npchoice([0,1,2,3,4,5],p=[0.1,0.1,0.2,0.2,0.2,0.2]) # (a3)
        #count = npchoice([0,1,2,3,4,5],p=[0.1,0.1,0.2,0.2,0.2,0.2]) # (a4)
        #count = npchoice([0,1,2,3,4,5],p=[0.0,0.0,0.25,0.25,0.25,0.25]) # (a5)

        for x in range(count):
            # Note: verb_error redirects to replace_error and vice versa if nothing happened
            error_probs = [.30,.25,.25,.20] #original (a1)
            #error_probs = [.25,.30,.30,.15] # (a2)
            #error_probs = [.40,.25,.25,.10] #(a3)
            #error_probs = [.30,.30,.30,.10] #(a4)
            #error_probs = [.35,.25,.25,.15] #(a5)

            error_fun = npchoice([self.insert_error, self.verb_error, self.replace_error, self.delete_error],p=error_probs)  # 从4种错误里面随便选一个, 选择概率是error_probs,选一个错误函数.
            self.sentence = error_fun()
            self.tokenize()

        return self.sentence
Exemplo n.º 11
0
	def trainset(self,fname,tportion=0.25,epochs=50):
		if 'datasets/' not in fname:
			fname = 'datasets/' + fname
		if '.json' not in fname:
			fname = fname + '.json'
		f = open(fname)
		mlist = loadJSON(f)
		f.close()
		tportion = int(len(mlist)*max(0,min(1.0,tportion)))
		for k in range(epochs):
			print 'Training: epoch #' + str(k)
			for match in npchoice(mlist,tportion,replace=False):
				a,b = match['a'],match['b']
				self.update(a,b,match['val'])
Exemplo n.º 12
0
def pull(numPulls):
    global currentCharaters, pulledCharaters 
    pulledCharaters += currentCharaters
    currentCharaters = []
    for i in range(numPulls):  #pull the charaters 
        currentCharaters.append(choice(npchoice(charList, None, p=pullChances)))
    for child in pulls.winfo_children():      #destroy the cards in the pull frame 
        child.destroy()
    for child in collection.winfo_children(): #destroy the cards in the collection frame 
        child.destroy()
    for i in range(len(currentCharaters)):    #add the cards in the pull frame 
        addCard(pulls, currentCharaters[i], i % charsPerRow, i // charsPerRow)
    for i in range(len(pulledCharaters)):     #add the cards in the collection frame 
        addCard(collection, pulledCharaters[i], i % charsPerRow, i // charsPerRow)
Exemplo n.º 13
0
    def delete_error(self):
        if len(self.tokenized) > 0:
            insertable = list(range(len(self.tokenized)))
            index = random.choice(insertable)

            plist = list(COMMON_DELETES.values())
            plistsum = sum(plist)
            plist = [x / plistsum for x in plist]

            # Choose a bad word
            ins_word = npchoice(list(COMMON_DELETES.keys()), p=plist)
            self.tokenized.insert(index, ins_word)

        return ' '.join(self.tokenized)
Exemplo n.º 14
0
 def trainset(self, fname, tportion=0.25, epochs=50):
     if 'datasets/' not in fname:
         fname = 'datasets/' + fname
     if '.json' not in fname:
         fname = fname + '.json'
     f = open(fname)
     mlist = loadJSON(f)
     f.close()
     tportion = int(len(mlist) * max(0, min(1.0, tportion)))
     for k in range(epochs):
         print 'Training: epoch #' + str(k)
         for match in npchoice(mlist, tportion, replace=False):
             a, b = match['a'], match['b']
             self.update(a, b, match['val'])
Exemplo n.º 15
0
    def accuracyCheck(self, user, opponent):
        # Move's target is the opponent, so check if it's immune to the attack
        if self.opponentImmune(opponent.getTypes()) and self.targetOpponent:
            self.messages.append(" - But it failed...")
            return False

        # Not immune/Not attacking opponent, check accuracy
        accuracy_check = npchoice([True, False],
                                  1,
                                  p=[self.accuracy, 1 - self.accuracy])
        if accuracy_check == False:
            self.messages.append(" - But it missed!")
            return False

        return True
Exemplo n.º 16
0
    def reproduce_sexually(self, egg_donor, sperm_donor):
        """Produce two gametes, an egg and a sperm, from input Gods. Combine
        them to produce a genome a la sexual reproduction. Assign divinity
        according to probabilities in p_divinity. The more divine the parents,
        the more divine their offspring.
        """
        egg_word = random.choice(egg_donor.genome)
        egg = self.generate_gamete(egg_word)
        sperm_word = random.choice(sperm_donor.genome)
        sperm = self.generate_gamete(sperm_word)

        self.genome = list(set(egg + sperm)) # Eliminate duplicates
        self.parents = [egg_donor.name, sperm_donor.name]
        self.generation = max(egg_donor.generation, sperm_donor.generation) + 1
        sum_ = egg_donor.divinity + sperm_donor.divinity
        self.divinity = int(npchoice(divinities, 1, p=p_divinity[sum_])[0])
Exemplo n.º 17
0
    def generate_map(self):
        """
        Generates a list of cells to be loaded as a layout

        @return a grid of Cell enums randomly generated
        """
        n, m = self.n, self.m
        grid = ['' for i in range(n * m)]
        # ------------------- treasure and start are fixed ------------------- #
        grid[0] = Cell.treasure
        grid[n * m - 1] = Cell.start
        required = [Cell.golden_key, Cell.magic_sword]
        while len(required) > 0:
            h = randint(1, n * m - 2)
            if grid[h] == '': grid[h] = required.pop()

        cell_p = [
            (Cell.empty, 0.5),
            (Cell.wall, 0.2),
            (Cell.magic_portal, 0.05),
            (Cell.crack, 0.05),
            (Cell.moving_platform, 0.05),
            (Cell.trap, 0.05),
            (Cell.enemy_normal, 0.1),
        ]

        if not self.default:
            for index, item in enumerate(cell_p):
                itemlist = list(item)
                if itemlist[0] == Cell.enemy_normal:
                    itemlist[1] = 0.05
                item = tuple(itemlist)
                cell_p[index] = item

            cell_p.append((Cell.enemy_special, 0.05))

        cells = [cell for (cell, _) in cell_p]
        distrib = [p for (_, p) in cell_p]
        for h in range(n * m):
            cell = npchoice(cells, p=distrib)
            if grid[h] == '': grid[h] = cell

        assert self.valid(grid)
        return grid
Exemplo n.º 18
0
    def set_epithet(self):
        """Divine an appropriate epithet for this God. (See what I did there?)"""
        if self.divinity == human:
            obsession = random.choice(self.genome)
            if self.gender == female:
                self.epithet = 'ordinary woman'
            elif self.gender == male:
                self.epithet = 'ordinary man'
            else:
                self.epithet = 'ordinary human being'
            self.epithet += ' who loves ' + obsession
            return # Return early. The rest of the function deals with gods.

        if self.gender == female:
            title = 'Goddess'
        elif self.gender == male:
            title = 'God'
        else:
            title = 'Divine Being'
        if self.divinity == demi_god:
            title = 'Semi-' + title if self.gender == non_binary else 'Demi-' + title

        num_domains = npchoice([1,2,3,4], 1, p=[0.05, 0.35, 0.55, 0.05])[0]

        if num_domains == 1:
            template = '%s of %s'
        if num_domains == 2:
            template = '%s of %s and %s'
        elif num_domains == 3:
            template = '%s of %s, %s, and %s' # Oxford comma, the most divine punctuation.
        elif num_domains == 4:
            template = '%s of %s, %s, %s, and %s'

        self.domains = [d.title() for d in random.sample(self.genome, num_domains)]

        # Put it all together
        self.epithet = template % (title, *self.domains)
Exemplo n.º 19
0
def union2(*args):
    if DEBUG:
        print "[UNION] args:", args
    # args = [a.strip() if type(a) == str else a for a in args]
    actions = args
    p = None

    try:
        # Probability is given as list
        if isinstance(args[-1], List):
            p = args[-1]
            actions = args[:-1]
            if len(p) != len(actions):
                raise Exception('List of probabilities must have the same size as the number of arguments.')

        elif isinstance(args[-1], Number):
            px = args[-1]   # The probability is one number; is assigned to the first argument
            actions = args[:-1]
            py = 1.0 - px
            pz = py / (len(actions) - 1)  # The probability of the remainder of arguments is equally distributed
            p = [px] + [pz]*(len(actions) - 1)

    except TypeError as te:
        if type(args[-1]) == float:
            p = args[-1]
            actions = args[:-1]
        else:
            p = 1.0/len(args)
        actions = [c.replace('\n', '').replace('\r', '') for c in actions]

    except ValueError as ve:
        pass

    if DEBUG:
        print "Actions: ", actions
        print "p: ", p
    return npchoice(actions, p=p)
Exemplo n.º 20
0
def spawn_animal(grid, rivers=river, trees=trees):

    # Based in prob distribution, either spawn near a random river point, random tree point or random free point, while checking if point is legal.
    spawn_point = npchoice(["river", "trees", "free"], 1, p=[0.5, 0.4, 0.1])

    if spawn_point == "river":
        # First, select a random river point
        proximity_point = spawn_near_point(
            random.choice(rivers)[0],
            random.choice(rivers)[1])
        while get_grid_position(proximity_point[0], proximity_point[1],
                                grid) != " ":
            proximity_point = spawn_near_point(
                random.choice(rivers)[0],
                random.choice(rivers)[1])
    elif spawn_point == "trees":
        proximity_point = spawn_near_point(
            random.choice(trees)[0],
            random.choice(trees)[1])
        while get_grid_position(proximity_point[0], proximity_point[1],
                                grid) != " ":
            proximity_point = spawn_near_point(
                random.choice(rivers)[0],
                random.choice(rivers)[1])
    elif spawn_point == "free":
        proximity_point = generate_random_animal_positions(grid, 1)[0]
        while get_grid_position(proximity_point[0], proximity_point[1],
                                grid) != " ":
            proximity_point = generate_random_animal_positions(grid, 1)
    else:
        proximity_point = generate_random_animal_positions(grid, 1)[0]
        while get_grid_position(proximity_point[0], proximity_point[1],
                                grid) != " ":
            proximity_point = generate_random_animal_positions(grid, 1)

    return proximity_point
Exemplo n.º 21
0
 def takeSample(self, withReplacement, num):
     return npchoice(self.data, num, replace=withReplacement).tolist()
Exemplo n.º 22
0
def make_dca_spaced_pitch_sequence(offset,
                                   weights_option,
                                   length,
                                   pitch_range_slider,
                                   pitches=None,
                                   show_data=False,
                                   print_ly=False):
    if not pitches:
        pitches = list(
            range(pitch_range_slider.value[0],
                  pitch_range_slider.value[1] + 1))
    counts = [0] * len(pitches)

    weights = []

    if weights_option.value == 'equal':
        weights = [1] * len(
            pitches)  # how much to weigh each element's probability

    elif weights_option.value == 'favor lower':
        for i, pitch in enumerate(pitches):
            weight = (i + 1)**2
            weights.append(weight)
        weights.reverse()

    elif weights_option.value == 'favor center':
        middle = len(pitches) / 2
        for i in range(1, int(middle) + 1):
            weights.append(i**2)
        if middle.is_integer() == False:
            weights.append((middle + 0.5)**2)
        for i in range(int(middle), 0, -1):
            weights.append(i**2)

    elif weights_option.value == 'favor upper':
        for i, pitch in enumerate(pitches):
            weight = (i + 1)**2
            weights.append(weight)

    if show_data:
        print("Weights:", weights, "\n")

    pcprobs = get_probs(weights, counts)

    sequence = []

    note_count = 1
    for note in range(length.value):
        # random choice according to probability
        note_choice = npchoice(pitches, p=pcprobs)
        element = pitches.index(note_choice)
        note = note_choice + offset

        # add note to sequence
        sequence.append(note)

        # now update counts
        for i, pitch in enumerate(pitches):
            if i == element:
                counts[i] = 0
            else:
                counts[i] += 1

        # recalculate pcprobs
        pcprobs = get_probs(weights, counts)

        if show_data:
            print("Note ", note_count, ":")
            print("Random index choice:", note_choice)
            print("Current counts:", counts)
            print("Current probabilities:", pcprobs, "\n")

        note_count += 1

    if print_ly:
        output_sequence_ly(sequence)

    return sequence
Exemplo n.º 23
0
Arquivo: Agnt.py Projeto: myhamidi/RL
 def _RetRandomAction(self):
     if len(self.epsilon) > 1:
         return npchoice(a=self.actions, size=1, p=self.epsilon[1:])[0]
     else:
         return random.choice(self.actions)
Exemplo n.º 24
0
def chooseResponse(word):
    dictn=returnResponsesPercentage(word)
    response = list(dictn.keys())
    chance=list(dictn.values())
    chc=  npchoice(response,1,p=chance)
    return chc
Exemplo n.º 25
0
def vote(request, decision_group_id):
    decision_group = get_object_or_404(DecisionGroup, pk=decision_group_id)
    statistics = Statistics.load()

    try:
        selected_decision = decision_group.decision_set.get(
            pk=request.POST['decision'])
        persons = selected_decision.person_set.all()
        outcomes = selected_decision.outcome_set.all()
    except (KeyError, Decision.DoesNotExist):
        return render(
            request, 'polls/detail.html', {
                'decision_group': decision_group,
                'error_message': "You didn't select a decision.",
            })
    else:
        selected_decision.votes += 1

        # Set variables that  need to be set each decision
        request.session["who_died"] = []
        request.session["description"] = selected_decision.description
        request.session["killed_bool"] = False  # If you kill any this decision
        request.session[
            "killed"] = 0  # Refers to the number killed in this decision

        if decision_group.scenario_type == 'I':

            # Check if session variables exist
            # TODO: Loop through variables with same initial value instead of using multiple ifs

            if 'kill_count' not in request.session:
                request.session["kill_count"] = 0

            if 'male_kc' not in request.session:
                request.session["male_kc"] = 0

            if 'female_kc' not in request.session:
                request.session["female_kc"] = 0

            if 'age' not in request.session:
                request.session["age"] = []

            if 'status' not in request.session:
                request.session["status"] = 0.0

            if 'sum_status' not in request.session:
                request.session["sum_status"] = 0

            if 'status_percent' not in request.session:
                request.session["status_percent"] = 0.0

            if 'num_decisions' not in request.session:
                request.session["num_decisions"] = 0

            if 'decisions_range' not in request.session:
                request.session["decisions_range"] = []

            if 'kill_list' not in request.session:
                request.session["kill_list"] = []

            if 'male_kill_list' not in request.session:
                request.session["male_kill_list"] = []

            if 'female_kill_list' not in request.session:
                request.session["female_kill_list"] = []

            request.session["num_decisions"] += 1

            # Dicts for variables

            prob_dict = {
                'VL': range(0, 20),
                'LW': range(20, 40),
                'MD': range(40, 60),
                'HI': range(60, 80),
                'VH': range(80, 100)
            }

            age_dict = {'C': 'Child', 'A': 'Adult', 'O': 'Old'}

            status_dict = {'C': 'Criminal', 'A': 'Average', 'D': 'Doctor'}

            # Core logic for person deaths (prob is inverse because of ranges -- see the dict above)

            for person in persons:
                if (1.0 - choice(prob_dict[person.probability]) /
                        100.0) < random():
                    request.session["killed"] += 1
                    request.session["kill_count"] += 1
                    request.session["killed_bool"] = True
                    request.session["age"].append(person.age)
                    request.session["who_died"].append(1)

                    if person.age == 'C':
                        statistics.age_total -= 1
                    elif person.age == 'O':
                        statistics.age_total += 1

                    if person.status == 'D':
                        request.session["status"] -= 1.0
                        request.session["sum_status"] += 1
                        statistics.status_total -= 1.0
                        statistics.status_decisions += 1

                    elif person.status == 'C':
                        request.session["status"] += 1.0
                        request.session["sum_status"] += 1
                        statistics.status_total += 1.0
                        statistics.status_decisions += 1

                    if person.gender == 'M':
                        request.session["male_kc"] += 1
                        statistics.male_kc += 1
                    elif person.gender == 'F':
                        request.session["female_kc"] += 1
                        statistics.female_kc += 1

                else:
                    request.session["who_died"].append(0)

            # Post processing of deaths and other factors

            if request.session["sum_status"] != 0:
                request.session["status_percent"] = request.session[
                    "status"] / request.session["sum_status"]
            else:
                request.session["status_percent"] = 0

            if request.session["status_percent"] < 0:
                request.session[
                    "social_preference"] = "You have a {:.2f}% preference for criminals over doctors.".format(
                        abs(request.session["status_percent"]) * 100.0)
            elif request.session["status_percent"] > 0:
                request.session[
                    "social_preference"] = "You have a {:.2f}% preference for doctors over criminals.".format(
                        abs(request.session["status_percent"]) * 100.0)
            else:
                request.session[
                    "social_preference"] = "You have no preference for doctors vs. criminals."

            if request.session["age"]:
                request.session["most_killed_age"] = age_dict[max(
                    set(request.session["age"]),
                    key=request.session["age"].count)]

            # TODO: Remove decisions range, replace with range(num_decisions)
            request.session["decisions_range"].append(
                request.session["num_decisions"])
            request.session["kill_list"].append(request.session["kill_count"])
            request.session["male_kill_list"].append(
                request.session["male_kc"])
            request.session["female_kill_list"].append(
                request.session["female_kc"])

            # Statistics

            statistics.total_decisions += 1
            statistics.individual_decisions += 1
            statistics.kill_count += request.session["killed"]

            # Age preference

            if statistics.age_total < 0:
                statistics.age_preference = 'O'
            elif statistics.age_total > 0:
                statistics.age_preference = 'C'
            else:
                statistics.age_preference = 'A'

            # Status preference

            print(statistics.status_total)

            if statistics.status_total < 0:
                statistics.status_preference = 'C'
            elif statistics.status_total > 0:
                statistics.status_preference = 'D'
            else:
                statistics.status_preference = 'A'

            # Sanity checks
            #request.session["test"] = request.session["decisions_range"]
            #request.session["test2"] = request.session["kill_count"]

        else:
            if 'outcome' not in request.session:
                request.session["outcome"] = ""

            if 'confidence' not in request.session:
                request.session["confidence"] = 0

            if 'group_kill_count' not in request.session:
                request.session["group_kill_count"] = 0

            if 'lives_saved' not in request.session:
                request.session["lives_saved"] = 0

            if 'group_num_decisions' not in request.session:
                request.session["group_num_decisions"] = 0

            if 'group_decisions_range' not in request.session:
                request.session["group_decisions_range"] = []

            if 'group_kill_list' not in request.session:
                request.session["group_kill_list"] = []

            if 'lives_saved_list' not in request.session:
                request.session["lives_saved_list"] = []

            request.session["group_num_decisions"] += 1
            request.session["saved"] = 0

            selected_outcome = npchoice(
                [outcome for outcome in outcomes],
                p=[outcome.likelihood / 100.0 for outcome in outcomes])

            death_range = selected_outcome.max_value - selected_outcome.min_value

            conf_dict = {
                'LW': death_range / 4.0,
                'MD': death_range / 8.0,
                'HI': death_range / 16.0,
            }

            request.session["outcome"] = selected_outcome.outcome_description

            request.session["killed"] = int(
                round(
                    get_truncated_normal(
                        mean=selected_outcome.predicted_num_deaths,
                        sd=conf_dict[selected_outcome.confidence],
                        low=selected_outcome.min_value,
                        upp=selected_outcome.max_value)))

            if request.session["killed"] > 0:
                request.session["killed_bool"] = True

            request.session["group_kill_count"] += request.session["killed"]
            statistics.group_kill_count += request.session["killed"]

            saved = (selected_outcome.max_value - request.session["killed"])
            request.session["lives_saved"] += saved
            request.session["saved"] = saved

            request.session["group_decisions_range"].append(
                request.session["group_num_decisions"])
            request.session["group_kill_list"].append(
                request.session["group_kill_count"])
            request.session["lives_saved_list"].append(
                request.session["lives_saved"])

            if selected_outcome.confidence == 'LW':
                request.session["confidence"] += 0
                statistics.confidence_total += 1
            elif selected_outcome.confidence == 'MD':
                request.session["confidence"] += 2
            elif selected_outcome.confidence == 'HI':
                request.session["confidence"] += 4
                statistics.confidence_total -= 1

            # Formula is (2 - [sum of conf]/[2*number of decisions])/2, which simplifies to the below
            if request.session["group_num_decisions"] != 0:
                val = 1 - (request.session["confidence"] /
                           (4 * request.session["group_num_decisions"]))
                request.session[
                    "confidence_preference"] = "You have a {:.2f}% preference for risk.".format(
                        val * 100)
            else:
                request.session[
                    "confidence_preference"] = "Error with risk preference"

            statistics.total_decisions += 1
            statistics.group_decisions += 1
            statistics.lives_saved += saved

            interval = 2 * statistics.group_decisions / 3

            if statistics.confidence_total >= (
                    -statistics.group_decisions
            ) and statistics.confidence_total < (-statistics.group_decisions +
                                                 interval):
                statistics.confidence_preference = 'HI'
            elif statistics.confidence_total <= interval / 2:
                statistics.confidence_preference = 'MD'
            else:
                statistics.confidence_preference = 'LW'

        # Save to db and return the http response redirect to results page
        selected_decision.save()
        statistics.save()
        return HttpResponseRedirect(
            reverse('polls:results', args=(decision_group.id, )))
Exemplo n.º 26
0
 def takeSample(self, withReplacement, num):
     return npchoice(self.data, num, replace=withReplacement).tolist()