from otree.api import * import random import time import math import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import ScalarMappable from matplotlib.colors import Normalize import seaborn as sns import pandas as pd import os from ast import literal_eval from collections import OrderedDict import string random_start = True doc = """ "Widget to rank/reorder items". See http://sortablejs.github.io/Sortable/ for more examples. """ class Constants(BaseConstants): name_in_url = 'rank_widget' players_per_group = 30 num_rounds =50 with open("nationalities.txt") as f: nationalities = f.readlines() nationalities = [x.strip() for x in nationalities] nationalities = list(zip(range(len(nationalities)), nationalities)) nationalities = [list(tpl) for tpl in nationalities] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass def make_ati_field(label): return models.IntegerField( choices=[[1, 'completely disagree'], [2, 'largely disagree'], [3, 'slightly disagree'], [4, 'slightly agree'], [5, 'largely agree'], [6, 'completely agree']], label=label, widget=widgets.RadioSelect, ) class Player(BasePlayer): correct_city = models.StringField() team_result = models.StringField() start_time = models.IntegerField() end_time = models.IntegerField() time_stamp_page_ready = models.LongStringField() start_time_questions = models.IntegerField() start_time_outro = models.IntegerField() start_time_phase2_intro = models.IntegerField() start_time_intro = models.IntegerField() start_time_part1 = models.IntegerField() start_time_part2 = models.IntegerField() start_time_survey = models.IntegerField() start_time_questions = models.IntegerField() start_time_phase1_intro = models.IntegerField() start_time_chart = models.IntegerField() end_time_phase1_intro = models.IntegerField() end_time_phase2_intro = models.IntegerField() positionX_array = models.LongStringField() positionY_array = models.LongStringField() positionX_screen = models.LongStringField() positionY_screen = models.LongStringField() positionX_page = models.LongStringField() positionY_page = models.LongStringField() positionX_page_after = models.LongStringField() positionY_page_after = models.LongStringField() positionX_array_click = models.LongStringField() positionY_array_click = models.LongStringField() positionX_array_click_mousedown = models.LongStringField() positionY_array_click_mousedown = models.LongStringField() positionX_array_click_page = models.LongStringField() positionY_array_click_page = models.LongStringField() positionX_array_click_mousedown_page = models.LongStringField() positionY_array_click_mousedown_page = models.LongStringField() positionX_array_click_page_after = models.LongStringField() positionY_array_click_page_after = models.LongStringField() positionX_array_click_mousedown_page_after = models.LongStringField() positionY_array_click_mousedown_page_after = models.LongStringField() time_stamps_click_mousedown = models.LongStringField() time_stamps_click = models.LongStringField() hidden_array = models.LongStringField() time_stamps = models.LongStringField() positionY_array_clickarray_cities_infield = models.LongStringField() offset_timezone = models.LongStringField() position_drop0_otree = models.LongStringField() position_drop1_otree = models.LongStringField() position_drop2_otree = models.LongStringField() position_drop3_otree = models.LongStringField() position_drop4_otree = models.LongStringField() position_drop5_otree = models.LongStringField() position_drag1_otree = models.LongStringField() position_drag2_otree = models.LongStringField() position_drag3_otree = models.LongStringField() position_drag4_otree = models.LongStringField() position_drag5_otree = models.LongStringField() position_next_otree = models.LongStringField() position_help_otree = models.LongStringField() position_drop1_otree_after = models.LongStringField() position_drop2_otree_after = models.LongStringField() position_drop3_otree_after = models.LongStringField() position_drop4_otree_after = models.LongStringField() position_drop5_otree_after = models.LongStringField() time_stamp_page_ready_after = models.LongStringField() position_next_otree_after = models.LongStringField() position_help1_otree_after = models.LongStringField() position_help2_otree_after = models.LongStringField() position_position_draggable_otree_after = models.LongStringField() scrollX_array = models.LongStringField() scrollY_array = models.LongStringField() scrollX_array_after = models.LongStringField() scrollY_array_after = models.LongStringField() browser = models.LongStringField() user_data = models.LongStringField() screen_width = models.IntegerField() screen_height = models.IntegerField() availWidth = models.IntegerField() availHeight = models.IntegerField() colorDepth = models.IntegerField() pixelDepth = models.IntegerField() start_time_after = models.IntegerField() end_time_after = models.IntegerField() positionX_array_after = models.LongStringField() positionY_array_after = models.LongStringField() positionX_screen_after = models.LongStringField() positionY_screen_after = models.LongStringField() positionX_array_click_after = models.LongStringField() positionY_array_click_after = models.LongStringField() positionX_array_click_mousedown_after = models.LongStringField() positionY_array_click_mousedown_after = models.LongStringField() time_stamps_click_mousedown_after = models.LongStringField() hidden_array_after = models.LongStringField() time_stamps_after = models.LongStringField() time_stamps_click_after = models.LongStringField() list_of_best_ranked_cities= models.LongStringField() bonus_final_answers = models.FloatField() bonus_team_answers = models.FloatField() attention_question_1 = models.BooleanField() attention_question_2 = models.BooleanField() prolific_id = models.StringField(label="Please provide your Prolific participant ID:") prolific_id_checkup = models.StringField(label="Please reenter your Prolific participant ID:") tie = models.BooleanField() all_equal_voted_options = models.LongStringField() browser_after = models.LongStringField() user_data_after = models.LongStringField() screen_width_after = models.IntegerField() screen_height_after = models.IntegerField() availWidth_after = models.IntegerField() availHeight_after = models.IntegerField() colorDepth_after = models.IntegerField() pixelDepth_after = models.IntegerField() array_resultfield = models.LongStringField(blank=True) array_cities_infield = models.LongStringField(blank=True) array_resultfield_for_python_2 = models.LongStringField(blank=True) array_cities_infield_for_python = models.LongStringField() array_resultfield_for_python_all_2 = models.LongStringField(blank=True) array_cities_infield_all = models.LongStringField(blank=True) array_resultfield_all = models.LongStringField(blank=True) firstelement_check = models.LongStringField(blank=True) secondelement_check = models.LongStringField(blank=True) thirdelement_check = models.LongStringField(blank=True) fourthelement_check = models.LongStringField(blank=True) fifthelement_check = models.LongStringField(blank=True) feedback_participant = models.LongStringField(blank=True, label= "Would you like to give us some feedback?") random_id = models.LongStringField() results_shown_stringid0 = models.LongStringField() results_shown_otreeid0 = models.LongStringField() results_shown_stringid1 = models.LongStringField() results_shown_otreeid1 = models.LongStringField() results_shown_stringid2 = models.LongStringField() results_shown_otreeid2 = models.LongStringField() results_shown_stringid3 = models.LongStringField() results_shown_otreeid3 = models.LongStringField() results_shown_stringid4 = models.LongStringField() results_shown_otreeid4 = models.LongStringField() mail_info = models.LongStringField(blank=True) age = models.IntegerField(label="What is your age?", max=100) gender = models.IntegerField(label="What is your gender?",choices=[ [1, 'male'], [2, 'female'], [3, 'diverse'], [4, 'No answer'] ], widget=widgets.RadioSelect ) nationality = models.IntegerField( label="What is your nationality?", choices = Constants.nationalities, blank=True ) #gender = models.IntegerField(choices=[[0, 'Man' ],[1, 'Non-binary' ],[2, 'Woman' ],[3, 'Prefer to self-describe, below' ]], label='How do you identify') #gender_self = models.StringField(label='Self-describe:') educ = models.IntegerField(choices=[[0, 'No Formal Schooling' ], [1, '1st Grade' ], [2, '2nd Grade' ], [3, '3rd Grade' ], [4, '4th Grade' ], [5, '5th Grade' ], [6, '6th Grade' ], [7, '7th Grade' ], [8, '8th Grade' ], [9, '9th Grade' ], [10, '10th Grade' ], [11, '11th Grade' ], [12, '12th Grade No Diploma' ], [13, 'High School Graduate' ], [14, 'General Equivalency Diploma' ], [15, 'Some College, No Degree' ], [16, 'VoTech Program' ], [17, 'Associate Degree' ], [18, 'Bachelor Degree' ], [19, 'Masters Degree' ], [20, 'Professional Doctorate Degree' ], [21, 'Academic Doctorate Degree' ], [22, 'Refused' ], [23, 'Dont Know']], label='What is the highest level of education you have achieved?') ati1 = make_ati_field('I like to occupy myself in greater detail with technical systems.') ati2 = make_ati_field('I like testing the functions of new technical systems.') ati3 = make_ati_field('I predominantly deal with technical systems because I have to.') ati4 = make_ati_field('When I have a new technical system in front of me, I try it out intensively.') ati5 = make_ati_field('I enjoy spending time becoming acquainted with a new technical system.') ati6 = make_ati_field('It is enough for me that a technical system works; I don’t care how or why.') ati7 = make_ati_field('I try to understand how a technical system exactly works.') ati8 = make_ati_field('It is enough for me to know the basic functions of a technical system.') ati9 = make_ati_field('I try to make full use of the capabilities of a technical system.') satisfaction = models.IntegerField( label = 'Overall, how satisfied were you with this experiment?', choices=[ [1,"Extremely dissatisfied"], [2,"Somewhat dissatisfied"], [3,"Neither satisfied nor dissatisfied"], [4,"Somewhat satisfied"], [5,"Extremely satisfied"] ], widget=widgets.RadioSelect ) #def firstelement_check_error_message(player, value): # if value !='is_rated': # print('value 1 is', value) # return 'Feld 1 wurde nicht zugeordnet' #def secondelement_check_error_message(player, value): # print('value 2 is', value) # if value !='is_rated': # return 'Feld 2 wurde nicht zugeordnet' #def thirdelement_check_error_message(player, value): # if value !='is_rated': # print('value 3 is', value) # return 'Feld 3 wurde nicht zugeordnet' #def fourthelement_check_error_message(player, value):# # print('value 4 is', value) # if value !='is_rated': # return 'Feld 4 wurde nicht zugeordnet' #def fifthelement_check_error_message(player, value): # print('value 5 is', value) # if value !='is_rated': # return 'Feld 5 wurde nicht zugeordnet' class Intro(Page): form_fields = ['prolific_id', 'prolific_id_checkup'] form_model = 'player' def vars_for_template(player): player.start_time_intro = int(time.time()) def is_displayed(player): return player.round_number == 1 def error_message(player, values): if values["prolific_id"] != values["prolific_id_checkup"]: return "Error: The Prolific IDs did not match. Please try again." if values["prolific_id"] == None or values["prolific_id_checkup"] == None: return "Error: Please fill both fields asking for your Prolific ID." class Instructions_part1(Page): form_model = 'player' def vars_for_template(player): player.start_time_part1 = int(time.time()) def is_displayed(player): return player.round_number == 1 class Survey(Page): form_model = 'player' form_fields = ['age', 'educ', 'nationality', 'gender'] def vars_for_template(player): player.start_time_survey = int(time.time()) def is_displayed(player): return player.round_number == 1 class Instructions_part2(Page): form_model = 'player' def vars_for_template(player): player.start_time_part2 = int(time.time()) def is_displayed(player): return player.round_number == 1 class Phase_One(Page): form_model = 'player' form_fields = ['positionX_array', 'positionY_array', 'positionX_screen', 'positionY_screen', 'positionX_page', 'positionY_page', 'hidden_array','time_stamps', 'positionX_array_click', 'positionY_array_click', 'array_cities_infield', 'array_resultfield', "array_cities_infield_all", "array_resultfield_all", "firstelement_check", "secondelement_check", "thirdelement_check","fourthelement_check", "fifthelement_check", 'positionX_array_click_mousedown', 'positionY_array_click_mousedown', 'time_stamps_click_mousedown', 'positionX_array_click', 'positionY_array_click', 'time_stamps_click', 'browser', 'user_data', 'screen_width', 'screen_height', 'availWidth', 'availHeight', 'colorDepth', 'pixelDepth', 'time_stamp_page_ready', 'positionX_array_click_mousedown_page','positionY_array_click_mousedown_page', 'positionX_array_click_page', 'positionY_array_click_page', 'position_drop0_otree', 'position_drop1_otree', 'position_drop2_otree', 'position_drop3_otree', 'position_drop4_otree', 'position_drop5_otree', 'position_drag1_otree','position_drag2_otree','position_drag3_otree','position_drag4_otree','position_drag5_otree', 'position_next_otree', 'position_help_otree', 'scrollX_array', 'scrollY_array', 'offset_timezone'] #Error-Handling (https://otree.readthedocs.io/en/latest/forms.html#field-name-error-message) def error_message(player, values): if values["firstelement_check"] != "is_rated" or values["secondelement_check"] != "is_rated" or values["thirdelement_check"] != "is_rated" or values["fourthelement_check"] != "is_rated" or values["fifthelement_check"] != "is_rated": return "Error: Please assign every location to a result field to continue." def vars_for_template(player): correct_city, choices = get_data_for_quiz(player.round_number, False) player.start_time = int(time.time()) #random.shuffle(choices) chosen_image_link = "random_sample_otree/" + 'image_' + str(player.round_number-1) + '.jpeg' image_link_helpbutton = "help_button_image.png" player.correct_city = correct_city city1, city2, city3, city4, city5 = choices[0], choices[1], choices[2], choices[3], choices[4] return {"image_link_helpbutton": image_link_helpbutton, "choices":choices,"chosen_image_link":chosen_image_link,"city1":city1,"city2": city2,"city3":city3,"city4":city4,"city5":city5} def before_next_page(player, timeout_happened): player.random_id = get_random_string(20) player.end_time = int(time.time()) Order_helpclass.create(player=player, time=player.end_time, order_player = player.id_in_group) parsed_array_cities_infield = player.array_cities_infield.split(",") parsed_array_resultfield = player.array_resultfield.split(",") parsed_array_resultfield = list(map(int, parsed_array_resultfield)) x = player.positionX_array.split(",") y = player.positionY_array.split(",") time_stamp = player.time_stamps.split(",") y = list(map(int, y)) x = list(map(int, x)) time_stamp = list(map(int, time_stamp)) #make_plot(x, y, time_stamp, player) class Phase_One_Instructions(Page): form_model = 'player' form_fields = ['positionX_array', 'positionY_array', 'time_stamps', 'array_cities_infield', 'array_resultfield', "array_cities_infield_all", "array_resultfield_all", "firstelement_check", "secondelement_check", "thirdelement_check","fourthelement_check", "fifthelement_check"] #Error-Handling (https://otree.readthedocs.io/en/latest/forms.html#field-name-error-message) def error_message(player, values): if values["firstelement_check"] != "is_rated" or values["secondelement_check"] != "is_rated" or values["thirdelement_check"] != "is_rated" or values["fourthelement_check"] != "is_rated" or values["fifthelement_check"] != "is_rated": return "Error: Please assign every location to a result field to continue." def vars_for_template(player): correct_city, choices = get_data_for_quiz(player.round_number, True) player.start_time_phase1_intro = int(time.time()) #random.shuffle(choices) chosen_image_link = "random_sample_otree/" + 'image_' + str(49) + '.jpeg' player.correct_city = correct_city city1, city2, city3, city4, city5 = choices[0], choices[1], choices[2], choices[3], choices[4] return {"choices":choices,"chosen_image_link":chosen_image_link,"city1":city1,"city2": city2,"city3":city3,"city4":city4,"city5":city5} def before_next_page(player, timeout_happened): player.end_time_phase1_intro = int(time.time()) Order_helpclass_introduction.create(player=player, time=player.end_time_phase1_intro, order_player = player.id_in_group) parsed_array_cities_infield = player.array_cities_infield.split(",") parsed_array_resultfield = player.array_resultfield.split(",") parsed_array_resultfield = list(map(int, parsed_array_resultfield)) x = player.positionX_array.split(",") y = player.positionY_array.split(",") time_stamp = player.time_stamps.split(",") y = list(map(int, y)) x = list(map(int, x)) time_stamp = list(map(int, time_stamp)) def is_displayed(player): return player.round_number == 1 class Phase_Two(Page): form_model = 'player' form_fields = ['array_resultfield_for_python_2', 'array_resultfield_for_python_all_2', 'hidden_array_after', 'positionX_array_after', 'positionY_array_after', 'time_stamps_after', 'time_stamps_click_after', 'positionX_array_click_mousedown_after', 'positionY_array_click_mousedown_after', 'time_stamps_click_mousedown_after', 'positionX_array_click_after', 'positionY_array_click_after', 'positionX_page_after', 'positionY_page_after', 'positionX_screen_after', 'positionY_screen_after', 'browser_after', 'user_data_after', 'screen_width_after', 'screen_height_after', 'availWidth_after', 'availHeight_after', 'colorDepth_after', 'pixelDepth_after', 'time_stamp_page_ready_after', 'position_drop1_otree_after','position_drop2_otree_after','position_drop3_otree_after','position_drop4_otree_after','position_drop5_otree_after', 'position_next_otree_after', 'position_help1_otree_after', 'position_help2_otree_after', 'position_position_draggable_otree_after', 'scrollX_array_after', 'scrollY_array_after', 'positionX_array_click_page_after', 'positionY_array_click_page_after','positionX_array_click_mousedown_page_after', 'positionY_array_click_mousedown_page_after'] def vars_for_template(player): player.start_time_after = int(time.time()) #get and parse data of 4 players that finished round before current player data_before = Order_helpclass.filter() data_before_index = data_before.copy() number_of_players_per_group=5 for x in range(len(data_before_index)): if(data_before_index[x].player.round_number != player.round_number): data_before.remove(data_before_index[x]) correct_city, choices = get_data_for_quiz(player.round_number, False) if(len(data_before) >= 1): parsed_array_resultfield = data_before[len(data_before)-1].player.array_resultfield.split(",") parsed_array_cities_infield = data_before[len(data_before)-1].player.array_cities_infield.split(",") player.results_shown_stringid0 = data_before[len(data_before)-1].player.random_id player.results_shown_otreeid0 = str(data_before[len(data_before)-1].player.id_in_group) else: parsed_array_resultfield = get_random_result() parsed_array_cities_infield = choices player.results_shown_stringid0 = str(parsed_array_resultfield) player.results_shown_otreeid0 = "random choice player 0" print("random choice player") #for x in range(len(data_before_index)): # if(data_before_index[x].player == player): # data_before.remove(data_before_index[x]) if(len(data_before) >= 2): parsed_array_resultfield1 = data_before[len(data_before)-2].player.array_resultfield.split(",") parsed_array_cities_infield1 = data_before[len(data_before)-2].player.array_cities_infield.split(",") player.results_shown_stringid1 = data_before[len(data_before)-2].player.random_id player.results_shown_otreeid1 = str(data_before[len(data_before)-2].player.id_in_group) else: if random_start == True: parsed_array_resultfield1 = get_random_result() parsed_array_cities_infield1 = choices player.results_shown_stringid1 = str(parsed_array_resultfield1) player.results_shown_otreeid1 = "random choice player 1" print("random choice player 1") else: parsed_array_resultfield1, parsed_array_cities_infield1, player.results_shown_stringid1, player.results_shown_otreeid1 = get_results_from_old_round(player.round_number, len(data_before), 1) print(parsed_array_resultfield1) print(parsed_array_cities_infield1) if(len(data_before) >= 3): parsed_array_resultfield2 = data_before[len(data_before)-3].player.array_resultfield.split(",") parsed_array_cities_infield2 = data_before[len(data_before)-3].player.array_cities_infield.split(",") player.results_shown_stringid2 = data_before[len(data_before)-3].player.random_id player.results_shown_otreeid2 = str(data_before[len(data_before)-3].player.id_in_group) else: if random_start == True: parsed_array_resultfield2 = get_random_result() parsed_array_cities_infield2 = choices player.results_shown_stringid2 = str(parsed_array_resultfield2) player.results_shown_otreeid2 = "random choice player 2" print("random choice player 2") else: parsed_array_resultfield2, parsed_array_cities_infield2, player.results_shown_stringid2, player.results_shown_otreeid2, = get_results_from_old_round(player.round_number, len(data_before), 2) if(len(data_before) >= 4): parsed_array_resultfield3 = data_before[len(data_before)-4].player.array_resultfield.split(",") parsed_array_cities_infield3 = data_before[len(data_before)-4].player.array_cities_infield.split(",") player.results_shown_stringid3 = data_before[len(data_before)-4].player.random_id player.results_shown_otreeid3 = str(data_before[len(data_before)-4].player.id_in_group) else: if random_start == True: parsed_array_resultfield3 = get_random_result() parsed_array_cities_infield3 = choices player.results_shown_stringid3 = str(parsed_array_resultfield3) player.results_shown_otreeid3 = "random choice player 3" print("random choice player 3") else: parsed_array_resultfield3, parsed_array_cities_infield3, player.results_shown_stringid3, player.results_shown_otreeid3, = get_results_from_old_round(player.round_number, len(data_before), 3) if(len(data_before) >= 5): parsed_array_resultfield4 = data_before[len(data_before)-5].player.array_resultfield.split(",") parsed_array_cities_infield4 = data_before[len(data_before)-5].player.array_cities_infield.split(",") player.results_shown_stringid4 = data_before[len(data_before)-5].player.random_id player.results_shown_otreeid4 = str(data_before[len(data_before)-5].player.id_in_group) else: if random_start == True: parsed_array_resultfield4 = get_random_result() parsed_array_cities_infield4 = choices player.results_shown_stringid4 = str(parsed_array_resultfield4) player.results_shown_otreeid4 = "random choice player 4" print("random choice player 4") else: parsed_array_resultfield4, parsed_array_cities_infield4, player.results_shown_stringid4, player.results_shown_otreeid4, = get_results_from_old_round(player.round_number, len(data_before), 4) #add rejected cities to lists random.shuffle(choices) random.shuffle(choices) #prepare parsed rating for charts parsed_array_resultfield, parsed_array_cities_infield_tag_string, parsed_array_cities_infield, best_ranked_city = raking_results_to_charts_less_color(parsed_array_cities_infield, parsed_array_resultfield, 0) parsed_array_resultfield1, parsed_array_cities_infield_tag_string1, parsed_array_cities_infield1, best_ranked_city1 = raking_results_to_charts_less_color(parsed_array_cities_infield1, parsed_array_resultfield1, 1) parsed_array_resultfield2, parsed_array_cities_infield_tag_string2, parsed_array_cities_infield2, best_ranked_city2 = raking_results_to_charts_less_color(parsed_array_cities_infield2, parsed_array_resultfield2, 2) parsed_array_resultfield3, parsed_array_cities_infield_tag_string3, parsed_array_cities_infield3, best_ranked_city3 = raking_results_to_charts_less_color(parsed_array_cities_infield3, parsed_array_resultfield3, 3) parsed_array_resultfield4, parsed_array_cities_infield_tag_string4, parsed_array_cities_infield4, best_ranked_city4 = raking_results_to_charts_less_color(parsed_array_cities_infield4, parsed_array_resultfield4, 4) city1, city2, city3, city4, city5 = parsed_array_cities_infield4[0], parsed_array_cities_infield4[1], parsed_array_cities_infield4[2], parsed_array_cities_infield4[3], parsed_array_cities_infield4[4] list_of_best_ranked_cities = [best_ranked_city1, best_ranked_city2, best_ranked_city3, best_ranked_city4] player.list_of_best_ranked_cities = str(list_of_best_ranked_cities) for_team_chart_player0 = [0,0,0,0,0] for_team_chart_player1 = [0,0,0,0,0] for_team_chart_player2 = [0,0,0,0,0] for_team_chart_player3 = [0,0,0,0,0] for_team_chart_player4 = [0,0,0,0,0] index = 0 for city in parsed_array_cities_infield: if city == best_ranked_city: for_team_chart_player0[index]= 1 if city == best_ranked_city1: for_team_chart_player1[index]= 1 if city == best_ranked_city2: for_team_chart_player2[index]= 1 if city == best_ranked_city3: for_team_chart_player3[index]= 1 if city == best_ranked_city4: for_team_chart_player4[index]= 1 index = index + 1 text_chart_player = "Your Answer: " + str(best_ranked_city) return {"parsed_array_resultfield": parsed_array_resultfield, "parsed_array_cities_infield":parsed_array_cities_infield_tag_string, "parsed_array_resultfield1": parsed_array_resultfield1, "parsed_array_resultfield2": parsed_array_resultfield2, "parsed_array_resultfield3": parsed_array_resultfield3, "parsed_array_resultfield4": parsed_array_resultfield4, "city1":city1, "city2":city2, "city3":city3, "city4":city4, "city5":city5, "for_team_chart_player0": for_team_chart_player0, "for_team_chart_player1": for_team_chart_player1, "for_team_chart_player2": for_team_chart_player2, "for_team_chart_player3": for_team_chart_player3, "for_team_chart_player4": for_team_chart_player4, "text_chart_player": text_chart_player} def before_next_page(player, timeout_happened): player.end_time_after = int(time.time()) list_of_best_ranked_cities = player.list_of_best_ranked_cities.split(",") list_of_best_ranked_cities = [s.replace("[", "") for s in list_of_best_ranked_cities] list_of_best_ranked_cities = [s.replace("]", "") for s in list_of_best_ranked_cities] list_of_best_ranked_cities = [s.replace(" '", "") for s in list_of_best_ranked_cities] list_of_best_ranked_cities = [s.replace("'", "") for s in list_of_best_ranked_cities] given_answer_player = player.array_resultfield_for_python_2.split(",")[0] list_of_best_ranked_cities.append(given_answer_player) #team_result = max(set(list_of_best_ranked_cities), key = list_of_best_ranked_cities.count) max_count = 0 for element in list_of_best_ranked_cities: count = list_of_best_ranked_cities.count(element) if count > max_count: max_count = count all_cities_max_count = [] for element in list_of_best_ranked_cities: count = list_of_best_ranked_cities.count(element) if count == max_count: all_cities_max_count.append(element) all_equal_voted_options = set(all_cities_max_count) if len(all_equal_voted_options) > 1: player.tie = True else: player.tie = False team_result =random.sample(all_equal_voted_options, 1) player.team_result = team_result[0] player.all_equal_voted_options = str(all_equal_voted_options) if player.round_number == 14: if given_answer_player == "Paris (France)": player.attention_question_1 = True else: player.attention_question_1 = False if player.round_number == 30: if given_answer_player == "Athens (Greece)": player.attention_question_2 = True else: player.attention_question_2 = False def error_message(player, values): if len(values['array_resultfield_for_python_2']) > 0: print(values['array_resultfield_for_python_2']) else: return "Error: Please drag the circle to your final answer." class Phase_Two_Instructions_Chart(Page): form_model = 'player' def vars_for_template(player): player.start_time_chart = int(time.time()) data_before = Order_helpclass_introduction.filter() data_before_index = data_before.copy() number_of_players_per_group=5 for x in range(len(data_before_index)): if(data_before_index[x].player.round_number != player.round_number): data_before.remove(data_before_index[x]) correct_city, choices = get_data_for_quiz(player.round_number, True) parsed_array_resultfield = data_before[len(data_before)-1].player.array_resultfield.split(",") parsed_array_cities_infield = data_before[len(data_before)-1].player.array_cities_infield.split(",") parsed_array_resultfield1 = get_random_result() parsed_array_cities_infield1 = choices parsed_array_resultfield2 = get_random_result() parsed_array_cities_infield2 = choices parsed_array_resultfield3 = get_random_result() parsed_array_cities_infield3 = choices parsed_array_resultfield4 = get_random_result() parsed_array_cities_infield4 = choices #add rejected cities to lists random.shuffle(choices) #prepare parsed rating for charts parsed_array_resultfield, parsed_array_cities_infield_tag_string, parsed_array_cities_infield, best_ranked_city = raking_results_to_charts_less_color(parsed_array_cities_infield, parsed_array_resultfield, 0) return {"parsed_array_cities_infield": parsed_array_cities_infield_tag_string} def is_displayed(player): return player.round_number == 1 class Phase_Two_Instructions(Page): form_model = 'player' form_fields = ['array_resultfield_for_python_2', 'array_resultfield_for_python_all_2', 'positionX_array_after', 'positionY_array_after' , 'time_stamps_after'] def vars_for_template(player): player.start_time_phase2_intro = int(time.time()) #get and parse data of 4 players that finished round before current player data_before = Order_helpclass_introduction.filter() data_before_index = data_before.copy() number_of_players_per_group=5 for x in range(len(data_before_index)): if(data_before_index[x].player.round_number != player.round_number): data_before.remove(data_before_index[x]) correct_city, choices = get_data_for_quiz(player.round_number, True) parsed_array_resultfield = data_before[len(data_before)-1].player.array_resultfield.split(",") parsed_array_cities_infield = data_before[len(data_before)-1].player.array_cities_infield.split(",") parsed_array_resultfield1 = get_random_result() parsed_array_cities_infield1 = choices parsed_array_resultfield2 = get_random_result() parsed_array_cities_infield2 = choices parsed_array_resultfield3 = get_random_result() parsed_array_cities_infield3 = choices parsed_array_resultfield4 = get_random_result() parsed_array_cities_infield4 = choices #add rejected cities to lists random.shuffle(choices) #prepare parsed rating for charts parsed_array_resultfield, parsed_array_cities_infield_tag_string, parsed_array_cities_infield, best_ranked_city = raking_results_to_charts_less_color(parsed_array_cities_infield, parsed_array_resultfield, 0) parsed_array_resultfield1, parsed_array_cities_infield_tag_string1, parsed_array_cities_infield1, best_ranked_city1 = raking_results_to_charts_less_color(parsed_array_cities_infield1, parsed_array_resultfield1, 1) parsed_array_resultfield2, parsed_array_cities_infield_tag_string2, parsed_array_cities_infield2, best_ranked_city2 = raking_results_to_charts_less_color(parsed_array_cities_infield2, parsed_array_resultfield2, 2) parsed_array_resultfield3, parsed_array_cities_infield_tag_string3, parsed_array_cities_infield3, best_ranked_city3 = raking_results_to_charts_less_color(parsed_array_cities_infield3, parsed_array_resultfield3, 3) parsed_array_resultfield4, parsed_array_cities_infield_tag_string4, parsed_array_cities_infield4, best_ranked_city4 = raking_results_to_charts_less_color(parsed_array_cities_infield4, parsed_array_resultfield4, 4) city1, city2, city3, city4, city5 = parsed_array_cities_infield4[0], parsed_array_cities_infield4[1], parsed_array_cities_infield4[2], parsed_array_cities_infield4[3], parsed_array_cities_infield4[4] list_of_best_ranked_cities = [best_ranked_city1, best_ranked_city2, best_ranked_city3, best_ranked_city4] #team_result = max(set(list_of_best_ranked_cities), key = list_of_best_ranked_cities.count) for_team_chart_player0 = [0,0,0,0,0] for_team_chart_player1 = [0,0,0,0,0] for_team_chart_player2 = [0,0,0,0,0] for_team_chart_player3 = [0,0,0,0,0] for_team_chart_player4 = [0,0,0,0,0] index = 0 for city in parsed_array_cities_infield: if city == best_ranked_city: for_team_chart_player0[index]= 1 if city == best_ranked_city1: for_team_chart_player1[index]= 1 if city == best_ranked_city2: for_team_chart_player2[index]= 1 if city == best_ranked_city3: for_team_chart_player3[index]= 1 if city == best_ranked_city4: for_team_chart_player4[index]= 1 index = index + 1 text_chart_player = "Your Answer: " + str(best_ranked_city) return {"parsed_array_resultfield": parsed_array_resultfield, "parsed_array_cities_infield":parsed_array_cities_infield_tag_string, "parsed_array_resultfield1": parsed_array_resultfield1, "parsed_array_resultfield2": parsed_array_resultfield2, "parsed_array_resultfield3": parsed_array_resultfield3, "parsed_array_resultfield4": parsed_array_resultfield4, "city1":city1, "city2":city2, "city3":city3, "city4":city4, "city5":city5, "for_team_chart_player0": for_team_chart_player0, "for_team_chart_player1": for_team_chart_player1, "for_team_chart_player2": for_team_chart_player2, "for_team_chart_player3": for_team_chart_player3, "for_team_chart_player4": for_team_chart_player4, "text_chart_player": text_chart_player} def before_next_page(player, timeout_happened): player.end_time_phase2_intro = int(time.time()) def is_displayed(player): return player.round_number == 1 #Error-Handling (https://otree.readthedocs.io/en/latest/forms.html#field-name-error-message) def error_message(player, values): if len(values['array_resultfield_for_python_2']) > 0: print(values['array_resultfield_for_python_2']) else: return "Error: Please drag the circle to your final answer." class Solution(Page): form_model = 'player' def vars_for_template(player): correct_city, choices = get_data_for_quiz(player.round_number, False) own_result = player.array_resultfield_for_python_2.split(",")[0] answerstring = "Your results in this round:" all_equal_voted_options = player.all_equal_voted_options tie = player.tie team_result = player.team_result if own_result == correct_city: correctness_answer = "correct" else: correctness_answer = "wrong" if team_result == correct_city: correctness_answer_team = "correct" else: correctness_answer_team = "wrong" return{"correct_city": correct_city, "correctness_answer": correctness_answer, "correctness_answer_team": correctness_answer_team, "answerstring": answerstring} class Result(Page): form_model = 'player' def vars_for_template(player): answerstring = "Your Results:" players_all = player.in_all_rounds() all_own_results= [] all_team_results = [] all_correct_cities= [] number_correct_final_answers = 0 number_correct_final_answers_team = 0 number_played_rounds = 0 for player_in_round_x in players_all: number_played_rounds = number_played_rounds + 1 own_result = player_in_round_x.array_resultfield_for_python_2.split(",")[0] teamresult = player_in_round_x.team_result correct_city, choices = get_data_for_quiz(player_in_round_x.round_number, False) if own_result == correct_city: number_correct_final_answers = number_correct_final_answers + 1 if teamresult == correct_city: number_correct_final_answers_team = number_correct_final_answers_team + 1 all_own_results.append(own_result) all_correct_cities.append(correct_city) all_team_results.append(teamresult) accuracy = round(number_correct_final_answers/number_played_rounds,2) accuracy_team = round(number_correct_final_answers_team / number_played_rounds,2) bonus_final_anwers = accuracy bonus_final_anwers_team = accuracy_team accuracy_to_display = round(accuracy *100) accuracy_to_display = str(accuracy_to_display) + "%" accuracy_to_display_team = round(accuracy_team *100) accuracy_to_display_team = str(accuracy_to_display_team) + "%" bonus_final_anwers = round(bonus_final_anwers * 1,2) bonus_final_anwers_team = round(bonus_final_anwers_team * 1,2) bonus_final_anwers = str(bonus_final_anwers) + "£" bonus_final_anwers_team = str(bonus_final_anwers_team) + "£" if player_in_round_x.round_number == 14: attention_question_1 = player_in_round_x.attention_question_1 if player_in_round_x.round_number == 30: attention_question_2 = player_in_round_x.attention_question_2 player.bonus_final_answers = accuracy player.bonus_team_answers = accuracy_team both_attentiontests_false = False if attention_question_1 == False and attention_question_2 == False: both_attentiontests_false = True return{"answerstring": answerstring, "all_own_results": all_own_results,"all_team_results": all_team_results, "all_correct_cities": all_correct_cities, "accuracy_to_display": accuracy_to_display, "bonus_final_anwers": bonus_final_anwers, "accuracy_to_display_team": accuracy_to_display_team, "bonus_final_anwers_team": bonus_final_anwers_team, "number_played_rounds":number_played_rounds, "both_attentiontests_false": both_attentiontests_false} def is_displayed(self): return self.round_number == Constants.num_rounds class Questions(Page): form_model = 'player' form_fields = ['ati1', 'ati2', 'ati3', 'ati4', 'ati5', 'ati6', 'ati7', 'ati8', 'ati9'] def vars_for_template(player): player.start_time_questions = int(time.time()) rng = range(1,7) labels = ['completely disagree', 'largely disagree', 'slightly disagree', 'slightly agree', 'largely agree', 'completely agree'] return {"rng": rng, "labels": labels} def is_displayed(self): return self.round_number == Constants.num_rounds class Outro(Page): form_model = 'player' form_fields = ['mail_info', 'satisfaction', "feedback_participant"] def vars_for_template(player): player.start_time_outro = int(time.time()) def is_displayed(self): return self.round_number == Constants.num_rounds def before_next_page(player, timeout_happened): print(player.satisfaction) class BacktoProlific(Page): form_model = 'player' def is_displayed(self): return self.round_number == Constants.num_rounds class Order_helpclass(ExtraModel): player = models.Link(Player) time = models.IntegerField() order_player = models.StringField() class Order_helpclass_introduction(ExtraModel): player = models.Link(Player) time = models.IntegerField() order_player = models.StringField() def get_data_for_quiz(round_number, instuction_round): images_table = pd.read_csv('sample_images_key_otree.csv') if round_number==1 and instuction_round== True: choices = images_table['all_options_cities_string'].iloc[49] choices = literal_eval(choices) correct_city = images_table['city_string'].iloc[49] else: choices = images_table['all_options_cities_string'].iloc[round_number-1] choices = literal_eval(choices) correct_city = images_table['city_string'].iloc[round_number-1] return correct_city, choices def get_results_from_old_round(round_number, lenght_of_existing_data, player_loaded): results_last_run = pd.read_csv('data_from_last_run.csv', sep= ",") player_loaded = lenght_of_existing_data + 3 - player_loaded parsed_array_resultfield_x = results_last_run['rank_widget.'+ str(round_number) + '.player.array_resultfield'][player_loaded].split(",") parsed_array_cities_infield_x =results_last_run['rank_widget.'+ str(round_number) + '.player.array_cities_infield'][player_loaded].split(",") results_shown_stringid_x =results_last_run['rank_widget.'+ str(round_number) + '.player.random_id'][player_loaded] results_shown_otreeid_x =str(results_last_run['rank_widget.'+ str(round_number) + '.player.id_in_group'][player_loaded]) return parsed_array_resultfield_x, parsed_array_cities_infield_x, results_shown_stringid_x, results_shown_otreeid_x def get_random_result(): random_result = np.zeros(np.random.randint(0,4)) random_result2 = random.sample(range(6), 5-len(random_result)) random_result = np.concatenate((random_result, random_result2), axis=0) np.random.shuffle(random_result) random_result_str = list() for elements in random_result: random_result_str.append(str(elements)) return random_result def calculate_distance(x1, y1, x2, y2): distance = math.sqrt((x1-x2)**2 + (y1-y2)**2) return distance def calculate_milisec_used(time1, time2): milisec = time2-time1 return milisec def calculate_speed(distance, milisec): if (milisec == 0): speed = 0 else: speed = distance/milisec return speed def calculate_speed_every_milisec(milisec_array, distances_array, x_array, y_array): indices_tobe_removed = [] for measurement in range(len(milisec_array)-1): if (milisec_array[measurement] == 0 or distances_array[measurement] == 0): indices_tobe_removed.append(measurement) distances_array[measurement + 1] = distances_array[measurement + 1] + distances_array[measurement] indices_tobe_removed = sorted(indices_tobe_removed, reverse=True) for idx in indices_tobe_removed: milisec_array.pop(idx) distances_array.pop(idx) x_array.pop(idx) y_array.pop(idx) return milisec_array, distances_array, x_array, y_array def make_plot(x, y, time_stamp, player): new_y =[] for y_element in y: new_y.append(abs(y_element-max(y))) plt.scatter(x, new_y, c=time_stamp) plt.savefig('plots_before/'+ str(player.id_in_group) + '_' + str(player.end_time) +'.png') plt.close() array_distances = [] for measurement in range(len(x)-1): mouse_distance = calculate_distance(x[measurement], new_y[measurement], x[measurement +1], new_y[measurement+1] ) array_distances.append(mouse_distance) array_milisec = [] for measurement in range(len(time_stamp)-1): milisecs = calculate_milisec_used(time_stamp[measurement], time_stamp[measurement+1]) array_milisec.append(milisecs) array_speed = [] for measurement in range(len(array_milisec)): speed = calculate_speed(array_distances[measurement], array_milisec[measurement]) array_speed.append(speed) x.remove(x[0]) new_y.remove(new_y[0]) colors = [] i = 0 for elemetns in range(len(new_y)): colors.append(i) i = i + 10 new_color = [] for elemetns in range(len(new_y)): color_new = random.uniform(min(array_speed), max(array_speed)) new_color.append(color_new) plt.scatter(x, new_y, c=np.sort(array_speed)) plt.savefig('plots_before_speed/'+ str(player.id_in_group) + '_' + str(player.end_time) +'.png') plt.close() milisec_array, distances_array, x_array, y_array = calculate_speed_every_milisec(array_milisec, array_distances, x, new_y) array_speed = [] for measurement in range(len(milisec_array)): speed = calculate_speed(distances_array[measurement], milisec_array[measurement]) array_speed.append(speed) plt.scatter(x, new_y, c=array_speed) plt.savefig('plots_before_speed_milisec/'+ str(player.id_in_group) + '_' + str(player.end_time) +'.png') plt.close() def raking_results_to_charts(parsed_array_cities_infield, parsed_array_resultfield): df_results_for_chart = pd.DataFrame() df_results_for_chart['cities'] = parsed_array_cities_infield df_results_for_chart['value'] = parsed_array_resultfield df_results_for_chart['value'] = df_results_for_chart['value'].apply(int) #define a dataframe that matches color to rating values backgroundColor = ['rgba(0,0,0,0.5)','rgba(253, 231, 37,0.5)','rgba(159, 218, 58,0.5)','rgba(74, 193, 109,0.5)','rgba(40, 161, 135,0.5)','rgba(39, 127, 142,0.5)'] backgroundColor_lines = ['rgba(0,0,0,1)','rgba(253, 231, 37,1)','rgba(159, 218, 58,1)','rgba(74, 193, 109,1)','rgba(40, 161, 135,1)','rgba(39, 127, 142,1)'] backgroundColor_index = [0,1,2,3,4,5] df_colors = pd.DataFrame() df_colors['value'] = backgroundColor_index df_colors['color_rgb'] = backgroundColor df_colors['line_color'] = backgroundColor_lines df_results_for_chart = pd.merge(df_results_for_chart, df_colors, on='value') df_results_for_chart = df_results_for_chart.sort_values(by=['cities']) backgroundColor = df_results_for_chart["color_rgb"].tolist() parsed_array_resultfield = df_results_for_chart["value"].tolist() parsed_array_cities_infield = df_results_for_chart["cities"].tolist() line_colors = df_results_for_chart["line_color"].tolist() df_results_for_chart = df_results_for_chart.sort_values(by=['value']) best_ranked_city = df_results_for_chart.iloc[4,0] return parsed_array_resultfield, parsed_array_cities_infield, backgroundColor, line_colors, best_ranked_city def raking_results_to_charts_less_color(parsed_array_cities_infield, parsed_array_resultfield, number_of_player): df_results_for_chart = pd.DataFrame() df_results_for_chart['cities'] = parsed_array_cities_infield df_results_for_chart['city_name_to_tag_string'] = parsed_array_cities_infield for index, row in df_results_for_chart.iterrows(): city_name_to_tag_string = row['city_name_to_tag_string'] city_name_to_tag_string = city_name_to_tag_string.split("(") country = city_name_to_tag_string[1] country = "(" + country[0:] city_name_to_tag_string[1] = country row['city_name_to_tag_string'] = city_name_to_tag_string df_results_for_chart['value'] = parsed_array_resultfield df_results_for_chart['value'] = df_results_for_chart['value'].apply(int) df_results_for_chart = df_results_for_chart.sort_values(by=['value']) df_results_for_chart = df_results_for_chart.reset_index(drop=True) best_ranked_city = df_results_for_chart.iloc[4,0] df_results_for_chart = df_results_for_chart.sort_values(by=['cities']) parsed_array_resultfield = df_results_for_chart["value"].tolist() parsed_array_cities_infield = df_results_for_chart["cities"].tolist() parsed_array_cities_infield_tag_string = df_results_for_chart["city_name_to_tag_string"].tolist() return parsed_array_resultfield, parsed_array_cities_infield_tag_string, parsed_array_cities_infield, best_ranked_city #https://pynative.com/python-generate-random-string/ def get_random_string(length): # With combination of lower and upper case result_str = ''.join(random.choice(string.ascii_letters) for i in range(length)) return result_str # print random string page_sequence = [Intro, Instructions_part1, Phase_One_Instructions, Phase_Two_Instructions, Instructions_part2, Survey, Phase_One, Phase_Two, Solution, Result, Outro,BacktoProlific] #page_sequence = [Phase_One, Phase_Two]