edsl 0.1.38.dev2__py3-none-any.whl → 0.1.38.dev3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. edsl/Base.py +303 -303
  2. edsl/BaseDiff.py +260 -260
  3. edsl/TemplateLoader.py +24 -24
  4. edsl/__init__.py +49 -49
  5. edsl/__version__.py +1 -1
  6. edsl/agents/Agent.py +858 -858
  7. edsl/agents/AgentList.py +362 -362
  8. edsl/agents/Invigilator.py +222 -222
  9. edsl/agents/InvigilatorBase.py +284 -284
  10. edsl/agents/PromptConstructor.py +353 -353
  11. edsl/agents/__init__.py +3 -3
  12. edsl/agents/descriptors.py +99 -99
  13. edsl/agents/prompt_helpers.py +129 -129
  14. edsl/auto/AutoStudy.py +117 -117
  15. edsl/auto/StageBase.py +230 -230
  16. edsl/auto/StageGenerateSurvey.py +178 -178
  17. edsl/auto/StageLabelQuestions.py +125 -125
  18. edsl/auto/StagePersona.py +61 -61
  19. edsl/auto/StagePersonaDimensionValueRanges.py +88 -88
  20. edsl/auto/StagePersonaDimensionValues.py +74 -74
  21. edsl/auto/StagePersonaDimensions.py +69 -69
  22. edsl/auto/StageQuestions.py +73 -73
  23. edsl/auto/SurveyCreatorPipeline.py +21 -21
  24. edsl/auto/utilities.py +224 -224
  25. edsl/base/Base.py +279 -279
  26. edsl/config.py +149 -149
  27. edsl/conversation/Conversation.py +290 -290
  28. edsl/conversation/car_buying.py +58 -58
  29. edsl/conversation/chips.py +95 -95
  30. edsl/conversation/mug_negotiation.py +81 -81
  31. edsl/conversation/next_speaker_utilities.py +93 -93
  32. edsl/coop/PriceFetcher.py +54 -54
  33. edsl/coop/__init__.py +2 -2
  34. edsl/coop/coop.py +961 -961
  35. edsl/coop/utils.py +131 -131
  36. edsl/data/Cache.py +530 -530
  37. edsl/data/CacheEntry.py +228 -228
  38. edsl/data/CacheHandler.py +149 -149
  39. edsl/data/RemoteCacheSync.py +97 -97
  40. edsl/data/SQLiteDict.py +292 -292
  41. edsl/data/__init__.py +4 -4
  42. edsl/data/orm.py +10 -10
  43. edsl/data_transfer_models.py +73 -73
  44. edsl/enums.py +173 -173
  45. edsl/exceptions/BaseException.py +21 -21
  46. edsl/exceptions/__init__.py +54 -54
  47. edsl/exceptions/agents.py +42 -42
  48. edsl/exceptions/cache.py +5 -5
  49. edsl/exceptions/configuration.py +16 -16
  50. edsl/exceptions/coop.py +10 -10
  51. edsl/exceptions/data.py +14 -14
  52. edsl/exceptions/general.py +34 -34
  53. edsl/exceptions/jobs.py +33 -33
  54. edsl/exceptions/language_models.py +63 -63
  55. edsl/exceptions/prompts.py +15 -15
  56. edsl/exceptions/questions.py +91 -91
  57. edsl/exceptions/results.py +29 -29
  58. edsl/exceptions/scenarios.py +22 -22
  59. edsl/exceptions/surveys.py +37 -37
  60. edsl/inference_services/AnthropicService.py +87 -87
  61. edsl/inference_services/AwsBedrock.py +120 -120
  62. edsl/inference_services/AzureAI.py +217 -217
  63. edsl/inference_services/DeepInfraService.py +18 -18
  64. edsl/inference_services/GoogleService.py +156 -156
  65. edsl/inference_services/GroqService.py +20 -20
  66. edsl/inference_services/InferenceServiceABC.py +147 -147
  67. edsl/inference_services/InferenceServicesCollection.py +97 -97
  68. edsl/inference_services/MistralAIService.py +123 -123
  69. edsl/inference_services/OllamaService.py +18 -18
  70. edsl/inference_services/OpenAIService.py +224 -224
  71. edsl/inference_services/TestService.py +89 -89
  72. edsl/inference_services/TogetherAIService.py +170 -170
  73. edsl/inference_services/models_available_cache.py +118 -118
  74. edsl/inference_services/rate_limits_cache.py +25 -25
  75. edsl/inference_services/registry.py +39 -39
  76. edsl/inference_services/write_available.py +10 -10
  77. edsl/jobs/Answers.py +56 -56
  78. edsl/jobs/Jobs.py +1358 -1358
  79. edsl/jobs/__init__.py +1 -1
  80. edsl/jobs/buckets/BucketCollection.py +63 -63
  81. edsl/jobs/buckets/ModelBuckets.py +65 -65
  82. edsl/jobs/buckets/TokenBucket.py +251 -251
  83. edsl/jobs/interviews/Interview.py +661 -661
  84. edsl/jobs/interviews/InterviewExceptionCollection.py +99 -99
  85. edsl/jobs/interviews/InterviewExceptionEntry.py +186 -186
  86. edsl/jobs/interviews/InterviewStatistic.py +63 -63
  87. edsl/jobs/interviews/InterviewStatisticsCollection.py +25 -25
  88. edsl/jobs/interviews/InterviewStatusDictionary.py +78 -78
  89. edsl/jobs/interviews/InterviewStatusLog.py +92 -92
  90. edsl/jobs/interviews/ReportErrors.py +66 -66
  91. edsl/jobs/interviews/interview_status_enum.py +9 -9
  92. edsl/jobs/runners/JobsRunnerAsyncio.py +361 -361
  93. edsl/jobs/runners/JobsRunnerStatus.py +332 -332
  94. edsl/jobs/tasks/QuestionTaskCreator.py +242 -242
  95. edsl/jobs/tasks/TaskCreators.py +64 -64
  96. edsl/jobs/tasks/TaskHistory.py +451 -451
  97. edsl/jobs/tasks/TaskStatusLog.py +23 -23
  98. edsl/jobs/tasks/task_status_enum.py +163 -163
  99. edsl/jobs/tokens/InterviewTokenUsage.py +27 -27
  100. edsl/jobs/tokens/TokenUsage.py +34 -34
  101. edsl/language_models/KeyLookup.py +30 -30
  102. edsl/language_models/LanguageModel.py +708 -708
  103. edsl/language_models/ModelList.py +109 -109
  104. edsl/language_models/RegisterLanguageModelsMeta.py +184 -184
  105. edsl/language_models/__init__.py +3 -3
  106. edsl/language_models/fake_openai_call.py +15 -15
  107. edsl/language_models/fake_openai_service.py +61 -61
  108. edsl/language_models/registry.py +137 -137
  109. edsl/language_models/repair.py +156 -156
  110. edsl/language_models/unused/ReplicateBase.py +83 -83
  111. edsl/language_models/utilities.py +64 -64
  112. edsl/notebooks/Notebook.py +258 -258
  113. edsl/notebooks/__init__.py +1 -1
  114. edsl/prompts/Prompt.py +357 -357
  115. edsl/prompts/__init__.py +2 -2
  116. edsl/questions/AnswerValidatorMixin.py +289 -289
  117. edsl/questions/QuestionBase.py +660 -660
  118. edsl/questions/QuestionBaseGenMixin.py +161 -161
  119. edsl/questions/QuestionBasePromptsMixin.py +217 -217
  120. edsl/questions/QuestionBudget.py +227 -227
  121. edsl/questions/QuestionCheckBox.py +359 -359
  122. edsl/questions/QuestionExtract.py +183 -183
  123. edsl/questions/QuestionFreeText.py +114 -114
  124. edsl/questions/QuestionFunctional.py +166 -166
  125. edsl/questions/QuestionList.py +231 -231
  126. edsl/questions/QuestionMultipleChoice.py +286 -286
  127. edsl/questions/QuestionNumerical.py +153 -153
  128. edsl/questions/QuestionRank.py +324 -324
  129. edsl/questions/Quick.py +41 -41
  130. edsl/questions/RegisterQuestionsMeta.py +71 -71
  131. edsl/questions/ResponseValidatorABC.py +174 -174
  132. edsl/questions/SimpleAskMixin.py +73 -73
  133. edsl/questions/__init__.py +26 -26
  134. edsl/questions/compose_questions.py +98 -98
  135. edsl/questions/decorators.py +21 -21
  136. edsl/questions/derived/QuestionLikertFive.py +76 -76
  137. edsl/questions/derived/QuestionLinearScale.py +87 -87
  138. edsl/questions/derived/QuestionTopK.py +93 -93
  139. edsl/questions/derived/QuestionYesNo.py +82 -82
  140. edsl/questions/descriptors.py +413 -413
  141. edsl/questions/prompt_templates/question_budget.jinja +13 -13
  142. edsl/questions/prompt_templates/question_checkbox.jinja +32 -32
  143. edsl/questions/prompt_templates/question_extract.jinja +11 -11
  144. edsl/questions/prompt_templates/question_free_text.jinja +3 -3
  145. edsl/questions/prompt_templates/question_linear_scale.jinja +11 -11
  146. edsl/questions/prompt_templates/question_list.jinja +17 -17
  147. edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -33
  148. edsl/questions/prompt_templates/question_numerical.jinja +36 -36
  149. edsl/questions/question_registry.py +147 -147
  150. edsl/questions/settings.py +12 -12
  151. edsl/questions/templates/budget/answering_instructions.jinja +7 -7
  152. edsl/questions/templates/budget/question_presentation.jinja +7 -7
  153. edsl/questions/templates/checkbox/answering_instructions.jinja +10 -10
  154. edsl/questions/templates/checkbox/question_presentation.jinja +22 -22
  155. edsl/questions/templates/extract/answering_instructions.jinja +7 -7
  156. edsl/questions/templates/likert_five/answering_instructions.jinja +10 -10
  157. edsl/questions/templates/likert_five/question_presentation.jinja +11 -11
  158. edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -5
  159. edsl/questions/templates/linear_scale/question_presentation.jinja +5 -5
  160. edsl/questions/templates/list/answering_instructions.jinja +3 -3
  161. edsl/questions/templates/list/question_presentation.jinja +5 -5
  162. edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -9
  163. edsl/questions/templates/multiple_choice/question_presentation.jinja +11 -11
  164. edsl/questions/templates/numerical/answering_instructions.jinja +6 -6
  165. edsl/questions/templates/numerical/question_presentation.jinja +6 -6
  166. edsl/questions/templates/rank/answering_instructions.jinja +11 -11
  167. edsl/questions/templates/rank/question_presentation.jinja +15 -15
  168. edsl/questions/templates/top_k/answering_instructions.jinja +8 -8
  169. edsl/questions/templates/top_k/question_presentation.jinja +22 -22
  170. edsl/questions/templates/yes_no/answering_instructions.jinja +6 -6
  171. edsl/questions/templates/yes_no/question_presentation.jinja +11 -11
  172. edsl/results/Dataset.py +293 -293
  173. edsl/results/DatasetExportMixin.py +717 -717
  174. edsl/results/DatasetTree.py +145 -145
  175. edsl/results/Result.py +456 -456
  176. edsl/results/Results.py +1071 -1071
  177. edsl/results/ResultsDBMixin.py +238 -238
  178. edsl/results/ResultsExportMixin.py +43 -43
  179. edsl/results/ResultsFetchMixin.py +33 -33
  180. edsl/results/ResultsGGMixin.py +121 -121
  181. edsl/results/ResultsToolsMixin.py +98 -98
  182. edsl/results/Selector.py +135 -135
  183. edsl/results/__init__.py +2 -2
  184. edsl/results/tree_explore.py +115 -115
  185. edsl/scenarios/FileStore.py +458 -458
  186. edsl/scenarios/Scenario.py +544 -544
  187. edsl/scenarios/ScenarioHtmlMixin.py +64 -64
  188. edsl/scenarios/ScenarioList.py +1112 -1112
  189. edsl/scenarios/ScenarioListExportMixin.py +52 -52
  190. edsl/scenarios/ScenarioListPdfMixin.py +261 -261
  191. edsl/scenarios/__init__.py +4 -4
  192. edsl/shared.py +1 -1
  193. edsl/study/ObjectEntry.py +173 -173
  194. edsl/study/ProofOfWork.py +113 -113
  195. edsl/study/SnapShot.py +80 -80
  196. edsl/study/Study.py +528 -528
  197. edsl/study/__init__.py +4 -4
  198. edsl/surveys/DAG.py +148 -148
  199. edsl/surveys/Memory.py +31 -31
  200. edsl/surveys/MemoryPlan.py +244 -244
  201. edsl/surveys/Rule.py +326 -326
  202. edsl/surveys/RuleCollection.py +387 -387
  203. edsl/surveys/Survey.py +1787 -1787
  204. edsl/surveys/SurveyCSS.py +261 -261
  205. edsl/surveys/SurveyExportMixin.py +259 -259
  206. edsl/surveys/SurveyFlowVisualizationMixin.py +121 -121
  207. edsl/surveys/SurveyQualtricsImport.py +284 -284
  208. edsl/surveys/__init__.py +3 -3
  209. edsl/surveys/base.py +53 -53
  210. edsl/surveys/descriptors.py +56 -56
  211. edsl/surveys/instructions/ChangeInstruction.py +49 -49
  212. edsl/surveys/instructions/Instruction.py +53 -53
  213. edsl/surveys/instructions/InstructionCollection.py +77 -77
  214. edsl/templates/error_reporting/base.html +23 -23
  215. edsl/templates/error_reporting/exceptions_by_model.html +34 -34
  216. edsl/templates/error_reporting/exceptions_by_question_name.html +16 -16
  217. edsl/templates/error_reporting/exceptions_by_type.html +16 -16
  218. edsl/templates/error_reporting/interview_details.html +115 -115
  219. edsl/templates/error_reporting/interviews.html +9 -9
  220. edsl/templates/error_reporting/overview.html +4 -4
  221. edsl/templates/error_reporting/performance_plot.html +1 -1
  222. edsl/templates/error_reporting/report.css +73 -73
  223. edsl/templates/error_reporting/report.html +117 -117
  224. edsl/templates/error_reporting/report.js +25 -25
  225. edsl/tools/__init__.py +1 -1
  226. edsl/tools/clusters.py +192 -192
  227. edsl/tools/embeddings.py +27 -27
  228. edsl/tools/embeddings_plotting.py +118 -118
  229. edsl/tools/plotting.py +112 -112
  230. edsl/tools/summarize.py +18 -18
  231. edsl/utilities/SystemInfo.py +28 -28
  232. edsl/utilities/__init__.py +22 -22
  233. edsl/utilities/ast_utilities.py +25 -25
  234. edsl/utilities/data/Registry.py +6 -6
  235. edsl/utilities/data/__init__.py +1 -1
  236. edsl/utilities/data/scooter_results.json +1 -1
  237. edsl/utilities/decorators.py +77 -77
  238. edsl/utilities/gcp_bucket/cloud_storage.py +96 -96
  239. edsl/utilities/interface.py +627 -627
  240. edsl/utilities/naming_utilities.py +263 -263
  241. edsl/utilities/repair_functions.py +28 -28
  242. edsl/utilities/restricted_python.py +70 -70
  243. edsl/utilities/utilities.py +409 -409
  244. {edsl-0.1.38.dev2.dist-info → edsl-0.1.38.dev3.dist-info}/LICENSE +21 -21
  245. {edsl-0.1.38.dev2.dist-info → edsl-0.1.38.dev3.dist-info}/METADATA +1 -1
  246. edsl-0.1.38.dev3.dist-info/RECORD +269 -0
  247. edsl-0.1.38.dev2.dist-info/RECORD +0 -269
  248. {edsl-0.1.38.dev2.dist-info → edsl-0.1.38.dev3.dist-info}/WHEEL +0 -0
edsl/surveys/Survey.py CHANGED
@@ -1,1787 +1,1787 @@
1
- """A Survey is collection of questions that can be administered to an Agent."""
2
-
3
- from __future__ import annotations
4
- import re
5
- import tempfile
6
- import requests
7
-
8
- from typing import Any, Generator, Optional, Union, List, Literal, Callable
9
- from uuid import uuid4
10
- from edsl.Base import Base
11
- from edsl.exceptions import SurveyCreationError, SurveyHasNoRulesError
12
- from edsl.exceptions.surveys import SurveyError
13
-
14
- from edsl.questions.QuestionBase import QuestionBase
15
- from edsl.surveys.base import RulePriority, EndOfSurvey
16
- from edsl.surveys.DAG import DAG
17
- from edsl.surveys.descriptors import QuestionsDescriptor
18
- from edsl.surveys.MemoryPlan import MemoryPlan
19
- from edsl.surveys.Rule import Rule
20
- from edsl.surveys.RuleCollection import RuleCollection
21
- from edsl.surveys.SurveyExportMixin import SurveyExportMixin
22
- from edsl.surveys.SurveyFlowVisualizationMixin import SurveyFlowVisualizationMixin
23
- from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
24
-
25
- from edsl.agents.Agent import Agent
26
-
27
- from edsl.surveys.instructions.InstructionCollection import InstructionCollection
28
- from edsl.surveys.instructions.Instruction import Instruction
29
- from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
30
-
31
-
32
- class ValidatedString(str):
33
- def __new__(cls, content):
34
- if "<>" in content:
35
- raise SurveyCreationError(
36
- "The expression contains '<>', which is not allowed. You probably mean '!='."
37
- )
38
- return super().__new__(cls, content)
39
-
40
-
41
- class Survey(SurveyExportMixin, SurveyFlowVisualizationMixin, Base):
42
- """A collection of questions that supports skip logic."""
43
-
44
- questions = QuestionsDescriptor()
45
- """
46
- A collection of questions that supports skip logic.
47
-
48
- Initalization:
49
- - `questions`: the questions in the survey (optional)
50
- - `question_names`: the names of the questions (optional)
51
- - `name`: the name of the survey (optional)
52
-
53
- Methods:
54
- -
55
-
56
- Notes:
57
- - The presumed order of the survey is the order in which questions are added.
58
- """
59
-
60
- def __init__(
61
- self,
62
- questions: Optional[
63
- list[Union[QuestionBase, Instruction, ChangeInstruction]]
64
- ] = None,
65
- memory_plan: Optional[MemoryPlan] = None,
66
- rule_collection: Optional[RuleCollection] = None,
67
- question_groups: Optional[dict[str, tuple[int, int]]] = None,
68
- name: Optional[str] = None,
69
- ):
70
- """Create a new survey.
71
-
72
- :param questions: The questions in the survey.
73
- :param memory_plan: The memory plan for the survey.
74
- :param rule_collection: The rule collection for the survey.
75
- :param question_groups: The groups of questions in the survey.
76
- :param name: The name of the survey - DEPRECATED.
77
-
78
-
79
- >>> from edsl import QuestionFreeText
80
- >>> q1 = QuestionFreeText(question_text = "What is your name?", question_name = "name")
81
- >>> q2 = QuestionFreeText(question_text = "What is your favorite color?", question_name = "color")
82
- >>> q3 = QuestionFreeText(question_text = "Is a hot dog a sandwich", question_name = "food")
83
- >>> s = Survey([q1, q2, q3], question_groups = {"demographics": (0, 1), "substantive":(3)})
84
-
85
-
86
- """
87
-
88
- self.raw_passed_questions = questions
89
-
90
- (
91
- true_questions,
92
- instruction_names_to_instructions,
93
- self.pseudo_indices,
94
- ) = self._separate_questions_and_instructions(questions or [])
95
-
96
- self.rule_collection = RuleCollection(
97
- num_questions=len(true_questions) if true_questions else None
98
- )
99
- # the RuleCollection needs to be present while we add the questions; we might override this later
100
- # if a rule_collection is provided. This allows us to serialize the survey with the rule_collection.
101
-
102
- self.questions = true_questions
103
- self.instruction_names_to_instructions = instruction_names_to_instructions
104
-
105
- self.memory_plan = memory_plan or MemoryPlan(self)
106
- if question_groups is not None:
107
- self.question_groups = question_groups
108
- else:
109
- self.question_groups = {}
110
-
111
- # if a rule collection is provided, use it instead
112
- if rule_collection is not None:
113
- self.rule_collection = rule_collection
114
-
115
- if name is not None:
116
- import warnings
117
-
118
- warnings.warn("name parameter to a survey is deprecated.")
119
-
120
- # region: Suvry instruction handling
121
- @property
122
- def relevant_instructions_dict(self) -> InstructionCollection:
123
- """Return a dictionary with keys as question names and values as instructions that are relevant to the question.
124
-
125
- >>> s = Survey.example(include_instructions=True)
126
- >>> s.relevant_instructions_dict
127
- {'q0': [Instruction(name="attention", text="Please pay attention!")], 'q1': [Instruction(name="attention", text="Please pay attention!")], 'q2': [Instruction(name="attention", text="Please pay attention!")]}
128
-
129
- """
130
- return InstructionCollection(
131
- self.instruction_names_to_instructions, self.questions
132
- )
133
-
134
- @staticmethod
135
- def _separate_questions_and_instructions(questions_and_instructions: list) -> tuple:
136
- """
137
- The 'pseudo_indices' attribute is a dictionary that maps question names to pseudo-indices
138
- that are used to order questions and instructions in the survey.
139
- Only questions get real indices; instructions get pseudo-indices.
140
- However, the order of the pseudo-indices is the same as the order questions and instructions are added to the survey.
141
-
142
- We don't have to know how many instructions there are to calculate the pseudo-indices because they are
143
- calculated by the inverse of one minus the sum of 1/2^n for n in the number of instructions run so far.
144
-
145
- >>> from edsl import Instruction
146
- >>> i = Instruction(text = "Pay attention to the following questions.", name = "intro")
147
- >>> i2 = Instruction(text = "How are you feeling today?", name = "followon_intro")
148
- >>> from edsl import QuestionFreeText; q1 = QuestionFreeText.example()
149
- >>> from edsl import QuestionMultipleChoice; q2 = QuestionMultipleChoice.example()
150
- >>> s = Survey([q1, i, i2, q2])
151
- >>> len(s.instruction_names_to_instructions)
152
- 2
153
- >>> s.pseudo_indices
154
- {'how_are_you': 0, 'intro': 0.5, 'followon_intro': 0.75, 'how_feeling': 1}
155
-
156
- >>> from edsl import ChangeInstruction
157
- >>> q3 = QuestionFreeText(question_text = "What is your favorite color?", question_name = "color")
158
- >>> i_change = ChangeInstruction(drop = ["intro"])
159
- >>> s = Survey([q1, i, q2, i_change, q3])
160
- >>> [i.name for i in s.relevant_instructions(q1)]
161
- []
162
- >>> [i.name for i in s.relevant_instructions(q2)]
163
- ['intro']
164
- >>> [i.name for i in s.relevant_instructions(q3)]
165
- []
166
-
167
- >>> i_change = ChangeInstruction(keep = ["poop"], drop = [])
168
- >>> s = Survey([q1, i, q2, i_change])
169
- Traceback (most recent call last):
170
- ...
171
- ValueError: ChangeInstruction change_instruction_0 references instruction poop which does not exist.
172
- """
173
- from edsl.surveys.instructions.Instruction import Instruction
174
- from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
175
-
176
- true_questions = []
177
- instruction_names_to_instructions = {}
178
-
179
- num_change_instructions = 0
180
- pseudo_indices = {}
181
- instructions_run_length = 0
182
- for entry in questions_and_instructions:
183
- if isinstance(entry, Instruction) or isinstance(entry, ChangeInstruction):
184
- if isinstance(entry, ChangeInstruction):
185
- entry.add_name(num_change_instructions)
186
- num_change_instructions += 1
187
- for prior_instruction in entry.keep + entry.drop:
188
- if prior_instruction not in instruction_names_to_instructions:
189
- raise ValueError(
190
- f"ChangeInstruction {entry.name} references instruction {prior_instruction} which does not exist."
191
- )
192
- instructions_run_length += 1
193
- delta = 1 - 1.0 / (2.0**instructions_run_length)
194
- pseudo_index = (len(true_questions) - 1) + delta
195
- entry.pseudo_index = pseudo_index
196
- instruction_names_to_instructions[entry.name] = entry
197
- elif isinstance(entry, QuestionBase):
198
- pseudo_index = len(true_questions)
199
- instructions_run_length = 0
200
- true_questions.append(entry)
201
- else:
202
- raise ValueError(
203
- f"Entry {repr(entry)} is not a QuestionBase or an Instruction."
204
- )
205
-
206
- pseudo_indices[entry.name] = pseudo_index
207
-
208
- return true_questions, instruction_names_to_instructions, pseudo_indices
209
-
210
- def relevant_instructions(self, question) -> dict:
211
- """This should be a dictionry with keys as question names and values as instructions that are relevant to the question.
212
-
213
- :param question: The question to get the relevant instructions for.
214
-
215
- # Did the instruction come before the question and was it not modified by a change instruction?
216
-
217
- """
218
- return self.relevant_instructions_dict[question]
219
-
220
- @property
221
- def max_pseudo_index(self) -> float:
222
- """Return the maximum pseudo index in the survey.
223
-
224
- Example:
225
-
226
- >>> s = Survey.example()
227
- >>> s.max_pseudo_index
228
- 2
229
- """
230
- if len(self.pseudo_indices) == 0:
231
- return -1
232
- return max(self.pseudo_indices.values())
233
-
234
- @property
235
- def last_item_was_instruction(self) -> bool:
236
- """Return whether the last item added to the survey was an instruction.
237
- This is used to determine the pseudo-index of the next item added to the survey.
238
-
239
- Example:
240
-
241
- >>> s = Survey.example()
242
- >>> s.last_item_was_instruction
243
- False
244
- >>> from edsl.surveys.instructions.Instruction import Instruction
245
- >>> s = s.add_instruction(Instruction(text="Pay attention to the following questions.", name="intro"))
246
- >>> s.last_item_was_instruction
247
- True
248
- """
249
- return isinstance(self.max_pseudo_index, float)
250
-
251
- def add_instruction(
252
- self, instruction: Union["Instruction", "ChangeInstruction"]
253
- ) -> Survey:
254
- """
255
- Add an instruction to the survey.
256
-
257
- :param instruction: The instruction to add to the survey.
258
-
259
- >>> from edsl import Instruction
260
- >>> i = Instruction(text="Pay attention to the following questions.", name="intro")
261
- >>> s = Survey().add_instruction(i)
262
- >>> s.instruction_names_to_instructions
263
- {'intro': Instruction(name="intro", text="Pay attention to the following questions.")}
264
- >>> s.pseudo_indices
265
- {'intro': -0.5}
266
- """
267
- import math
268
-
269
- if instruction.name in self.instruction_names_to_instructions:
270
- raise SurveyCreationError(
271
- f"""Instruction name '{instruction.name}' already exists in survey. Existing names are {self.instruction_names_to_instructions.keys()}."""
272
- )
273
- self.instruction_names_to_instructions[instruction.name] = instruction
274
-
275
- # was the last thing added an instruction or a question?
276
- if self.last_item_was_instruction:
277
- pseudo_index = (
278
- self.max_pseudo_index
279
- + (math.ceil(self.max_pseudo_index) - self.max_pseudo_index) / 2
280
- )
281
- else:
282
- pseudo_index = self.max_pseudo_index + 1.0 / 2.0
283
- self.pseudo_indices[instruction.name] = pseudo_index
284
-
285
- return self
286
-
287
- # endregion
288
-
289
- # region: Simulation methods
290
-
291
- @classmethod
292
- def random_survey(self):
293
- """Create a random survey."""
294
- from edsl.questions import QuestionMultipleChoice, QuestionFreeText
295
- from random import choice
296
-
297
- num_questions = 10
298
- questions = []
299
- for i in range(num_questions):
300
- if choice([True, False]):
301
- q = QuestionMultipleChoice(
302
- question_text="nothing",
303
- question_name="q_" + str(i),
304
- question_options=list(range(3)),
305
- )
306
- questions.append(q)
307
- else:
308
- questions.append(
309
- QuestionFreeText(
310
- question_text="nothing", question_name="q_" + str(i)
311
- )
312
- )
313
- s = Survey(questions)
314
- start_index = choice(range(num_questions - 1))
315
- end_index = choice(range(start_index + 1, 10))
316
- s = s.add_rule(f"q_{start_index}", "True", f"q_{end_index}")
317
- question_to_delete = choice(range(num_questions))
318
- s.delete_question(f"q_{question_to_delete}")
319
- return s
320
-
321
- def simulate(self) -> dict:
322
- """Simulate the survey and return the answers."""
323
- i = self.gen_path_through_survey()
324
- q = next(i)
325
- num_passes = 0
326
- while True:
327
- num_passes += 1
328
- try:
329
- answer = q._simulate_answer()
330
- q = i.send({q.question_name: answer["answer"]})
331
- except StopIteration:
332
- break
333
-
334
- if num_passes > 100:
335
- print("Too many passes.")
336
- raise Exception("Too many passes.")
337
- return self.answers
338
-
339
- def create_agent(self) -> "Agent":
340
- """Create an agent from the simulated answers."""
341
- answers_dict = self.simulate()
342
-
343
- def construct_answer_dict_function(traits: dict) -> Callable:
344
- def func(self, question: "QuestionBase", scenario=None):
345
- return traits.get(question.question_name, None)
346
-
347
- return func
348
-
349
- return Agent(traits=answers_dict).add_direct_question_answering_method(
350
- construct_answer_dict_function(answers_dict)
351
- )
352
-
353
- def simulate_results(self) -> "Results":
354
- """Simulate the survey and return the results."""
355
- a = self.create_agent()
356
- return self.by([a]).run()
357
-
358
- # endregion
359
-
360
- # region: Access methods
361
- def _get_question_index(
362
- self, q: Union[QuestionBase, str, EndOfSurvey.__class__]
363
- ) -> Union[int, EndOfSurvey.__class__]:
364
- """Return the index of the question or EndOfSurvey object.
365
-
366
- :param q: The question or question name to get the index of.
367
-
368
- It can handle it if the user passes in the question name, the question object, or the EndOfSurvey object.
369
-
370
- >>> s = Survey.example()
371
- >>> s._get_question_index("q0")
372
- 0
373
-
374
- This doesnt' work with questions that don't exist:
375
-
376
- >>> s._get_question_index("poop")
377
- Traceback (most recent call last):
378
- ...
379
- edsl.exceptions.surveys.SurveyError: Question name poop not found in survey. The current question names are {'q0': 0, 'q1': 1, 'q2': 2}.
380
- ...
381
- """
382
- if q == EndOfSurvey:
383
- return EndOfSurvey
384
- else:
385
- question_name = q if isinstance(q, str) else q.question_name
386
- if question_name not in self.question_name_to_index:
387
- raise SurveyError(
388
- f"""Question name {question_name} not found in survey. The current question names are {self.question_name_to_index}."""
389
- )
390
- return self.question_name_to_index[question_name]
391
-
392
- def get(self, question_name: str) -> QuestionBase:
393
- """
394
- Return the question object given the question name.
395
-
396
- :param question_name: The name of the question to get.
397
-
398
- >>> s = Survey.example()
399
- >>> s.get_question("q0")
400
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
401
- """
402
- if question_name not in self.question_name_to_index:
403
- raise SurveyError(f"Question name {question_name} not found in survey.")
404
- index = self.question_name_to_index[question_name]
405
- return self._questions[index]
406
-
407
- def get_question(self, question_name: str) -> QuestionBase:
408
- """Return the question object given the question name."""
409
- # import warnings
410
- # warnings.warn("survey.get_question is deprecated. Use subscript operator instead.")
411
- return self.get(question_name)
412
-
413
- def question_names_to_questions(self) -> dict:
414
- """Return a dictionary mapping question names to question attributes."""
415
- return {q.question_name: q for q in self.questions}
416
-
417
- @property
418
- def question_names(self) -> list[str]:
419
- """Return a list of question names in the survey.
420
-
421
- Example:
422
-
423
- >>> s = Survey.example()
424
- >>> s.question_names
425
- ['q0', 'q1', 'q2']
426
- """
427
- return [q.question_name for q in self.questions]
428
-
429
- @property
430
- def question_name_to_index(self) -> dict[str, int]:
431
- """Return a dictionary mapping question names to question indices.
432
-
433
- Example:
434
-
435
- >>> s = Survey.example()
436
- >>> s.question_name_to_index
437
- {'q0': 0, 'q1': 1, 'q2': 2}
438
- """
439
- return {q.question_name: i for i, q in enumerate(self.questions)}
440
-
441
- # endregion
442
-
443
- # region: serialization methods
444
- def __hash__(self) -> int:
445
- """Return a hash of the question."""
446
- from edsl.utilities.utilities import dict_hash
447
-
448
- return dict_hash(self.to_dict(add_edsl_version=False))
449
-
450
- def to_dict(self, add_edsl_version=True) -> dict[str, Any]:
451
- """Serialize the Survey object to a dictionary.
452
-
453
- >>> s = Survey.example()
454
- >>> s.to_dict(add_edsl_version = False).keys()
455
- dict_keys(['questions', 'memory_plan', 'rule_collection', 'question_groups'])
456
- """
457
- return {
458
- "questions": [
459
- q.to_dict(add_edsl_version=add_edsl_version)
460
- for q in self.recombined_questions_and_instructions()
461
- ],
462
- "memory_plan": self.memory_plan.to_dict(add_edsl_version=add_edsl_version),
463
- "rule_collection": self.rule_collection.to_dict(
464
- add_edsl_version=add_edsl_version
465
- ),
466
- "question_groups": self.question_groups,
467
- }
468
-
469
- @classmethod
470
- @remove_edsl_version
471
- def from_dict(cls, data: dict) -> Survey:
472
- """Deserialize the dictionary back to a Survey object.
473
-
474
- :param data: The dictionary to deserialize.
475
-
476
- >>> d = Survey.example().to_dict()
477
- >>> s = Survey.from_dict(d)
478
- >>> s == Survey.example()
479
- True
480
-
481
- >>> s = Survey.example(include_instructions = True)
482
- >>> d = s.to_dict()
483
- >>> news = Survey.from_dict(d)
484
- >>> news == s
485
- True
486
-
487
- """
488
-
489
- def get_class(pass_dict):
490
- if (class_name := pass_dict.get("edsl_class_name")) == "QuestionBase":
491
- return QuestionBase
492
- elif class_name == "Instruction":
493
- from edsl.surveys.instructions.Instruction import Instruction
494
-
495
- return Instruction
496
- elif class_name == "ChangeInstruction":
497
- from edsl.surveys.instructions.ChangeInstruction import (
498
- ChangeInstruction,
499
- )
500
-
501
- return ChangeInstruction
502
- else:
503
- return QuestionBase
504
-
505
- questions = [
506
- get_class(q_dict).from_dict(q_dict) for q_dict in data["questions"]
507
- ]
508
- memory_plan = MemoryPlan.from_dict(data["memory_plan"])
509
- survey = cls(
510
- questions=questions,
511
- memory_plan=memory_plan,
512
- rule_collection=RuleCollection.from_dict(data["rule_collection"]),
513
- question_groups=data["question_groups"],
514
- )
515
- return survey
516
-
517
- # endregion
518
-
519
- # region: Survey template parameters
520
- @property
521
- def scenario_attributes(self) -> list[str]:
522
- """Return a list of attributes that admissible Scenarios should have.
523
-
524
- Here we have a survey with a question that uses a jinja2 style {{ }} template:
525
-
526
- >>> from edsl import QuestionFreeText
527
- >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your name?", question_name="name"))
528
- >>> s.scenario_attributes
529
- ['greeting']
530
-
531
- >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your {{ attribute }}?", question_name="name"))
532
- >>> s.scenario_attributes
533
- ['greeting', 'attribute']
534
-
535
-
536
- """
537
- temp = []
538
- for question in self.questions:
539
- question_text = question.question_text
540
- # extract the contents of all {{ }} in the question text using regex
541
- matches = re.findall(r"\{\{(.+?)\}\}", question_text)
542
- # remove whitespace
543
- matches = [match.strip() for match in matches]
544
- # add them to the temp list
545
- temp.extend(matches)
546
- return temp
547
-
548
- @property
549
- def parameters(self):
550
- """Return a set of parameters in the survey.
551
-
552
- >>> s = Survey.example()
553
- >>> s.parameters
554
- set()
555
- """
556
- return set.union(*[q.parameters for q in self.questions])
557
-
558
- @property
559
- def parameters_by_question(self):
560
- """Return a dictionary of parameters by question in the survey.
561
- >>> from edsl import QuestionFreeText
562
- >>> q = QuestionFreeText(question_name = "example", question_text = "What is the capital of {{ country}}?")
563
- >>> s = Survey([q])
564
- >>> s.parameters_by_question
565
- {'example': {'country'}}
566
- """
567
- return {q.question_name: q.parameters for q in self.questions}
568
-
569
- # endregion
570
-
571
- # region: Survey construction
572
-
573
- # region: Adding questions and combining surveys
574
- def __add__(self, other: Survey) -> Survey:
575
- """Combine two surveys.
576
-
577
- :param other: The other survey to combine with this one.
578
- >>> s1 = Survey.example()
579
- >>> from edsl import QuestionFreeText
580
- >>> s2 = Survey([QuestionFreeText(question_text="What is your name?", question_name="yo")])
581
- >>> s3 = s1 + s2
582
- Traceback (most recent call last):
583
- ...
584
- edsl.exceptions.surveys.SurveyCreationError: ...
585
- ...
586
- >>> s3 = s1.clear_non_default_rules() + s2
587
- >>> len(s3.questions)
588
- 4
589
-
590
- """
591
- if (
592
- len(self.rule_collection.non_default_rules) > 0
593
- or len(other.rule_collection.non_default_rules) > 0
594
- ):
595
- raise SurveyCreationError(
596
- "Cannot combine two surveys with non-default rules. Please use the 'clear_non_default_rules' method to remove non-default rules from the survey.",
597
- )
598
-
599
- return Survey(questions=self.questions + other.questions)
600
-
601
- def move_question(self, identifier: Union[str, int], new_index: int):
602
- if isinstance(identifier, str):
603
- if identifier not in self.question_names:
604
- raise SurveyError(
605
- f"Question name '{identifier}' does not exist in the survey."
606
- )
607
- index = self.question_name_to_index[identifier]
608
- elif isinstance(identifier, int):
609
- if identifier < 0 or identifier >= len(self.questions):
610
- raise SurveyError(f"Index {identifier} is out of range.")
611
- index = identifier
612
- else:
613
- raise SurveyError(
614
- "Identifier must be either a string (question name) or an integer (question index)."
615
- )
616
-
617
- moving_question = self._questions[index]
618
-
619
- new_survey = self.delete_question(index)
620
- new_survey.add_question(moving_question, new_index)
621
- return new_survey
622
-
623
- def delete_question(self, identifier: Union[str, int]) -> Survey:
624
- """
625
- Delete a question from the survey.
626
-
627
- :param identifier: The name or index of the question to delete.
628
- :return: The updated Survey object.
629
-
630
- >>> from edsl import QuestionMultipleChoice, Survey
631
- >>> q1 = QuestionMultipleChoice(question_text="Q1", question_options=["A", "B"], question_name="q1")
632
- >>> q2 = QuestionMultipleChoice(question_text="Q2", question_options=["C", "D"], question_name="q2")
633
- >>> s = Survey().add_question(q1).add_question(q2)
634
- >>> _ = s.delete_question("q1")
635
- >>> len(s.questions)
636
- 1
637
- >>> _ = s.delete_question(0)
638
- >>> len(s.questions)
639
- 0
640
- """
641
- if isinstance(identifier, str):
642
- if identifier not in self.question_names:
643
- raise SurveyError(
644
- f"Question name '{identifier}' does not exist in the survey."
645
- )
646
- index = self.question_name_to_index[identifier]
647
- elif isinstance(identifier, int):
648
- if identifier < 0 or identifier >= len(self.questions):
649
- raise SurveyError(f"Index {identifier} is out of range.")
650
- index = identifier
651
- else:
652
- raise SurveyError(
653
- "Identifier must be either a string (question name) or an integer (question index)."
654
- )
655
-
656
- # Remove the question
657
- deleted_question = self._questions.pop(index)
658
- del self.pseudo_indices[deleted_question.question_name]
659
-
660
- # Update indices
661
- for question_name, old_index in self.pseudo_indices.items():
662
- if old_index > index:
663
- self.pseudo_indices[question_name] = old_index - 1
664
-
665
- # Update rules
666
- new_rule_collection = RuleCollection()
667
- for rule in self.rule_collection:
668
- if rule.current_q == index:
669
- continue # Remove rules associated with the deleted question
670
- if rule.current_q > index:
671
- rule.current_q -= 1
672
- if rule.next_q > index:
673
- rule.next_q -= 1
674
-
675
- if rule.next_q == index:
676
- if index == len(self.questions):
677
- rule.next_q = EndOfSurvey
678
- else:
679
- rule.next_q = index
680
-
681
- new_rule_collection.add_rule(rule)
682
- self.rule_collection = new_rule_collection
683
-
684
- # Update memory plan if it exists
685
- if hasattr(self, "memory_plan"):
686
- self.memory_plan.remove_question(deleted_question.question_name)
687
-
688
- return self
689
-
690
- def add_question(
691
- self, question: QuestionBase, index: Optional[int] = None
692
- ) -> Survey:
693
- """
694
- Add a question to survey.
695
-
696
- :param question: The question to add to the survey.
697
- :param question_name: The name of the question. If not provided, the question name is used.
698
-
699
- The question is appended at the end of the self.questions list
700
- A default rule is created that the next index is the next question.
701
-
702
- >>> from edsl import QuestionMultipleChoice
703
- >>> q = QuestionMultipleChoice(question_text = "Do you like school?", question_options=["yes", "no"], question_name="q0")
704
- >>> s = Survey().add_question(q)
705
-
706
- >>> s = Survey().add_question(q).add_question(q)
707
- Traceback (most recent call last):
708
- ...
709
- edsl.exceptions.surveys.SurveyCreationError: Question name 'q0' already exists in survey. Existing names are ['q0'].
710
- ...
711
- """
712
- if question.question_name in self.question_names:
713
- raise SurveyCreationError(
714
- f"""Question name '{question.question_name}' already exists in survey. Existing names are {self.question_names}."""
715
- )
716
- if index is None:
717
- index = len(self.questions)
718
-
719
- if index > len(self.questions):
720
- raise SurveyCreationError(
721
- f"Index {index} is greater than the number of questions in the survey."
722
- )
723
- if index < 0:
724
- raise SurveyCreationError(f"Index {index} is less than 0.")
725
-
726
- interior_insertion = index != len(self.questions)
727
-
728
- # index = len(self.questions)
729
- # TODO: This is a bit ugly because the user
730
- # doesn't "know" about _questions - it's generated by the
731
- # descriptor.
732
- self._questions.insert(index, question)
733
-
734
- if interior_insertion:
735
- for question_name, old_index in self.pseudo_indices.items():
736
- if old_index >= index:
737
- self.pseudo_indices[question_name] = old_index + 1
738
-
739
- self.pseudo_indices[question.question_name] = index
740
-
741
- ## Re-do question_name to index - this is done automatically
742
- # for question_name, old_index in self.question_name_to_index.items():
743
- # if old_index >= index:
744
- # self.question_name_to_index[question_name] = old_index + 1
745
-
746
- ## Need to re-do the rule collection and the indices of the questions
747
-
748
- ## If a rule is before the insertion index and next_q is also before the insertion index, no change needed.
749
- ## If the rule is before the insertion index but next_q is after the insertion index, increment the next_q by 1
750
- ## If the rule is after the insertion index, increment the current_q by 1 and the next_q by 1
751
-
752
- # using index + 1 presumes there is a next question
753
- if interior_insertion:
754
- for rule in self.rule_collection:
755
- if rule.current_q >= index:
756
- rule.current_q += 1
757
- if rule.next_q >= index:
758
- rule.next_q += 1
759
-
760
- # add a new rule
761
- self.rule_collection.add_rule(
762
- Rule(
763
- current_q=index,
764
- expression="True",
765
- next_q=index + 1,
766
- question_name_to_index=self.question_name_to_index,
767
- priority=RulePriority.DEFAULT.value,
768
- )
769
- )
770
-
771
- # a question might be added before the memory plan is created
772
- # it's ok because the memory plan will be updated when it is created
773
- if hasattr(self, "memory_plan"):
774
- self.memory_plan.add_question(question)
775
-
776
- return self
777
-
778
- def recombined_questions_and_instructions(
779
- self,
780
- ) -> list[Union[QuestionBase, "Instruction"]]:
781
- """Return a list of questions and instructions sorted by pseudo index."""
782
- questions_and_instructions = self._questions + list(
783
- self.instruction_names_to_instructions.values()
784
- )
785
- return sorted(
786
- questions_and_instructions, key=lambda x: self.pseudo_indices[x.name]
787
- )
788
-
789
- # endregion
790
-
791
- # region: Memory plan methods
792
- def set_full_memory_mode(self) -> Survey:
793
- """Add instructions to a survey that the agent should remember all of the answers to the questions in the survey.
794
-
795
- >>> s = Survey.example().set_full_memory_mode()
796
-
797
- """
798
- self._set_memory_plan(lambda i: self.question_names[:i])
799
- return self
800
-
801
- def set_lagged_memory(self, lags: int) -> Survey:
802
- """Add instructions to a survey that the agent should remember the answers to the questions in the survey.
803
-
804
- The agent should remember the answers to the questions in the survey from the previous lags.
805
- """
806
- self._set_memory_plan(lambda i: self.question_names[max(0, i - lags) : i])
807
- return self
808
-
809
- def _set_memory_plan(self, prior_questions_func: Callable):
810
- """Set memory plan based on a provided function determining prior questions.
811
-
812
- :param prior_questions_func: A function that takes the index of the current question and returns a list of prior questions to remember.
813
-
814
- >>> s = Survey.example()
815
- >>> s._set_memory_plan(lambda i: s.question_names[:i])
816
-
817
- """
818
- for i, question_name in enumerate(self.question_names):
819
- self.memory_plan.add_memory_collection(
820
- focal_question=question_name,
821
- prior_questions=prior_questions_func(i),
822
- )
823
-
824
- def add_targeted_memory(
825
- self,
826
- focal_question: Union[QuestionBase, str],
827
- prior_question: Union[QuestionBase, str],
828
- ) -> Survey:
829
- """Add instructions to a survey than when answering focal_question.
830
-
831
- :param focal_question: The question that the agent is answering.
832
- :param prior_question: The question that the agent should remember when answering the focal question.
833
-
834
- Here we add instructions to a survey than when answering q2 they should remember q1:
835
-
836
- >>> s = Survey.example().add_targeted_memory("q2", "q0")
837
- >>> s.memory_plan
838
- {'q2': Memory(prior_questions=['q0'])}
839
-
840
- The agent should also remember the answers to prior_questions listed in prior_questions.
841
- """
842
- focal_question_name = self.question_names[
843
- self._get_question_index(focal_question)
844
- ]
845
- prior_question_name = self.question_names[
846
- self._get_question_index(prior_question)
847
- ]
848
-
849
- self.memory_plan.add_single_memory(
850
- focal_question=focal_question_name,
851
- prior_question=prior_question_name,
852
- )
853
-
854
- return self
855
-
856
- def add_memory_collection(
857
- self,
858
- focal_question: Union[QuestionBase, str],
859
- prior_questions: List[Union[QuestionBase, str]],
860
- ) -> Survey:
861
- """Add prior questions and responses so the agent has them when answering.
862
-
863
- This adds instructions to a survey than when answering focal_question, the agent should also remember the answers to prior_questions listed in prior_questions.
864
-
865
- :param focal_question: The question that the agent is answering.
866
- :param prior_questions: The questions that the agent should remember when answering the focal question.
867
-
868
- Here we have it so that when answering q2, the agent should remember answers to q0 and q1:
869
-
870
- >>> s = Survey.example().add_memory_collection("q2", ["q0", "q1"])
871
- >>> s.memory_plan
872
- {'q2': Memory(prior_questions=['q0', 'q1'])}
873
- """
874
- focal_question_name = self.question_names[
875
- self._get_question_index(focal_question)
876
- ]
877
-
878
- prior_question_names = [
879
- self.question_names[self._get_question_index(prior_question)]
880
- for prior_question in prior_questions
881
- ]
882
-
883
- self.memory_plan.add_memory_collection(
884
- focal_question=focal_question_name, prior_questions=prior_question_names
885
- )
886
- return self
887
-
888
- # endregion
889
- # endregion
890
- # endregion
891
-
892
- # region: Question groups
893
- def add_question_group(
894
- self,
895
- start_question: Union[QuestionBase, str],
896
- end_question: Union[QuestionBase, str],
897
- group_name: str,
898
- ) -> Survey:
899
- """Add a group of questions to the survey.
900
-
901
- :param start_question: The first question in the group.
902
- :param end_question: The last question in the group.
903
- :param group_name: The name of the group.
904
-
905
- Example:
906
-
907
- >>> s = Survey.example().add_question_group("q0", "q1", "group1")
908
- >>> s.question_groups
909
- {'group1': (0, 1)}
910
-
911
- The name of the group must be a valid identifier:
912
-
913
- >>> s = Survey.example().add_question_group("q0", "q2", "1group1")
914
- Traceback (most recent call last):
915
- ...
916
- edsl.exceptions.surveys.SurveyCreationError: Group name 1group1 is not a valid identifier.
917
- ...
918
- >>> s = Survey.example().add_question_group("q0", "q1", "q0")
919
- Traceback (most recent call last):
920
- ...
921
- edsl.exceptions.surveys.SurveyCreationError: ...
922
- ...
923
- >>> s = Survey.example().add_question_group("q1", "q0", "group1")
924
- Traceback (most recent call last):
925
- ...
926
- edsl.exceptions.surveys.SurveyCreationError: ...
927
- ...
928
- """
929
-
930
- if not group_name.isidentifier():
931
- raise SurveyCreationError(
932
- f"Group name {group_name} is not a valid identifier."
933
- )
934
-
935
- if group_name in self.question_groups:
936
- raise SurveyCreationError(
937
- f"Group name {group_name} already exists in the survey."
938
- )
939
-
940
- if group_name in self.question_name_to_index:
941
- raise SurveyCreationError(
942
- f"Group name {group_name} already exists as a question name in the survey."
943
- )
944
-
945
- start_index = self._get_question_index(start_question)
946
- end_index = self._get_question_index(end_question)
947
-
948
- if start_index > end_index:
949
- raise SurveyCreationError(
950
- f"Start index {start_index} is greater than end index {end_index}."
951
- )
952
-
953
- for existing_group_name, (
954
- existing_start_index,
955
- existing_end_index,
956
- ) in self.question_groups.items():
957
- if start_index < existing_start_index and end_index > existing_end_index:
958
- raise SurveyCreationError(
959
- f"Group {group_name} contains the questions in the new group."
960
- )
961
- if start_index > existing_start_index and end_index < existing_end_index:
962
- raise SurveyCreationError(
963
- f"Group {group_name} is contained in the new group."
964
- )
965
- if start_index < existing_start_index and end_index > existing_start_index:
966
- raise SurveyCreationError(
967
- f"Group {group_name} overlaps with the new group."
968
- )
969
- if start_index < existing_end_index and end_index > existing_end_index:
970
- raise SurveyCreationError(
971
- f"Group {group_name} overlaps with the new group."
972
- )
973
-
974
- self.question_groups[group_name] = (start_index, end_index)
975
- return self
976
-
977
- # endregion
978
-
979
- # region: Survey rules
980
- def show_rules(self) -> None:
981
- """Print out the rules in the survey.
982
-
983
- >>> s = Survey.example()
984
- >>> s.show_rules()
985
- ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
986
- ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
987
- ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
988
- │ 0 │ True │ 1 │ -1 │ False │
989
- │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
990
- │ 1 │ True │ 2 │ -1 │ False │
991
- │ 2 │ True │ 3 │ -1 │ False │
992
- └───────────┴─────────────┴────────┴──────────┴─────────────┘
993
- """
994
- self.rule_collection.show_rules()
995
-
996
- def add_stop_rule(
997
- self, question: Union[QuestionBase, str], expression: str
998
- ) -> Survey:
999
- """Add a rule that stops the survey.
1000
- The rule is evaluated *after* the question is answered. If the rule is true, the survey ends.
1001
-
1002
- :param question: The question to add the stop rule to.
1003
- :param expression: The expression to evaluate.
1004
-
1005
- If this rule is true, the survey ends.
1006
-
1007
- Here, answering "yes" to q0 ends the survey:
1008
-
1009
- >>> s = Survey.example().add_stop_rule("q0", "q0 == 'yes'")
1010
- >>> s.next_question("q0", {"q0": "yes"})
1011
- EndOfSurvey
1012
-
1013
- By comparison, answering "no" to q0 does not end the survey:
1014
-
1015
- >>> s.next_question("q0", {"q0": "no"}).question_name
1016
- 'q1'
1017
-
1018
- >>> s.add_stop_rule("q0", "q1 <> 'yes'")
1019
- Traceback (most recent call last):
1020
- ...
1021
- edsl.exceptions.surveys.SurveyCreationError: The expression contains '<>', which is not allowed. You probably mean '!='.
1022
- ...
1023
- """
1024
- expression = ValidatedString(expression)
1025
- prior_question_appears = False
1026
- for prior_question in self.questions:
1027
- if prior_question.question_name in expression:
1028
- prior_question_appears = True
1029
-
1030
- if not prior_question_appears:
1031
- import warnings
1032
-
1033
- warnings.warn(
1034
- f"The expression {expression} does not contain any prior question names. This is probably a mistake."
1035
- )
1036
- self.add_rule(question, expression, EndOfSurvey)
1037
- return self
1038
-
1039
- def clear_non_default_rules(self) -> Survey:
1040
- """Remove all non-default rules from the survey.
1041
-
1042
- >>> Survey.example().show_rules()
1043
- ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1044
- ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1045
- ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1046
- │ 0 │ True │ 1 │ -1 │ False │
1047
- │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
1048
- │ 1 │ True │ 2 │ -1 │ False │
1049
- │ 2 │ True │ 3 │ -1 │ False │
1050
- └───────────┴─────────────┴────────┴──────────┴─────────────┘
1051
- >>> Survey.example().clear_non_default_rules().show_rules()
1052
- ┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1053
- ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1054
- ┡━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1055
- │ 0 │ True │ 1 │ -1 │ False │
1056
- │ 1 │ True │ 2 │ -1 │ False │
1057
- │ 2 │ True │ 3 │ -1 │ False │
1058
- └───────────┴────────────┴────────┴──────────┴─────────────┘
1059
- """
1060
- s = Survey()
1061
- for question in self.questions:
1062
- s.add_question(question)
1063
- return s
1064
-
1065
- def add_skip_rule(
1066
- self, question: Union[QuestionBase, str], expression: str
1067
- ) -> Survey:
1068
- """
1069
- Adds a per-question skip rule to the survey.
1070
-
1071
- :param question: The question to add the skip rule to.
1072
- :param expression: The expression to evaluate.
1073
-
1074
- This adds a rule that skips 'q0' always, before the question is answered:
1075
-
1076
- >>> from edsl import QuestionFreeText
1077
- >>> q0 = QuestionFreeText.example()
1078
- >>> q0.question_name = "q0"
1079
- >>> q1 = QuestionFreeText.example()
1080
- >>> q1.question_name = "q1"
1081
- >>> s = Survey([q0, q1]).add_skip_rule("q0", "True")
1082
- >>> s.next_question("q0", {}).question_name
1083
- 'q1'
1084
-
1085
- Note that this is different from a rule that jumps to some other question *after* the question is answered.
1086
-
1087
- """
1088
- question_index = self._get_question_index(question)
1089
- self._add_rule(question, expression, question_index + 1, before_rule=True)
1090
- return self
1091
-
1092
- def _get_new_rule_priority(
1093
- self, question_index: int, before_rule: bool = False
1094
- ) -> int:
1095
- """Return the priority for the new rule.
1096
-
1097
- :param question_index: The index of the question to add the rule to.
1098
- :param before_rule: Whether the rule is evaluated before the question is answered.
1099
-
1100
- >>> s = Survey.example()
1101
- >>> s._get_new_rule_priority(0)
1102
- 1
1103
- """
1104
- current_priorities = [
1105
- rule.priority
1106
- for rule in self.rule_collection.applicable_rules(
1107
- question_index, before_rule
1108
- )
1109
- ]
1110
- if len(current_priorities) == 0:
1111
- return RulePriority.DEFAULT.value + 1
1112
-
1113
- max_priority = max(current_priorities)
1114
- # newer rules take priority over older rules
1115
- new_priority = (
1116
- RulePriority.DEFAULT.value
1117
- if len(current_priorities) == 0
1118
- else max_priority + 1
1119
- )
1120
- return new_priority
1121
-
1122
- def add_rule(
1123
- self,
1124
- question: Union[QuestionBase, str],
1125
- expression: str,
1126
- next_question: Union[QuestionBase, int],
1127
- before_rule: bool = False,
1128
- ) -> Survey:
1129
- """
1130
- Add a rule to a Question of the Survey.
1131
-
1132
- :param question: The question to add the rule to.
1133
- :param expression: The expression to evaluate.
1134
- :param next_question: The next question to go to if the rule is true.
1135
- :param before_rule: Whether the rule is evaluated before the question is answered.
1136
-
1137
- This adds a rule that if the answer to q0 is 'yes', the next question is q2 (as opposed to q1)
1138
-
1139
- >>> s = Survey.example().add_rule("q0", "{{ q0 }} == 'yes'", "q2")
1140
- >>> s.next_question("q0", {"q0": "yes"}).question_name
1141
- 'q2'
1142
-
1143
- """
1144
- return self._add_rule(
1145
- question, expression, next_question, before_rule=before_rule
1146
- )
1147
-
1148
- def _add_rule(
1149
- self,
1150
- question: Union[QuestionBase, str],
1151
- expression: str,
1152
- next_question: Union[QuestionBase, str, int],
1153
- before_rule: bool = False,
1154
- ) -> Survey:
1155
- """
1156
- Add a rule to a Question of the Survey with the appropriate priority.
1157
-
1158
- :param question: The question to add the rule to.
1159
- :param expression: The expression to evaluate.
1160
- :param next_question: The next question to go to if the rule is true.
1161
- :param before_rule: Whether the rule is evaluated before the question is answered.
1162
-
1163
-
1164
- - The last rule added for the question will have the highest priority.
1165
- - If there are no rules, the rule added gets priority -1.
1166
- """
1167
- question_index = self._get_question_index(question)
1168
-
1169
- # Might not have the name of the next question yet
1170
- if isinstance(next_question, int):
1171
- next_question_index = next_question
1172
- else:
1173
- next_question_index = self._get_question_index(next_question)
1174
-
1175
- new_priority = self._get_new_rule_priority(question_index, before_rule)
1176
-
1177
- self.rule_collection.add_rule(
1178
- Rule(
1179
- current_q=question_index,
1180
- expression=expression,
1181
- next_q=next_question_index,
1182
- question_name_to_index=self.question_name_to_index,
1183
- priority=new_priority,
1184
- before_rule=before_rule,
1185
- )
1186
- )
1187
-
1188
- return self
1189
-
1190
- # endregion
1191
-
1192
- # region: Forward methods
1193
- def by(self, *args: Union["Agent", "Scenario", "LanguageModel"]) -> "Jobs":
1194
- """Add Agents, Scenarios, and LanguageModels to a survey and returns a runnable Jobs object.
1195
-
1196
- :param args: The Agents, Scenarios, and LanguageModels to add to the survey.
1197
-
1198
- This takes the survey and adds an Agent and a Scenario via 'by' which converts to a Jobs object:
1199
-
1200
- >>> s = Survey.example(); from edsl import Agent; from edsl import Scenario
1201
- >>> s.by(Agent.example()).by(Scenario.example())
1202
- Jobs(...)
1203
- """
1204
- from edsl.jobs.Jobs import Jobs
1205
-
1206
- job = Jobs(survey=self)
1207
- return job.by(*args)
1208
-
1209
- def to_jobs(self):
1210
- """Convert the survey to a Jobs object."""
1211
- from edsl.jobs.Jobs import Jobs
1212
-
1213
- return Jobs(survey=self)
1214
-
1215
- def show_prompts(self):
1216
- return self.to_jobs().show_prompts()
1217
-
1218
- # endregion
1219
-
1220
- # region: Running the survey
1221
-
1222
- def __call__(
1223
- self,
1224
- model=None,
1225
- agent=None,
1226
- cache=None,
1227
- disable_remote_cache: bool = False,
1228
- disable_remote_inference: bool = False,
1229
- **kwargs,
1230
- ):
1231
- """Run the survey with default model, taking the required survey as arguments.
1232
-
1233
- >>> from edsl.questions import QuestionFunctional
1234
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1235
- >>> q = QuestionFunctional(question_name = "q0", func = f)
1236
- >>> s = Survey([q])
1237
- >>> s(period = "morning", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
1238
- 'yes'
1239
- >>> s(period = "evening", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
1240
- 'no'
1241
- """
1242
- job = self.get_job(model, agent, **kwargs)
1243
- return job.run(
1244
- cache=cache,
1245
- disable_remote_cache=disable_remote_cache,
1246
- disable_remote_inference=disable_remote_inference,
1247
- )
1248
-
1249
- async def run_async(
1250
- self,
1251
- model: Optional["Model"] = None,
1252
- agent: Optional["Agent"] = None,
1253
- cache: Optional["Cache"] = None,
1254
- disable_remote_inference: bool = False,
1255
- **kwargs,
1256
- ):
1257
- """Run the survey with default model, taking the required survey as arguments.
1258
-
1259
- >>> import asyncio
1260
- >>> from edsl.questions import QuestionFunctional
1261
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1262
- >>> q = QuestionFunctional(question_name = "q0", func = f)
1263
- >>> s = Survey([q])
1264
- >>> async def test_run_async(): result = await s.run_async(period="morning", disable_remote_inference = True); print(result.select("answer.q0").first())
1265
- >>> asyncio.run(test_run_async())
1266
- yes
1267
- >>> import asyncio
1268
- >>> from edsl.questions import QuestionFunctional
1269
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1270
- >>> q = QuestionFunctional(question_name = "q0", func = f)
1271
- >>> s = Survey([q])
1272
- >>> async def test_run_async(): result = await s.run_async(period="evening", disable_remote_inference = True); print(result.select("answer.q0").first())
1273
- >>> asyncio.run(test_run_async())
1274
- no
1275
- """
1276
- # TODO: temp fix by creating a cache
1277
- if cache is None:
1278
- from edsl.data import Cache
1279
-
1280
- c = Cache()
1281
- else:
1282
- c = cache
1283
- jobs: "Jobs" = self.get_job(model=model, agent=agent, **kwargs)
1284
- return await jobs.run_async(
1285
- cache=c, disable_remote_inference=disable_remote_inference
1286
- )
1287
-
1288
- def run(self, *args, **kwargs) -> "Results":
1289
- """Turn the survey into a Job and runs it.
1290
-
1291
- >>> from edsl import QuestionFreeText
1292
- >>> s = Survey([QuestionFreeText.example()])
1293
- >>> from edsl.language_models import LanguageModel
1294
- >>> m = LanguageModel.example(test_model = True, canned_response = "Great!")
1295
- >>> results = s.by(m).run(cache = False, disable_remote_cache = True, disable_remote_inference = True)
1296
- >>> results.select('answer.*')
1297
- Dataset([{'answer.how_are_you': ['Great!']}])
1298
- """
1299
- from edsl.jobs.Jobs import Jobs
1300
-
1301
- return Jobs(survey=self).run(*args, **kwargs)
1302
-
1303
- # region: Survey flow
1304
- def next_question(
1305
- self, current_question: Union[str, QuestionBase], answers: dict
1306
- ) -> Union[QuestionBase, EndOfSurvey.__class__]:
1307
- """
1308
- Return the next question in a survey.
1309
-
1310
- :param current_question: The current question in the survey.
1311
- :param answers: The answers for the survey so far
1312
-
1313
- - If called with no arguments, it returns the first question in the survey.
1314
- - If no answers are provided for a question with a rule, the next question is returned. If answers are provided, the next question is determined by the rules and the answers.
1315
- - If the next question is the last question in the survey, an EndOfSurvey object is returned.
1316
-
1317
- >>> s = Survey.example()
1318
- >>> s.next_question("q0", {"q0": "yes"}).question_name
1319
- 'q2'
1320
- >>> s.next_question("q0", {"q0": "no"}).question_name
1321
- 'q1'
1322
-
1323
- """
1324
- if isinstance(current_question, str):
1325
- current_question = self.get_question(current_question)
1326
-
1327
- question_index = self.question_name_to_index[current_question.question_name]
1328
- next_question_object = self.rule_collection.next_question(
1329
- question_index, answers
1330
- )
1331
-
1332
- if next_question_object.num_rules_found == 0:
1333
- raise SurveyHasNoRulesError
1334
-
1335
- if next_question_object.next_q == EndOfSurvey:
1336
- return EndOfSurvey
1337
- else:
1338
- if next_question_object.next_q >= len(self.questions):
1339
- return EndOfSurvey
1340
- else:
1341
- return self.questions[next_question_object.next_q]
1342
-
1343
- def gen_path_through_survey(self) -> Generator[QuestionBase, dict, None]:
1344
- """
1345
- Generate a coroutine that can be used to conduct an Interview.
1346
-
1347
- The coroutine is a generator that yields a question and receives answers.
1348
- It starts with the first question in the survey.
1349
- The coroutine ends when an EndOfSurvey object is returned.
1350
-
1351
- For the example survey, this is the rule table:
1352
-
1353
- >>> s = Survey.example()
1354
- >>> s.show_rules()
1355
- ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1356
- ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1357
- ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1358
- │ 0 │ True │ 1 │ -1 │ False │
1359
- │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
1360
- │ 1 │ True │ 2 │ -1 │ False │
1361
- │ 2 │ True │ 3 │ -1 │ False │
1362
- └───────────┴─────────────┴────────┴──────────┴─────────────┘
1363
-
1364
- Note that q0 has a rule that if the answer is 'yes', the next question is q2. If the answer is 'no', the next question is q1.
1365
-
1366
- Here is the path through the survey if the answer to q0 is 'yes':
1367
-
1368
- >>> i = s.gen_path_through_survey()
1369
- >>> next(i)
1370
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1371
- >>> i.send({"q0": "yes"})
1372
- Question('multiple_choice', question_name = \"""q2\""", question_text = \"""Why?\""", question_options = ['**lack*** of killer bees in cafeteria', 'other'])
1373
-
1374
- And here is the path through the survey if the answer to q0 is 'no':
1375
-
1376
- >>> i2 = s.gen_path_through_survey()
1377
- >>> next(i2)
1378
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1379
- >>> i2.send({"q0": "no"})
1380
- Question('multiple_choice', question_name = \"""q1\""", question_text = \"""Why not?\""", question_options = ['killer bees in cafeteria', 'other'])
1381
-
1382
-
1383
- """
1384
- self.answers = {}
1385
- question = self._questions[0]
1386
- # should the first question be skipped?
1387
- if self.rule_collection.skip_question_before_running(0, self.answers):
1388
- question = self.next_question(question, self.answers)
1389
-
1390
- while not question == EndOfSurvey:
1391
- # breakpoint()
1392
- answer = yield question
1393
- self.answers.update(answer)
1394
- # print(f"Answers: {self.answers}")
1395
- ## TODO: This should also include survey and agent attributes
1396
- question = self.next_question(question, self.answers)
1397
-
1398
- # endregion
1399
-
1400
- # regions: DAG construction
1401
- def textify(self, index_dag: DAG) -> DAG:
1402
- """Convert the DAG of question indices to a DAG of question names.
1403
-
1404
- :param index_dag: The DAG of question indices.
1405
-
1406
- Example:
1407
-
1408
- >>> s = Survey.example()
1409
- >>> d = s.dag()
1410
- >>> d
1411
- {1: {0}, 2: {0}}
1412
- >>> s.textify(d)
1413
- {'q1': {'q0'}, 'q2': {'q0'}}
1414
- """
1415
-
1416
- def get_name(index: int):
1417
- """Return the name of the question given the index."""
1418
- if index >= len(self.questions):
1419
- return EndOfSurvey
1420
- try:
1421
- return self.questions[index].question_name
1422
- except IndexError:
1423
- print(
1424
- f"The index is {index} but the length of the questions is {len(self.questions)}"
1425
- )
1426
- raise SurveyError
1427
-
1428
- try:
1429
- text_dag = {}
1430
- for child_index, parent_indices in index_dag.items():
1431
- parent_names = {get_name(index) for index in parent_indices}
1432
- child_name = get_name(child_index)
1433
- text_dag[child_name] = parent_names
1434
- return text_dag
1435
- except IndexError:
1436
- raise
1437
-
1438
- @property
1439
- def piping_dag(self) -> DAG:
1440
- """Figures out the DAG of piping dependencies.
1441
-
1442
- >>> from edsl import QuestionFreeText
1443
- >>> q0 = QuestionFreeText(question_text="Here is a question", question_name="q0")
1444
- >>> q1 = QuestionFreeText(question_text="You previously answered {{ q0 }}---how do you feel now?", question_name="q1")
1445
- >>> s = Survey([q0, q1])
1446
- >>> s.piping_dag
1447
- {1: {0}}
1448
- """
1449
- d = {}
1450
- for question_name, depenencies in self.parameters_by_question.items():
1451
- if depenencies:
1452
- question_index = self.question_name_to_index[question_name]
1453
- for dependency in depenencies:
1454
- if dependency not in self.question_name_to_index:
1455
- pass
1456
- else:
1457
- dependency_index = self.question_name_to_index[dependency]
1458
- if question_index not in d:
1459
- d[question_index] = set()
1460
- d[question_index].add(dependency_index)
1461
- return d
1462
-
1463
- def dag(self, textify: bool = False) -> DAG:
1464
- """Return the DAG of the survey, which reflects both skip-logic and memory.
1465
-
1466
- :param textify: Whether to return the DAG with question names instead of indices.
1467
-
1468
- >>> s = Survey.example()
1469
- >>> d = s.dag()
1470
- >>> d
1471
- {1: {0}, 2: {0}}
1472
-
1473
- """
1474
- memory_dag = self.memory_plan.dag
1475
- rule_dag = self.rule_collection.dag
1476
- piping_dag = self.piping_dag
1477
- if textify:
1478
- memory_dag = DAG(self.textify(memory_dag))
1479
- rule_dag = DAG(self.textify(rule_dag))
1480
- piping_dag = DAG(self.textify(piping_dag))
1481
- return memory_dag + rule_dag + piping_dag
1482
-
1483
- ###################
1484
- # DUNDER METHODS
1485
- ###################
1486
- def __len__(self) -> int:
1487
- """Return the number of questions in the survey.
1488
-
1489
- >>> s = Survey.example()
1490
- >>> len(s)
1491
- 3
1492
- """
1493
- return len(self._questions)
1494
-
1495
- def __getitem__(self, index) -> QuestionBase:
1496
- """Return the question object given the question index.
1497
-
1498
- :param index: The index of the question to get.
1499
-
1500
- >>> s = Survey.example()
1501
- >>> s[0]
1502
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1503
-
1504
- """
1505
- if isinstance(index, int):
1506
- return self._questions[index]
1507
- elif isinstance(index, str):
1508
- return getattr(self, index)
1509
-
1510
- def _diff(self, other):
1511
- """Used for debugging. Print out the differences between two surveys."""
1512
- from rich import print
1513
-
1514
- for key, value in self.to_dict().items():
1515
- if value != other.to_dict()[key]:
1516
- print(f"Key: {key}")
1517
- print("\n")
1518
- print(f"Self: {value}")
1519
- print("\n")
1520
- print(f"Other: {other.to_dict()[key]}")
1521
- print("\n\n")
1522
-
1523
- def __eq__(self, other) -> bool:
1524
- """Return True if the two surveys have the same to_dict.
1525
-
1526
- :param other: The other survey to compare to.
1527
-
1528
- >>> s = Survey.example()
1529
- >>> s == s
1530
- True
1531
-
1532
- >>> s == "poop"
1533
- False
1534
-
1535
- """
1536
- if not isinstance(other, Survey):
1537
- return False
1538
- return self.to_dict() == other.to_dict()
1539
-
1540
- @classmethod
1541
- def from_qsf(
1542
- cls, qsf_file: Optional[str] = None, url: Optional[str] = None
1543
- ) -> Survey:
1544
- """Create a Survey object from a Qualtrics QSF file."""
1545
-
1546
- if url and qsf_file:
1547
- raise ValueError("Only one of url or qsf_file can be provided.")
1548
-
1549
- if (not url) and (not qsf_file):
1550
- raise ValueError("Either url or qsf_file must be provided.")
1551
-
1552
- if url:
1553
- response = requests.get(url)
1554
- response.raise_for_status() # Ensure the request was successful
1555
-
1556
- # Save the Excel file to a temporary file
1557
- with tempfile.NamedTemporaryFile(suffix=".qsf", delete=False) as temp_file:
1558
- temp_file.write(response.content)
1559
- qsf_file = temp_file.name
1560
-
1561
- from edsl.surveys.SurveyQualtricsImport import SurveyQualtricsImport
1562
-
1563
- so = SurveyQualtricsImport(qsf_file)
1564
- return so.create_survey()
1565
-
1566
- # region: Display methods
1567
- def print(self):
1568
- """Print the survey in a rich format.
1569
-
1570
- >>> s = Survey.example()
1571
- >>> s.print()
1572
- {
1573
- "questions": [
1574
- ...
1575
- }
1576
- """
1577
- from rich import print_json
1578
- import json
1579
-
1580
- print_json(json.dumps(self.to_dict()))
1581
-
1582
- def __repr__(self) -> str:
1583
- """Return a string representation of the survey."""
1584
-
1585
- # questions_string = ", ".join([repr(q) for q in self._questions])
1586
- questions_string = ", ".join([repr(q) for q in self.raw_passed_questions or []])
1587
- # question_names_string = ", ".join([repr(name) for name in self.question_names])
1588
- return f"Survey(questions=[{questions_string}], memory_plan={self.memory_plan}, rule_collection={self.rule_collection}, question_groups={self.question_groups})"
1589
-
1590
- def _repr_html_(self) -> str:
1591
- from edsl.utilities.utilities import data_to_html
1592
-
1593
- return data_to_html(self.to_dict())
1594
-
1595
- def rich_print(self) -> Table:
1596
- """Print the survey in a rich format.
1597
-
1598
- >>> t = Survey.example().rich_print()
1599
- >>> print(t) # doctest: +SKIP
1600
- ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
1601
- ┃ Questions ┃
1602
- ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
1603
- │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┓ │
1604
- │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1605
- │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━┩ │
1606
- │ │ q0 │ multiple_choice │ Do you like school? │ yes, no │ │
1607
- │ └───────────────┴─────────────────┴─────────────────────┴─────────┘ │
1608
- │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │
1609
- │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1610
- │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │
1611
- │ │ q1 │ multiple_choice │ Why not? │ killer bees in cafeteria, other │ │
1612
- │ └───────────────┴─────────────────┴───────────────┴─────────────────────────────────┘ │
1613
- │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │
1614
- │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1615
- │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │
1616
- │ │ q2 │ multiple_choice │ Why? │ **lack*** of killer bees in cafeteria, other │ │
1617
- │ └───────────────┴─────────────────┴───────────────┴──────────────────────────────────────────────┘ │
1618
- └────────────────────────────────────────────────────────────────────────────────────────────────────┘
1619
- """
1620
- from rich.table import Table
1621
-
1622
- table = Table(show_header=True, header_style="bold magenta")
1623
- table.add_column("Questions", style="dim")
1624
-
1625
- for question in self._questions:
1626
- table.add_row(question.rich_print())
1627
-
1628
- return table
1629
-
1630
- # endregion
1631
-
1632
- def codebook(self) -> dict[str, str]:
1633
- """Create a codebook for the survey, mapping question names to question text.
1634
-
1635
- >>> s = Survey.example()
1636
- >>> s.codebook()
1637
- {'q0': 'Do you like school?', 'q1': 'Why not?', 'q2': 'Why?'}
1638
- """
1639
- codebook = {}
1640
- for question in self._questions:
1641
- codebook[question.question_name] = question.question_text
1642
- return codebook
1643
-
1644
- # region: Export methods
1645
- def to_csv(self, filename: str = None):
1646
- """Export the survey to a CSV file.
1647
-
1648
- :param filename: The name of the file to save the CSV to.
1649
-
1650
- >>> s = Survey.example()
1651
- >>> s.to_csv() # doctest: +SKIP
1652
- index question_name question_text question_options question_type
1653
- 0 0 q0 Do you like school? [yes, no] multiple_choice
1654
- 1 1 q1 Why not? [killer bees in cafeteria, other] multiple_choice
1655
- 2 2 q2 Why? [**lack*** of killer bees in cafeteria, other] multiple_choice
1656
- """
1657
- raw_data = []
1658
- for index, question in enumerate(self._questions):
1659
- d = {"index": index}
1660
- question_dict = question.to_dict()
1661
- _ = question_dict.pop("edsl_version")
1662
- _ = question_dict.pop("edsl_class_name")
1663
- d.update(question_dict)
1664
- raw_data.append(d)
1665
- from pandas import DataFrame
1666
-
1667
- df = DataFrame(raw_data)
1668
- if filename:
1669
- df.to_csv(filename, index=False)
1670
- else:
1671
- return df
1672
-
1673
- # endregion
1674
-
1675
- @classmethod
1676
- def example(
1677
- cls,
1678
- params: bool = False,
1679
- randomize: bool = False,
1680
- include_instructions=False,
1681
- custom_instructions: Optional[str] = None,
1682
- ) -> Survey:
1683
- """Return an example survey.
1684
-
1685
- >>> s = Survey.example()
1686
- >>> [q.question_text for q in s.questions]
1687
- ['Do you like school?', 'Why not?', 'Why?']
1688
- """
1689
- from edsl.questions.QuestionMultipleChoice import QuestionMultipleChoice
1690
-
1691
- addition = "" if not randomize else str(uuid4())
1692
- q0 = QuestionMultipleChoice(
1693
- question_text=f"Do you like school?{addition}",
1694
- question_options=["yes", "no"],
1695
- question_name="q0",
1696
- )
1697
- q1 = QuestionMultipleChoice(
1698
- question_text="Why not?",
1699
- question_options=["killer bees in cafeteria", "other"],
1700
- question_name="q1",
1701
- )
1702
- q2 = QuestionMultipleChoice(
1703
- question_text="Why?",
1704
- question_options=["**lack*** of killer bees in cafeteria", "other"],
1705
- question_name="q2",
1706
- )
1707
- if params:
1708
- q3 = QuestionMultipleChoice(
1709
- question_text="To the question '{{ q0.question_text}}', you said '{{ q0.answer }}'. Do you still feel this way?",
1710
- question_options=["yes", "no"],
1711
- question_name="q3",
1712
- )
1713
- s = cls(questions=[q0, q1, q2, q3])
1714
- return s
1715
-
1716
- if include_instructions:
1717
- from edsl import Instruction
1718
-
1719
- custom_instructions = (
1720
- custom_instructions if custom_instructions else "Please pay attention!"
1721
- )
1722
-
1723
- i = Instruction(text=custom_instructions, name="attention")
1724
- s = cls(questions=[i, q0, q1, q2])
1725
- return s
1726
-
1727
- s = cls(questions=[q0, q1, q2])
1728
- s = s.add_rule(q0, "q0 == 'yes'", q2)
1729
- return s
1730
-
1731
- def get_job(self, model=None, agent=None, **kwargs):
1732
- if model is None:
1733
- from edsl import Model
1734
-
1735
- model = Model()
1736
-
1737
- from edsl.scenarios.Scenario import Scenario
1738
-
1739
- s = Scenario(kwargs)
1740
-
1741
- if not agent:
1742
- from edsl import Agent
1743
-
1744
- agent = Agent()
1745
-
1746
- return self.by(s).by(agent).by(model)
1747
-
1748
-
1749
- def main():
1750
- """Run the example survey."""
1751
-
1752
- def example_survey():
1753
- """Return an example survey."""
1754
- from edsl.questions.QuestionMultipleChoice import QuestionMultipleChoice
1755
- from edsl.surveys.Survey import Survey
1756
-
1757
- q0 = QuestionMultipleChoice(
1758
- question_text="Do you like school?",
1759
- question_options=["yes", "no"],
1760
- question_name="q0",
1761
- )
1762
- q1 = QuestionMultipleChoice(
1763
- question_text="Why not?",
1764
- question_options=["killer bees in cafeteria", "other"],
1765
- question_name="q1",
1766
- )
1767
- q2 = QuestionMultipleChoice(
1768
- question_text="Why?",
1769
- question_options=["**lack*** of killer bees in cafeteria", "other"],
1770
- question_name="q2",
1771
- )
1772
- s = Survey(questions=[q0, q1, q2])
1773
- s = s.add_rule(q0, "q0 == 'yes'", q2)
1774
- return s
1775
-
1776
- s = example_survey()
1777
- survey_dict = s.to_dict()
1778
- s2 = Survey.from_dict(survey_dict)
1779
- results = s2.run()
1780
- print(results)
1781
-
1782
-
1783
- if __name__ == "__main__":
1784
- import doctest
1785
-
1786
- # doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.SKIP)
1787
- doctest.testmod(optionflags=doctest.ELLIPSIS)
1
+ """A Survey is collection of questions that can be administered to an Agent."""
2
+
3
+ from __future__ import annotations
4
+ import re
5
+ import tempfile
6
+ import requests
7
+
8
+ from typing import Any, Generator, Optional, Union, List, Literal, Callable
9
+ from uuid import uuid4
10
+ from edsl.Base import Base
11
+ from edsl.exceptions import SurveyCreationError, SurveyHasNoRulesError
12
+ from edsl.exceptions.surveys import SurveyError
13
+
14
+ from edsl.questions.QuestionBase import QuestionBase
15
+ from edsl.surveys.base import RulePriority, EndOfSurvey
16
+ from edsl.surveys.DAG import DAG
17
+ from edsl.surveys.descriptors import QuestionsDescriptor
18
+ from edsl.surveys.MemoryPlan import MemoryPlan
19
+ from edsl.surveys.Rule import Rule
20
+ from edsl.surveys.RuleCollection import RuleCollection
21
+ from edsl.surveys.SurveyExportMixin import SurveyExportMixin
22
+ from edsl.surveys.SurveyFlowVisualizationMixin import SurveyFlowVisualizationMixin
23
+ from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
24
+
25
+ from edsl.agents.Agent import Agent
26
+
27
+ from edsl.surveys.instructions.InstructionCollection import InstructionCollection
28
+ from edsl.surveys.instructions.Instruction import Instruction
29
+ from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
30
+
31
+
32
+ class ValidatedString(str):
33
+ def __new__(cls, content):
34
+ if "<>" in content:
35
+ raise SurveyCreationError(
36
+ "The expression contains '<>', which is not allowed. You probably mean '!='."
37
+ )
38
+ return super().__new__(cls, content)
39
+
40
+
41
+ class Survey(SurveyExportMixin, SurveyFlowVisualizationMixin, Base):
42
+ """A collection of questions that supports skip logic."""
43
+
44
+ questions = QuestionsDescriptor()
45
+ """
46
+ A collection of questions that supports skip logic.
47
+
48
+ Initalization:
49
+ - `questions`: the questions in the survey (optional)
50
+ - `question_names`: the names of the questions (optional)
51
+ - `name`: the name of the survey (optional)
52
+
53
+ Methods:
54
+ -
55
+
56
+ Notes:
57
+ - The presumed order of the survey is the order in which questions are added.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ questions: Optional[
63
+ list[Union[QuestionBase, Instruction, ChangeInstruction]]
64
+ ] = None,
65
+ memory_plan: Optional[MemoryPlan] = None,
66
+ rule_collection: Optional[RuleCollection] = None,
67
+ question_groups: Optional[dict[str, tuple[int, int]]] = None,
68
+ name: Optional[str] = None,
69
+ ):
70
+ """Create a new survey.
71
+
72
+ :param questions: The questions in the survey.
73
+ :param memory_plan: The memory plan for the survey.
74
+ :param rule_collection: The rule collection for the survey.
75
+ :param question_groups: The groups of questions in the survey.
76
+ :param name: The name of the survey - DEPRECATED.
77
+
78
+
79
+ >>> from edsl import QuestionFreeText
80
+ >>> q1 = QuestionFreeText(question_text = "What is your name?", question_name = "name")
81
+ >>> q2 = QuestionFreeText(question_text = "What is your favorite color?", question_name = "color")
82
+ >>> q3 = QuestionFreeText(question_text = "Is a hot dog a sandwich", question_name = "food")
83
+ >>> s = Survey([q1, q2, q3], question_groups = {"demographics": (0, 1), "substantive":(3)})
84
+
85
+
86
+ """
87
+
88
+ self.raw_passed_questions = questions
89
+
90
+ (
91
+ true_questions,
92
+ instruction_names_to_instructions,
93
+ self.pseudo_indices,
94
+ ) = self._separate_questions_and_instructions(questions or [])
95
+
96
+ self.rule_collection = RuleCollection(
97
+ num_questions=len(true_questions) if true_questions else None
98
+ )
99
+ # the RuleCollection needs to be present while we add the questions; we might override this later
100
+ # if a rule_collection is provided. This allows us to serialize the survey with the rule_collection.
101
+
102
+ self.questions = true_questions
103
+ self.instruction_names_to_instructions = instruction_names_to_instructions
104
+
105
+ self.memory_plan = memory_plan or MemoryPlan(self)
106
+ if question_groups is not None:
107
+ self.question_groups = question_groups
108
+ else:
109
+ self.question_groups = {}
110
+
111
+ # if a rule collection is provided, use it instead
112
+ if rule_collection is not None:
113
+ self.rule_collection = rule_collection
114
+
115
+ if name is not None:
116
+ import warnings
117
+
118
+ warnings.warn("name parameter to a survey is deprecated.")
119
+
120
+ # region: Suvry instruction handling
121
+ @property
122
+ def relevant_instructions_dict(self) -> InstructionCollection:
123
+ """Return a dictionary with keys as question names and values as instructions that are relevant to the question.
124
+
125
+ >>> s = Survey.example(include_instructions=True)
126
+ >>> s.relevant_instructions_dict
127
+ {'q0': [Instruction(name="attention", text="Please pay attention!")], 'q1': [Instruction(name="attention", text="Please pay attention!")], 'q2': [Instruction(name="attention", text="Please pay attention!")]}
128
+
129
+ """
130
+ return InstructionCollection(
131
+ self.instruction_names_to_instructions, self.questions
132
+ )
133
+
134
+ @staticmethod
135
+ def _separate_questions_and_instructions(questions_and_instructions: list) -> tuple:
136
+ """
137
+ The 'pseudo_indices' attribute is a dictionary that maps question names to pseudo-indices
138
+ that are used to order questions and instructions in the survey.
139
+ Only questions get real indices; instructions get pseudo-indices.
140
+ However, the order of the pseudo-indices is the same as the order questions and instructions are added to the survey.
141
+
142
+ We don't have to know how many instructions there are to calculate the pseudo-indices because they are
143
+ calculated by the inverse of one minus the sum of 1/2^n for n in the number of instructions run so far.
144
+
145
+ >>> from edsl import Instruction
146
+ >>> i = Instruction(text = "Pay attention to the following questions.", name = "intro")
147
+ >>> i2 = Instruction(text = "How are you feeling today?", name = "followon_intro")
148
+ >>> from edsl import QuestionFreeText; q1 = QuestionFreeText.example()
149
+ >>> from edsl import QuestionMultipleChoice; q2 = QuestionMultipleChoice.example()
150
+ >>> s = Survey([q1, i, i2, q2])
151
+ >>> len(s.instruction_names_to_instructions)
152
+ 2
153
+ >>> s.pseudo_indices
154
+ {'how_are_you': 0, 'intro': 0.5, 'followon_intro': 0.75, 'how_feeling': 1}
155
+
156
+ >>> from edsl import ChangeInstruction
157
+ >>> q3 = QuestionFreeText(question_text = "What is your favorite color?", question_name = "color")
158
+ >>> i_change = ChangeInstruction(drop = ["intro"])
159
+ >>> s = Survey([q1, i, q2, i_change, q3])
160
+ >>> [i.name for i in s.relevant_instructions(q1)]
161
+ []
162
+ >>> [i.name for i in s.relevant_instructions(q2)]
163
+ ['intro']
164
+ >>> [i.name for i in s.relevant_instructions(q3)]
165
+ []
166
+
167
+ >>> i_change = ChangeInstruction(keep = ["poop"], drop = [])
168
+ >>> s = Survey([q1, i, q2, i_change])
169
+ Traceback (most recent call last):
170
+ ...
171
+ ValueError: ChangeInstruction change_instruction_0 references instruction poop which does not exist.
172
+ """
173
+ from edsl.surveys.instructions.Instruction import Instruction
174
+ from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
175
+
176
+ true_questions = []
177
+ instruction_names_to_instructions = {}
178
+
179
+ num_change_instructions = 0
180
+ pseudo_indices = {}
181
+ instructions_run_length = 0
182
+ for entry in questions_and_instructions:
183
+ if isinstance(entry, Instruction) or isinstance(entry, ChangeInstruction):
184
+ if isinstance(entry, ChangeInstruction):
185
+ entry.add_name(num_change_instructions)
186
+ num_change_instructions += 1
187
+ for prior_instruction in entry.keep + entry.drop:
188
+ if prior_instruction not in instruction_names_to_instructions:
189
+ raise ValueError(
190
+ f"ChangeInstruction {entry.name} references instruction {prior_instruction} which does not exist."
191
+ )
192
+ instructions_run_length += 1
193
+ delta = 1 - 1.0 / (2.0**instructions_run_length)
194
+ pseudo_index = (len(true_questions) - 1) + delta
195
+ entry.pseudo_index = pseudo_index
196
+ instruction_names_to_instructions[entry.name] = entry
197
+ elif isinstance(entry, QuestionBase):
198
+ pseudo_index = len(true_questions)
199
+ instructions_run_length = 0
200
+ true_questions.append(entry)
201
+ else:
202
+ raise ValueError(
203
+ f"Entry {repr(entry)} is not a QuestionBase or an Instruction."
204
+ )
205
+
206
+ pseudo_indices[entry.name] = pseudo_index
207
+
208
+ return true_questions, instruction_names_to_instructions, pseudo_indices
209
+
210
+ def relevant_instructions(self, question) -> dict:
211
+ """This should be a dictionry with keys as question names and values as instructions that are relevant to the question.
212
+
213
+ :param question: The question to get the relevant instructions for.
214
+
215
+ # Did the instruction come before the question and was it not modified by a change instruction?
216
+
217
+ """
218
+ return self.relevant_instructions_dict[question]
219
+
220
+ @property
221
+ def max_pseudo_index(self) -> float:
222
+ """Return the maximum pseudo index in the survey.
223
+
224
+ Example:
225
+
226
+ >>> s = Survey.example()
227
+ >>> s.max_pseudo_index
228
+ 2
229
+ """
230
+ if len(self.pseudo_indices) == 0:
231
+ return -1
232
+ return max(self.pseudo_indices.values())
233
+
234
+ @property
235
+ def last_item_was_instruction(self) -> bool:
236
+ """Return whether the last item added to the survey was an instruction.
237
+ This is used to determine the pseudo-index of the next item added to the survey.
238
+
239
+ Example:
240
+
241
+ >>> s = Survey.example()
242
+ >>> s.last_item_was_instruction
243
+ False
244
+ >>> from edsl.surveys.instructions.Instruction import Instruction
245
+ >>> s = s.add_instruction(Instruction(text="Pay attention to the following questions.", name="intro"))
246
+ >>> s.last_item_was_instruction
247
+ True
248
+ """
249
+ return isinstance(self.max_pseudo_index, float)
250
+
251
+ def add_instruction(
252
+ self, instruction: Union["Instruction", "ChangeInstruction"]
253
+ ) -> Survey:
254
+ """
255
+ Add an instruction to the survey.
256
+
257
+ :param instruction: The instruction to add to the survey.
258
+
259
+ >>> from edsl import Instruction
260
+ >>> i = Instruction(text="Pay attention to the following questions.", name="intro")
261
+ >>> s = Survey().add_instruction(i)
262
+ >>> s.instruction_names_to_instructions
263
+ {'intro': Instruction(name="intro", text="Pay attention to the following questions.")}
264
+ >>> s.pseudo_indices
265
+ {'intro': -0.5}
266
+ """
267
+ import math
268
+
269
+ if instruction.name in self.instruction_names_to_instructions:
270
+ raise SurveyCreationError(
271
+ f"""Instruction name '{instruction.name}' already exists in survey. Existing names are {self.instruction_names_to_instructions.keys()}."""
272
+ )
273
+ self.instruction_names_to_instructions[instruction.name] = instruction
274
+
275
+ # was the last thing added an instruction or a question?
276
+ if self.last_item_was_instruction:
277
+ pseudo_index = (
278
+ self.max_pseudo_index
279
+ + (math.ceil(self.max_pseudo_index) - self.max_pseudo_index) / 2
280
+ )
281
+ else:
282
+ pseudo_index = self.max_pseudo_index + 1.0 / 2.0
283
+ self.pseudo_indices[instruction.name] = pseudo_index
284
+
285
+ return self
286
+
287
+ # endregion
288
+
289
+ # region: Simulation methods
290
+
291
+ @classmethod
292
+ def random_survey(self):
293
+ """Create a random survey."""
294
+ from edsl.questions import QuestionMultipleChoice, QuestionFreeText
295
+ from random import choice
296
+
297
+ num_questions = 10
298
+ questions = []
299
+ for i in range(num_questions):
300
+ if choice([True, False]):
301
+ q = QuestionMultipleChoice(
302
+ question_text="nothing",
303
+ question_name="q_" + str(i),
304
+ question_options=list(range(3)),
305
+ )
306
+ questions.append(q)
307
+ else:
308
+ questions.append(
309
+ QuestionFreeText(
310
+ question_text="nothing", question_name="q_" + str(i)
311
+ )
312
+ )
313
+ s = Survey(questions)
314
+ start_index = choice(range(num_questions - 1))
315
+ end_index = choice(range(start_index + 1, 10))
316
+ s = s.add_rule(f"q_{start_index}", "True", f"q_{end_index}")
317
+ question_to_delete = choice(range(num_questions))
318
+ s.delete_question(f"q_{question_to_delete}")
319
+ return s
320
+
321
+ def simulate(self) -> dict:
322
+ """Simulate the survey and return the answers."""
323
+ i = self.gen_path_through_survey()
324
+ q = next(i)
325
+ num_passes = 0
326
+ while True:
327
+ num_passes += 1
328
+ try:
329
+ answer = q._simulate_answer()
330
+ q = i.send({q.question_name: answer["answer"]})
331
+ except StopIteration:
332
+ break
333
+
334
+ if num_passes > 100:
335
+ print("Too many passes.")
336
+ raise Exception("Too many passes.")
337
+ return self.answers
338
+
339
+ def create_agent(self) -> "Agent":
340
+ """Create an agent from the simulated answers."""
341
+ answers_dict = self.simulate()
342
+
343
+ def construct_answer_dict_function(traits: dict) -> Callable:
344
+ def func(self, question: "QuestionBase", scenario=None):
345
+ return traits.get(question.question_name, None)
346
+
347
+ return func
348
+
349
+ return Agent(traits=answers_dict).add_direct_question_answering_method(
350
+ construct_answer_dict_function(answers_dict)
351
+ )
352
+
353
+ def simulate_results(self) -> "Results":
354
+ """Simulate the survey and return the results."""
355
+ a = self.create_agent()
356
+ return self.by([a]).run()
357
+
358
+ # endregion
359
+
360
+ # region: Access methods
361
+ def _get_question_index(
362
+ self, q: Union[QuestionBase, str, EndOfSurvey.__class__]
363
+ ) -> Union[int, EndOfSurvey.__class__]:
364
+ """Return the index of the question or EndOfSurvey object.
365
+
366
+ :param q: The question or question name to get the index of.
367
+
368
+ It can handle it if the user passes in the question name, the question object, or the EndOfSurvey object.
369
+
370
+ >>> s = Survey.example()
371
+ >>> s._get_question_index("q0")
372
+ 0
373
+
374
+ This doesnt' work with questions that don't exist:
375
+
376
+ >>> s._get_question_index("poop")
377
+ Traceback (most recent call last):
378
+ ...
379
+ edsl.exceptions.surveys.SurveyError: Question name poop not found in survey. The current question names are {'q0': 0, 'q1': 1, 'q2': 2}.
380
+ ...
381
+ """
382
+ if q == EndOfSurvey:
383
+ return EndOfSurvey
384
+ else:
385
+ question_name = q if isinstance(q, str) else q.question_name
386
+ if question_name not in self.question_name_to_index:
387
+ raise SurveyError(
388
+ f"""Question name {question_name} not found in survey. The current question names are {self.question_name_to_index}."""
389
+ )
390
+ return self.question_name_to_index[question_name]
391
+
392
+ def get(self, question_name: str) -> QuestionBase:
393
+ """
394
+ Return the question object given the question name.
395
+
396
+ :param question_name: The name of the question to get.
397
+
398
+ >>> s = Survey.example()
399
+ >>> s.get_question("q0")
400
+ Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
401
+ """
402
+ if question_name not in self.question_name_to_index:
403
+ raise SurveyError(f"Question name {question_name} not found in survey.")
404
+ index = self.question_name_to_index[question_name]
405
+ return self._questions[index]
406
+
407
+ def get_question(self, question_name: str) -> QuestionBase:
408
+ """Return the question object given the question name."""
409
+ # import warnings
410
+ # warnings.warn("survey.get_question is deprecated. Use subscript operator instead.")
411
+ return self.get(question_name)
412
+
413
+ def question_names_to_questions(self) -> dict:
414
+ """Return a dictionary mapping question names to question attributes."""
415
+ return {q.question_name: q for q in self.questions}
416
+
417
+ @property
418
+ def question_names(self) -> list[str]:
419
+ """Return a list of question names in the survey.
420
+
421
+ Example:
422
+
423
+ >>> s = Survey.example()
424
+ >>> s.question_names
425
+ ['q0', 'q1', 'q2']
426
+ """
427
+ return [q.question_name for q in self.questions]
428
+
429
+ @property
430
+ def question_name_to_index(self) -> dict[str, int]:
431
+ """Return a dictionary mapping question names to question indices.
432
+
433
+ Example:
434
+
435
+ >>> s = Survey.example()
436
+ >>> s.question_name_to_index
437
+ {'q0': 0, 'q1': 1, 'q2': 2}
438
+ """
439
+ return {q.question_name: i for i, q in enumerate(self.questions)}
440
+
441
+ # endregion
442
+
443
+ # region: serialization methods
444
+ def __hash__(self) -> int:
445
+ """Return a hash of the question."""
446
+ from edsl.utilities.utilities import dict_hash
447
+
448
+ return dict_hash(self.to_dict(add_edsl_version=False))
449
+
450
+ def to_dict(self, add_edsl_version=True) -> dict[str, Any]:
451
+ """Serialize the Survey object to a dictionary.
452
+
453
+ >>> s = Survey.example()
454
+ >>> s.to_dict(add_edsl_version = False).keys()
455
+ dict_keys(['questions', 'memory_plan', 'rule_collection', 'question_groups'])
456
+ """
457
+ return {
458
+ "questions": [
459
+ q.to_dict(add_edsl_version=add_edsl_version)
460
+ for q in self.recombined_questions_and_instructions()
461
+ ],
462
+ "memory_plan": self.memory_plan.to_dict(add_edsl_version=add_edsl_version),
463
+ "rule_collection": self.rule_collection.to_dict(
464
+ add_edsl_version=add_edsl_version
465
+ ),
466
+ "question_groups": self.question_groups,
467
+ }
468
+
469
+ @classmethod
470
+ @remove_edsl_version
471
+ def from_dict(cls, data: dict) -> Survey:
472
+ """Deserialize the dictionary back to a Survey object.
473
+
474
+ :param data: The dictionary to deserialize.
475
+
476
+ >>> d = Survey.example().to_dict()
477
+ >>> s = Survey.from_dict(d)
478
+ >>> s == Survey.example()
479
+ True
480
+
481
+ >>> s = Survey.example(include_instructions = True)
482
+ >>> d = s.to_dict()
483
+ >>> news = Survey.from_dict(d)
484
+ >>> news == s
485
+ True
486
+
487
+ """
488
+
489
+ def get_class(pass_dict):
490
+ if (class_name := pass_dict.get("edsl_class_name")) == "QuestionBase":
491
+ return QuestionBase
492
+ elif class_name == "Instruction":
493
+ from edsl.surveys.instructions.Instruction import Instruction
494
+
495
+ return Instruction
496
+ elif class_name == "ChangeInstruction":
497
+ from edsl.surveys.instructions.ChangeInstruction import (
498
+ ChangeInstruction,
499
+ )
500
+
501
+ return ChangeInstruction
502
+ else:
503
+ return QuestionBase
504
+
505
+ questions = [
506
+ get_class(q_dict).from_dict(q_dict) for q_dict in data["questions"]
507
+ ]
508
+ memory_plan = MemoryPlan.from_dict(data["memory_plan"])
509
+ survey = cls(
510
+ questions=questions,
511
+ memory_plan=memory_plan,
512
+ rule_collection=RuleCollection.from_dict(data["rule_collection"]),
513
+ question_groups=data["question_groups"],
514
+ )
515
+ return survey
516
+
517
+ # endregion
518
+
519
+ # region: Survey template parameters
520
+ @property
521
+ def scenario_attributes(self) -> list[str]:
522
+ """Return a list of attributes that admissible Scenarios should have.
523
+
524
+ Here we have a survey with a question that uses a jinja2 style {{ }} template:
525
+
526
+ >>> from edsl import QuestionFreeText
527
+ >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your name?", question_name="name"))
528
+ >>> s.scenario_attributes
529
+ ['greeting']
530
+
531
+ >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your {{ attribute }}?", question_name="name"))
532
+ >>> s.scenario_attributes
533
+ ['greeting', 'attribute']
534
+
535
+
536
+ """
537
+ temp = []
538
+ for question in self.questions:
539
+ question_text = question.question_text
540
+ # extract the contents of all {{ }} in the question text using regex
541
+ matches = re.findall(r"\{\{(.+?)\}\}", question_text)
542
+ # remove whitespace
543
+ matches = [match.strip() for match in matches]
544
+ # add them to the temp list
545
+ temp.extend(matches)
546
+ return temp
547
+
548
+ @property
549
+ def parameters(self):
550
+ """Return a set of parameters in the survey.
551
+
552
+ >>> s = Survey.example()
553
+ >>> s.parameters
554
+ set()
555
+ """
556
+ return set.union(*[q.parameters for q in self.questions])
557
+
558
+ @property
559
+ def parameters_by_question(self):
560
+ """Return a dictionary of parameters by question in the survey.
561
+ >>> from edsl import QuestionFreeText
562
+ >>> q = QuestionFreeText(question_name = "example", question_text = "What is the capital of {{ country}}?")
563
+ >>> s = Survey([q])
564
+ >>> s.parameters_by_question
565
+ {'example': {'country'}}
566
+ """
567
+ return {q.question_name: q.parameters for q in self.questions}
568
+
569
+ # endregion
570
+
571
+ # region: Survey construction
572
+
573
+ # region: Adding questions and combining surveys
574
+ def __add__(self, other: Survey) -> Survey:
575
+ """Combine two surveys.
576
+
577
+ :param other: The other survey to combine with this one.
578
+ >>> s1 = Survey.example()
579
+ >>> from edsl import QuestionFreeText
580
+ >>> s2 = Survey([QuestionFreeText(question_text="What is your name?", question_name="yo")])
581
+ >>> s3 = s1 + s2
582
+ Traceback (most recent call last):
583
+ ...
584
+ edsl.exceptions.surveys.SurveyCreationError: ...
585
+ ...
586
+ >>> s3 = s1.clear_non_default_rules() + s2
587
+ >>> len(s3.questions)
588
+ 4
589
+
590
+ """
591
+ if (
592
+ len(self.rule_collection.non_default_rules) > 0
593
+ or len(other.rule_collection.non_default_rules) > 0
594
+ ):
595
+ raise SurveyCreationError(
596
+ "Cannot combine two surveys with non-default rules. Please use the 'clear_non_default_rules' method to remove non-default rules from the survey.",
597
+ )
598
+
599
+ return Survey(questions=self.questions + other.questions)
600
+
601
+ def move_question(self, identifier: Union[str, int], new_index: int):
602
+ if isinstance(identifier, str):
603
+ if identifier not in self.question_names:
604
+ raise SurveyError(
605
+ f"Question name '{identifier}' does not exist in the survey."
606
+ )
607
+ index = self.question_name_to_index[identifier]
608
+ elif isinstance(identifier, int):
609
+ if identifier < 0 or identifier >= len(self.questions):
610
+ raise SurveyError(f"Index {identifier} is out of range.")
611
+ index = identifier
612
+ else:
613
+ raise SurveyError(
614
+ "Identifier must be either a string (question name) or an integer (question index)."
615
+ )
616
+
617
+ moving_question = self._questions[index]
618
+
619
+ new_survey = self.delete_question(index)
620
+ new_survey.add_question(moving_question, new_index)
621
+ return new_survey
622
+
623
+ def delete_question(self, identifier: Union[str, int]) -> Survey:
624
+ """
625
+ Delete a question from the survey.
626
+
627
+ :param identifier: The name or index of the question to delete.
628
+ :return: The updated Survey object.
629
+
630
+ >>> from edsl import QuestionMultipleChoice, Survey
631
+ >>> q1 = QuestionMultipleChoice(question_text="Q1", question_options=["A", "B"], question_name="q1")
632
+ >>> q2 = QuestionMultipleChoice(question_text="Q2", question_options=["C", "D"], question_name="q2")
633
+ >>> s = Survey().add_question(q1).add_question(q2)
634
+ >>> _ = s.delete_question("q1")
635
+ >>> len(s.questions)
636
+ 1
637
+ >>> _ = s.delete_question(0)
638
+ >>> len(s.questions)
639
+ 0
640
+ """
641
+ if isinstance(identifier, str):
642
+ if identifier not in self.question_names:
643
+ raise SurveyError(
644
+ f"Question name '{identifier}' does not exist in the survey."
645
+ )
646
+ index = self.question_name_to_index[identifier]
647
+ elif isinstance(identifier, int):
648
+ if identifier < 0 or identifier >= len(self.questions):
649
+ raise SurveyError(f"Index {identifier} is out of range.")
650
+ index = identifier
651
+ else:
652
+ raise SurveyError(
653
+ "Identifier must be either a string (question name) or an integer (question index)."
654
+ )
655
+
656
+ # Remove the question
657
+ deleted_question = self._questions.pop(index)
658
+ del self.pseudo_indices[deleted_question.question_name]
659
+
660
+ # Update indices
661
+ for question_name, old_index in self.pseudo_indices.items():
662
+ if old_index > index:
663
+ self.pseudo_indices[question_name] = old_index - 1
664
+
665
+ # Update rules
666
+ new_rule_collection = RuleCollection()
667
+ for rule in self.rule_collection:
668
+ if rule.current_q == index:
669
+ continue # Remove rules associated with the deleted question
670
+ if rule.current_q > index:
671
+ rule.current_q -= 1
672
+ if rule.next_q > index:
673
+ rule.next_q -= 1
674
+
675
+ if rule.next_q == index:
676
+ if index == len(self.questions):
677
+ rule.next_q = EndOfSurvey
678
+ else:
679
+ rule.next_q = index
680
+
681
+ new_rule_collection.add_rule(rule)
682
+ self.rule_collection = new_rule_collection
683
+
684
+ # Update memory plan if it exists
685
+ if hasattr(self, "memory_plan"):
686
+ self.memory_plan.remove_question(deleted_question.question_name)
687
+
688
+ return self
689
+
690
+ def add_question(
691
+ self, question: QuestionBase, index: Optional[int] = None
692
+ ) -> Survey:
693
+ """
694
+ Add a question to survey.
695
+
696
+ :param question: The question to add to the survey.
697
+ :param question_name: The name of the question. If not provided, the question name is used.
698
+
699
+ The question is appended at the end of the self.questions list
700
+ A default rule is created that the next index is the next question.
701
+
702
+ >>> from edsl import QuestionMultipleChoice
703
+ >>> q = QuestionMultipleChoice(question_text = "Do you like school?", question_options=["yes", "no"], question_name="q0")
704
+ >>> s = Survey().add_question(q)
705
+
706
+ >>> s = Survey().add_question(q).add_question(q)
707
+ Traceback (most recent call last):
708
+ ...
709
+ edsl.exceptions.surveys.SurveyCreationError: Question name 'q0' already exists in survey. Existing names are ['q0'].
710
+ ...
711
+ """
712
+ if question.question_name in self.question_names:
713
+ raise SurveyCreationError(
714
+ f"""Question name '{question.question_name}' already exists in survey. Existing names are {self.question_names}."""
715
+ )
716
+ if index is None:
717
+ index = len(self.questions)
718
+
719
+ if index > len(self.questions):
720
+ raise SurveyCreationError(
721
+ f"Index {index} is greater than the number of questions in the survey."
722
+ )
723
+ if index < 0:
724
+ raise SurveyCreationError(f"Index {index} is less than 0.")
725
+
726
+ interior_insertion = index != len(self.questions)
727
+
728
+ # index = len(self.questions)
729
+ # TODO: This is a bit ugly because the user
730
+ # doesn't "know" about _questions - it's generated by the
731
+ # descriptor.
732
+ self._questions.insert(index, question)
733
+
734
+ if interior_insertion:
735
+ for question_name, old_index in self.pseudo_indices.items():
736
+ if old_index >= index:
737
+ self.pseudo_indices[question_name] = old_index + 1
738
+
739
+ self.pseudo_indices[question.question_name] = index
740
+
741
+ ## Re-do question_name to index - this is done automatically
742
+ # for question_name, old_index in self.question_name_to_index.items():
743
+ # if old_index >= index:
744
+ # self.question_name_to_index[question_name] = old_index + 1
745
+
746
+ ## Need to re-do the rule collection and the indices of the questions
747
+
748
+ ## If a rule is before the insertion index and next_q is also before the insertion index, no change needed.
749
+ ## If the rule is before the insertion index but next_q is after the insertion index, increment the next_q by 1
750
+ ## If the rule is after the insertion index, increment the current_q by 1 and the next_q by 1
751
+
752
+ # using index + 1 presumes there is a next question
753
+ if interior_insertion:
754
+ for rule in self.rule_collection:
755
+ if rule.current_q >= index:
756
+ rule.current_q += 1
757
+ if rule.next_q >= index:
758
+ rule.next_q += 1
759
+
760
+ # add a new rule
761
+ self.rule_collection.add_rule(
762
+ Rule(
763
+ current_q=index,
764
+ expression="True",
765
+ next_q=index + 1,
766
+ question_name_to_index=self.question_name_to_index,
767
+ priority=RulePriority.DEFAULT.value,
768
+ )
769
+ )
770
+
771
+ # a question might be added before the memory plan is created
772
+ # it's ok because the memory plan will be updated when it is created
773
+ if hasattr(self, "memory_plan"):
774
+ self.memory_plan.add_question(question)
775
+
776
+ return self
777
+
778
+ def recombined_questions_and_instructions(
779
+ self,
780
+ ) -> list[Union[QuestionBase, "Instruction"]]:
781
+ """Return a list of questions and instructions sorted by pseudo index."""
782
+ questions_and_instructions = self._questions + list(
783
+ self.instruction_names_to_instructions.values()
784
+ )
785
+ return sorted(
786
+ questions_and_instructions, key=lambda x: self.pseudo_indices[x.name]
787
+ )
788
+
789
+ # endregion
790
+
791
+ # region: Memory plan methods
792
+ def set_full_memory_mode(self) -> Survey:
793
+ """Add instructions to a survey that the agent should remember all of the answers to the questions in the survey.
794
+
795
+ >>> s = Survey.example().set_full_memory_mode()
796
+
797
+ """
798
+ self._set_memory_plan(lambda i: self.question_names[:i])
799
+ return self
800
+
801
+ def set_lagged_memory(self, lags: int) -> Survey:
802
+ """Add instructions to a survey that the agent should remember the answers to the questions in the survey.
803
+
804
+ The agent should remember the answers to the questions in the survey from the previous lags.
805
+ """
806
+ self._set_memory_plan(lambda i: self.question_names[max(0, i - lags) : i])
807
+ return self
808
+
809
+ def _set_memory_plan(self, prior_questions_func: Callable):
810
+ """Set memory plan based on a provided function determining prior questions.
811
+
812
+ :param prior_questions_func: A function that takes the index of the current question and returns a list of prior questions to remember.
813
+
814
+ >>> s = Survey.example()
815
+ >>> s._set_memory_plan(lambda i: s.question_names[:i])
816
+
817
+ """
818
+ for i, question_name in enumerate(self.question_names):
819
+ self.memory_plan.add_memory_collection(
820
+ focal_question=question_name,
821
+ prior_questions=prior_questions_func(i),
822
+ )
823
+
824
+ def add_targeted_memory(
825
+ self,
826
+ focal_question: Union[QuestionBase, str],
827
+ prior_question: Union[QuestionBase, str],
828
+ ) -> Survey:
829
+ """Add instructions to a survey than when answering focal_question.
830
+
831
+ :param focal_question: The question that the agent is answering.
832
+ :param prior_question: The question that the agent should remember when answering the focal question.
833
+
834
+ Here we add instructions to a survey than when answering q2 they should remember q1:
835
+
836
+ >>> s = Survey.example().add_targeted_memory("q2", "q0")
837
+ >>> s.memory_plan
838
+ {'q2': Memory(prior_questions=['q0'])}
839
+
840
+ The agent should also remember the answers to prior_questions listed in prior_questions.
841
+ """
842
+ focal_question_name = self.question_names[
843
+ self._get_question_index(focal_question)
844
+ ]
845
+ prior_question_name = self.question_names[
846
+ self._get_question_index(prior_question)
847
+ ]
848
+
849
+ self.memory_plan.add_single_memory(
850
+ focal_question=focal_question_name,
851
+ prior_question=prior_question_name,
852
+ )
853
+
854
+ return self
855
+
856
+ def add_memory_collection(
857
+ self,
858
+ focal_question: Union[QuestionBase, str],
859
+ prior_questions: List[Union[QuestionBase, str]],
860
+ ) -> Survey:
861
+ """Add prior questions and responses so the agent has them when answering.
862
+
863
+ This adds instructions to a survey than when answering focal_question, the agent should also remember the answers to prior_questions listed in prior_questions.
864
+
865
+ :param focal_question: The question that the agent is answering.
866
+ :param prior_questions: The questions that the agent should remember when answering the focal question.
867
+
868
+ Here we have it so that when answering q2, the agent should remember answers to q0 and q1:
869
+
870
+ >>> s = Survey.example().add_memory_collection("q2", ["q0", "q1"])
871
+ >>> s.memory_plan
872
+ {'q2': Memory(prior_questions=['q0', 'q1'])}
873
+ """
874
+ focal_question_name = self.question_names[
875
+ self._get_question_index(focal_question)
876
+ ]
877
+
878
+ prior_question_names = [
879
+ self.question_names[self._get_question_index(prior_question)]
880
+ for prior_question in prior_questions
881
+ ]
882
+
883
+ self.memory_plan.add_memory_collection(
884
+ focal_question=focal_question_name, prior_questions=prior_question_names
885
+ )
886
+ return self
887
+
888
+ # endregion
889
+ # endregion
890
+ # endregion
891
+
892
+ # region: Question groups
893
+ def add_question_group(
894
+ self,
895
+ start_question: Union[QuestionBase, str],
896
+ end_question: Union[QuestionBase, str],
897
+ group_name: str,
898
+ ) -> Survey:
899
+ """Add a group of questions to the survey.
900
+
901
+ :param start_question: The first question in the group.
902
+ :param end_question: The last question in the group.
903
+ :param group_name: The name of the group.
904
+
905
+ Example:
906
+
907
+ >>> s = Survey.example().add_question_group("q0", "q1", "group1")
908
+ >>> s.question_groups
909
+ {'group1': (0, 1)}
910
+
911
+ The name of the group must be a valid identifier:
912
+
913
+ >>> s = Survey.example().add_question_group("q0", "q2", "1group1")
914
+ Traceback (most recent call last):
915
+ ...
916
+ edsl.exceptions.surveys.SurveyCreationError: Group name 1group1 is not a valid identifier.
917
+ ...
918
+ >>> s = Survey.example().add_question_group("q0", "q1", "q0")
919
+ Traceback (most recent call last):
920
+ ...
921
+ edsl.exceptions.surveys.SurveyCreationError: ...
922
+ ...
923
+ >>> s = Survey.example().add_question_group("q1", "q0", "group1")
924
+ Traceback (most recent call last):
925
+ ...
926
+ edsl.exceptions.surveys.SurveyCreationError: ...
927
+ ...
928
+ """
929
+
930
+ if not group_name.isidentifier():
931
+ raise SurveyCreationError(
932
+ f"Group name {group_name} is not a valid identifier."
933
+ )
934
+
935
+ if group_name in self.question_groups:
936
+ raise SurveyCreationError(
937
+ f"Group name {group_name} already exists in the survey."
938
+ )
939
+
940
+ if group_name in self.question_name_to_index:
941
+ raise SurveyCreationError(
942
+ f"Group name {group_name} already exists as a question name in the survey."
943
+ )
944
+
945
+ start_index = self._get_question_index(start_question)
946
+ end_index = self._get_question_index(end_question)
947
+
948
+ if start_index > end_index:
949
+ raise SurveyCreationError(
950
+ f"Start index {start_index} is greater than end index {end_index}."
951
+ )
952
+
953
+ for existing_group_name, (
954
+ existing_start_index,
955
+ existing_end_index,
956
+ ) in self.question_groups.items():
957
+ if start_index < existing_start_index and end_index > existing_end_index:
958
+ raise SurveyCreationError(
959
+ f"Group {group_name} contains the questions in the new group."
960
+ )
961
+ if start_index > existing_start_index and end_index < existing_end_index:
962
+ raise SurveyCreationError(
963
+ f"Group {group_name} is contained in the new group."
964
+ )
965
+ if start_index < existing_start_index and end_index > existing_start_index:
966
+ raise SurveyCreationError(
967
+ f"Group {group_name} overlaps with the new group."
968
+ )
969
+ if start_index < existing_end_index and end_index > existing_end_index:
970
+ raise SurveyCreationError(
971
+ f"Group {group_name} overlaps with the new group."
972
+ )
973
+
974
+ self.question_groups[group_name] = (start_index, end_index)
975
+ return self
976
+
977
+ # endregion
978
+
979
+ # region: Survey rules
980
+ def show_rules(self) -> None:
981
+ """Print out the rules in the survey.
982
+
983
+ >>> s = Survey.example()
984
+ >>> s.show_rules()
985
+ ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
986
+ ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
987
+ ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
988
+ │ 0 │ True │ 1 │ -1 │ False │
989
+ │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
990
+ │ 1 │ True │ 2 │ -1 │ False │
991
+ │ 2 │ True │ 3 │ -1 │ False │
992
+ └───────────┴─────────────┴────────┴──────────┴─────────────┘
993
+ """
994
+ self.rule_collection.show_rules()
995
+
996
+ def add_stop_rule(
997
+ self, question: Union[QuestionBase, str], expression: str
998
+ ) -> Survey:
999
+ """Add a rule that stops the survey.
1000
+ The rule is evaluated *after* the question is answered. If the rule is true, the survey ends.
1001
+
1002
+ :param question: The question to add the stop rule to.
1003
+ :param expression: The expression to evaluate.
1004
+
1005
+ If this rule is true, the survey ends.
1006
+
1007
+ Here, answering "yes" to q0 ends the survey:
1008
+
1009
+ >>> s = Survey.example().add_stop_rule("q0", "q0 == 'yes'")
1010
+ >>> s.next_question("q0", {"q0": "yes"})
1011
+ EndOfSurvey
1012
+
1013
+ By comparison, answering "no" to q0 does not end the survey:
1014
+
1015
+ >>> s.next_question("q0", {"q0": "no"}).question_name
1016
+ 'q1'
1017
+
1018
+ >>> s.add_stop_rule("q0", "q1 <> 'yes'")
1019
+ Traceback (most recent call last):
1020
+ ...
1021
+ edsl.exceptions.surveys.SurveyCreationError: The expression contains '<>', which is not allowed. You probably mean '!='.
1022
+ ...
1023
+ """
1024
+ expression = ValidatedString(expression)
1025
+ prior_question_appears = False
1026
+ for prior_question in self.questions:
1027
+ if prior_question.question_name in expression:
1028
+ prior_question_appears = True
1029
+
1030
+ if not prior_question_appears:
1031
+ import warnings
1032
+
1033
+ warnings.warn(
1034
+ f"The expression {expression} does not contain any prior question names. This is probably a mistake."
1035
+ )
1036
+ self.add_rule(question, expression, EndOfSurvey)
1037
+ return self
1038
+
1039
+ def clear_non_default_rules(self) -> Survey:
1040
+ """Remove all non-default rules from the survey.
1041
+
1042
+ >>> Survey.example().show_rules()
1043
+ ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1044
+ ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1045
+ ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1046
+ │ 0 │ True │ 1 │ -1 │ False │
1047
+ │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
1048
+ │ 1 │ True │ 2 │ -1 │ False │
1049
+ │ 2 │ True │ 3 │ -1 │ False │
1050
+ └───────────┴─────────────┴────────┴──────────┴─────────────┘
1051
+ >>> Survey.example().clear_non_default_rules().show_rules()
1052
+ ┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1053
+ ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1054
+ ┡━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1055
+ │ 0 │ True │ 1 │ -1 │ False │
1056
+ │ 1 │ True │ 2 │ -1 │ False │
1057
+ │ 2 │ True │ 3 │ -1 │ False │
1058
+ └───────────┴────────────┴────────┴──────────┴─────────────┘
1059
+ """
1060
+ s = Survey()
1061
+ for question in self.questions:
1062
+ s.add_question(question)
1063
+ return s
1064
+
1065
+ def add_skip_rule(
1066
+ self, question: Union[QuestionBase, str], expression: str
1067
+ ) -> Survey:
1068
+ """
1069
+ Adds a per-question skip rule to the survey.
1070
+
1071
+ :param question: The question to add the skip rule to.
1072
+ :param expression: The expression to evaluate.
1073
+
1074
+ This adds a rule that skips 'q0' always, before the question is answered:
1075
+
1076
+ >>> from edsl import QuestionFreeText
1077
+ >>> q0 = QuestionFreeText.example()
1078
+ >>> q0.question_name = "q0"
1079
+ >>> q1 = QuestionFreeText.example()
1080
+ >>> q1.question_name = "q1"
1081
+ >>> s = Survey([q0, q1]).add_skip_rule("q0", "True")
1082
+ >>> s.next_question("q0", {}).question_name
1083
+ 'q1'
1084
+
1085
+ Note that this is different from a rule that jumps to some other question *after* the question is answered.
1086
+
1087
+ """
1088
+ question_index = self._get_question_index(question)
1089
+ self._add_rule(question, expression, question_index + 1, before_rule=True)
1090
+ return self
1091
+
1092
+ def _get_new_rule_priority(
1093
+ self, question_index: int, before_rule: bool = False
1094
+ ) -> int:
1095
+ """Return the priority for the new rule.
1096
+
1097
+ :param question_index: The index of the question to add the rule to.
1098
+ :param before_rule: Whether the rule is evaluated before the question is answered.
1099
+
1100
+ >>> s = Survey.example()
1101
+ >>> s._get_new_rule_priority(0)
1102
+ 1
1103
+ """
1104
+ current_priorities = [
1105
+ rule.priority
1106
+ for rule in self.rule_collection.applicable_rules(
1107
+ question_index, before_rule
1108
+ )
1109
+ ]
1110
+ if len(current_priorities) == 0:
1111
+ return RulePriority.DEFAULT.value + 1
1112
+
1113
+ max_priority = max(current_priorities)
1114
+ # newer rules take priority over older rules
1115
+ new_priority = (
1116
+ RulePriority.DEFAULT.value
1117
+ if len(current_priorities) == 0
1118
+ else max_priority + 1
1119
+ )
1120
+ return new_priority
1121
+
1122
+ def add_rule(
1123
+ self,
1124
+ question: Union[QuestionBase, str],
1125
+ expression: str,
1126
+ next_question: Union[QuestionBase, int],
1127
+ before_rule: bool = False,
1128
+ ) -> Survey:
1129
+ """
1130
+ Add a rule to a Question of the Survey.
1131
+
1132
+ :param question: The question to add the rule to.
1133
+ :param expression: The expression to evaluate.
1134
+ :param next_question: The next question to go to if the rule is true.
1135
+ :param before_rule: Whether the rule is evaluated before the question is answered.
1136
+
1137
+ This adds a rule that if the answer to q0 is 'yes', the next question is q2 (as opposed to q1)
1138
+
1139
+ >>> s = Survey.example().add_rule("q0", "{{ q0 }} == 'yes'", "q2")
1140
+ >>> s.next_question("q0", {"q0": "yes"}).question_name
1141
+ 'q2'
1142
+
1143
+ """
1144
+ return self._add_rule(
1145
+ question, expression, next_question, before_rule=before_rule
1146
+ )
1147
+
1148
+ def _add_rule(
1149
+ self,
1150
+ question: Union[QuestionBase, str],
1151
+ expression: str,
1152
+ next_question: Union[QuestionBase, str, int],
1153
+ before_rule: bool = False,
1154
+ ) -> Survey:
1155
+ """
1156
+ Add a rule to a Question of the Survey with the appropriate priority.
1157
+
1158
+ :param question: The question to add the rule to.
1159
+ :param expression: The expression to evaluate.
1160
+ :param next_question: The next question to go to if the rule is true.
1161
+ :param before_rule: Whether the rule is evaluated before the question is answered.
1162
+
1163
+
1164
+ - The last rule added for the question will have the highest priority.
1165
+ - If there are no rules, the rule added gets priority -1.
1166
+ """
1167
+ question_index = self._get_question_index(question)
1168
+
1169
+ # Might not have the name of the next question yet
1170
+ if isinstance(next_question, int):
1171
+ next_question_index = next_question
1172
+ else:
1173
+ next_question_index = self._get_question_index(next_question)
1174
+
1175
+ new_priority = self._get_new_rule_priority(question_index, before_rule)
1176
+
1177
+ self.rule_collection.add_rule(
1178
+ Rule(
1179
+ current_q=question_index,
1180
+ expression=expression,
1181
+ next_q=next_question_index,
1182
+ question_name_to_index=self.question_name_to_index,
1183
+ priority=new_priority,
1184
+ before_rule=before_rule,
1185
+ )
1186
+ )
1187
+
1188
+ return self
1189
+
1190
+ # endregion
1191
+
1192
+ # region: Forward methods
1193
+ def by(self, *args: Union["Agent", "Scenario", "LanguageModel"]) -> "Jobs":
1194
+ """Add Agents, Scenarios, and LanguageModels to a survey and returns a runnable Jobs object.
1195
+
1196
+ :param args: The Agents, Scenarios, and LanguageModels to add to the survey.
1197
+
1198
+ This takes the survey and adds an Agent and a Scenario via 'by' which converts to a Jobs object:
1199
+
1200
+ >>> s = Survey.example(); from edsl import Agent; from edsl import Scenario
1201
+ >>> s.by(Agent.example()).by(Scenario.example())
1202
+ Jobs(...)
1203
+ """
1204
+ from edsl.jobs.Jobs import Jobs
1205
+
1206
+ job = Jobs(survey=self)
1207
+ return job.by(*args)
1208
+
1209
+ def to_jobs(self):
1210
+ """Convert the survey to a Jobs object."""
1211
+ from edsl.jobs.Jobs import Jobs
1212
+
1213
+ return Jobs(survey=self)
1214
+
1215
+ def show_prompts(self):
1216
+ return self.to_jobs().show_prompts()
1217
+
1218
+ # endregion
1219
+
1220
+ # region: Running the survey
1221
+
1222
+ def __call__(
1223
+ self,
1224
+ model=None,
1225
+ agent=None,
1226
+ cache=None,
1227
+ disable_remote_cache: bool = False,
1228
+ disable_remote_inference: bool = False,
1229
+ **kwargs,
1230
+ ):
1231
+ """Run the survey with default model, taking the required survey as arguments.
1232
+
1233
+ >>> from edsl.questions import QuestionFunctional
1234
+ >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1235
+ >>> q = QuestionFunctional(question_name = "q0", func = f)
1236
+ >>> s = Survey([q])
1237
+ >>> s(period = "morning", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
1238
+ 'yes'
1239
+ >>> s(period = "evening", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
1240
+ 'no'
1241
+ """
1242
+ job = self.get_job(model, agent, **kwargs)
1243
+ return job.run(
1244
+ cache=cache,
1245
+ disable_remote_cache=disable_remote_cache,
1246
+ disable_remote_inference=disable_remote_inference,
1247
+ )
1248
+
1249
+ async def run_async(
1250
+ self,
1251
+ model: Optional["Model"] = None,
1252
+ agent: Optional["Agent"] = None,
1253
+ cache: Optional["Cache"] = None,
1254
+ disable_remote_inference: bool = False,
1255
+ **kwargs,
1256
+ ):
1257
+ """Run the survey with default model, taking the required survey as arguments.
1258
+
1259
+ >>> import asyncio
1260
+ >>> from edsl.questions import QuestionFunctional
1261
+ >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1262
+ >>> q = QuestionFunctional(question_name = "q0", func = f)
1263
+ >>> s = Survey([q])
1264
+ >>> async def test_run_async(): result = await s.run_async(period="morning", disable_remote_inference = True); print(result.select("answer.q0").first())
1265
+ >>> asyncio.run(test_run_async())
1266
+ yes
1267
+ >>> import asyncio
1268
+ >>> from edsl.questions import QuestionFunctional
1269
+ >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
1270
+ >>> q = QuestionFunctional(question_name = "q0", func = f)
1271
+ >>> s = Survey([q])
1272
+ >>> async def test_run_async(): result = await s.run_async(period="evening", disable_remote_inference = True); print(result.select("answer.q0").first())
1273
+ >>> asyncio.run(test_run_async())
1274
+ no
1275
+ """
1276
+ # TODO: temp fix by creating a cache
1277
+ if cache is None:
1278
+ from edsl.data import Cache
1279
+
1280
+ c = Cache()
1281
+ else:
1282
+ c = cache
1283
+ jobs: "Jobs" = self.get_job(model=model, agent=agent, **kwargs)
1284
+ return await jobs.run_async(
1285
+ cache=c, disable_remote_inference=disable_remote_inference
1286
+ )
1287
+
1288
+ def run(self, *args, **kwargs) -> "Results":
1289
+ """Turn the survey into a Job and runs it.
1290
+
1291
+ >>> from edsl import QuestionFreeText
1292
+ >>> s = Survey([QuestionFreeText.example()])
1293
+ >>> from edsl.language_models import LanguageModel
1294
+ >>> m = LanguageModel.example(test_model = True, canned_response = "Great!")
1295
+ >>> results = s.by(m).run(cache = False, disable_remote_cache = True, disable_remote_inference = True)
1296
+ >>> results.select('answer.*')
1297
+ Dataset([{'answer.how_are_you': ['Great!']}])
1298
+ """
1299
+ from edsl.jobs.Jobs import Jobs
1300
+
1301
+ return Jobs(survey=self).run(*args, **kwargs)
1302
+
1303
+ # region: Survey flow
1304
+ def next_question(
1305
+ self, current_question: Union[str, QuestionBase], answers: dict
1306
+ ) -> Union[QuestionBase, EndOfSurvey.__class__]:
1307
+ """
1308
+ Return the next question in a survey.
1309
+
1310
+ :param current_question: The current question in the survey.
1311
+ :param answers: The answers for the survey so far
1312
+
1313
+ - If called with no arguments, it returns the first question in the survey.
1314
+ - If no answers are provided for a question with a rule, the next question is returned. If answers are provided, the next question is determined by the rules and the answers.
1315
+ - If the next question is the last question in the survey, an EndOfSurvey object is returned.
1316
+
1317
+ >>> s = Survey.example()
1318
+ >>> s.next_question("q0", {"q0": "yes"}).question_name
1319
+ 'q2'
1320
+ >>> s.next_question("q0", {"q0": "no"}).question_name
1321
+ 'q1'
1322
+
1323
+ """
1324
+ if isinstance(current_question, str):
1325
+ current_question = self.get_question(current_question)
1326
+
1327
+ question_index = self.question_name_to_index[current_question.question_name]
1328
+ next_question_object = self.rule_collection.next_question(
1329
+ question_index, answers
1330
+ )
1331
+
1332
+ if next_question_object.num_rules_found == 0:
1333
+ raise SurveyHasNoRulesError
1334
+
1335
+ if next_question_object.next_q == EndOfSurvey:
1336
+ return EndOfSurvey
1337
+ else:
1338
+ if next_question_object.next_q >= len(self.questions):
1339
+ return EndOfSurvey
1340
+ else:
1341
+ return self.questions[next_question_object.next_q]
1342
+
1343
+ def gen_path_through_survey(self) -> Generator[QuestionBase, dict, None]:
1344
+ """
1345
+ Generate a coroutine that can be used to conduct an Interview.
1346
+
1347
+ The coroutine is a generator that yields a question and receives answers.
1348
+ It starts with the first question in the survey.
1349
+ The coroutine ends when an EndOfSurvey object is returned.
1350
+
1351
+ For the example survey, this is the rule table:
1352
+
1353
+ >>> s = Survey.example()
1354
+ >>> s.show_rules()
1355
+ ┏━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━┓
1356
+ ┃ current_q ┃ expression ┃ next_q ┃ priority ┃ before_rule ┃
1357
+ ┡━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━┩
1358
+ │ 0 │ True │ 1 │ -1 │ False │
1359
+ │ 0 │ q0 == 'yes' │ 2 │ 0 │ False │
1360
+ │ 1 │ True │ 2 │ -1 │ False │
1361
+ │ 2 │ True │ 3 │ -1 │ False │
1362
+ └───────────┴─────────────┴────────┴──────────┴─────────────┘
1363
+
1364
+ Note that q0 has a rule that if the answer is 'yes', the next question is q2. If the answer is 'no', the next question is q1.
1365
+
1366
+ Here is the path through the survey if the answer to q0 is 'yes':
1367
+
1368
+ >>> i = s.gen_path_through_survey()
1369
+ >>> next(i)
1370
+ Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1371
+ >>> i.send({"q0": "yes"})
1372
+ Question('multiple_choice', question_name = \"""q2\""", question_text = \"""Why?\""", question_options = ['**lack*** of killer bees in cafeteria', 'other'])
1373
+
1374
+ And here is the path through the survey if the answer to q0 is 'no':
1375
+
1376
+ >>> i2 = s.gen_path_through_survey()
1377
+ >>> next(i2)
1378
+ Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1379
+ >>> i2.send({"q0": "no"})
1380
+ Question('multiple_choice', question_name = \"""q1\""", question_text = \"""Why not?\""", question_options = ['killer bees in cafeteria', 'other'])
1381
+
1382
+
1383
+ """
1384
+ self.answers = {}
1385
+ question = self._questions[0]
1386
+ # should the first question be skipped?
1387
+ if self.rule_collection.skip_question_before_running(0, self.answers):
1388
+ question = self.next_question(question, self.answers)
1389
+
1390
+ while not question == EndOfSurvey:
1391
+ # breakpoint()
1392
+ answer = yield question
1393
+ self.answers.update(answer)
1394
+ # print(f"Answers: {self.answers}")
1395
+ ## TODO: This should also include survey and agent attributes
1396
+ question = self.next_question(question, self.answers)
1397
+
1398
+ # endregion
1399
+
1400
+ # regions: DAG construction
1401
+ def textify(self, index_dag: DAG) -> DAG:
1402
+ """Convert the DAG of question indices to a DAG of question names.
1403
+
1404
+ :param index_dag: The DAG of question indices.
1405
+
1406
+ Example:
1407
+
1408
+ >>> s = Survey.example()
1409
+ >>> d = s.dag()
1410
+ >>> d
1411
+ {1: {0}, 2: {0}}
1412
+ >>> s.textify(d)
1413
+ {'q1': {'q0'}, 'q2': {'q0'}}
1414
+ """
1415
+
1416
+ def get_name(index: int):
1417
+ """Return the name of the question given the index."""
1418
+ if index >= len(self.questions):
1419
+ return EndOfSurvey
1420
+ try:
1421
+ return self.questions[index].question_name
1422
+ except IndexError:
1423
+ print(
1424
+ f"The index is {index} but the length of the questions is {len(self.questions)}"
1425
+ )
1426
+ raise SurveyError
1427
+
1428
+ try:
1429
+ text_dag = {}
1430
+ for child_index, parent_indices in index_dag.items():
1431
+ parent_names = {get_name(index) for index in parent_indices}
1432
+ child_name = get_name(child_index)
1433
+ text_dag[child_name] = parent_names
1434
+ return text_dag
1435
+ except IndexError:
1436
+ raise
1437
+
1438
+ @property
1439
+ def piping_dag(self) -> DAG:
1440
+ """Figures out the DAG of piping dependencies.
1441
+
1442
+ >>> from edsl import QuestionFreeText
1443
+ >>> q0 = QuestionFreeText(question_text="Here is a question", question_name="q0")
1444
+ >>> q1 = QuestionFreeText(question_text="You previously answered {{ q0 }}---how do you feel now?", question_name="q1")
1445
+ >>> s = Survey([q0, q1])
1446
+ >>> s.piping_dag
1447
+ {1: {0}}
1448
+ """
1449
+ d = {}
1450
+ for question_name, depenencies in self.parameters_by_question.items():
1451
+ if depenencies:
1452
+ question_index = self.question_name_to_index[question_name]
1453
+ for dependency in depenencies:
1454
+ if dependency not in self.question_name_to_index:
1455
+ pass
1456
+ else:
1457
+ dependency_index = self.question_name_to_index[dependency]
1458
+ if question_index not in d:
1459
+ d[question_index] = set()
1460
+ d[question_index].add(dependency_index)
1461
+ return d
1462
+
1463
+ def dag(self, textify: bool = False) -> DAG:
1464
+ """Return the DAG of the survey, which reflects both skip-logic and memory.
1465
+
1466
+ :param textify: Whether to return the DAG with question names instead of indices.
1467
+
1468
+ >>> s = Survey.example()
1469
+ >>> d = s.dag()
1470
+ >>> d
1471
+ {1: {0}, 2: {0}}
1472
+
1473
+ """
1474
+ memory_dag = self.memory_plan.dag
1475
+ rule_dag = self.rule_collection.dag
1476
+ piping_dag = self.piping_dag
1477
+ if textify:
1478
+ memory_dag = DAG(self.textify(memory_dag))
1479
+ rule_dag = DAG(self.textify(rule_dag))
1480
+ piping_dag = DAG(self.textify(piping_dag))
1481
+ return memory_dag + rule_dag + piping_dag
1482
+
1483
+ ###################
1484
+ # DUNDER METHODS
1485
+ ###################
1486
+ def __len__(self) -> int:
1487
+ """Return the number of questions in the survey.
1488
+
1489
+ >>> s = Survey.example()
1490
+ >>> len(s)
1491
+ 3
1492
+ """
1493
+ return len(self._questions)
1494
+
1495
+ def __getitem__(self, index) -> QuestionBase:
1496
+ """Return the question object given the question index.
1497
+
1498
+ :param index: The index of the question to get.
1499
+
1500
+ >>> s = Survey.example()
1501
+ >>> s[0]
1502
+ Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1503
+
1504
+ """
1505
+ if isinstance(index, int):
1506
+ return self._questions[index]
1507
+ elif isinstance(index, str):
1508
+ return getattr(self, index)
1509
+
1510
+ def _diff(self, other):
1511
+ """Used for debugging. Print out the differences between two surveys."""
1512
+ from rich import print
1513
+
1514
+ for key, value in self.to_dict().items():
1515
+ if value != other.to_dict()[key]:
1516
+ print(f"Key: {key}")
1517
+ print("\n")
1518
+ print(f"Self: {value}")
1519
+ print("\n")
1520
+ print(f"Other: {other.to_dict()[key]}")
1521
+ print("\n\n")
1522
+
1523
+ def __eq__(self, other) -> bool:
1524
+ """Return True if the two surveys have the same to_dict.
1525
+
1526
+ :param other: The other survey to compare to.
1527
+
1528
+ >>> s = Survey.example()
1529
+ >>> s == s
1530
+ True
1531
+
1532
+ >>> s == "poop"
1533
+ False
1534
+
1535
+ """
1536
+ if not isinstance(other, Survey):
1537
+ return False
1538
+ return self.to_dict() == other.to_dict()
1539
+
1540
+ @classmethod
1541
+ def from_qsf(
1542
+ cls, qsf_file: Optional[str] = None, url: Optional[str] = None
1543
+ ) -> Survey:
1544
+ """Create a Survey object from a Qualtrics QSF file."""
1545
+
1546
+ if url and qsf_file:
1547
+ raise ValueError("Only one of url or qsf_file can be provided.")
1548
+
1549
+ if (not url) and (not qsf_file):
1550
+ raise ValueError("Either url or qsf_file must be provided.")
1551
+
1552
+ if url:
1553
+ response = requests.get(url)
1554
+ response.raise_for_status() # Ensure the request was successful
1555
+
1556
+ # Save the Excel file to a temporary file
1557
+ with tempfile.NamedTemporaryFile(suffix=".qsf", delete=False) as temp_file:
1558
+ temp_file.write(response.content)
1559
+ qsf_file = temp_file.name
1560
+
1561
+ from edsl.surveys.SurveyQualtricsImport import SurveyQualtricsImport
1562
+
1563
+ so = SurveyQualtricsImport(qsf_file)
1564
+ return so.create_survey()
1565
+
1566
+ # region: Display methods
1567
+ def print(self):
1568
+ """Print the survey in a rich format.
1569
+
1570
+ >>> s = Survey.example()
1571
+ >>> s.print()
1572
+ {
1573
+ "questions": [
1574
+ ...
1575
+ }
1576
+ """
1577
+ from rich import print_json
1578
+ import json
1579
+
1580
+ print_json(json.dumps(self.to_dict()))
1581
+
1582
+ def __repr__(self) -> str:
1583
+ """Return a string representation of the survey."""
1584
+
1585
+ # questions_string = ", ".join([repr(q) for q in self._questions])
1586
+ questions_string = ", ".join([repr(q) for q in self.raw_passed_questions or []])
1587
+ # question_names_string = ", ".join([repr(name) for name in self.question_names])
1588
+ return f"Survey(questions=[{questions_string}], memory_plan={self.memory_plan}, rule_collection={self.rule_collection}, question_groups={self.question_groups})"
1589
+
1590
+ def _repr_html_(self) -> str:
1591
+ from edsl.utilities.utilities import data_to_html
1592
+
1593
+ return data_to_html(self.to_dict())
1594
+
1595
+ def rich_print(self) -> Table:
1596
+ """Print the survey in a rich format.
1597
+
1598
+ >>> t = Survey.example().rich_print()
1599
+ >>> print(t) # doctest: +SKIP
1600
+ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
1601
+ ┃ Questions ┃
1602
+ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
1603
+ │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┓ │
1604
+ │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1605
+ │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━┩ │
1606
+ │ │ q0 │ multiple_choice │ Do you like school? │ yes, no │ │
1607
+ │ └───────────────┴─────────────────┴─────────────────────┴─────────┘ │
1608
+ │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │
1609
+ │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1610
+ │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │
1611
+ │ │ q1 │ multiple_choice │ Why not? │ killer bees in cafeteria, other │ │
1612
+ │ └───────────────┴─────────────────┴───────────────┴─────────────────────────────────┘ │
1613
+ │ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │
1614
+ │ ┃ Question Name ┃ Question Type ┃ Question Text ┃ Options ┃ │
1615
+ │ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │
1616
+ │ │ q2 │ multiple_choice │ Why? │ **lack*** of killer bees in cafeteria, other │ │
1617
+ │ └───────────────┴─────────────────┴───────────────┴──────────────────────────────────────────────┘ │
1618
+ └────────────────────────────────────────────────────────────────────────────────────────────────────┘
1619
+ """
1620
+ from rich.table import Table
1621
+
1622
+ table = Table(show_header=True, header_style="bold magenta")
1623
+ table.add_column("Questions", style="dim")
1624
+
1625
+ for question in self._questions:
1626
+ table.add_row(question.rich_print())
1627
+
1628
+ return table
1629
+
1630
+ # endregion
1631
+
1632
+ def codebook(self) -> dict[str, str]:
1633
+ """Create a codebook for the survey, mapping question names to question text.
1634
+
1635
+ >>> s = Survey.example()
1636
+ >>> s.codebook()
1637
+ {'q0': 'Do you like school?', 'q1': 'Why not?', 'q2': 'Why?'}
1638
+ """
1639
+ codebook = {}
1640
+ for question in self._questions:
1641
+ codebook[question.question_name] = question.question_text
1642
+ return codebook
1643
+
1644
+ # region: Export methods
1645
+ def to_csv(self, filename: str = None):
1646
+ """Export the survey to a CSV file.
1647
+
1648
+ :param filename: The name of the file to save the CSV to.
1649
+
1650
+ >>> s = Survey.example()
1651
+ >>> s.to_csv() # doctest: +SKIP
1652
+ index question_name question_text question_options question_type
1653
+ 0 0 q0 Do you like school? [yes, no] multiple_choice
1654
+ 1 1 q1 Why not? [killer bees in cafeteria, other] multiple_choice
1655
+ 2 2 q2 Why? [**lack*** of killer bees in cafeteria, other] multiple_choice
1656
+ """
1657
+ raw_data = []
1658
+ for index, question in enumerate(self._questions):
1659
+ d = {"index": index}
1660
+ question_dict = question.to_dict()
1661
+ _ = question_dict.pop("edsl_version")
1662
+ _ = question_dict.pop("edsl_class_name")
1663
+ d.update(question_dict)
1664
+ raw_data.append(d)
1665
+ from pandas import DataFrame
1666
+
1667
+ df = DataFrame(raw_data)
1668
+ if filename:
1669
+ df.to_csv(filename, index=False)
1670
+ else:
1671
+ return df
1672
+
1673
+ # endregion
1674
+
1675
+ @classmethod
1676
+ def example(
1677
+ cls,
1678
+ params: bool = False,
1679
+ randomize: bool = False,
1680
+ include_instructions=False,
1681
+ custom_instructions: Optional[str] = None,
1682
+ ) -> Survey:
1683
+ """Return an example survey.
1684
+
1685
+ >>> s = Survey.example()
1686
+ >>> [q.question_text for q in s.questions]
1687
+ ['Do you like school?', 'Why not?', 'Why?']
1688
+ """
1689
+ from edsl.questions.QuestionMultipleChoice import QuestionMultipleChoice
1690
+
1691
+ addition = "" if not randomize else str(uuid4())
1692
+ q0 = QuestionMultipleChoice(
1693
+ question_text=f"Do you like school?{addition}",
1694
+ question_options=["yes", "no"],
1695
+ question_name="q0",
1696
+ )
1697
+ q1 = QuestionMultipleChoice(
1698
+ question_text="Why not?",
1699
+ question_options=["killer bees in cafeteria", "other"],
1700
+ question_name="q1",
1701
+ )
1702
+ q2 = QuestionMultipleChoice(
1703
+ question_text="Why?",
1704
+ question_options=["**lack*** of killer bees in cafeteria", "other"],
1705
+ question_name="q2",
1706
+ )
1707
+ if params:
1708
+ q3 = QuestionMultipleChoice(
1709
+ question_text="To the question '{{ q0.question_text}}', you said '{{ q0.answer }}'. Do you still feel this way?",
1710
+ question_options=["yes", "no"],
1711
+ question_name="q3",
1712
+ )
1713
+ s = cls(questions=[q0, q1, q2, q3])
1714
+ return s
1715
+
1716
+ if include_instructions:
1717
+ from edsl import Instruction
1718
+
1719
+ custom_instructions = (
1720
+ custom_instructions if custom_instructions else "Please pay attention!"
1721
+ )
1722
+
1723
+ i = Instruction(text=custom_instructions, name="attention")
1724
+ s = cls(questions=[i, q0, q1, q2])
1725
+ return s
1726
+
1727
+ s = cls(questions=[q0, q1, q2])
1728
+ s = s.add_rule(q0, "q0 == 'yes'", q2)
1729
+ return s
1730
+
1731
+ def get_job(self, model=None, agent=None, **kwargs):
1732
+ if model is None:
1733
+ from edsl import Model
1734
+
1735
+ model = Model()
1736
+
1737
+ from edsl.scenarios.Scenario import Scenario
1738
+
1739
+ s = Scenario(kwargs)
1740
+
1741
+ if not agent:
1742
+ from edsl import Agent
1743
+
1744
+ agent = Agent()
1745
+
1746
+ return self.by(s).by(agent).by(model)
1747
+
1748
+
1749
+ def main():
1750
+ """Run the example survey."""
1751
+
1752
+ def example_survey():
1753
+ """Return an example survey."""
1754
+ from edsl.questions.QuestionMultipleChoice import QuestionMultipleChoice
1755
+ from edsl.surveys.Survey import Survey
1756
+
1757
+ q0 = QuestionMultipleChoice(
1758
+ question_text="Do you like school?",
1759
+ question_options=["yes", "no"],
1760
+ question_name="q0",
1761
+ )
1762
+ q1 = QuestionMultipleChoice(
1763
+ question_text="Why not?",
1764
+ question_options=["killer bees in cafeteria", "other"],
1765
+ question_name="q1",
1766
+ )
1767
+ q2 = QuestionMultipleChoice(
1768
+ question_text="Why?",
1769
+ question_options=["**lack*** of killer bees in cafeteria", "other"],
1770
+ question_name="q2",
1771
+ )
1772
+ s = Survey(questions=[q0, q1, q2])
1773
+ s = s.add_rule(q0, "q0 == 'yes'", q2)
1774
+ return s
1775
+
1776
+ s = example_survey()
1777
+ survey_dict = s.to_dict()
1778
+ s2 = Survey.from_dict(survey_dict)
1779
+ results = s2.run()
1780
+ print(results)
1781
+
1782
+
1783
+ if __name__ == "__main__":
1784
+ import doctest
1785
+
1786
+ # doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.SKIP)
1787
+ doctest.testmod(optionflags=doctest.ELLIPSIS)