Package: otreeutils
otreeutilsMarch 2021, Markus Konradmarkus.konrad@wzb.eu/Berlin Social Science CenterA package with common oTree utilitiesThis repository contains the packageotreeutils. It features a set of common helper / utility functions and classes often needed when developing experiments withoTree. So far, this covers the following use cases:Easier creation of surveys:define all survey questions in a single data structure, letotreeutilscreate the requiredPlayerfieldscreate a table of Likert scale inputs ("Likert matrix")create single Likert scale fields from given labelseasy survey forms styling via CSS due to cleanly structured HTML outputmake survey forms with conditional inputsExtensions to oTree's admin interface forusing custom data models, which include:Live session data view shows data from custom modelsExport page allows download of complete data with data from custom modelsExport page allows download in nested JSON formatDisplaying and validating understanding questionsDisplaying warnings to participants when a timeout occurs on a page (no automatic form submission after timeout)More convenient development process by optional automatic fill-in of forms (saves you from clicking through many inputs during development)Setting custom URLs for pages (instead of default: the page's class name)This screenshot shows an example survey page with a Likert matrix:The package isavailable on PyPIand can be installed  viapip install otreeutils.Compatibility note:This package is compatible with oTree v3.3.x. If you have an older oTree version, check out theCHANGESfile to see which version is compatible with your oTree version. You can install the exact version then withpip install otreeutils==x.y.zwherex.y.zdenotes an otreeutils version number.CitationIf you usedotreeutilsin your published research, please cite it as follows:Konrad, M. (2018). oTree: Implementing experiments with dynamically determined data quantity.Journal of Behavioral and Experimental Finance.ExamplesThe repository contains three example apps which show the respective features and how they can be used in own experiments:otreeutils_example1-- Understanding questions and timeout warningsotreeutils_example2-- Surveysotreeutils_example3_market-- Market: An example showing custom data models to collect a dynamically determined data quantity. Shows how otreeutils' admin extensions allow live data view and data export for these requirements. Companion code forKonrad 2018. Seeits dedicated README page.LimitationsThe admin interface extensions have still a limitation: Data export with all data from custom models is only possible with per app download option, not with the "all apps" option.RequirementsThis package requires oTree v3.3.x and optionallypandas. The requirements will be installed along with otreeutils when usingpip(see below).Installation and setupIn order to use otreeutils in your experiment implementation, you only need to do the following things:Either install the package fromPyPIviapip(pip install otreeutils) or download/clone this github repository and copy theotreeutilsfolder to your oTree experiment directory.Edit yoursettings.pyso that you add "otreeutils" to yourINSTALLED_APPSlist.Don't forget this, otherwise the required templates and static files cannot be loaded correctly!API overviewIt's best to have a look at the (documented) examples to see how to use the API.otreeutils.pagesmoduleExtendedPageclassA common page extension to oTree's defaultPageclass.
All other page classes inotreeutilsextend this class. Allows to define a custom page URL viacustom_name_in_url, timeout warnings, a page title and provides a template variabledebugwith which you can toggle debug code in your templates / JavaScript parts.The template variabledebug(integer – 0 or 1) is toggled using an additionalAPPS_DEBUGvariable insettings.py. See thesettings.pyof this repository. This is quite useful for example in order to fill in the correct questions on a page with understanding questions automatically in a debug session (so that it is easier to click through the pages).There is also a page variabledebug_fill_forms_randomly, which can be set for any page derived from theExtendedPageclass (i.e. also for survey pages -- see below). If you set this variable toTrue, then all form inputs on the page are automatically filled in with random values once you visit the page. This happens when you run the experiment in "debug mode", i.e. whenAPPS_DEBUGis set toTrue. By default,debug_fill_forms_randomlyis set toFalse. You can enable this feature for a given page like this:fromotreeutils.pagesimportExtendedPageclassMyPage(ExtendedPage):debug_fill_forms_randomly=TrueThis saves time when you click through an experiment with many complex forms.UnderstandingQuestionsPageclassBase class to implement understanding questions. A participant must complete all questions in order to proceed. You can display hints. Use it as follows:fromotreeutils.pagesimportUnderstandingQuestionsPageclassSomeUnderstandingQuestions(UnderstandingQuestionsPage):page_title='Set a page title'questions=[{'question':'What is π?','options':[1.2345,3.14159],'correct':3.14159,'hint':'You can have a look at Wikipedia!'# this is optional},# ...]By default, the performance of the participant is not recorded, but you can optionally provide aform_modeland set a field inform_field_n_wrong_attemptswhich defines in which field the number of wrong attempts is written.If you setAPPS_DEBUGtoTrue, the correct answers will already be filled in order to skip swiftly through pages during development.otreeutils.surveysmodulecreate_player_model_for_surveyfunctionThis function allows to dynamically create aPlayermodel class for a survey. It can be used as follows inmodels.py.At first you define your questions per page in a survey definitions data structure, for example like this:fromotreeutils.surveysimportcreate_player_model_for_surveyGENDER_CHOICES=(('female','Female'),('male','Male'),('no_answer','Prefer not to answer'),)SURVEY_DEFINITIONS={'SurveyPage1':{'page_title':'Survey Questions - Page 1','survey_fields':[('q1_a',{# field name (which will also end up in your "Player" class and hence in your output data)'text':'How old are you?',# survey question'field':models.PositiveIntegerField(min=18,max=100),# the same as in normal oTree model field definitions}),('q1_b',{'text':'Please tell us your gender.','field':models.CharField(choices=GENDER_CHOICES),}),# ... more questions]},# ... more pages}Note howSURVEY_DEFINITIONSis a dictionary which maps pages to the survey questions that should appear on each page. We will later create aSurveyPage1page class inpages.py.Now you create thePlayerclass by passing the name of the module for which it will be created. This should be  themodelsmodule of your app, so in your case this is'survey.models'if your app is namedsurvey. The second parameter is the survey definitions that we just created:Player=create_player_model_for_survey('otreeutils_example2.models',SURVEY_DEFINITIONS)The attributes (model fields, etc.) will be automatically created. When you runotree resetdb, you will see that the fieldsq1_a,q1_b, etc. will be generated in the database.You may also add extra (non-survey) fields to yourPlayerclass, by passing a dict to the optionalother_fieldsparameter:Player=create_player_model_for_survey('otreeutils_example2.models',SURVEY_DEFINITIONS,other_fields={'treatment':models.IntegerField()})Likert score inputs viagenerate_likert_fieldandgenerate_likert_tablefunctionsThe functiongenerate_likert_fieldallows you to easily generate fields for a given Likert scale and can be used inside a survey definitions data structure:fromotreeutils.surveysimportgenerate_likert_fieldlikert_5_labels=('Strongly disagree',# value: 1'Disagree',# value: 2'Neither agree nor disagree',# ...'Agree','Strongly agree'# value: 5)likert_5point_field=generate_likert_field(likert_5_labels)The objectlikert_5point_fieldis now afunctionto generate new fields of the specified Likert scale:# ...SURVEY_DEFINITIONS={'SurveyPage2':{'page_title':'A Likert 5-point scale example','survey_fields':[('q_otree_surveys',{# most of the time, you'd add a "help_text" for a Likert scale question. You can use HTML:'help_text':"""<p>Consider this quote:</p><blockquote>"oTree is great to make surveys, too."</blockquote><p>What do you think?</p>""",'field':likert_5point_field(),# don't forget the parentheses at the end!}),('q_just_likert',{'label':'Another Likert scale input:',# optional, no HTML'field':likert_5point_field(),# don't forget the parentheses at the end!}),]},# ... more pages}The functiongenerate_likert_tableallows you to easily generate a table of Likert scale inputs like a matrix with the Likert scale increments in the columns and your questions in the rows:# ...SURVEY_DEFINITIONS={'SurveyPage3':{'page_title':'A Likert scale table example','survey_fields':[# create a table of Likert scale choices# we use the same 5-point scale a before and specify four rows for the table,# each with a tuple (field name, label)generate_likert_table(likert_5_labels,[('q_pizza_tasty','Tasty'),('q_pizza_spicy','Spicy'),('q_pizza_cold','Too cold'),('q_pizza_satiable','Satiable'),],form_help_initial='<p>How was your latest Pizza?</p>',# HTML to be placed on top of formform_help_final='<p>Thank you!</p>'# HTML to be placed below form)]},# ... more pages}There are several additional parameters that you can pass togenerate_likert_table()which will control the display and behavior of the table:table_repeat_header_each_n_rows=<integer>: set to integer N > 0 to repeat the table header after every N rowstable_cols_equal_width=<True/False>: adjust form columns so that they have equal widthtable_row_header_width_pct=<number>: if form columns should have equal width, this specifies the width of the first column (the table row header) in percent (default: 25)table_rows_equal_height=<True/False>: adjust form rows so that they have equal heighttable_rows_alternate=<True/False>: alternate form rows between "odd" and "even" CSS classes (alternates background colors)table_rows_randomize=<True/False>: randomize form rowstable_rows_highlight=<True/False>: highlight form rows on mouse-overtable_cells_highlight=<True/False>: highlight form cells on mouse-overtable_cells_clickable=<True/False>: make form cells clickable for selection (otherwise only the small radio buttons can be clicked)More options for surveysTo implement advanced features such as conditional input display, have a look at the example appotreeutils_example2.SurveyPageclassYou can then create the survey pages which will contain the questions for the respective pages as defined before inSURVEY_DEFINITIONS:# (in pages.py)fromotreeutils.surveysimportSurveyPage,setup_survey_pages# Create the survey page classes; their names must correspond to the names used in the survey definitionclassSurveyPage1(SurveyPage):passclassSurveyPage2(SurveyPage):pass# more pages ...# Create a list of survey pages.survey_pages=[SurveyPage1,SurveyPage2,# more pages ...]Since eachSurveyPageis derived from theExtendedPageclass, you can also enable the automatic fill-in feature. This means that all form inputs on the page are automatically filled in with random values once you visit the page. That happens when you run the experiment in "debug mode", i.e. whenAPPS_DEBUGis set toTrue. By default,debug_fill_forms_randomlyis set toFalse. You can enable this feature for a given survey page like this:classSurveyPage3(SurveyPage):debug_fill_forms_randomly=TrueThis saves time when you click through an experiment with many survey fields.setup_survey_pagesfunctionNow all survey pages need to be set up. ThePlayerclass will be passed to all survey pages and the questions for each page will be set according to their order.# Common setup for all pages (will set the questions per page)setup_survey_pages(models.Player,survey_pages)Finally, we can set thepage_sequencein order to use our survey pages:page_sequence=[SurveyIntro,# define some pages that come before the survey# ...]# add the survey pages to the page sequence listpage_sequence.extend(survey_pages)# we could add more pages after the survey here# ...Have a look into the example implementations provided asotreeutils_example1(understanding questions, simple page extensions),otreeutils_example2(surveys) andotreeutils_example3_market(custom data models).otreeutils.scriptsmoduleThis module allows creating scripts that interface with oTree from the command line. Importingotreeutils.scriptsmakes sure that everything is correctly set up and the settings are loaded. An example might be a script which exports data from the current sessions for specific apps as JSON file:importsysfromotreeutilsimportscripts# this is the most import line and must be included at the beginningiflen(sys.argv)!=2:print('call this script with a single argument: python%s<output.json>'%sys.argv[0])exit(1)output_file=sys.argv[1]apps=['intro','my_app','outro']print('loading data...')# get the data as hierarchical data structure. this is esp. useful if you use# custom data modelscombined=scripts.get_hierarchical_data_for_apps(apps)print('writing data to file',output_file)scripts.save_data_as_json_file(combined,output_file,indent=2)print('done.')Custom data models and admin extensionsIf you implement custom data models and want to use otreeutils' admin extensions you additionally need to follow these steps:1. Install all dependenciesMake sure that you install otreeutils with extra dependencies viapip install otreeutils[admin].2. Add configuration class to custom modelsFor each of the custom models that you want to include in the live data view or extended data export, you have to define a subclass calledCustomModelConflike this:fromotree.db.modelsimportModel,ForeignKey# import base Model class and ForeignKey# ...classFruitOffer(Model):amount=models.IntegerField(label='Amount',min=0,initial=0)# ... more fields here ...seller=ForeignKey(Player)classCustomModelConf:"""Configuration for otreeutils admin extensions."""data_view={# define this attribute if you want to include this model in the live data view'exclude_fields':['seller'],'link_with':'seller'}export_data={# define this attribute if you want to include this model in the data export'exclude_fields':['seller_id'],'link_with':'seller'}3. Add a custom urls moduleIn your experiment app, add a fileurls.pyand simply include the custom URL patters from otreeutils as follows:fromotreeutils.admin_extensions.urlsimporturlpatterns# add more custom URL rules here if necessary# ...4. Import thecustom_exportfunction inmodels.pyIn your experiment app, add the following line tomodels.py:fromotreeutils.admin_extensionsimportcustom_exportThis makes sure that the data from the custom data models can be exported via oTree's admin interface.5. Updatesettings.pyto load the custom URLs and channel routesAdd this line to yoursettings.py:ROOT_URLCONF='<APP_PACKAGE>.urls'Instead of<APP_PACKAGE>write your app's package name (e.g. "market" if your app is named "market").And don't forget to edit your settings.py so that you add "otreeutils" to your INSTALLED_APPS list!That's it! When you visit the admin pages, they won't really look different, however, the live data view will now support your custom models and in the data export view you can download the dataincludingthe custom models' data with the "custom" link.So far, the "all-apps" download option will not include the custom models' data.LicenseApache License 2.0. See LICENSE file.