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