edsl 0.1.46__py3-none-any.whl → 0.1.48__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 (328) hide show
  1. edsl/__init__.py +44 -39
  2. edsl/__version__.py +1 -1
  3. edsl/agents/__init__.py +4 -2
  4. edsl/agents/{Agent.py → agent.py} +442 -152
  5. edsl/agents/{AgentList.py → agent_list.py} +220 -162
  6. edsl/agents/descriptors.py +46 -7
  7. edsl/{exceptions/agents.py → agents/exceptions.py} +3 -12
  8. edsl/base/__init__.py +75 -0
  9. edsl/base/base_class.py +1303 -0
  10. edsl/base/data_transfer_models.py +114 -0
  11. edsl/base/enums.py +215 -0
  12. edsl/base.py +8 -0
  13. edsl/buckets/__init__.py +25 -0
  14. edsl/buckets/bucket_collection.py +324 -0
  15. edsl/buckets/model_buckets.py +206 -0
  16. edsl/buckets/token_bucket.py +502 -0
  17. edsl/{jobs/buckets/TokenBucketAPI.py → buckets/token_bucket_api.py} +1 -1
  18. edsl/buckets/token_bucket_client.py +509 -0
  19. edsl/caching/__init__.py +20 -0
  20. edsl/caching/cache.py +814 -0
  21. edsl/caching/cache_entry.py +427 -0
  22. edsl/{data/CacheHandler.py → caching/cache_handler.py} +14 -15
  23. edsl/caching/exceptions.py +24 -0
  24. edsl/caching/orm.py +30 -0
  25. edsl/{data/RemoteCacheSync.py → caching/remote_cache_sync.py} +3 -3
  26. edsl/caching/sql_dict.py +441 -0
  27. edsl/config/__init__.py +8 -0
  28. edsl/config/config_class.py +177 -0
  29. edsl/config.py +4 -176
  30. edsl/conversation/Conversation.py +7 -7
  31. edsl/conversation/car_buying.py +4 -4
  32. edsl/conversation/chips.py +6 -6
  33. edsl/coop/__init__.py +25 -2
  34. edsl/coop/coop.py +430 -113
  35. edsl/coop/{ExpectedParrotKeyHandler.py → ep_key_handling.py} +86 -10
  36. edsl/coop/exceptions.py +62 -0
  37. edsl/coop/price_fetcher.py +126 -0
  38. edsl/coop/utils.py +89 -24
  39. edsl/data_transfer_models.py +5 -72
  40. edsl/dataset/__init__.py +10 -0
  41. edsl/{results/Dataset.py → dataset/dataset.py} +116 -36
  42. edsl/dataset/dataset_operations_mixin.py +1492 -0
  43. edsl/{results/DatasetTree.py → dataset/dataset_tree.py} +156 -75
  44. edsl/{results/TableDisplay.py → dataset/display/table_display.py} +18 -7
  45. edsl/{results → dataset/display}/table_renderers.py +58 -2
  46. edsl/{results → dataset}/file_exports.py +4 -5
  47. edsl/{results → dataset}/smart_objects.py +2 -2
  48. edsl/enums.py +5 -205
  49. edsl/inference_services/__init__.py +5 -0
  50. edsl/inference_services/{AvailableModelCacheHandler.py → available_model_cache_handler.py} +2 -3
  51. edsl/inference_services/{AvailableModelFetcher.py → available_model_fetcher.py} +8 -14
  52. edsl/inference_services/data_structures.py +3 -2
  53. edsl/{exceptions/inference_services.py → inference_services/exceptions.py} +1 -1
  54. edsl/inference_services/{InferenceServiceABC.py → inference_service_abc.py} +1 -1
  55. edsl/inference_services/{InferenceServicesCollection.py → inference_services_collection.py} +8 -7
  56. edsl/inference_services/registry.py +4 -41
  57. edsl/inference_services/{ServiceAvailability.py → service_availability.py} +5 -25
  58. edsl/inference_services/services/__init__.py +31 -0
  59. edsl/inference_services/{AnthropicService.py → services/anthropic_service.py} +3 -3
  60. edsl/inference_services/{AwsBedrock.py → services/aws_bedrock.py} +2 -2
  61. edsl/inference_services/{AzureAI.py → services/azure_ai.py} +2 -2
  62. edsl/inference_services/{DeepInfraService.py → services/deep_infra_service.py} +1 -3
  63. edsl/inference_services/{DeepSeekService.py → services/deep_seek_service.py} +2 -4
  64. edsl/inference_services/{GoogleService.py → services/google_service.py} +5 -4
  65. edsl/inference_services/{GroqService.py → services/groq_service.py} +1 -1
  66. edsl/inference_services/{MistralAIService.py → services/mistral_ai_service.py} +3 -3
  67. edsl/inference_services/{OllamaService.py → services/ollama_service.py} +1 -7
  68. edsl/inference_services/{OpenAIService.py → services/open_ai_service.py} +5 -6
  69. edsl/inference_services/{PerplexityService.py → services/perplexity_service.py} +12 -12
  70. edsl/inference_services/{TestService.py → services/test_service.py} +7 -6
  71. edsl/inference_services/{TogetherAIService.py → services/together_ai_service.py} +2 -6
  72. edsl/inference_services/{XAIService.py → services/xai_service.py} +1 -1
  73. edsl/inference_services/write_available.py +1 -2
  74. edsl/instructions/__init__.py +6 -0
  75. edsl/{surveys/instructions/Instruction.py → instructions/instruction.py} +11 -6
  76. edsl/{surveys/instructions/InstructionCollection.py → instructions/instruction_collection.py} +10 -5
  77. edsl/{surveys/InstructionHandler.py → instructions/instruction_handler.py} +3 -3
  78. edsl/{jobs/interviews → interviews}/ReportErrors.py +2 -2
  79. edsl/interviews/__init__.py +4 -0
  80. edsl/{jobs/AnswerQuestionFunctionConstructor.py → interviews/answering_function.py} +45 -18
  81. edsl/{jobs/interviews/InterviewExceptionEntry.py → interviews/exception_tracking.py} +107 -22
  82. edsl/interviews/interview.py +638 -0
  83. edsl/{jobs/interviews/InterviewStatusDictionary.py → interviews/interview_status_dictionary.py} +21 -12
  84. edsl/{jobs/interviews/InterviewStatusLog.py → interviews/interview_status_log.py} +16 -7
  85. edsl/{jobs/InterviewTaskManager.py → interviews/interview_task_manager.py} +12 -7
  86. edsl/{jobs/RequestTokenEstimator.py → interviews/request_token_estimator.py} +8 -3
  87. edsl/{jobs/interviews/InterviewStatistic.py → interviews/statistics.py} +36 -10
  88. edsl/invigilators/__init__.py +38 -0
  89. edsl/invigilators/invigilator_base.py +477 -0
  90. edsl/{agents/Invigilator.py → invigilators/invigilators.py} +263 -10
  91. edsl/invigilators/prompt_constructor.py +476 -0
  92. edsl/{agents → invigilators}/prompt_helpers.py +2 -1
  93. edsl/{agents/QuestionInstructionPromptBuilder.py → invigilators/question_instructions_prompt_builder.py} +18 -13
  94. edsl/{agents → invigilators}/question_option_processor.py +96 -21
  95. edsl/{agents/QuestionTemplateReplacementsBuilder.py → invigilators/question_template_replacements_builder.py} +64 -12
  96. edsl/jobs/__init__.py +7 -1
  97. edsl/jobs/async_interview_runner.py +99 -35
  98. edsl/jobs/check_survey_scenario_compatibility.py +7 -5
  99. edsl/jobs/data_structures.py +153 -22
  100. edsl/{exceptions/jobs.py → jobs/exceptions.py} +2 -1
  101. edsl/jobs/{FetchInvigilator.py → fetch_invigilator.py} +4 -4
  102. edsl/jobs/{loggers/HTMLTableJobLogger.py → html_table_job_logger.py} +6 -2
  103. edsl/jobs/{Jobs.py → jobs.py} +321 -155
  104. edsl/jobs/{JobsChecks.py → jobs_checks.py} +15 -7
  105. edsl/jobs/{JobsComponentConstructor.py → jobs_component_constructor.py} +20 -17
  106. edsl/jobs/{InterviewsConstructor.py → jobs_interview_constructor.py} +10 -5
  107. edsl/jobs/jobs_pricing_estimation.py +347 -0
  108. edsl/jobs/{JobsRemoteInferenceLogger.py → jobs_remote_inference_logger.py} +4 -3
  109. edsl/jobs/jobs_runner_asyncio.py +282 -0
  110. edsl/jobs/{JobsRemoteInferenceHandler.py → remote_inference.py} +19 -22
  111. edsl/jobs/results_exceptions_handler.py +2 -2
  112. edsl/key_management/__init__.py +28 -0
  113. edsl/key_management/key_lookup.py +161 -0
  114. edsl/{language_models/key_management/KeyLookupBuilder.py → key_management/key_lookup_builder.py} +118 -47
  115. edsl/key_management/key_lookup_collection.py +82 -0
  116. edsl/key_management/models.py +218 -0
  117. edsl/language_models/__init__.py +7 -2
  118. edsl/language_models/{ComputeCost.py → compute_cost.py} +18 -3
  119. edsl/{exceptions/language_models.py → language_models/exceptions.py} +2 -1
  120. edsl/language_models/language_model.py +1080 -0
  121. edsl/language_models/model.py +10 -25
  122. edsl/language_models/{ModelList.py → model_list.py} +9 -14
  123. edsl/language_models/{RawResponseHandler.py → raw_response_handler.py} +1 -1
  124. edsl/language_models/{RegisterLanguageModelsMeta.py → registry.py} +1 -1
  125. edsl/language_models/repair.py +4 -4
  126. edsl/language_models/utilities.py +4 -4
  127. edsl/notebooks/__init__.py +3 -1
  128. edsl/notebooks/{Notebook.py → notebook.py} +7 -8
  129. edsl/prompts/__init__.py +1 -1
  130. edsl/{exceptions/prompts.py → prompts/exceptions.py} +3 -1
  131. edsl/prompts/{Prompt.py → prompt.py} +101 -95
  132. edsl/questions/HTMLQuestion.py +1 -1
  133. edsl/questions/__init__.py +154 -25
  134. edsl/questions/answer_validator_mixin.py +1 -1
  135. edsl/questions/compose_questions.py +4 -3
  136. edsl/questions/derived/question_likert_five.py +166 -0
  137. edsl/questions/derived/{QuestionLinearScale.py → question_linear_scale.py} +4 -4
  138. edsl/questions/derived/{QuestionTopK.py → question_top_k.py} +4 -4
  139. edsl/questions/derived/{QuestionYesNo.py → question_yes_no.py} +4 -5
  140. edsl/questions/descriptors.py +24 -30
  141. edsl/questions/loop_processor.py +65 -19
  142. edsl/questions/question_base.py +881 -0
  143. edsl/questions/question_base_gen_mixin.py +15 -16
  144. edsl/questions/{QuestionBasePromptsMixin.py → question_base_prompts_mixin.py} +2 -2
  145. edsl/questions/{QuestionBudget.py → question_budget.py} +3 -4
  146. edsl/questions/{QuestionCheckBox.py → question_check_box.py} +16 -16
  147. edsl/questions/{QuestionDict.py → question_dict.py} +39 -5
  148. edsl/questions/{QuestionExtract.py → question_extract.py} +9 -9
  149. edsl/questions/question_free_text.py +282 -0
  150. edsl/questions/{QuestionFunctional.py → question_functional.py} +6 -5
  151. edsl/questions/{QuestionList.py → question_list.py} +6 -7
  152. edsl/questions/{QuestionMatrix.py → question_matrix.py} +6 -5
  153. edsl/questions/{QuestionMultipleChoice.py → question_multiple_choice.py} +126 -21
  154. edsl/questions/{QuestionNumerical.py → question_numerical.py} +5 -5
  155. edsl/questions/{QuestionRank.py → question_rank.py} +6 -6
  156. edsl/questions/question_registry.py +10 -16
  157. edsl/questions/register_questions_meta.py +8 -4
  158. edsl/questions/response_validator_abc.py +17 -16
  159. edsl/results/__init__.py +4 -1
  160. edsl/{exceptions/results.py → results/exceptions.py} +1 -1
  161. edsl/results/report.py +197 -0
  162. edsl/results/{Result.py → result.py} +131 -45
  163. edsl/results/{Results.py → results.py} +420 -216
  164. edsl/results/results_selector.py +344 -25
  165. edsl/scenarios/__init__.py +30 -3
  166. edsl/scenarios/{ConstructDownloadLink.py → construct_download_link.py} +7 -0
  167. edsl/scenarios/directory_scanner.py +156 -13
  168. edsl/scenarios/document_chunker.py +186 -0
  169. edsl/scenarios/exceptions.py +101 -0
  170. edsl/scenarios/file_methods.py +2 -3
  171. edsl/scenarios/file_store.py +755 -0
  172. edsl/scenarios/handlers/__init__.py +14 -14
  173. edsl/scenarios/handlers/{csv.py → csv_file_store.py} +1 -2
  174. edsl/scenarios/handlers/{docx.py → docx_file_store.py} +8 -7
  175. edsl/scenarios/handlers/{html.py → html_file_store.py} +1 -2
  176. edsl/scenarios/handlers/{jpeg.py → jpeg_file_store.py} +1 -1
  177. edsl/scenarios/handlers/{json.py → json_file_store.py} +1 -1
  178. edsl/scenarios/handlers/latex_file_store.py +5 -0
  179. edsl/scenarios/handlers/{md.py → md_file_store.py} +1 -1
  180. edsl/scenarios/handlers/{pdf.py → pdf_file_store.py} +2 -2
  181. edsl/scenarios/handlers/{png.py → png_file_store.py} +1 -1
  182. edsl/scenarios/handlers/{pptx.py → pptx_file_store.py} +8 -7
  183. edsl/scenarios/handlers/{py.py → py_file_store.py} +1 -3
  184. edsl/scenarios/handlers/{sql.py → sql_file_store.py} +2 -1
  185. edsl/scenarios/handlers/{sqlite.py → sqlite_file_store.py} +2 -3
  186. edsl/scenarios/handlers/{txt.py → txt_file_store.py} +1 -1
  187. edsl/scenarios/scenario.py +928 -0
  188. edsl/scenarios/scenario_join.py +18 -5
  189. edsl/scenarios/{ScenarioList.py → scenario_list.py} +424 -106
  190. edsl/scenarios/{ScenarioListPdfMixin.py → scenario_list_pdf_tools.py} +16 -15
  191. edsl/scenarios/scenario_selector.py +5 -1
  192. edsl/study/ObjectEntry.py +2 -2
  193. edsl/study/SnapShot.py +5 -5
  194. edsl/study/Study.py +20 -21
  195. edsl/study/__init__.py +6 -4
  196. edsl/surveys/__init__.py +7 -4
  197. edsl/surveys/dag/__init__.py +2 -0
  198. edsl/surveys/{ConstructDAG.py → dag/construct_dag.py} +3 -3
  199. edsl/surveys/{DAG.py → dag/dag.py} +13 -10
  200. edsl/surveys/descriptors.py +1 -1
  201. edsl/surveys/{EditSurvey.py → edit_survey.py} +9 -9
  202. edsl/{exceptions/surveys.py → surveys/exceptions.py} +1 -2
  203. edsl/surveys/memory/__init__.py +3 -0
  204. edsl/surveys/{MemoryPlan.py → memory/memory_plan.py} +10 -9
  205. edsl/surveys/rules/__init__.py +3 -0
  206. edsl/surveys/{Rule.py → rules/rule.py} +103 -43
  207. edsl/surveys/{RuleCollection.py → rules/rule_collection.py} +21 -30
  208. edsl/surveys/{RuleManager.py → rules/rule_manager.py} +19 -13
  209. edsl/surveys/survey.py +1743 -0
  210. edsl/surveys/{SurveyExportMixin.py → survey_export.py} +22 -27
  211. edsl/surveys/{SurveyFlowVisualization.py → survey_flow_visualization.py} +11 -2
  212. edsl/surveys/{Simulator.py → survey_simulator.py} +10 -3
  213. edsl/tasks/__init__.py +32 -0
  214. edsl/{jobs/tasks/QuestionTaskCreator.py → tasks/question_task_creator.py} +115 -57
  215. edsl/tasks/task_creators.py +135 -0
  216. edsl/{jobs/tasks/TaskHistory.py → tasks/task_history.py} +86 -47
  217. edsl/{jobs/tasks → tasks}/task_status_enum.py +91 -7
  218. edsl/tasks/task_status_log.py +85 -0
  219. edsl/tokens/__init__.py +2 -0
  220. edsl/tokens/interview_token_usage.py +53 -0
  221. edsl/utilities/PrettyList.py +1 -1
  222. edsl/utilities/SystemInfo.py +25 -22
  223. edsl/utilities/__init__.py +29 -21
  224. edsl/utilities/gcp_bucket/__init__.py +2 -0
  225. edsl/utilities/gcp_bucket/cloud_storage.py +99 -96
  226. edsl/utilities/interface.py +44 -536
  227. edsl/{results/MarkdownToPDF.py → utilities/markdown_to_pdf.py} +13 -5
  228. edsl/utilities/repair_functions.py +1 -1
  229. {edsl-0.1.46.dist-info → edsl-0.1.48.dist-info}/METADATA +3 -2
  230. edsl-0.1.48.dist-info/RECORD +347 -0
  231. edsl/Base.py +0 -426
  232. edsl/BaseDiff.py +0 -260
  233. edsl/agents/InvigilatorBase.py +0 -260
  234. edsl/agents/PromptConstructor.py +0 -318
  235. edsl/auto/AutoStudy.py +0 -130
  236. edsl/auto/StageBase.py +0 -243
  237. edsl/auto/StageGenerateSurvey.py +0 -178
  238. edsl/auto/StageLabelQuestions.py +0 -125
  239. edsl/auto/StagePersona.py +0 -61
  240. edsl/auto/StagePersonaDimensionValueRanges.py +0 -88
  241. edsl/auto/StagePersonaDimensionValues.py +0 -74
  242. edsl/auto/StagePersonaDimensions.py +0 -69
  243. edsl/auto/StageQuestions.py +0 -74
  244. edsl/auto/SurveyCreatorPipeline.py +0 -21
  245. edsl/auto/utilities.py +0 -218
  246. edsl/base/Base.py +0 -279
  247. edsl/coop/PriceFetcher.py +0 -54
  248. edsl/data/Cache.py +0 -580
  249. edsl/data/CacheEntry.py +0 -230
  250. edsl/data/SQLiteDict.py +0 -292
  251. edsl/data/__init__.py +0 -5
  252. edsl/data/orm.py +0 -10
  253. edsl/exceptions/cache.py +0 -5
  254. edsl/exceptions/coop.py +0 -14
  255. edsl/exceptions/data.py +0 -14
  256. edsl/exceptions/scenarios.py +0 -29
  257. edsl/jobs/Answers.py +0 -43
  258. edsl/jobs/JobsPrompts.py +0 -354
  259. edsl/jobs/buckets/BucketCollection.py +0 -134
  260. edsl/jobs/buckets/ModelBuckets.py +0 -65
  261. edsl/jobs/buckets/TokenBucket.py +0 -283
  262. edsl/jobs/buckets/TokenBucketClient.py +0 -191
  263. edsl/jobs/interviews/Interview.py +0 -395
  264. edsl/jobs/interviews/InterviewExceptionCollection.py +0 -99
  265. edsl/jobs/interviews/InterviewStatisticsCollection.py +0 -25
  266. edsl/jobs/runners/JobsRunnerAsyncio.py +0 -163
  267. edsl/jobs/runners/JobsRunnerStatusData.py +0 -0
  268. edsl/jobs/tasks/TaskCreators.py +0 -64
  269. edsl/jobs/tasks/TaskStatusLog.py +0 -23
  270. edsl/jobs/tokens/InterviewTokenUsage.py +0 -27
  271. edsl/language_models/LanguageModel.py +0 -635
  272. edsl/language_models/ServiceDataSources.py +0 -0
  273. edsl/language_models/key_management/KeyLookup.py +0 -63
  274. edsl/language_models/key_management/KeyLookupCollection.py +0 -38
  275. edsl/language_models/key_management/models.py +0 -137
  276. edsl/questions/QuestionBase.py +0 -539
  277. edsl/questions/QuestionFreeText.py +0 -130
  278. edsl/questions/derived/QuestionLikertFive.py +0 -76
  279. edsl/results/DatasetExportMixin.py +0 -911
  280. edsl/results/ResultsExportMixin.py +0 -45
  281. edsl/results/TextEditor.py +0 -50
  282. edsl/results/results_fetch_mixin.py +0 -33
  283. edsl/results/results_tools_mixin.py +0 -98
  284. edsl/scenarios/DocumentChunker.py +0 -104
  285. edsl/scenarios/FileStore.py +0 -564
  286. edsl/scenarios/Scenario.py +0 -548
  287. edsl/scenarios/ScenarioHtmlMixin.py +0 -65
  288. edsl/scenarios/ScenarioListExportMixin.py +0 -45
  289. edsl/scenarios/handlers/latex.py +0 -5
  290. edsl/shared.py +0 -1
  291. edsl/surveys/Survey.py +0 -1306
  292. edsl/surveys/SurveyQualtricsImport.py +0 -284
  293. edsl/surveys/SurveyToApp.py +0 -141
  294. edsl/surveys/instructions/__init__.py +0 -0
  295. edsl/tools/__init__.py +0 -1
  296. edsl/tools/clusters.py +0 -192
  297. edsl/tools/embeddings.py +0 -27
  298. edsl/tools/embeddings_plotting.py +0 -118
  299. edsl/tools/plotting.py +0 -112
  300. edsl/tools/summarize.py +0 -18
  301. edsl/utilities/data/Registry.py +0 -6
  302. edsl/utilities/data/__init__.py +0 -1
  303. edsl/utilities/data/scooter_results.json +0 -1
  304. edsl-0.1.46.dist-info/RECORD +0 -366
  305. /edsl/coop/{CoopFunctionsMixin.py → coop_functions.py} +0 -0
  306. /edsl/{results → dataset/display}/CSSParameterizer.py +0 -0
  307. /edsl/{language_models/key_management → dataset/display}/__init__.py +0 -0
  308. /edsl/{results → dataset/display}/table_data_class.py +0 -0
  309. /edsl/{results → dataset/display}/table_display.css +0 -0
  310. /edsl/{results/ResultsGGMixin.py → dataset/r/ggplot.py} +0 -0
  311. /edsl/{results → dataset}/tree_explore.py +0 -0
  312. /edsl/{surveys/instructions/ChangeInstruction.py → instructions/change_instruction.py} +0 -0
  313. /edsl/{jobs/interviews → interviews}/interview_status_enum.py +0 -0
  314. /edsl/jobs/{runners/JobsRunnerStatus.py → jobs_runner_status.py} +0 -0
  315. /edsl/language_models/{PriceManager.py → price_manager.py} +0 -0
  316. /edsl/language_models/{fake_openai_call.py → unused/fake_openai_call.py} +0 -0
  317. /edsl/language_models/{fake_openai_service.py → unused/fake_openai_service.py} +0 -0
  318. /edsl/notebooks/{NotebookToLaTeX.py → notebook_to_latex.py} +0 -0
  319. /edsl/{exceptions/questions.py → questions/exceptions.py} +0 -0
  320. /edsl/questions/{SimpleAskMixin.py → simple_ask_mixin.py} +0 -0
  321. /edsl/surveys/{Memory.py → memory/memory.py} +0 -0
  322. /edsl/surveys/{MemoryManagement.py → memory/memory_management.py} +0 -0
  323. /edsl/surveys/{SurveyCSS.py → survey_css.py} +0 -0
  324. /edsl/{jobs/tokens/TokenUsage.py → tokens/token_usage.py} +0 -0
  325. /edsl/{results/MarkdownToDocx.py → utilities/markdown_to_docx.py} +0 -0
  326. /edsl/{TemplateLoader.py → utilities/template_loader.py} +0 -0
  327. {edsl-0.1.46.dist-info → edsl-0.1.48.dist-info}/LICENSE +0 -0
  328. {edsl-0.1.46.dist-info → edsl-0.1.48.dist-info}/WHEEL +0 -0
edsl/surveys/Survey.py DELETED
@@ -1,1306 +0,0 @@
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 random
6
-
7
- from typing import (
8
- Any,
9
- Generator,
10
- Optional,
11
- Union,
12
- List,
13
- Literal,
14
- Callable,
15
- TYPE_CHECKING,
16
- )
17
- from uuid import uuid4
18
- from edsl.Base import Base
19
- from edsl.exceptions.surveys import SurveyCreationError, SurveyHasNoRulesError
20
- from edsl.exceptions.surveys import SurveyError
21
- from collections import UserDict
22
-
23
-
24
- class PseudoIndices(UserDict):
25
- @property
26
- def max_pseudo_index(self) -> float:
27
- """Return the maximum pseudo index in the survey.
28
- >>> Survey.example()._pseudo_indices.max_pseudo_index
29
- 2
30
- """
31
- if len(self) == 0:
32
- return -1
33
- return max(self.values())
34
-
35
- @property
36
- def last_item_was_instruction(self) -> bool:
37
- """Return whether the last item added to the survey was an instruction.
38
-
39
- This is used to determine the pseudo-index of the next item added to the survey.
40
-
41
- Example:
42
-
43
- >>> s = Survey.example()
44
- >>> s._pseudo_indices.last_item_was_instruction
45
- False
46
- >>> from edsl.surveys.instructions.Instruction import Instruction
47
- >>> s = s.add_instruction(Instruction(text="Pay attention to the following questions.", name="intro"))
48
- >>> s._pseudo_indices.last_item_was_instruction
49
- True
50
- """
51
- return isinstance(self.max_pseudo_index, float)
52
-
53
-
54
- if TYPE_CHECKING:
55
- from edsl.questions.QuestionBase import QuestionBase
56
- from edsl.agents.Agent import Agent
57
- from edsl.surveys.DAG import DAG
58
- from edsl.language_models.LanguageModel import LanguageModel
59
- from edsl.scenarios.Scenario import Scenario
60
- from edsl.data.Cache import Cache
61
-
62
- # This is a hack to get around the fact that TypeAlias is not available in typing until Python 3.10
63
- try:
64
- from typing import TypeAlias
65
- except ImportError:
66
- from typing import _GenericAlias as TypeAlias
67
-
68
- QuestionType: TypeAlias = Union[QuestionBase, Instruction, ChangeInstruction]
69
- QuestionGroupType: TypeAlias = dict[str, tuple[int, int]]
70
-
71
-
72
- from edsl.utilities.remove_edsl_version import remove_edsl_version
73
-
74
- from edsl.surveys.instructions.InstructionCollection import InstructionCollection
75
- from edsl.surveys.instructions.Instruction import Instruction
76
- from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
77
-
78
- from edsl.surveys.base import EndOfSurvey
79
- from edsl.surveys.descriptors import QuestionsDescriptor
80
- from edsl.surveys.MemoryPlan import MemoryPlan
81
- from edsl.surveys.RuleCollection import RuleCollection
82
- from edsl.surveys.SurveyExportMixin import SurveyExportMixin
83
- from edsl.surveys.SurveyFlowVisualization import SurveyFlowVisualization
84
- from edsl.surveys.InstructionHandler import InstructionHandler
85
- from edsl.surveys.EditSurvey import EditSurvey
86
- from edsl.surveys.Simulator import Simulator
87
- from edsl.surveys.MemoryManagement import MemoryManagement
88
- from edsl.surveys.RuleManager import RuleManager
89
-
90
-
91
- class Survey(SurveyExportMixin, Base):
92
- """A collection of questions that supports skip logic."""
93
-
94
- __documentation__ = """https://docs.expectedparrot.com/en/latest/surveys.html"""
95
-
96
- questions = QuestionsDescriptor()
97
- """
98
- A collection of questions that supports skip logic.
99
-
100
- Initalization:
101
- - `questions`: the questions in the survey (optional)
102
- - `question_names`: the names of the questions (optional)
103
- - `name`: the name of the survey (optional)
104
-
105
- Methods:
106
- -
107
-
108
- Notes:
109
- - The presumed order of the survey is the order in which questions are added.
110
- """
111
-
112
- def __init__(
113
- self,
114
- questions: Optional[List["QuestionType"]] = None,
115
- memory_plan: Optional["MemoryPlan"] = None,
116
- rule_collection: Optional["RuleCollection"] = None,
117
- question_groups: Optional["QuestionGroupType"] = None,
118
- name: Optional[str] = None,
119
- questions_to_randomize: Optional[List[str]] = None,
120
- ):
121
- """Create a new survey.
122
-
123
- :param questions: The questions in the survey.
124
- :param memory_plan: The memory plan for the survey.
125
- :param rule_collection: The rule collection for the survey.
126
- :param question_groups: The groups of questions in the survey.
127
- :param name: The name of the survey - DEPRECATED.
128
-
129
-
130
- >>> from edsl import QuestionFreeText
131
- >>> q1 = QuestionFreeText(question_text = "What is your name?", question_name = "name")
132
- >>> q2 = QuestionFreeText(question_text = "What is your favorite color?", question_name = "color")
133
- >>> q3 = QuestionFreeText(question_text = "Is a hot dog a sandwich", question_name = "food")
134
- >>> s = Survey([q1, q2, q3], question_groups = {"demographics": (0, 1), "substantive":(3)})
135
-
136
-
137
- """
138
-
139
- self.raw_passed_questions = questions
140
-
141
- true_questions = self._process_raw_questions(self.raw_passed_questions)
142
-
143
- self.rule_collection = RuleCollection(
144
- num_questions=len(true_questions) if true_questions else None
145
- )
146
- # the RuleCollection needs to be present while we add the questions; we might override this later
147
- # if a rule_collection is provided. This allows us to serialize the survey with the rule_collection.
148
-
149
- # this is where the Questions constructor is called.
150
- self.questions = true_questions
151
- # self.instruction_names_to_instructions = instruction_names_to_instructions
152
-
153
- self.memory_plan = memory_plan or MemoryPlan(self)
154
- if question_groups is not None:
155
- self.question_groups = question_groups
156
- else:
157
- self.question_groups = {}
158
-
159
- # if a rule collection is provided, use it instead of the constructed one
160
- if rule_collection is not None:
161
- self.rule_collection = rule_collection
162
-
163
- if name is not None:
164
- import warnings
165
-
166
- warnings.warn("name parameter to a survey is deprecated.")
167
-
168
- if questions_to_randomize is not None:
169
- self.questions_to_randomize = questions_to_randomize
170
- else:
171
- self.questions_to_randomize = []
172
-
173
- self._seed = None
174
-
175
- def draw(self) -> "Survey":
176
- """Return a new survey with a randomly selected permutation of the options."""
177
- if self._seed is None: # only set once
178
- self._seed = hash(self)
179
- random.seed(self._seed)
180
-
181
- if len(self.questions_to_randomize) == 0:
182
- return self
183
-
184
- new_questions = []
185
- for question in self.questions:
186
- if question.question_name in self.questions_to_randomize:
187
- new_questions.append(question.draw())
188
- else:
189
- new_questions.append(question.duplicate())
190
-
191
- d = self.to_dict()
192
- d["questions"] = [q.to_dict() for q in new_questions]
193
- return Survey.from_dict(d)
194
-
195
- def _process_raw_questions(self, questions: Optional[List["QuestionType"]]) -> list:
196
- """Process the raw questions passed to the survey."""
197
- handler = InstructionHandler(self)
198
- components = handler.separate_questions_and_instructions(questions or [])
199
- self._instruction_names_to_instructions = (
200
- components.instruction_names_to_instructions
201
- )
202
- self._pseudo_indices = PseudoIndices(components.pseudo_indices)
203
- return components.true_questions
204
-
205
- # region: Survey instruction handling
206
- @property
207
- def _relevant_instructions_dict(self) -> InstructionCollection:
208
- """Return a dictionary with keys as question names and values as instructions that are relevant to the question.
209
-
210
- >>> s = Survey.example(include_instructions=True)
211
- >>> s._relevant_instructions_dict
212
- {'q0': [Instruction(name="attention", text="Please pay attention!")], 'q1': [Instruction(name="attention", text="Please pay attention!")], 'q2': [Instruction(name="attention", text="Please pay attention!")]}
213
-
214
- """
215
- return InstructionCollection(
216
- self._instruction_names_to_instructions, self.questions
217
- )
218
-
219
- def _relevant_instructions(self, question: QuestionBase) -> dict:
220
- """This should be a dictionry with keys as question names and values as instructions that are relevant to the question.
221
-
222
- :param question: The question to get the relevant instructions for.
223
-
224
- # Did the instruction come before the question and was it not modified by a change instruction?
225
-
226
- """
227
- return InstructionCollection(
228
- self._instruction_names_to_instructions, self.questions
229
- )[question]
230
-
231
- def show_flow(self, filename: Optional[str] = None) -> None:
232
- """Show the flow of the survey."""
233
- SurveyFlowVisualization(self).show_flow(filename=filename)
234
-
235
- def add_instruction(
236
- self, instruction: Union["Instruction", "ChangeInstruction"]
237
- ) -> Survey:
238
- """
239
- Add an instruction to the survey.
240
-
241
- :param instruction: The instruction to add to the survey.
242
-
243
- >>> from edsl import Instruction
244
- >>> i = Instruction(text="Pay attention to the following questions.", name="intro")
245
- >>> s = Survey().add_instruction(i)
246
- >>> s._instruction_names_to_instructions
247
- {'intro': Instruction(name="intro", text="Pay attention to the following questions.")}
248
- >>> s._pseudo_indices
249
- {'intro': -0.5}
250
- """
251
- return EditSurvey(self).add_instruction(instruction)
252
-
253
- # endregion
254
- @classmethod
255
- def random_survey(cls):
256
- return Simulator.random_survey()
257
-
258
- def simulate(self) -> dict:
259
- """Simulate the survey and return the answers."""
260
- return Simulator(self).simulate()
261
-
262
- # endregion
263
-
264
- # region: Access methods
265
- def _get_question_index(
266
- self, q: Union[QuestionBase, str, EndOfSurvey.__class__]
267
- ) -> Union[int, EndOfSurvey.__class__]:
268
- """Return the index of the question or EndOfSurvey object.
269
-
270
- :param q: The question or question name to get the index of.
271
-
272
- It can handle it if the user passes in the question name, the question object, or the EndOfSurvey object.
273
-
274
- >>> s = Survey.example()
275
- >>> s._get_question_index("q0")
276
- 0
277
-
278
- This doesnt' work with questions that don't exist:
279
-
280
- >>> s._get_question_index("poop")
281
- Traceback (most recent call last):
282
- ...
283
- edsl.exceptions.surveys.SurveyError: Question name poop not found in survey. The current question names are {'q0': 0, 'q1': 1, 'q2': 2}.
284
- ...
285
- """
286
- if q == EndOfSurvey:
287
- return EndOfSurvey
288
- else:
289
- question_name = q if isinstance(q, str) else q.question_name
290
- if question_name not in self.question_name_to_index:
291
- raise SurveyError(
292
- f"""Question name {question_name} not found in survey. The current question names are {self.question_name_to_index}."""
293
- )
294
- return self.question_name_to_index[question_name]
295
-
296
- def _get_question_by_name(self, question_name: str) -> QuestionBase:
297
- """
298
- Return the question object given the question name.
299
-
300
- :param question_name: The name of the question to get.
301
-
302
- >>> s = Survey.example()
303
- >>> s._get_question_by_name("q0")
304
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
305
- """
306
- if question_name not in self.question_name_to_index:
307
- raise SurveyError(f"Question name {question_name} not found in survey.")
308
- return self._questions[self.question_name_to_index[question_name]]
309
-
310
- def question_names_to_questions(self) -> dict:
311
- """Return a dictionary mapping question names to question attributes."""
312
- return {q.question_name: q for q in self.questions}
313
-
314
- @property
315
- def question_names(self) -> list[str]:
316
- """Return a list of question names in the survey.
317
-
318
- Example:
319
-
320
- >>> s = Survey.example()
321
- >>> s.question_names
322
- ['q0', 'q1', 'q2']
323
- """
324
- return [q.question_name for q in self.questions]
325
-
326
- @property
327
- def question_name_to_index(self) -> dict[str, int]:
328
- """Return a dictionary mapping question names to question indices.
329
-
330
- Example:
331
-
332
- >>> s = Survey.example()
333
- >>> s.question_name_to_index
334
- {'q0': 0, 'q1': 1, 'q2': 2}
335
- """
336
- return {q.question_name: i for i, q in enumerate(self.questions)}
337
-
338
- # endregion
339
-
340
- # region: serialization methods
341
- def to_dict(self, add_edsl_version=True) -> dict[str, Any]:
342
- """Serialize the Survey object to a dictionary.
343
-
344
- >>> s = Survey.example()
345
- >>> s.to_dict(add_edsl_version = False).keys()
346
- dict_keys(['questions', 'memory_plan', 'rule_collection', 'question_groups'])
347
- """
348
- from edsl import __version__
349
-
350
- d = {
351
- "questions": [
352
- q.to_dict(add_edsl_version=add_edsl_version)
353
- for q in self._recombined_questions_and_instructions()
354
- ],
355
- "memory_plan": self.memory_plan.to_dict(add_edsl_version=add_edsl_version),
356
- "rule_collection": self.rule_collection.to_dict(
357
- add_edsl_version=add_edsl_version
358
- ),
359
- "question_groups": self.question_groups,
360
- }
361
- if self.questions_to_randomize != []:
362
- d["questions_to_randomize"] = self.questions_to_randomize
363
-
364
- if add_edsl_version:
365
- d["edsl_version"] = __version__
366
- d["edsl_class_name"] = "Survey"
367
- return d
368
-
369
- @classmethod
370
- @remove_edsl_version
371
- def from_dict(cls, data: dict) -> Survey:
372
- """Deserialize the dictionary back to a Survey object.
373
-
374
- :param data: The dictionary to deserialize.
375
-
376
- >>> d = Survey.example().to_dict()
377
- >>> s = Survey.from_dict(d)
378
- >>> s == Survey.example()
379
- True
380
-
381
- >>> s = Survey.example(include_instructions = True)
382
- >>> d = s.to_dict()
383
- >>> news = Survey.from_dict(d)
384
- >>> news == s
385
- True
386
-
387
- """
388
-
389
- def get_class(pass_dict):
390
- from edsl.questions.QuestionBase import QuestionBase
391
-
392
- if (class_name := pass_dict.get("edsl_class_name")) == "QuestionBase":
393
- return QuestionBase
394
- elif pass_dict.get("edsl_class_name") == "QuestionDict":
395
- from edsl.questions.QuestionDict import QuestionDict
396
-
397
- return QuestionDict
398
- elif class_name == "Instruction":
399
- from edsl.surveys.instructions.Instruction import Instruction
400
-
401
- return Instruction
402
- elif class_name == "ChangeInstruction":
403
- from edsl.surveys.instructions.ChangeInstruction import (
404
- ChangeInstruction,
405
- )
406
-
407
- return ChangeInstruction
408
- else:
409
- return QuestionBase
410
-
411
- questions = [
412
- get_class(q_dict).from_dict(q_dict) for q_dict in data["questions"]
413
- ]
414
- memory_plan = MemoryPlan.from_dict(data["memory_plan"])
415
- if "questions_to_randomize" in data:
416
- questions_to_randomize = data["questions_to_randomize"]
417
- else:
418
- questions_to_randomize = None
419
- survey = cls(
420
- questions=questions,
421
- memory_plan=memory_plan,
422
- rule_collection=RuleCollection.from_dict(data["rule_collection"]),
423
- question_groups=data["question_groups"],
424
- questions_to_randomize=questions_to_randomize,
425
- )
426
- return survey
427
-
428
- # endregion
429
-
430
- # region: Survey template parameters
431
- @property
432
- def scenario_attributes(self) -> list[str]:
433
- """Return a list of attributes that admissible Scenarios should have.
434
-
435
- Here we have a survey with a question that uses a jinja2 style {{ }} template:
436
-
437
- >>> from edsl import QuestionFreeText
438
- >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your name?", question_name="name"))
439
- >>> s.scenario_attributes
440
- ['greeting']
441
-
442
- >>> s = Survey().add_question(QuestionFreeText(question_text="{{ greeting }}. What is your {{ attribute }}?", question_name="name"))
443
- >>> s.scenario_attributes
444
- ['greeting', 'attribute']
445
-
446
-
447
- """
448
- temp = []
449
- for question in self.questions:
450
- question_text = question.question_text
451
- # extract the contents of all {{ }} in the question text using regex
452
- matches = re.findall(r"\{\{(.+?)\}\}", question_text)
453
- # remove whitespace
454
- matches = [match.strip() for match in matches]
455
- # add them to the temp list
456
- temp.extend(matches)
457
- return temp
458
-
459
- @property
460
- def parameters(self):
461
- """Return a set of parameters in the survey.
462
-
463
- >>> s = Survey.example()
464
- >>> s.parameters
465
- set()
466
- """
467
- return set.union(*[q.parameters for q in self.questions])
468
-
469
- @property
470
- def parameters_by_question(self):
471
- """Return a dictionary of parameters by question in the survey.
472
- >>> from edsl import QuestionFreeText
473
- >>> q = QuestionFreeText(question_name = "example", question_text = "What is the capital of {{ country}}?")
474
- >>> s = Survey([q])
475
- >>> s.parameters_by_question
476
- {'example': {'country'}}
477
- """
478
- return {q.question_name: q.parameters for q in self.questions}
479
-
480
- # endregion
481
-
482
- # region: Survey construction
483
-
484
- # region: Adding questions and combining surveys
485
- def __add__(self, other: Survey) -> Survey:
486
- """Combine two surveys.
487
-
488
- :param other: The other survey to combine with this one.
489
- >>> s1 = Survey.example()
490
- >>> from edsl import QuestionFreeText
491
- >>> s2 = Survey([QuestionFreeText(question_text="What is your name?", question_name="yo")])
492
- >>> s3 = s1 + s2
493
- Traceback (most recent call last):
494
- ...
495
- edsl.exceptions.surveys.SurveyCreationError: ...
496
- ...
497
- >>> s3 = s1.clear_non_default_rules() + s2
498
- >>> len(s3.questions)
499
- 4
500
-
501
- """
502
- if (
503
- len(self.rule_collection.non_default_rules) > 0
504
- or len(other.rule_collection.non_default_rules) > 0
505
- ):
506
- raise SurveyCreationError(
507
- "Cannot combine two surveys with non-default rules. Please use the 'clear_non_default_rules' method to remove non-default rules from the survey.",
508
- )
509
-
510
- return Survey(questions=self.questions + other.questions)
511
-
512
- def move_question(self, identifier: Union[str, int], new_index: int) -> Survey:
513
- """
514
- >>> from edsl import QuestionMultipleChoice, Survey
515
- >>> s = Survey.example()
516
- >>> s.question_names
517
- ['q0', 'q1', 'q2']
518
- >>> s.move_question("q0", 2).question_names
519
- ['q1', 'q2', 'q0']
520
- """
521
- return EditSurvey(self).move_question(identifier, new_index)
522
-
523
- def delete_question(self, identifier: Union[str, int]) -> Survey:
524
- """
525
- Delete a question from the survey.
526
-
527
- :param identifier: The name or index of the question to delete.
528
- :return: The updated Survey object.
529
-
530
- >>> from edsl import QuestionMultipleChoice, Survey
531
- >>> q1 = QuestionMultipleChoice(question_text="Q1", question_options=["A", "B"], question_name="q1")
532
- >>> q2 = QuestionMultipleChoice(question_text="Q2", question_options=["C", "D"], question_name="q2")
533
- >>> s = Survey().add_question(q1).add_question(q2)
534
- >>> _ = s.delete_question("q1")
535
- >>> len(s.questions)
536
- 1
537
- >>> _ = s.delete_question(0)
538
- >>> len(s.questions)
539
- 0
540
- """
541
- return EditSurvey(self).delete_question(identifier)
542
-
543
- def add_question(
544
- self, question: QuestionBase, index: Optional[int] = None
545
- ) -> Survey:
546
- """
547
- Add a question to survey.
548
-
549
- :param question: The question to add to the survey.
550
- :param question_name: The name of the question. If not provided, the question name is used.
551
-
552
- The question is appended at the end of the self.questions list
553
- A default rule is created that the next index is the next question.
554
-
555
- >>> from edsl import QuestionMultipleChoice
556
- >>> q = QuestionMultipleChoice(question_text = "Do you like school?", question_options=["yes", "no"], question_name="q0")
557
- >>> s = Survey().add_question(q)
558
-
559
- >>> s = Survey().add_question(q).add_question(q)
560
- Traceback (most recent call last):
561
- ...
562
- edsl.exceptions.surveys.SurveyCreationError: Question name 'q0' already exists in survey. Existing names are ['q0'].
563
- ...
564
- """
565
- return EditSurvey(self).add_question(question, index)
566
-
567
- def _recombined_questions_and_instructions(
568
- self,
569
- ) -> list[Union[QuestionBase, "Instruction"]]:
570
- """Return a list of questions and instructions sorted by pseudo index."""
571
- questions_and_instructions = self._questions + list(
572
- self._instruction_names_to_instructions.values()
573
- )
574
- return sorted(
575
- questions_and_instructions, key=lambda x: self._pseudo_indices[x.name]
576
- )
577
-
578
- # endregion
579
-
580
- # region: Memory plan methods
581
- def set_full_memory_mode(self) -> Survey:
582
- """Add instructions to a survey that the agent should remember all of the answers to the questions in the survey.
583
-
584
- >>> s = Survey.example().set_full_memory_mode()
585
-
586
- """
587
- MemoryManagement(self)._set_memory_plan(lambda i: self.question_names[:i])
588
- return self
589
-
590
- def set_lagged_memory(self, lags: int) -> Survey:
591
- """Add instructions to a survey that the agent should remember the answers to the questions in the survey.
592
-
593
- The agent should remember the answers to the questions in the survey from the previous lags.
594
- """
595
- MemoryManagement(self)._set_memory_plan(
596
- lambda i: self.question_names[max(0, i - lags) : i]
597
- )
598
- return self
599
-
600
- def _set_memory_plan(self, prior_questions_func: Callable) -> None:
601
- """Set memory plan based on a provided function determining prior questions.
602
-
603
- :param prior_questions_func: A function that takes the index of the current question and returns a list of prior questions to remember.
604
-
605
- >>> s = Survey.example()
606
- >>> s._set_memory_plan(lambda i: s.question_names[:i])
607
-
608
- """
609
- MemoryManagement(self)._set_memory_plan(prior_questions_func)
610
-
611
- def add_targeted_memory(
612
- self,
613
- focal_question: Union[QuestionBase, str],
614
- prior_question: Union[QuestionBase, str],
615
- ) -> Survey:
616
- """Add instructions to a survey than when answering focal_question.
617
-
618
- :param focal_question: The question that the agent is answering.
619
- :param prior_question: The question that the agent should remember when answering the focal question.
620
-
621
- Here we add instructions to a survey than when answering q2 they should remember q1:
622
-
623
- >>> s = Survey.example().add_targeted_memory("q2", "q0")
624
- >>> s.memory_plan
625
- {'q2': Memory(prior_questions=['q0'])}
626
-
627
- The agent should also remember the answers to prior_questions listed in prior_questions.
628
- """
629
- return MemoryManagement(self).add_targeted_memory(
630
- focal_question, prior_question
631
- )
632
-
633
- def add_memory_collection(
634
- self,
635
- focal_question: Union[QuestionBase, str],
636
- prior_questions: List[Union[QuestionBase, str]],
637
- ) -> Survey:
638
- """Add prior questions and responses so the agent has them when answering.
639
-
640
- 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.
641
-
642
- :param focal_question: The question that the agent is answering.
643
- :param prior_questions: The questions that the agent should remember when answering the focal question.
644
-
645
- Here we have it so that when answering q2, the agent should remember answers to q0 and q1:
646
-
647
- >>> s = Survey.example().add_memory_collection("q2", ["q0", "q1"])
648
- >>> s.memory_plan
649
- {'q2': Memory(prior_questions=['q0', 'q1'])}
650
- """
651
- return MemoryManagement(self).add_memory_collection(
652
- focal_question, prior_questions
653
- )
654
-
655
- # region: Question groups
656
- def add_question_group(
657
- self,
658
- start_question: Union[QuestionBase, str],
659
- end_question: Union[QuestionBase, str],
660
- group_name: str,
661
- ) -> Survey:
662
- """Add a group of questions to the survey.
663
-
664
- :param start_question: The first question in the group.
665
- :param end_question: The last question in the group.
666
- :param group_name: The name of the group.
667
-
668
- Example:
669
-
670
- >>> s = Survey.example().add_question_group("q0", "q1", "group1")
671
- >>> s.question_groups
672
- {'group1': (0, 1)}
673
-
674
- The name of the group must be a valid identifier:
675
-
676
- >>> s = Survey.example().add_question_group("q0", "q2", "1group1")
677
- Traceback (most recent call last):
678
- ...
679
- edsl.exceptions.surveys.SurveyCreationError: Group name 1group1 is not a valid identifier.
680
- ...
681
- >>> s = Survey.example().add_question_group("q0", "q1", "q0")
682
- Traceback (most recent call last):
683
- ...
684
- edsl.exceptions.surveys.SurveyCreationError: ...
685
- ...
686
- >>> s = Survey.example().add_question_group("q1", "q0", "group1")
687
- Traceback (most recent call last):
688
- ...
689
- edsl.exceptions.surveys.SurveyCreationError: ...
690
- ...
691
- """
692
-
693
- if not group_name.isidentifier():
694
- raise SurveyCreationError(
695
- f"Group name {group_name} is not a valid identifier."
696
- )
697
-
698
- if group_name in self.question_groups:
699
- raise SurveyCreationError(
700
- f"Group name {group_name} already exists in the survey."
701
- )
702
-
703
- if group_name in self.question_name_to_index:
704
- raise SurveyCreationError(
705
- f"Group name {group_name} already exists as a question name in the survey."
706
- )
707
-
708
- start_index = self._get_question_index(start_question)
709
- end_index = self._get_question_index(end_question)
710
-
711
- if start_index > end_index:
712
- raise SurveyCreationError(
713
- f"Start index {start_index} is greater than end index {end_index}."
714
- )
715
-
716
- for existing_group_name, (
717
- existing_start_index,
718
- existing_end_index,
719
- ) in self.question_groups.items():
720
- if start_index < existing_start_index and end_index > existing_end_index:
721
- raise SurveyCreationError(
722
- f"Group {group_name} contains the questions in the new group."
723
- )
724
- if start_index > existing_start_index and end_index < existing_end_index:
725
- raise SurveyCreationError(
726
- f"Group {group_name} is contained in the new group."
727
- )
728
- if start_index < existing_start_index and end_index > existing_start_index:
729
- raise SurveyCreationError(
730
- f"Group {group_name} overlaps with the new group."
731
- )
732
- if start_index < existing_end_index and end_index > existing_end_index:
733
- raise SurveyCreationError(
734
- f"Group {group_name} overlaps with the new group."
735
- )
736
-
737
- self.question_groups[group_name] = (start_index, end_index)
738
- return self
739
-
740
- # endregion
741
-
742
- # region: Survey rules
743
- def show_rules(self) -> None:
744
- """Print out the rules in the survey.
745
-
746
- >>> s = Survey.example()
747
- >>> s.show_rules()
748
- Dataset([{'current_q': [0, 0, 1, 2]}, {'expression': ['True', "q0 == 'yes'", 'True', 'True']}, {'next_q': [1, 2, 2, 3]}, {'priority': [-1, 0, -1, -1]}, {'before_rule': [False, False, False, False]}])
749
- """
750
- return self.rule_collection.show_rules()
751
-
752
- def add_stop_rule(
753
- self, question: Union[QuestionBase, str], expression: str
754
- ) -> Survey:
755
- """Add a rule that stops the survey.
756
- The rule is evaluated *after* the question is answered. If the rule is true, the survey ends.
757
-
758
- :param question: The question to add the stop rule to.
759
- :param expression: The expression to evaluate.
760
-
761
- If this rule is true, the survey ends.
762
-
763
- Here, answering "yes" to q0 ends the survey:
764
-
765
- >>> s = Survey.example().add_stop_rule("q0", "q0 == 'yes'")
766
- >>> s.next_question("q0", {"q0": "yes"})
767
- EndOfSurvey
768
-
769
- By comparison, answering "no" to q0 does not end the survey:
770
-
771
- >>> s.next_question("q0", {"q0": "no"}).question_name
772
- 'q1'
773
-
774
- >>> s.add_stop_rule("q0", "q1 <> 'yes'")
775
- Traceback (most recent call last):
776
- ...
777
- edsl.exceptions.surveys.SurveyCreationError: The expression contains '<>', which is not allowed. You probably mean '!='.
778
- ...
779
- """
780
- return RuleManager(self).add_stop_rule(question, expression)
781
-
782
- def clear_non_default_rules(self) -> Survey:
783
- """Remove all non-default rules from the survey.
784
-
785
- >>> Survey.example().show_rules()
786
- Dataset([{'current_q': [0, 0, 1, 2]}, {'expression': ['True', "q0 == 'yes'", 'True', 'True']}, {'next_q': [1, 2, 2, 3]}, {'priority': [-1, 0, -1, -1]}, {'before_rule': [False, False, False, False]}])
787
- >>> Survey.example().clear_non_default_rules().show_rules()
788
- Dataset([{'current_q': [0, 1, 2]}, {'expression': ['True', 'True', 'True']}, {'next_q': [1, 2, 3]}, {'priority': [-1, -1, -1]}, {'before_rule': [False, False, False]}])
789
- """
790
- s = Survey()
791
- for question in self.questions:
792
- s.add_question(question)
793
- return s
794
-
795
- def add_skip_rule(
796
- self, question: Union[QuestionBase, str], expression: str
797
- ) -> Survey:
798
- """
799
- Adds a per-question skip rule to the survey.
800
-
801
- :param question: The question to add the skip rule to.
802
- :param expression: The expression to evaluate.
803
-
804
- This adds a rule that skips 'q0' always, before the question is answered:
805
-
806
- >>> from edsl import QuestionFreeText
807
- >>> q0 = QuestionFreeText.example()
808
- >>> q0.question_name = "q0"
809
- >>> q1 = QuestionFreeText.example()
810
- >>> q1.question_name = "q1"
811
- >>> s = Survey([q0, q1]).add_skip_rule("q0", "True")
812
- >>> s.next_question("q0", {}).question_name
813
- 'q1'
814
-
815
- Note that this is different from a rule that jumps to some other question *after* the question is answered.
816
-
817
- """
818
- question_index = self._get_question_index(question)
819
- return RuleManager(self).add_rule(
820
- question, expression, question_index + 1, before_rule=True
821
- )
822
-
823
- def add_rule(
824
- self,
825
- question: Union[QuestionBase, str],
826
- expression: str,
827
- next_question: Union[QuestionBase, int],
828
- before_rule: bool = False,
829
- ) -> Survey:
830
- """
831
- Add a rule to a Question of the Survey.
832
-
833
- :param question: The question to add the rule to.
834
- :param expression: The expression to evaluate.
835
- :param next_question: The next question to go to if the rule is true.
836
- :param before_rule: Whether the rule is evaluated before the question is answered.
837
-
838
- This adds a rule that if the answer to q0 is 'yes', the next question is q2 (as opposed to q1)
839
-
840
- >>> s = Survey.example().add_rule("q0", "{{ q0 }} == 'yes'", "q2")
841
- >>> s.next_question("q0", {"q0": "yes"}).question_name
842
- 'q2'
843
-
844
- """
845
- return RuleManager(self).add_rule(
846
- question, expression, next_question, before_rule=before_rule
847
- )
848
-
849
- # endregion
850
-
851
- # region: Forward methods
852
- def by(self, *args: Union["Agent", "Scenario", "LanguageModel"]) -> "Jobs":
853
- """Add Agents, Scenarios, and LanguageModels to a survey and returns a runnable Jobs object.
854
-
855
- :param args: The Agents, Scenarios, and LanguageModels to add to the survey.
856
-
857
- This takes the survey and adds an Agent and a Scenario via 'by' which converts to a Jobs object:
858
-
859
- >>> s = Survey.example(); from edsl.agents import Agent; from edsl import Scenario
860
- >>> s.by(Agent.example()).by(Scenario.example())
861
- Jobs(...)
862
- """
863
- from edsl.jobs.Jobs import Jobs
864
-
865
- return Jobs(survey=self).by(*args)
866
-
867
- def to_jobs(self):
868
- """Convert the survey to a Jobs object.
869
- >>> s = Survey.example()
870
- >>> s.to_jobs()
871
- Jobs(...)
872
- """
873
- from edsl.jobs.Jobs import Jobs
874
-
875
- return Jobs(survey=self)
876
-
877
- def show_prompts(self):
878
- """Show the prompts for the survey."""
879
- return self.to_jobs().show_prompts()
880
-
881
- # endregion
882
-
883
- # region: Running the survey
884
-
885
- def __call__(
886
- self,
887
- model=None,
888
- agent=None,
889
- cache=None,
890
- verbose=False,
891
- disable_remote_cache: bool = False,
892
- disable_remote_inference: bool = False,
893
- **kwargs,
894
- ):
895
- """Run the survey with default model, taking the required survey as arguments.
896
-
897
- >>> from edsl.questions import QuestionFunctional
898
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
899
- >>> q = QuestionFunctional(question_name = "q0", func = f)
900
- >>> s = Survey([q])
901
- >>> s(period = "morning", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
902
- 'yes'
903
- >>> s(period = "evening", cache = False, disable_remote_cache = True, disable_remote_inference = True).select("answer.q0").first()
904
- 'no'
905
- """
906
-
907
- return self.get_job(model, agent, **kwargs).run(
908
- cache=cache,
909
- verbose=verbose,
910
- disable_remote_cache=disable_remote_cache,
911
- disable_remote_inference=disable_remote_inference,
912
- )
913
-
914
- async def run_async(
915
- self,
916
- model: Optional["LanguageModel"] = None,
917
- agent: Optional["Agent"] = None,
918
- cache: Optional["Cache"] = None,
919
- disable_remote_inference: bool = False,
920
- disable_remote_cache: bool = False,
921
- **kwargs,
922
- ):
923
- """Run the survey with default model, taking the required survey as arguments.
924
-
925
- >>> import asyncio
926
- >>> from edsl.questions import QuestionFunctional
927
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
928
- >>> q = QuestionFunctional(question_name = "q0", func = f)
929
- >>> s = Survey([q])
930
- >>> async def test_run_async(): result = await s.run_async(period="morning", disable_remote_inference = True, disable_remote_cache=True); print(result.select("answer.q0").first())
931
- >>> asyncio.run(test_run_async())
932
- yes
933
- >>> import asyncio
934
- >>> from edsl.questions import QuestionFunctional
935
- >>> def f(scenario, agent_traits): return "yes" if scenario["period"] == "morning" else "no"
936
- >>> q = QuestionFunctional(question_name = "q0", func = f)
937
- >>> s = Survey([q])
938
- >>> async def test_run_async(): result = await s.run_async(period="evening", disable_remote_inference = True, disable_remote_cache = True); print(result.select("answer.q0").first())
939
- >>> results = asyncio.run(test_run_async())
940
- no
941
- """
942
- # TODO: temp fix by creating a cache
943
- if cache is None:
944
- from edsl.data import Cache
945
-
946
- c = Cache()
947
- else:
948
- c = cache
949
-
950
- jobs: "Jobs" = self.get_job(model=model, agent=agent, **kwargs).using(c)
951
- return await jobs.run_async(
952
- disable_remote_inference=disable_remote_inference,
953
- disable_remote_cache=disable_remote_cache,
954
- )
955
-
956
- def run(self, *args, **kwargs) -> "Results":
957
- """Turn the survey into a Job and runs it.
958
-
959
- >>> from edsl import QuestionFreeText
960
- >>> s = Survey([QuestionFreeText.example()])
961
- >>> from edsl.language_models import LanguageModel
962
- >>> m = LanguageModel.example(test_model = True, canned_response = "Great!")
963
- >>> results = s.by(m).run(cache = False, disable_remote_cache = True, disable_remote_inference = True)
964
- >>> results.select('answer.*')
965
- Dataset([{'answer.how_are_you': ['Great!']}])
966
- """
967
- from edsl.jobs.Jobs import Jobs
968
-
969
- return Jobs(survey=self).run(*args, **kwargs)
970
-
971
- def using(self, obj: Union["Cache", "KeyLookup", "BucketCollection"]) -> "Jobs":
972
- """Turn the survey into a Job and appends the arguments to the Job."""
973
- from edsl.jobs.Jobs import Jobs
974
-
975
- return Jobs(survey=self).using(obj)
976
-
977
- def duplicate(self):
978
- """Duplicate the survey.
979
-
980
- >>> s = Survey.example()
981
- >>> s2 = s.duplicate()
982
- >>> s == s2
983
- True
984
- >>> s is s2
985
- False
986
-
987
- """
988
- return Survey.from_dict(self.to_dict())
989
-
990
- # region: Survey flow
991
- def next_question(
992
- self,
993
- current_question: Optional[Union[str, QuestionBase]] = None,
994
- answers: Optional[dict] = None,
995
- ) -> Union[QuestionBase, EndOfSurvey.__class__]:
996
- """
997
- Return the next question in a survey.
998
-
999
- :param current_question: The current question in the survey.
1000
- :param answers: The answers for the survey so far
1001
-
1002
- - If called with no arguments, it returns the first question in the survey.
1003
- - 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.
1004
- - If the next question is the last question in the survey, an EndOfSurvey object is returned.
1005
-
1006
- >>> s = Survey.example()
1007
- >>> s.next_question("q0", {"q0": "yes"}).question_name
1008
- 'q2'
1009
- >>> s.next_question("q0", {"q0": "no"}).question_name
1010
- 'q1'
1011
-
1012
- """
1013
- if current_question is None:
1014
- return self.questions[0]
1015
-
1016
- if isinstance(current_question, str):
1017
- current_question = self._get_question_by_name(current_question)
1018
-
1019
- question_index = self.question_name_to_index[current_question.question_name]
1020
- next_question_object = self.rule_collection.next_question(
1021
- question_index, answers
1022
- )
1023
-
1024
- if next_question_object.num_rules_found == 0:
1025
- raise SurveyHasNoRulesError
1026
-
1027
- if next_question_object.next_q == EndOfSurvey:
1028
- return EndOfSurvey
1029
- else:
1030
- if next_question_object.next_q >= len(self.questions):
1031
- return EndOfSurvey
1032
- else:
1033
- return self.questions[next_question_object.next_q]
1034
-
1035
- def gen_path_through_survey(self) -> Generator[QuestionBase, dict, None]:
1036
- """
1037
- Generate a coroutine that can be used to conduct an Interview.
1038
-
1039
- The coroutine is a generator that yields a question and receives answers.
1040
- It starts with the first question in the survey.
1041
- The coroutine ends when an EndOfSurvey object is returned.
1042
-
1043
- For the example survey, this is the rule table:
1044
-
1045
- >>> s = Survey.example()
1046
- >>> s.show_rules()
1047
- Dataset([{'current_q': [0, 0, 1, 2]}, {'expression': ['True', "q0 == 'yes'", 'True', 'True']}, {'next_q': [1, 2, 2, 3]}, {'priority': [-1, 0, -1, -1]}, {'before_rule': [False, False, False, False]}])
1048
-
1049
- 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.
1050
-
1051
- Here is the path through the survey if the answer to q0 is 'yes':
1052
-
1053
- >>> i = s.gen_path_through_survey()
1054
- >>> next(i)
1055
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1056
- >>> i.send({"q0": "yes"})
1057
- Question('multiple_choice', question_name = \"""q2\""", question_text = \"""Why?\""", question_options = ['**lack*** of killer bees in cafeteria', 'other'])
1058
-
1059
- And here is the path through the survey if the answer to q0 is 'no':
1060
-
1061
- >>> i2 = s.gen_path_through_survey()
1062
- >>> next(i2)
1063
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1064
- >>> i2.send({"q0": "no"})
1065
- Question('multiple_choice', question_name = \"""q1\""", question_text = \"""Why not?\""", question_options = ['killer bees in cafeteria', 'other'])
1066
-
1067
-
1068
- """
1069
- self.answers = {}
1070
- question = self._questions[0]
1071
- # should the first question be skipped?
1072
- if self.rule_collection.skip_question_before_running(0, self.answers):
1073
- question = self.next_question(question, self.answers)
1074
-
1075
- while not question == EndOfSurvey:
1076
- answer = yield question
1077
- self.answers.update(answer)
1078
- # print(f"Answers: {self.answers}")
1079
- ## TODO: This should also include survey and agent attributes
1080
- question = self.next_question(question, self.answers)
1081
-
1082
- # endregion
1083
-
1084
- def dag(self, textify: bool = False) -> DAG:
1085
- """Return the DAG of the survey, which reflects both skip-logic and memory.
1086
-
1087
- :param textify: Whether to return the DAG with question names instead of indices.
1088
-
1089
- >>> s = Survey.example()
1090
- >>> d = s.dag()
1091
- >>> d
1092
- {1: {0}, 2: {0}}
1093
-
1094
- """
1095
- from edsl.surveys.ConstructDAG import ConstructDAG
1096
-
1097
- return ConstructDAG(self).dag(textify)
1098
-
1099
- ###################
1100
- # DUNDER METHODS
1101
- ###################
1102
- def __len__(self) -> int:
1103
- """Return the number of questions in the survey.
1104
-
1105
- >>> s = Survey.example()
1106
- >>> len(s)
1107
- 3
1108
- """
1109
- return len(self._questions)
1110
-
1111
- def __getitem__(self, index) -> QuestionBase:
1112
- """Return the question object given the question index.
1113
-
1114
- :param index: The index of the question to get.
1115
-
1116
- >>> s = Survey.example()
1117
- >>> s[0]
1118
- Question('multiple_choice', question_name = \"""q0\""", question_text = \"""Do you like school?\""", question_options = ['yes', 'no'])
1119
-
1120
- """
1121
- if isinstance(index, int):
1122
- return self._questions[index]
1123
- elif isinstance(index, str):
1124
- return getattr(self, index)
1125
-
1126
- # def _diff(self, other):
1127
- # """Used for debugging. Print out the differences between two surveys."""
1128
- # from rich import print
1129
-
1130
- # for key, value in self.to_dict().items():
1131
- # if value != other.to_dict()[key]:
1132
- # print(f"Key: {key}")
1133
- # print("\n")
1134
- # print(f"Self: {value}")
1135
- # print("\n")
1136
- # print(f"Other: {other.to_dict()[key]}")
1137
- # print("\n\n")
1138
-
1139
- def __repr__(self) -> str:
1140
- """Return a string representation of the survey."""
1141
-
1142
- # questions_string = ", ".join([repr(q) for q in self._questions])
1143
- questions_string = ", ".join([repr(q) for q in self.raw_passed_questions or []])
1144
- # question_names_string = ", ".join([repr(name) for name in self.question_names])
1145
- return f"Survey(questions=[{questions_string}], memory_plan={self.memory_plan}, rule_collection={self.rule_collection}, question_groups={self.question_groups}, questions_to_randomize={self.questions_to_randomize})"
1146
-
1147
- def _summary(self) -> dict:
1148
- return {
1149
- "# questions": len(self),
1150
- "question_name list": self.question_names,
1151
- }
1152
-
1153
- def tree(self, node_list: Optional[List[str]] = None):
1154
- return self.to_scenario_list().tree(node_list=node_list)
1155
-
1156
- def table(self, *fields, tablefmt=None) -> Table:
1157
- return self.to_scenario_list().to_dataset().table(*fields, tablefmt=tablefmt)
1158
-
1159
- # endregion
1160
-
1161
- def codebook(self) -> dict[str, str]:
1162
- """Create a codebook for the survey, mapping question names to question text.
1163
-
1164
- >>> s = Survey.example()
1165
- >>> s.codebook()
1166
- {'q0': 'Do you like school?', 'q1': 'Why not?', 'q2': 'Why?'}
1167
- """
1168
- codebook = {}
1169
- for question in self._questions:
1170
- codebook[question.question_name] = question.question_text
1171
- return codebook
1172
-
1173
- @classmethod
1174
- def example(
1175
- cls,
1176
- params: bool = False,
1177
- randomize: bool = False,
1178
- include_instructions=False,
1179
- custom_instructions: Optional[str] = None,
1180
- ) -> Survey:
1181
- """Return an example survey.
1182
-
1183
- >>> s = Survey.example()
1184
- >>> [q.question_text for q in s.questions]
1185
- ['Do you like school?', 'Why not?', 'Why?']
1186
- """
1187
- from edsl.questions.QuestionMultipleChoice import QuestionMultipleChoice
1188
-
1189
- addition = "" if not randomize else str(uuid4())
1190
- q0 = QuestionMultipleChoice(
1191
- question_text=f"Do you like school?{addition}",
1192
- question_options=["yes", "no"],
1193
- question_name="q0",
1194
- )
1195
- q1 = QuestionMultipleChoice(
1196
- question_text="Why not?",
1197
- question_options=["killer bees in cafeteria", "other"],
1198
- question_name="q1",
1199
- )
1200
- q2 = QuestionMultipleChoice(
1201
- question_text="Why?",
1202
- question_options=["**lack*** of killer bees in cafeteria", "other"],
1203
- question_name="q2",
1204
- )
1205
- if params:
1206
- q3 = QuestionMultipleChoice(
1207
- question_text="To the question '{{ q0.question_text}}', you said '{{ q0.answer }}'. Do you still feel this way?",
1208
- question_options=["yes", "no"],
1209
- question_name="q3",
1210
- )
1211
- s = cls(questions=[q0, q1, q2, q3])
1212
- return s
1213
-
1214
- if include_instructions:
1215
- from edsl import Instruction
1216
-
1217
- custom_instructions = (
1218
- custom_instructions if custom_instructions else "Please pay attention!"
1219
- )
1220
-
1221
- i = Instruction(text=custom_instructions, name="attention")
1222
- s = cls(questions=[i, q0, q1, q2])
1223
- return s
1224
-
1225
- s = cls(questions=[q0, q1, q2])
1226
- s = s.add_rule(q0, "q0 == 'yes'", q2)
1227
- return s
1228
-
1229
- def get_job(self, model=None, agent=None, **kwargs):
1230
- if model is None:
1231
- from edsl.language_models.model import Model
1232
-
1233
- model = Model()
1234
-
1235
- from edsl.scenarios.Scenario import Scenario
1236
-
1237
- s = Scenario(kwargs)
1238
-
1239
- if not agent:
1240
- from edsl.agents.Agent import Agent
1241
-
1242
- agent = Agent()
1243
-
1244
- return self.by(s).by(agent).by(model)
1245
-
1246
- ###################
1247
- # COOP METHODS
1248
- ###################
1249
- def humanize(
1250
- self,
1251
- project_name: str = "Project",
1252
- survey_description: Optional[str] = None,
1253
- survey_alias: Optional[str] = None,
1254
- survey_visibility: Optional["VisibilityType"] = "unlisted",
1255
- ) -> dict:
1256
- """
1257
- Send the survey to Coop.
1258
-
1259
- Then, create a project on Coop so you can share the survey with human respondents.
1260
- """
1261
- from edsl.coop import Coop
1262
-
1263
- c = Coop()
1264
- project_details = c.create_project(
1265
- self, project_name, survey_description, survey_alias, survey_visibility
1266
- )
1267
- return project_details
1268
-
1269
-
1270
- def main():
1271
- """Run the example survey."""
1272
-
1273
- def example_survey():
1274
- """Return an example survey."""
1275
- from edsl import QuestionMultipleChoice, QuestionList, QuestionNumerical, Survey
1276
-
1277
- q0 = QuestionMultipleChoice(
1278
- question_name="q0",
1279
- question_text="What is the capital of France?",
1280
- question_options=["London", "Paris", "Rome", "Boston", "I don't know"],
1281
- )
1282
- q1 = QuestionList(
1283
- question_name="q1",
1284
- question_text="Name some cities in France.",
1285
- max_list_items=5,
1286
- )
1287
- q2 = QuestionNumerical(
1288
- question_name="q2",
1289
- question_text="What is the population of {{ q0.answer }}?",
1290
- )
1291
- s = Survey(questions=[q0, q1, q2])
1292
- s = s.add_rule(q0, "q0 == 'Paris'", q2)
1293
- return s
1294
-
1295
- s = example_survey()
1296
- survey_dict = s.to_dict()
1297
- s2 = Survey.from_dict(survey_dict)
1298
- results = s2.run()
1299
- print(results)
1300
-
1301
-
1302
- if __name__ == "__main__":
1303
- import doctest
1304
-
1305
- # doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.SKIP)
1306
- doctest.testmod(optionflags=doctest.ELLIPSIS)