edsl 0.1.38.dev3__py3-none-any.whl → 0.1.39__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 (341) hide show
  1. edsl/Base.py +413 -303
  2. edsl/BaseDiff.py +260 -260
  3. edsl/TemplateLoader.py +24 -24
  4. edsl/__init__.py +57 -49
  5. edsl/__version__.py +1 -1
  6. edsl/agents/Agent.py +1071 -858
  7. edsl/agents/AgentList.py +551 -362
  8. edsl/agents/Invigilator.py +284 -222
  9. edsl/agents/InvigilatorBase.py +257 -284
  10. edsl/agents/PromptConstructor.py +272 -353
  11. edsl/agents/QuestionInstructionPromptBuilder.py +128 -0
  12. edsl/agents/QuestionTemplateReplacementsBuilder.py +137 -0
  13. edsl/agents/__init__.py +2 -3
  14. edsl/agents/descriptors.py +99 -99
  15. edsl/agents/prompt_helpers.py +129 -129
  16. edsl/agents/question_option_processor.py +172 -0
  17. edsl/auto/AutoStudy.py +130 -117
  18. edsl/auto/StageBase.py +243 -230
  19. edsl/auto/StageGenerateSurvey.py +178 -178
  20. edsl/auto/StageLabelQuestions.py +125 -125
  21. edsl/auto/StagePersona.py +61 -61
  22. edsl/auto/StagePersonaDimensionValueRanges.py +88 -88
  23. edsl/auto/StagePersonaDimensionValues.py +74 -74
  24. edsl/auto/StagePersonaDimensions.py +69 -69
  25. edsl/auto/StageQuestions.py +74 -73
  26. edsl/auto/SurveyCreatorPipeline.py +21 -21
  27. edsl/auto/utilities.py +218 -224
  28. edsl/base/Base.py +279 -279
  29. edsl/config.py +177 -149
  30. edsl/conversation/Conversation.py +290 -290
  31. edsl/conversation/car_buying.py +59 -58
  32. edsl/conversation/chips.py +95 -95
  33. edsl/conversation/mug_negotiation.py +81 -81
  34. edsl/conversation/next_speaker_utilities.py +93 -93
  35. edsl/coop/CoopFunctionsMixin.py +15 -0
  36. edsl/coop/ExpectedParrotKeyHandler.py +125 -0
  37. edsl/coop/PriceFetcher.py +54 -54
  38. edsl/coop/__init__.py +2 -2
  39. edsl/coop/coop.py +1106 -961
  40. edsl/coop/utils.py +131 -131
  41. edsl/data/Cache.py +573 -530
  42. edsl/data/CacheEntry.py +230 -228
  43. edsl/data/CacheHandler.py +168 -149
  44. edsl/data/RemoteCacheSync.py +186 -97
  45. edsl/data/SQLiteDict.py +292 -292
  46. edsl/data/__init__.py +5 -4
  47. edsl/data/orm.py +10 -10
  48. edsl/data_transfer_models.py +74 -73
  49. edsl/enums.py +202 -173
  50. edsl/exceptions/BaseException.py +21 -21
  51. edsl/exceptions/__init__.py +54 -54
  52. edsl/exceptions/agents.py +54 -42
  53. edsl/exceptions/cache.py +5 -5
  54. edsl/exceptions/configuration.py +16 -16
  55. edsl/exceptions/coop.py +10 -10
  56. edsl/exceptions/data.py +14 -14
  57. edsl/exceptions/general.py +34 -34
  58. edsl/exceptions/inference_services.py +5 -0
  59. edsl/exceptions/jobs.py +33 -33
  60. edsl/exceptions/language_models.py +63 -63
  61. edsl/exceptions/prompts.py +15 -15
  62. edsl/exceptions/questions.py +109 -91
  63. edsl/exceptions/results.py +29 -29
  64. edsl/exceptions/scenarios.py +29 -22
  65. edsl/exceptions/surveys.py +37 -37
  66. edsl/inference_services/AnthropicService.py +106 -87
  67. edsl/inference_services/AvailableModelCacheHandler.py +184 -0
  68. edsl/inference_services/AvailableModelFetcher.py +215 -0
  69. edsl/inference_services/AwsBedrock.py +118 -120
  70. edsl/inference_services/AzureAI.py +215 -217
  71. edsl/inference_services/DeepInfraService.py +18 -18
  72. edsl/inference_services/GoogleService.py +143 -156
  73. edsl/inference_services/GroqService.py +20 -20
  74. edsl/inference_services/InferenceServiceABC.py +80 -147
  75. edsl/inference_services/InferenceServicesCollection.py +138 -97
  76. edsl/inference_services/MistralAIService.py +120 -123
  77. edsl/inference_services/OllamaService.py +18 -18
  78. edsl/inference_services/OpenAIService.py +236 -224
  79. edsl/inference_services/PerplexityService.py +160 -0
  80. edsl/inference_services/ServiceAvailability.py +135 -0
  81. edsl/inference_services/TestService.py +90 -89
  82. edsl/inference_services/TogetherAIService.py +172 -170
  83. edsl/inference_services/data_structures.py +134 -0
  84. edsl/inference_services/models_available_cache.py +118 -118
  85. edsl/inference_services/rate_limits_cache.py +25 -25
  86. edsl/inference_services/registry.py +41 -39
  87. edsl/inference_services/write_available.py +10 -10
  88. edsl/jobs/AnswerQuestionFunctionConstructor.py +223 -0
  89. edsl/jobs/Answers.py +43 -56
  90. edsl/jobs/FetchInvigilator.py +47 -0
  91. edsl/jobs/InterviewTaskManager.py +98 -0
  92. edsl/jobs/InterviewsConstructor.py +50 -0
  93. edsl/jobs/Jobs.py +823 -1358
  94. edsl/jobs/JobsChecks.py +172 -0
  95. edsl/jobs/JobsComponentConstructor.py +189 -0
  96. edsl/jobs/JobsPrompts.py +270 -0
  97. edsl/jobs/JobsRemoteInferenceHandler.py +311 -0
  98. edsl/jobs/JobsRemoteInferenceLogger.py +239 -0
  99. edsl/jobs/RequestTokenEstimator.py +30 -0
  100. edsl/jobs/__init__.py +1 -1
  101. edsl/jobs/async_interview_runner.py +138 -0
  102. edsl/jobs/buckets/BucketCollection.py +104 -63
  103. edsl/jobs/buckets/ModelBuckets.py +65 -65
  104. edsl/jobs/buckets/TokenBucket.py +283 -251
  105. edsl/jobs/buckets/TokenBucketAPI.py +211 -0
  106. edsl/jobs/buckets/TokenBucketClient.py +191 -0
  107. edsl/jobs/check_survey_scenario_compatibility.py +85 -0
  108. edsl/jobs/data_structures.py +120 -0
  109. edsl/jobs/decorators.py +35 -0
  110. edsl/jobs/interviews/Interview.py +396 -661
  111. edsl/jobs/interviews/InterviewExceptionCollection.py +99 -99
  112. edsl/jobs/interviews/InterviewExceptionEntry.py +186 -186
  113. edsl/jobs/interviews/InterviewStatistic.py +63 -63
  114. edsl/jobs/interviews/InterviewStatisticsCollection.py +25 -25
  115. edsl/jobs/interviews/InterviewStatusDictionary.py +78 -78
  116. edsl/jobs/interviews/InterviewStatusLog.py +92 -92
  117. edsl/jobs/interviews/ReportErrors.py +66 -66
  118. edsl/jobs/interviews/interview_status_enum.py +9 -9
  119. edsl/jobs/jobs_status_enums.py +9 -0
  120. edsl/jobs/loggers/HTMLTableJobLogger.py +304 -0
  121. edsl/jobs/results_exceptions_handler.py +98 -0
  122. edsl/jobs/runners/JobsRunnerAsyncio.py +151 -361
  123. edsl/jobs/runners/JobsRunnerStatus.py +298 -332
  124. edsl/jobs/tasks/QuestionTaskCreator.py +244 -242
  125. edsl/jobs/tasks/TaskCreators.py +64 -64
  126. edsl/jobs/tasks/TaskHistory.py +470 -451
  127. edsl/jobs/tasks/TaskStatusLog.py +23 -23
  128. edsl/jobs/tasks/task_status_enum.py +161 -163
  129. edsl/jobs/tokens/InterviewTokenUsage.py +27 -27
  130. edsl/jobs/tokens/TokenUsage.py +34 -34
  131. edsl/language_models/ComputeCost.py +63 -0
  132. edsl/language_models/LanguageModel.py +626 -708
  133. edsl/language_models/ModelList.py +164 -109
  134. edsl/language_models/PriceManager.py +127 -0
  135. edsl/language_models/RawResponseHandler.py +106 -0
  136. edsl/language_models/RegisterLanguageModelsMeta.py +184 -184
  137. edsl/language_models/ServiceDataSources.py +0 -0
  138. edsl/language_models/__init__.py +2 -3
  139. edsl/language_models/fake_openai_call.py +15 -15
  140. edsl/language_models/fake_openai_service.py +61 -61
  141. edsl/language_models/key_management/KeyLookup.py +63 -0
  142. edsl/language_models/key_management/KeyLookupBuilder.py +273 -0
  143. edsl/language_models/key_management/KeyLookupCollection.py +38 -0
  144. edsl/language_models/key_management/__init__.py +0 -0
  145. edsl/language_models/key_management/models.py +131 -0
  146. edsl/language_models/model.py +256 -0
  147. edsl/language_models/repair.py +156 -156
  148. edsl/language_models/utilities.py +65 -64
  149. edsl/notebooks/Notebook.py +263 -258
  150. edsl/notebooks/NotebookToLaTeX.py +142 -0
  151. edsl/notebooks/__init__.py +1 -1
  152. edsl/prompts/Prompt.py +352 -357
  153. edsl/prompts/__init__.py +2 -2
  154. edsl/questions/ExceptionExplainer.py +77 -0
  155. edsl/questions/HTMLQuestion.py +103 -0
  156. edsl/questions/QuestionBase.py +518 -660
  157. edsl/questions/QuestionBasePromptsMixin.py +221 -217
  158. edsl/questions/QuestionBudget.py +227 -227
  159. edsl/questions/QuestionCheckBox.py +359 -359
  160. edsl/questions/QuestionExtract.py +180 -183
  161. edsl/questions/QuestionFreeText.py +113 -114
  162. edsl/questions/QuestionFunctional.py +166 -166
  163. edsl/questions/QuestionList.py +223 -231
  164. edsl/questions/QuestionMatrix.py +265 -0
  165. edsl/questions/QuestionMultipleChoice.py +330 -286
  166. edsl/questions/QuestionNumerical.py +151 -153
  167. edsl/questions/QuestionRank.py +314 -324
  168. edsl/questions/Quick.py +41 -41
  169. edsl/questions/SimpleAskMixin.py +74 -73
  170. edsl/questions/__init__.py +27 -26
  171. edsl/questions/{AnswerValidatorMixin.py → answer_validator_mixin.py} +334 -289
  172. edsl/questions/compose_questions.py +98 -98
  173. edsl/questions/data_structures.py +20 -0
  174. edsl/questions/decorators.py +21 -21
  175. edsl/questions/derived/QuestionLikertFive.py +76 -76
  176. edsl/questions/derived/QuestionLinearScale.py +90 -87
  177. edsl/questions/derived/QuestionTopK.py +93 -93
  178. edsl/questions/derived/QuestionYesNo.py +82 -82
  179. edsl/questions/descriptors.py +427 -413
  180. edsl/questions/loop_processor.py +149 -0
  181. edsl/questions/prompt_templates/question_budget.jinja +13 -13
  182. edsl/questions/prompt_templates/question_checkbox.jinja +32 -32
  183. edsl/questions/prompt_templates/question_extract.jinja +11 -11
  184. edsl/questions/prompt_templates/question_free_text.jinja +3 -3
  185. edsl/questions/prompt_templates/question_linear_scale.jinja +11 -11
  186. edsl/questions/prompt_templates/question_list.jinja +17 -17
  187. edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -33
  188. edsl/questions/prompt_templates/question_numerical.jinja +36 -36
  189. edsl/questions/{QuestionBaseGenMixin.py → question_base_gen_mixin.py} +168 -161
  190. edsl/questions/question_registry.py +177 -147
  191. edsl/questions/{RegisterQuestionsMeta.py → register_questions_meta.py} +71 -71
  192. edsl/questions/{ResponseValidatorABC.py → response_validator_abc.py} +188 -174
  193. edsl/questions/response_validator_factory.py +34 -0
  194. edsl/questions/settings.py +12 -12
  195. edsl/questions/templates/budget/answering_instructions.jinja +7 -7
  196. edsl/questions/templates/budget/question_presentation.jinja +7 -7
  197. edsl/questions/templates/checkbox/answering_instructions.jinja +10 -10
  198. edsl/questions/templates/checkbox/question_presentation.jinja +22 -22
  199. edsl/questions/templates/extract/answering_instructions.jinja +7 -7
  200. edsl/questions/templates/likert_five/answering_instructions.jinja +10 -10
  201. edsl/questions/templates/likert_five/question_presentation.jinja +11 -11
  202. edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -5
  203. edsl/questions/templates/linear_scale/question_presentation.jinja +5 -5
  204. edsl/questions/templates/list/answering_instructions.jinja +3 -3
  205. edsl/questions/templates/list/question_presentation.jinja +5 -5
  206. edsl/questions/templates/matrix/__init__.py +1 -0
  207. edsl/questions/templates/matrix/answering_instructions.jinja +5 -0
  208. edsl/questions/templates/matrix/question_presentation.jinja +20 -0
  209. edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -9
  210. edsl/questions/templates/multiple_choice/question_presentation.jinja +11 -11
  211. edsl/questions/templates/numerical/answering_instructions.jinja +6 -6
  212. edsl/questions/templates/numerical/question_presentation.jinja +6 -6
  213. edsl/questions/templates/rank/answering_instructions.jinja +11 -11
  214. edsl/questions/templates/rank/question_presentation.jinja +15 -15
  215. edsl/questions/templates/top_k/answering_instructions.jinja +8 -8
  216. edsl/questions/templates/top_k/question_presentation.jinja +22 -22
  217. edsl/questions/templates/yes_no/answering_instructions.jinja +6 -6
  218. edsl/questions/templates/yes_no/question_presentation.jinja +11 -11
  219. edsl/results/CSSParameterizer.py +108 -0
  220. edsl/results/Dataset.py +587 -293
  221. edsl/results/DatasetExportMixin.py +594 -717
  222. edsl/results/DatasetTree.py +295 -145
  223. edsl/results/MarkdownToDocx.py +122 -0
  224. edsl/results/MarkdownToPDF.py +111 -0
  225. edsl/results/Result.py +557 -456
  226. edsl/results/Results.py +1183 -1071
  227. edsl/results/ResultsExportMixin.py +45 -43
  228. edsl/results/ResultsGGMixin.py +121 -121
  229. edsl/results/TableDisplay.py +125 -0
  230. edsl/results/TextEditor.py +50 -0
  231. edsl/results/__init__.py +2 -2
  232. edsl/results/file_exports.py +252 -0
  233. edsl/results/{ResultsFetchMixin.py → results_fetch_mixin.py} +33 -33
  234. edsl/results/{Selector.py → results_selector.py} +145 -135
  235. edsl/results/{ResultsToolsMixin.py → results_tools_mixin.py} +98 -98
  236. edsl/results/smart_objects.py +96 -0
  237. edsl/results/table_data_class.py +12 -0
  238. edsl/results/table_display.css +78 -0
  239. edsl/results/table_renderers.py +118 -0
  240. edsl/results/tree_explore.py +115 -115
  241. edsl/scenarios/ConstructDownloadLink.py +109 -0
  242. edsl/scenarios/DocumentChunker.py +102 -0
  243. edsl/scenarios/DocxScenario.py +16 -0
  244. edsl/scenarios/FileStore.py +543 -458
  245. edsl/scenarios/PdfExtractor.py +40 -0
  246. edsl/scenarios/Scenario.py +498 -544
  247. edsl/scenarios/ScenarioHtmlMixin.py +65 -64
  248. edsl/scenarios/ScenarioList.py +1458 -1112
  249. edsl/scenarios/ScenarioListExportMixin.py +45 -52
  250. edsl/scenarios/ScenarioListPdfMixin.py +239 -261
  251. edsl/scenarios/__init__.py +3 -4
  252. edsl/scenarios/directory_scanner.py +96 -0
  253. edsl/scenarios/file_methods.py +85 -0
  254. edsl/scenarios/handlers/__init__.py +13 -0
  255. edsl/scenarios/handlers/csv.py +49 -0
  256. edsl/scenarios/handlers/docx.py +76 -0
  257. edsl/scenarios/handlers/html.py +37 -0
  258. edsl/scenarios/handlers/json.py +111 -0
  259. edsl/scenarios/handlers/latex.py +5 -0
  260. edsl/scenarios/handlers/md.py +51 -0
  261. edsl/scenarios/handlers/pdf.py +68 -0
  262. edsl/scenarios/handlers/png.py +39 -0
  263. edsl/scenarios/handlers/pptx.py +105 -0
  264. edsl/scenarios/handlers/py.py +294 -0
  265. edsl/scenarios/handlers/sql.py +313 -0
  266. edsl/scenarios/handlers/sqlite.py +149 -0
  267. edsl/scenarios/handlers/txt.py +33 -0
  268. edsl/scenarios/scenario_join.py +131 -0
  269. edsl/scenarios/scenario_selector.py +156 -0
  270. edsl/shared.py +1 -1
  271. edsl/study/ObjectEntry.py +173 -173
  272. edsl/study/ProofOfWork.py +113 -113
  273. edsl/study/SnapShot.py +80 -80
  274. edsl/study/Study.py +521 -528
  275. edsl/study/__init__.py +4 -4
  276. edsl/surveys/ConstructDAG.py +92 -0
  277. edsl/surveys/DAG.py +148 -148
  278. edsl/surveys/EditSurvey.py +221 -0
  279. edsl/surveys/InstructionHandler.py +100 -0
  280. edsl/surveys/Memory.py +31 -31
  281. edsl/surveys/MemoryManagement.py +72 -0
  282. edsl/surveys/MemoryPlan.py +244 -244
  283. edsl/surveys/Rule.py +327 -326
  284. edsl/surveys/RuleCollection.py +385 -387
  285. edsl/surveys/RuleManager.py +172 -0
  286. edsl/surveys/Simulator.py +75 -0
  287. edsl/surveys/Survey.py +1280 -1787
  288. edsl/surveys/SurveyCSS.py +273 -261
  289. edsl/surveys/SurveyExportMixin.py +259 -259
  290. edsl/surveys/{SurveyFlowVisualizationMixin.py → SurveyFlowVisualization.py} +181 -121
  291. edsl/surveys/SurveyQualtricsImport.py +284 -284
  292. edsl/surveys/SurveyToApp.py +141 -0
  293. edsl/surveys/__init__.py +5 -3
  294. edsl/surveys/base.py +53 -53
  295. edsl/surveys/descriptors.py +60 -56
  296. edsl/surveys/instructions/ChangeInstruction.py +48 -49
  297. edsl/surveys/instructions/Instruction.py +56 -53
  298. edsl/surveys/instructions/InstructionCollection.py +82 -77
  299. edsl/templates/error_reporting/base.html +23 -23
  300. edsl/templates/error_reporting/exceptions_by_model.html +34 -34
  301. edsl/templates/error_reporting/exceptions_by_question_name.html +16 -16
  302. edsl/templates/error_reporting/exceptions_by_type.html +16 -16
  303. edsl/templates/error_reporting/interview_details.html +115 -115
  304. edsl/templates/error_reporting/interviews.html +19 -10
  305. edsl/templates/error_reporting/overview.html +4 -4
  306. edsl/templates/error_reporting/performance_plot.html +1 -1
  307. edsl/templates/error_reporting/report.css +73 -73
  308. edsl/templates/error_reporting/report.html +117 -117
  309. edsl/templates/error_reporting/report.js +25 -25
  310. edsl/tools/__init__.py +1 -1
  311. edsl/tools/clusters.py +192 -192
  312. edsl/tools/embeddings.py +27 -27
  313. edsl/tools/embeddings_plotting.py +118 -118
  314. edsl/tools/plotting.py +112 -112
  315. edsl/tools/summarize.py +18 -18
  316. edsl/utilities/PrettyList.py +56 -0
  317. edsl/utilities/SystemInfo.py +28 -28
  318. edsl/utilities/__init__.py +22 -22
  319. edsl/utilities/ast_utilities.py +25 -25
  320. edsl/utilities/data/Registry.py +6 -6
  321. edsl/utilities/data/__init__.py +1 -1
  322. edsl/utilities/data/scooter_results.json +1 -1
  323. edsl/utilities/decorators.py +77 -77
  324. edsl/utilities/gcp_bucket/cloud_storage.py +96 -96
  325. edsl/utilities/interface.py +627 -627
  326. edsl/utilities/is_notebook.py +18 -0
  327. edsl/utilities/is_valid_variable_name.py +11 -0
  328. edsl/utilities/naming_utilities.py +263 -263
  329. edsl/utilities/remove_edsl_version.py +24 -0
  330. edsl/utilities/repair_functions.py +28 -28
  331. edsl/utilities/restricted_python.py +70 -70
  332. edsl/utilities/utilities.py +436 -409
  333. {edsl-0.1.38.dev3.dist-info → edsl-0.1.39.dist-info}/LICENSE +21 -21
  334. {edsl-0.1.38.dev3.dist-info → edsl-0.1.39.dist-info}/METADATA +13 -10
  335. edsl-0.1.39.dist-info/RECORD +358 -0
  336. {edsl-0.1.38.dev3.dist-info → edsl-0.1.39.dist-info}/WHEEL +1 -1
  337. edsl/language_models/KeyLookup.py +0 -30
  338. edsl/language_models/registry.py +0 -137
  339. edsl/language_models/unused/ReplicateBase.py +0 -83
  340. edsl/results/ResultsDBMixin.py +0 -238
  341. edsl-0.1.38.dev3.dist-info/RECORD +0 -269
@@ -1,1112 +1,1458 @@
1
- """A list of Scenarios to be used in a survey."""
2
-
3
- from __future__ import annotations
4
- from typing import Any, Optional, Union, List, Callable
5
- import csv
6
- import random
7
- from collections import UserList, Counter
8
- from collections.abc import Iterable
9
- import urllib.parse
10
- import urllib.request
11
- from io import StringIO
12
- from collections import defaultdict
13
- import inspect
14
-
15
- from simpleeval import EvalWithCompoundTypes
16
-
17
- from edsl.Base import Base
18
- from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
19
- from edsl.scenarios.Scenario import Scenario
20
- from edsl.scenarios.ScenarioListPdfMixin import ScenarioListPdfMixin
21
- from edsl.scenarios.ScenarioListExportMixin import ScenarioListExportMixin
22
-
23
- from edsl.utilities.naming_utilities import sanitize_string
24
- from edsl.utilities.utilities import is_valid_variable_name
25
-
26
-
27
- class ScenarioListMixin(ScenarioListPdfMixin, ScenarioListExportMixin):
28
- pass
29
-
30
-
31
- class ScenarioList(Base, UserList, ScenarioListMixin):
32
- """Class for creating a list of scenarios to be used in a survey."""
33
-
34
- def __init__(self, data: Optional[list] = None, codebook: Optional[dict] = None):
35
- """Initialize the ScenarioList class."""
36
- if data is not None:
37
- super().__init__(data)
38
- else:
39
- super().__init__([])
40
- self.codebook = codebook or {}
41
-
42
- def unique(self) -> ScenarioList:
43
- """Return a list of unique scenarios.
44
-
45
- >>> s = ScenarioList([Scenario({'a': 1}), Scenario({'a': 1}), Scenario({'a': 2})])
46
- >>> s.unique()
47
- ScenarioList([Scenario({'a': 1}), Scenario({'a': 2})])
48
- """
49
- return ScenarioList(list(set(self)))
50
-
51
- @property
52
- def has_jinja_braces(self) -> bool:
53
- """Check if the ScenarioList has Jinja braces."""
54
- return any([scenario.has_jinja_braces for scenario in self])
55
-
56
- def convert_jinja_braces(self) -> ScenarioList:
57
- """Convert Jinja braces to Python braces."""
58
- return ScenarioList([scenario.convert_jinja_braces() for scenario in self])
59
-
60
- def give_valid_names(self) -> ScenarioList:
61
- """Give valid names to the scenario keys.
62
-
63
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
64
- >>> s.give_valid_names()
65
- ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
66
- >>> s = ScenarioList([Scenario({'are you there John?': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
67
- >>> s.give_valid_names()
68
- ScenarioList([Scenario({'john': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
69
- """
70
- codebook = {}
71
- new_scenaerios = []
72
- for scenario in self:
73
- new_scenario = {}
74
- for key in scenario:
75
- if not is_valid_variable_name(key):
76
- if key in codebook:
77
- new_key = codebook[key]
78
- else:
79
- new_key = sanitize_string(key)
80
- if not is_valid_variable_name(new_key):
81
- new_key = f"var_{len(codebook)}"
82
- codebook[key] = new_key
83
- new_scenario[new_key] = scenario[key]
84
- else:
85
- new_scenario[key] = scenario[key]
86
- new_scenaerios.append(Scenario(new_scenario))
87
- return ScenarioList(new_scenaerios, codebook)
88
-
89
- def unpivot(self, id_vars=None, value_vars=None):
90
- """
91
- Unpivot the ScenarioList, allowing for id variables to be specified.
92
-
93
- Parameters:
94
- id_vars (list): Fields to use as identifier variables (kept in each entry)
95
- value_vars (list): Fields to unpivot. If None, all fields not in id_vars will be used.
96
-
97
- Example:
98
- >>> s = ScenarioList([
99
- ... Scenario({'id': 1, 'year': 2020, 'a': 10, 'b': 20}),
100
- ... Scenario({'id': 2, 'year': 2021, 'a': 15, 'b': 25})
101
- ... ])
102
- >>> s.unpivot(id_vars=['id', 'year'], value_vars=['a', 'b'])
103
- ScenarioList([Scenario({'id': 1, 'year': 2020, 'variable': 'a', 'value': 10}), Scenario({'id': 1, 'year': 2020, 'variable': 'b', 'value': 20}), Scenario({'id': 2, 'year': 2021, 'variable': 'a', 'value': 15}), Scenario({'id': 2, 'year': 2021, 'variable': 'b', 'value': 25})])
104
- """
105
- if id_vars is None:
106
- id_vars = []
107
- if value_vars is None:
108
- value_vars = [field for field in self[0].keys() if field not in id_vars]
109
-
110
- new_scenarios = []
111
- for scenario in self:
112
- for var in value_vars:
113
- new_scenario = {id_var: scenario[id_var] for id_var in id_vars}
114
- new_scenario["variable"] = var
115
- new_scenario["value"] = scenario[var]
116
- new_scenarios.append(Scenario(new_scenario))
117
-
118
- return ScenarioList(new_scenarios)
119
-
120
- def pivot(self, id_vars, var_name="variable", value_name="value"):
121
- """
122
- Pivot the ScenarioList from long to wide format.
123
-
124
- Parameters:
125
- id_vars (list): Fields to use as identifier variables
126
- var_name (str): Name of the variable column (default: 'variable')
127
- value_name (str): Name of the value column (default: 'value')
128
-
129
- Example:
130
- >>> s = ScenarioList([
131
- ... Scenario({'id': 1, 'year': 2020, 'variable': 'a', 'value': 10}),
132
- ... Scenario({'id': 1, 'year': 2020, 'variable': 'b', 'value': 20}),
133
- ... Scenario({'id': 2, 'year': 2021, 'variable': 'a', 'value': 15}),
134
- ... Scenario({'id': 2, 'year': 2021, 'variable': 'b', 'value': 25})
135
- ... ])
136
- >>> s.pivot(id_vars=['id', 'year'])
137
- ScenarioList([Scenario({'id': 1, 'year': 2020, 'a': 10, 'b': 20}), Scenario({'id': 2, 'year': 2021, 'a': 15, 'b': 25})])
138
- """
139
- pivoted_dict = {}
140
-
141
- for scenario in self:
142
- # Create a tuple of id values to use as a key
143
- id_key = tuple(scenario[id_var] for id_var in id_vars)
144
-
145
- # If this combination of id values hasn't been seen before, initialize it
146
- if id_key not in pivoted_dict:
147
- pivoted_dict[id_key] = {id_var: scenario[id_var] for id_var in id_vars}
148
-
149
- # Add the variable-value pair to the dict
150
- variable = scenario[var_name]
151
- value = scenario[value_name]
152
- pivoted_dict[id_key][variable] = value
153
-
154
- # Convert the dict of dicts to a list of Scenarios
155
- pivoted_scenarios = [
156
- Scenario(dict(zip(id_vars, id_key), **values))
157
- for id_key, values in pivoted_dict.items()
158
- ]
159
-
160
- return ScenarioList(pivoted_scenarios)
161
-
162
- def group_by(self, id_vars, variables, func):
163
- """
164
- Group the ScenarioList by id_vars and apply a function to the specified variables.
165
-
166
- Parameters:
167
- id_vars (list): Fields to use as identifier variables for grouping
168
- variables (list): Fields to pass to the aggregation function
169
- func (callable): Function to apply to the grouped variables.
170
- Should accept lists of values for each variable.
171
-
172
- Returns:
173
- ScenarioList: A new ScenarioList with the grouped and aggregated results
174
-
175
- Example:
176
- >>> def avg_sum(a, b):
177
- ... return {'avg_a': sum(a) / len(a), 'sum_b': sum(b)}
178
- >>> s = ScenarioList([
179
- ... Scenario({'group': 'A', 'year': 2020, 'a': 10, 'b': 20}),
180
- ... Scenario({'group': 'A', 'year': 2021, 'a': 15, 'b': 25}),
181
- ... Scenario({'group': 'B', 'year': 2020, 'a': 12, 'b': 22}),
182
- ... Scenario({'group': 'B', 'year': 2021, 'a': 17, 'b': 27})
183
- ... ])
184
- >>> s.group_by(id_vars=['group'], variables=['a', 'b'], func=avg_sum)
185
- ScenarioList([Scenario({'group': 'A', 'avg_a': 12.5, 'sum_b': 45}), Scenario({'group': 'B', 'avg_a': 14.5, 'sum_b': 49})])
186
- """
187
- # Check if the function is compatible with the specified variables
188
- func_params = inspect.signature(func).parameters
189
- if len(func_params) != len(variables):
190
- raise ValueError(
191
- f"Function {func.__name__} expects {len(func_params)} arguments, but {len(variables)} variables were provided"
192
- )
193
-
194
- # Group the scenarios
195
- grouped = defaultdict(lambda: defaultdict(list))
196
- for scenario in self:
197
- key = tuple(scenario[id_var] for id_var in id_vars)
198
- for var in variables:
199
- grouped[key][var].append(scenario[var])
200
-
201
- # Apply the function to each group
202
- result = []
203
- for key, group in grouped.items():
204
- try:
205
- aggregated = func(*[group[var] for var in variables])
206
- except Exception as e:
207
- raise ValueError(f"Error applying function to group {key}: {str(e)}")
208
-
209
- if not isinstance(aggregated, dict):
210
- raise ValueError(f"Function {func.__name__} must return a dictionary")
211
-
212
- new_scenario = dict(zip(id_vars, key))
213
- new_scenario.update(aggregated)
214
- result.append(Scenario(new_scenario))
215
-
216
- return ScenarioList(result)
217
-
218
- @property
219
- def parameters(self) -> set:
220
- """Return the set of parameters in the ScenarioList
221
-
222
- Example:
223
-
224
- >>> s = ScenarioList([Scenario({'a': 1}), Scenario({'b': 2})])
225
- >>> s.parameters == {'a', 'b'}
226
- True
227
- """
228
- if len(self) == 0:
229
- return set()
230
-
231
- return set.union(*[set(s.keys()) for s in self])
232
-
233
- def __hash__(self) -> int:
234
- """Return the hash of the ScenarioList.
235
-
236
- >>> s = ScenarioList.example()
237
- >>> hash(s)
238
- 1262252885757976162
239
- """
240
- from edsl.utilities.utilities import dict_hash
241
-
242
- return dict_hash(self.to_dict(sort=True, add_edsl_version=False))
243
-
244
- def __repr__(self):
245
- return f"ScenarioList({self.data})"
246
-
247
- def __mul__(self, other: ScenarioList) -> ScenarioList:
248
- """Takes the cross product of two ScenarioLists.
249
-
250
- >>> s1 = ScenarioList.from_list("a", [1, 2])
251
- >>> s2 = ScenarioList.from_list("b", [3, 4])
252
- >>> s1 * s2
253
- ScenarioList([Scenario({'a': 1, 'b': 3}), Scenario({'a': 1, 'b': 4}), Scenario({'a': 2, 'b': 3}), Scenario({'a': 2, 'b': 4})])
254
- """
255
- from itertools import product
256
-
257
- new_sl = []
258
- for s1, s2 in list(product(self, other)):
259
- new_sl.append(s1 + s2)
260
- return ScenarioList(new_sl)
261
-
262
- def times(self, other: ScenarioList) -> ScenarioList:
263
- """Takes the cross product of two ScenarioLists.
264
-
265
- Example:
266
-
267
- >>> s1 = ScenarioList([Scenario({'a': 1}), Scenario({'a': 2})])
268
- >>> s2 = ScenarioList([Scenario({'b': 1}), Scenario({'b': 2})])
269
- >>> s1.times(s2)
270
- ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2}), Scenario({'a': 2, 'b': 1}), Scenario({'a': 2, 'b': 2})])
271
- """
272
- return self.__mul__(other)
273
-
274
- def shuffle(self, seed: Optional[str] = "edsl") -> ScenarioList:
275
- """Shuffle the ScenarioList.
276
-
277
- >>> s = ScenarioList.from_list("a", [1,2,3,4])
278
- >>> s.shuffle()
279
- ScenarioList([Scenario({'a': 3}), Scenario({'a': 4}), Scenario({'a': 1}), Scenario({'a': 2})])
280
- """
281
- random.seed(seed)
282
- random.shuffle(self.data)
283
- return self
284
-
285
- def _repr_html_(self) -> str:
286
- from edsl.utilities.utilities import data_to_html
287
-
288
- data = self.to_dict()
289
- _ = data.pop("edsl_version")
290
- _ = data.pop("edsl_class_name")
291
- for s in data["scenarios"]:
292
- _ = s.pop("edsl_version")
293
- _ = s.pop("edsl_class_name")
294
- for scenario in data["scenarios"]:
295
- for key, value in scenario.items():
296
- if hasattr(value, "to_dict"):
297
- data[key] = value.to_dict()
298
- return data_to_html(data)
299
-
300
- def tally(self, field) -> dict:
301
- """Return a tally of the values in the field.
302
-
303
- Example:
304
-
305
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
306
- >>> s.tally('b')
307
- {1: 1, 2: 1}
308
- """
309
- return dict(Counter([scenario[field] for scenario in self]))
310
-
311
- def sample(self, n: int, seed="edsl") -> ScenarioList:
312
- """Return a random sample from the ScenarioList
313
-
314
- >>> s = ScenarioList.from_list("a", [1,2,3,4,5,6])
315
- >>> s.sample(3)
316
- ScenarioList([Scenario({'a': 2}), Scenario({'a': 1}), Scenario({'a': 3})])
317
- """
318
-
319
- random.seed(seed)
320
-
321
- return ScenarioList(random.sample(self.data, n))
322
-
323
- def expand(self, expand_field: str, number_field=False) -> ScenarioList:
324
- """Expand the ScenarioList by a field.
325
-
326
- Example:
327
-
328
- >>> s = ScenarioList( [ Scenario({'a':1, 'b':[1,2]}) ] )
329
- >>> s.expand('b')
330
- ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
331
- """
332
- new_scenarios = []
333
- for scenario in self:
334
- values = scenario[expand_field]
335
- if not isinstance(values, Iterable) or isinstance(values, str):
336
- values = [values]
337
- for index, value in enumerate(values):
338
- new_scenario = scenario.copy()
339
- new_scenario[expand_field] = value
340
- if number_field:
341
- new_scenario[expand_field + "_number"] = index + 1
342
- new_scenarios.append(new_scenario)
343
- return ScenarioList(new_scenarios)
344
-
345
- def concatenate(self, fields: List[str], separator: str = ";") -> "ScenarioList":
346
- """Concatenate specified fields into a single field.
347
-
348
- Args:
349
- fields (List[str]): List of field names to concatenate.
350
- separator (str, optional): Separator to use between field values. Defaults to ";".
351
-
352
- Returns:
353
- ScenarioList: A new ScenarioList with concatenated fields.
354
-
355
- Example:
356
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 2, 'c': 3}), Scenario({'a': 4, 'b': 5, 'c': 6})])
357
- >>> s.concatenate(['a', 'b', 'c'])
358
- ScenarioList([Scenario({'concat_a_b_c': '1;2;3'}), Scenario({'concat_a_b_c': '4;5;6'})])
359
- """
360
- new_scenarios = []
361
- for scenario in self:
362
- new_scenario = scenario.copy()
363
- concat_values = []
364
- for field in fields:
365
- if field in new_scenario:
366
- concat_values.append(str(new_scenario[field]))
367
- del new_scenario[field]
368
-
369
- new_field_name = f"concat_{'_'.join(fields)}"
370
- new_scenario[new_field_name] = separator.join(concat_values)
371
- new_scenarios.append(new_scenario)
372
-
373
- return ScenarioList(new_scenarios)
374
-
375
- def unpack_dict(
376
- self, field: str, prefix: Optional[str] = None, drop_field: bool = False
377
- ) -> ScenarioList:
378
- """Unpack a dictionary field into separate fields.
379
-
380
- Example:
381
-
382
- >>> s = ScenarioList([Scenario({'a': 1, 'b': {'c': 2, 'd': 3}})])
383
- >>> s.unpack_dict('b')
384
- ScenarioList([Scenario({'a': 1, 'b': {'c': 2, 'd': 3}, 'c': 2, 'd': 3})])
385
- """
386
- new_scenarios = []
387
- for scenario in self:
388
- new_scenario = scenario.copy()
389
- for key, value in scenario[field].items():
390
- if prefix:
391
- new_scenario[prefix + key] = value
392
- else:
393
- new_scenario[key] = value
394
- if drop_field:
395
- new_scenario.pop(field)
396
- new_scenarios.append(new_scenario)
397
- return ScenarioList(new_scenarios)
398
-
399
- def transform(
400
- self, field: str, func: Callable, new_name: Optional[str] = None
401
- ) -> ScenarioList:
402
- """Transform a field using a function."""
403
- new_scenarios = []
404
- for scenario in self:
405
- new_scenario = scenario.copy()
406
- new_scenario[new_name or field] = func(scenario[field])
407
- new_scenarios.append(new_scenario)
408
- return ScenarioList(new_scenarios)
409
-
410
- def mutate(
411
- self, new_var_string: str, functions_dict: Optional[dict[str, Callable]] = None
412
- ) -> ScenarioList:
413
- """
414
- Return a new ScenarioList with a new variable added.
415
-
416
- Example:
417
-
418
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
419
- >>> s.mutate("c = a + b")
420
- ScenarioList([Scenario({'a': 1, 'b': 2, 'c': 3}), Scenario({'a': 1, 'b': 1, 'c': 2})])
421
-
422
- """
423
- if "=" not in new_var_string:
424
- raise Exception(
425
- f"Mutate requires an '=' in the string, but '{new_var_string}' doesn't have one."
426
- )
427
- raw_var_name, expression = new_var_string.split("=", 1)
428
- var_name = raw_var_name.strip()
429
- from edsl.utilities.utilities import is_valid_variable_name
430
-
431
- if not is_valid_variable_name(var_name):
432
- raise Exception(f"{var_name} is not a valid variable name.")
433
-
434
- # create the evaluator
435
- functions_dict = functions_dict or {}
436
-
437
- def create_evaluator(scenario) -> EvalWithCompoundTypes:
438
- return EvalWithCompoundTypes(names=scenario, functions=functions_dict)
439
-
440
- def new_scenario(old_scenario: Scenario, var_name: str) -> Scenario:
441
- evaluator = create_evaluator(old_scenario)
442
- value = evaluator.eval(expression)
443
- new_s = old_scenario.copy()
444
- new_s[var_name] = value
445
- return new_s
446
-
447
- try:
448
- new_data = [new_scenario(s, var_name) for s in self]
449
- except Exception as e:
450
- raise Exception(f"Error in mutate. Exception:{e}")
451
-
452
- return ScenarioList(new_data)
453
-
454
- def order_by(self, *fields: str, reverse: bool = False) -> ScenarioList:
455
- """Order the scenarios by one or more fields.
456
-
457
- Example:
458
-
459
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
460
- >>> s.order_by('b', 'a')
461
- ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
462
- """
463
-
464
- def get_sort_key(scenario: Any) -> tuple:
465
- return tuple(scenario[field] for field in fields)
466
-
467
- return ScenarioList(sorted(self, key=get_sort_key, reverse=reverse))
468
-
469
- def filter(self, expression: str) -> ScenarioList:
470
- """
471
- Filter a list of scenarios based on an expression.
472
-
473
- Example:
474
-
475
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
476
- >>> s.filter("b == 2")
477
- ScenarioList([Scenario({'a': 1, 'b': 2})])
478
- """
479
-
480
- def create_evaluator(scenario: Scenario):
481
- """Create an evaluator for the given result.
482
- The 'combined_dict' is a mapping of all values for that Result object.
483
- """
484
- return EvalWithCompoundTypes(names=scenario)
485
-
486
- try:
487
- # iterates through all the results and evaluates the expression
488
- new_data = [
489
- scenario
490
- for scenario in self.data
491
- if create_evaluator(scenario).eval(expression)
492
- ]
493
- except Exception as e:
494
- print(f"Exception:{e}")
495
- raise Exception(f"Error in filter. Exception:{e}")
496
-
497
- return ScenarioList(new_data)
498
-
499
- def from_urls(
500
- self, urls: list[str], field_name: Optional[str] = "text"
501
- ) -> ScenarioList:
502
- """Create a ScenarioList from a list of URLs.
503
-
504
- :param urls: A list of URLs.
505
- :param field_name: The name of the field to store the text from the URLs.
506
-
507
-
508
- """
509
- return ScenarioList([Scenario.from_url(url, field_name) for url in urls])
510
-
511
- def select(self, *fields) -> ScenarioList:
512
- """
513
- Selects scenarios with only the references fields.
514
-
515
- Example:
516
-
517
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
518
- >>> s.select('a')
519
- ScenarioList([Scenario({'a': 1}), Scenario({'a': 1})])
520
- """
521
- if len(fields) == 1:
522
- fields_to_select = [list(fields)[0]]
523
- else:
524
- fields_to_select = list(fields)
525
-
526
- return ScenarioList(
527
- [scenario.select(fields_to_select) for scenario in self.data]
528
- )
529
-
530
- def drop(self, *fields) -> ScenarioList:
531
- """Drop fields from the scenarios.
532
-
533
- Example:
534
-
535
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
536
- >>> s.drop('a')
537
- ScenarioList([Scenario({'b': 1}), Scenario({'b': 2})])
538
- """
539
- return ScenarioList([scenario.drop(fields) for scenario in self.data])
540
-
541
- def keep(self, *fields) -> ScenarioList:
542
- """Keep only the specified fields in the scenarios.
543
-
544
- Example:
545
-
546
- >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
547
- >>> s.keep('a')
548
- ScenarioList([Scenario({'a': 1}), Scenario({'a': 1})])
549
- """
550
- return ScenarioList([scenario.keep(fields) for scenario in self.data])
551
-
552
- @classmethod
553
- def from_list(
554
- cls, name: str, values: list, func: Optional[Callable] = None
555
- ) -> ScenarioList:
556
- """Create a ScenarioList from a list of values.
557
-
558
- Example:
559
-
560
- >>> ScenarioList.from_list('name', ['Alice', 'Bob'])
561
- ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
562
- """
563
- if not func:
564
- func = lambda x: x
565
- return cls([Scenario({name: func(value)}) for value in values])
566
-
567
- def to_dataset(self) -> "Dataset":
568
- """
569
- >>> s = ScenarioList.from_list("a", [1,2,3])
570
- >>> s.to_dataset()
571
- Dataset([{'a': [1, 2, 3]}])
572
- >>> s = ScenarioList.from_list("a", [1,2,3]).add_list("b", [4,5,6])
573
- >>> s.to_dataset()
574
- Dataset([{'a': [1, 2, 3]}, {'b': [4, 5, 6]}])
575
- """
576
- from edsl.results.Dataset import Dataset
577
-
578
- keys = self[0].keys()
579
- data = [{key: [scenario[key] for scenario in self.data]} for key in keys]
580
- return Dataset(data)
581
-
582
- def split(
583
- self, field: str, split_on: str, index: int, new_name: Optional[str] = None
584
- ) -> ScenarioList:
585
- """Split a scenario fiel in multiple fields."""
586
- if new_name is None:
587
- new_name = field + "_split_" + str(index)
588
- new_scenarios = []
589
- for scenario in self:
590
- new_scenario = scenario.copy()
591
- new_scenario[new_name] = scenario[field].split(split_on)[index]
592
- new_scenarios.append(new_scenario)
593
- return ScenarioList(new_scenarios)
594
-
595
- def add_list(self, name, values) -> ScenarioList:
596
- """Add a list of values to a ScenarioList.
597
-
598
- Example:
599
-
600
- >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
601
- >>> s.add_list('age', [30, 25])
602
- ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
603
- """
604
- for i, value in enumerate(values):
605
- if i < len(self):
606
- self[i][name] = value
607
- else:
608
- self.append(Scenario({name: value}))
609
- return self
610
-
611
- def add_value(self, name: str, value: Any) -> ScenarioList:
612
- """Add a value to all scenarios in a ScenarioList.
613
-
614
- Example:
615
-
616
- >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
617
- >>> s.add_value('age', 30)
618
- ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 30})])
619
- """
620
- for scenario in self:
621
- scenario[name] = value
622
- return self
623
-
624
- def rename(self, replacement_dict: dict) -> ScenarioList:
625
- """Rename the fields in the scenarios.
626
-
627
- Example:
628
-
629
- >>> s = ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
630
- >>> s.rename({'name': 'first_name', 'age': 'years'})
631
- ScenarioList([Scenario({'first_name': 'Alice', 'years': 30}), Scenario({'first_name': 'Bob', 'years': 25})])
632
-
633
- """
634
-
635
- new_list = ScenarioList([])
636
- for obj in self:
637
- new_obj = obj.rename(replacement_dict)
638
- new_list.append(new_obj)
639
- return new_list
640
-
641
- @classmethod
642
- def from_sqlite(cls, filepath: str, table: str):
643
- import sqlite3
644
-
645
- with sqlite3.connect(filepath) as conn:
646
- cursor = conn.cursor()
647
- cursor.execute(f"SELECT * FROM {table}")
648
- columns = [description[0] for description in cursor.description]
649
- data = cursor.fetchall()
650
- return cls([Scenario(dict(zip(columns, row))) for row in data])
651
-
652
- @classmethod
653
- def from_latex(cls, tex_file_path: str):
654
- with open(tex_file_path, "r") as file:
655
- lines = file.readlines()
656
-
657
- processed_lines = []
658
- non_blank_lines = [
659
- (i, line.strip()) for i, line in enumerate(lines) if line.strip()
660
- ]
661
-
662
- for index, (line_no, text) in enumerate(non_blank_lines):
663
- entry = {
664
- "line_no": line_no + 1, # Using 1-based index for line numbers
665
- "text": text,
666
- "line_before": non_blank_lines[index - 1][1] if index > 0 else None,
667
- "line_after": (
668
- non_blank_lines[index + 1][1]
669
- if index < len(non_blank_lines) - 1
670
- else None
671
- ),
672
- }
673
- processed_lines.append(entry)
674
-
675
- return ScenarioList([Scenario(entry) for entry in processed_lines])
676
-
677
- @classmethod
678
- def from_google_doc(cls, url: str) -> ScenarioList:
679
- """Create a ScenarioList from a Google Doc.
680
-
681
- This method downloads the Google Doc as a Word file (.docx), saves it to a temporary file,
682
- and then reads it using the from_docx class method.
683
-
684
- Args:
685
- url (str): The URL to the Google Doc.
686
-
687
- Returns:
688
- ScenarioList: An instance of the ScenarioList class.
689
-
690
- """
691
- import tempfile
692
- import requests
693
- from docx import Document
694
-
695
- if "/edit" in url:
696
- doc_id = url.split("/d/")[1].split("/edit")[0]
697
- else:
698
- raise ValueError("Invalid Google Doc URL format.")
699
-
700
- export_url = f"https://docs.google.com/document/d/{doc_id}/export?format=docx"
701
-
702
- # Download the Google Doc as a Word file (.docx)
703
- response = requests.get(export_url)
704
- response.raise_for_status() # Ensure the request was successful
705
-
706
- # Save the Word file to a temporary file
707
- with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as temp_file:
708
- temp_file.write(response.content)
709
- temp_filename = temp_file.name
710
-
711
- # Call the from_docx class method with the temporary file
712
- return cls.from_docx(temp_filename)
713
-
714
- @classmethod
715
- def from_pandas(cls, df) -> ScenarioList:
716
- """Create a ScenarioList from a pandas DataFrame.
717
-
718
- Example:
719
-
720
- >>> import pandas as pd
721
- >>> df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 25], 'location': ['New York', 'Los Angeles']})
722
- >>> ScenarioList.from_pandas(df)
723
- ScenarioList([Scenario({'name': 'Alice', 'age': 30, 'location': 'New York'}), Scenario({'name': 'Bob', 'age': 25, 'location': 'Los Angeles'})])
724
- """
725
- return cls([Scenario(row) for row in df.to_dict(orient="records")])
726
-
727
- @classmethod
728
- def from_wikipedia(cls, url: str, table_index: int = 0):
729
- """
730
- Extracts a table from a Wikipedia page.
731
-
732
- Parameters:
733
- url (str): The URL of the Wikipedia page.
734
- table_index (int): The index of the table to extract (default is 0).
735
-
736
- Returns:
737
- pd.DataFrame: A DataFrame containing the extracted table.
738
- # # Example usage
739
- # url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
740
- # df = from_wikipedia(url, 0)
741
-
742
- # if not df.empty:
743
- # print(df.head())
744
- # else:
745
- # print("Failed to extract table.")
746
-
747
-
748
- """
749
- import pandas as pd
750
- import requests
751
- from requests.exceptions import RequestException
752
-
753
- try:
754
- # Check if the URL is reachable
755
- response = requests.get(url)
756
- response.raise_for_status() # Raises HTTPError for bad responses
757
-
758
- # Extract tables from the Wikipedia page
759
- tables = pd.read_html(url)
760
-
761
- # Ensure the requested table index is within the range of available tables
762
- if table_index >= len(tables) or table_index < 0:
763
- raise IndexError(
764
- f"Table index {table_index} is out of range. This page has {len(tables)} table(s)."
765
- )
766
-
767
- # Return the requested table as a DataFrame
768
- # return tables[table_index]
769
- return cls.from_pandas(tables[table_index])
770
-
771
- except RequestException as e:
772
- print(f"Error fetching the URL: {e}")
773
- except ValueError as e:
774
- print(f"Error parsing tables: {e}")
775
- except IndexError as e:
776
- print(e)
777
- except Exception as e:
778
- print(f"An unexpected error occurred: {e}")
779
-
780
- # Return an empty DataFrame in case of an error
781
- # return cls.from_pandas(pd.DataFrame())
782
-
783
- def to_key_value(self, field: str, value=None) -> Union[dict, set]:
784
- """Return the set of values in the field.
785
-
786
- Example:
787
-
788
- >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
789
- >>> s.to_key_value('name') == {'Alice', 'Bob'}
790
- True
791
- """
792
- if value is None:
793
- return {scenario[field] for scenario in self}
794
- else:
795
- return {scenario[field]: scenario[value] for scenario in self}
796
-
797
- @classmethod
798
- def from_excel(
799
- cls, filename: str, sheet_name: Optional[str] = None
800
- ) -> ScenarioList:
801
- """Create a ScenarioList from an Excel file.
802
-
803
- If the Excel file contains multiple sheets and no sheet_name is provided,
804
- the method will print the available sheets and require the user to specify one.
805
-
806
- Example:
807
-
808
- >>> import tempfile
809
- >>> import os
810
- >>> import pandas as pd
811
- >>> with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as f:
812
- ... df1 = pd.DataFrame({
813
- ... 'name': ['Alice', 'Bob'],
814
- ... 'age': [30, 25],
815
- ... 'location': ['New York', 'Los Angeles']
816
- ... })
817
- ... df2 = pd.DataFrame({
818
- ... 'name': ['Charlie', 'David'],
819
- ... 'age': [35, 40],
820
- ... 'location': ['Chicago', 'Boston']
821
- ... })
822
- ... with pd.ExcelWriter(f.name) as writer:
823
- ... df1.to_excel(writer, sheet_name='Sheet1', index=False)
824
- ... df2.to_excel(writer, sheet_name='Sheet2', index=False)
825
- ... temp_filename = f.name
826
- >>> scenario_list = ScenarioList.from_excel(temp_filename, sheet_name='Sheet1')
827
- >>> len(scenario_list)
828
- 2
829
- >>> scenario_list[0]['name']
830
- 'Alice'
831
- >>> scenario_list = ScenarioList.from_excel(temp_filename) # Should raise an error and list sheets
832
- Traceback (most recent call last):
833
- ...
834
- ValueError: Please provide a sheet name to load data from.
835
- """
836
- from edsl.scenarios.Scenario import Scenario
837
- import pandas as pd
838
-
839
- # Get all sheets
840
- all_sheets = pd.read_excel(filename, sheet_name=None)
841
-
842
- # If no sheet_name is provided and there is more than one sheet, print available sheets
843
- if sheet_name is None:
844
- if len(all_sheets) > 1:
845
- print("The Excel file contains multiple sheets:")
846
- for name in all_sheets.keys():
847
- print(f"- {name}")
848
- raise ValueError("Please provide a sheet name to load data from.")
849
- else:
850
- # If there is only one sheet, use it
851
- sheet_name = list(all_sheets.keys())[0]
852
-
853
- # Load the specified or determined sheet
854
- df = pd.read_excel(filename, sheet_name=sheet_name)
855
-
856
- observations = []
857
- for _, row in df.iterrows():
858
- observations.append(Scenario(row.to_dict()))
859
-
860
- return cls(observations)
861
-
862
- @classmethod
863
- def from_google_sheet(cls, url: str, sheet_name: str = None) -> ScenarioList:
864
- """Create a ScenarioList from a Google Sheet.
865
-
866
- This method downloads the Google Sheet as an Excel file, saves it to a temporary file,
867
- and then reads it using the from_excel class method.
868
-
869
- Args:
870
- url (str): The URL to the Google Sheet.
871
- sheet_name (str, optional): The name of the sheet to load. If None, the method will behave
872
- the same as from_excel regarding multiple sheets.
873
-
874
- Returns:
875
- ScenarioList: An instance of the ScenarioList class.
876
-
877
- """
878
- import pandas as pd
879
- import tempfile
880
- import requests
881
-
882
- if "/edit" in url:
883
- sheet_id = url.split("/d/")[1].split("/edit")[0]
884
- else:
885
- raise ValueError("Invalid Google Sheet URL format.")
886
-
887
- export_url = (
888
- f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
889
- )
890
-
891
- # Download the Google Sheet as an Excel file
892
- response = requests.get(export_url)
893
- response.raise_for_status() # Ensure the request was successful
894
-
895
- # Save the Excel file to a temporary file
896
- with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as temp_file:
897
- temp_file.write(response.content)
898
- temp_filename = temp_file.name
899
-
900
- # Call the from_excel class method with the temporary file
901
- return cls.from_excel(temp_filename, sheet_name=sheet_name)
902
-
903
- @classmethod
904
- def from_csv(cls, source: Union[str, urllib.parse.ParseResult]) -> ScenarioList:
905
- """Create a ScenarioList from a CSV file or URL.
906
-
907
- Args:
908
- source: A string representing either a local file path or a URL to a CSV file,
909
- or a urllib.parse.ParseResult object for a URL.
910
-
911
- Returns:
912
- ScenarioList: A ScenarioList object containing the data from the CSV.
913
-
914
- Example:
915
-
916
- >>> import tempfile
917
- >>> import os
918
- >>> with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.csv') as f:
919
- ... _ = f.write("name,age,location\\nAlice,30,New York\\nBob,25,Los Angeles\\n")
920
- ... temp_filename = f.name
921
- >>> scenario_list = ScenarioList.from_csv(temp_filename)
922
- >>> len(scenario_list)
923
- 2
924
- >>> scenario_list[0]['name']
925
- 'Alice'
926
- >>> scenario_list[1]['age']
927
- '25'
928
-
929
- >>> url = "https://example.com/data.csv"
930
- >>> ## scenario_list_from_url = ScenarioList.from_csv(url)
931
- """
932
- from edsl.scenarios.Scenario import Scenario
933
-
934
- def is_url(source):
935
- try:
936
- result = urllib.parse.urlparse(source)
937
- return all([result.scheme, result.netloc])
938
- except ValueError:
939
- return False
940
-
941
- if isinstance(source, str) and is_url(source):
942
- with urllib.request.urlopen(source) as response:
943
- csv_content = response.read().decode("utf-8")
944
- csv_file = StringIO(csv_content)
945
- elif isinstance(source, urllib.parse.ParseResult):
946
- with urllib.request.urlopen(source.geturl()) as response:
947
- csv_content = response.read().decode("utf-8")
948
- csv_file = StringIO(csv_content)
949
- else:
950
- csv_file = open(source, "r")
951
-
952
- try:
953
- reader = csv.reader(csv_file)
954
- header = next(reader)
955
- observations = [Scenario(dict(zip(header, row))) for row in reader]
956
- finally:
957
- csv_file.close()
958
-
959
- return cls(observations)
960
-
961
- def to_dict(self, sort=False, add_edsl_version=True) -> dict:
962
- """
963
- >>> s = ScenarioList([Scenario({'food': 'wood chips'}), Scenario({'food': 'wood-fired pizza'})])
964
- >>> s.to_dict()
965
- {'scenarios': [{'food': 'wood chips', 'edsl_version': '...', 'edsl_class_name': 'Scenario'}, {'food': 'wood-fired pizza', 'edsl_version': '...', 'edsl_class_name': 'Scenario'}], 'edsl_version': '...', 'edsl_class_name': 'ScenarioList'}
966
-
967
- """
968
- if sort:
969
- data = sorted(self, key=lambda x: hash(x))
970
- else:
971
- data = self
972
- d = {"scenarios": [s.to_dict(add_edsl_version=add_edsl_version) for s in data]}
973
- if add_edsl_version:
974
- from edsl import __version__
975
-
976
- d["edsl_version"] = __version__
977
- d["edsl_class_name"] = self.__class__.__name__
978
- return d
979
-
980
- @classmethod
981
- def gen(cls, scenario_dicts_list: List[dict]) -> ScenarioList:
982
- """Create a `ScenarioList` from a list of dictionaries.
983
-
984
- Example:
985
-
986
- >>> ScenarioList.gen([{'name': 'Alice'}, {'name': 'Bob'}])
987
- ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
988
-
989
- """
990
- from edsl.scenarios.Scenario import Scenario
991
-
992
- return cls([Scenario(s) for s in scenario_dicts_list])
993
-
994
- @classmethod
995
- @remove_edsl_version
996
- def from_dict(cls, data) -> ScenarioList:
997
- """Create a `ScenarioList` from a dictionary."""
998
- from edsl.scenarios.Scenario import Scenario
999
-
1000
- return cls([Scenario.from_dict(s) for s in data["scenarios"]])
1001
-
1002
- @classmethod
1003
- def from_nested_dict(cls, data: dict) -> ScenarioList:
1004
- """Create a `ScenarioList` from a nested dictionary."""
1005
- from edsl.scenarios.Scenario import Scenario
1006
-
1007
- s = ScenarioList()
1008
- for key, value in data.items():
1009
- s.add_list(key, value)
1010
- return s
1011
-
1012
- def code(self) -> str:
1013
- ## TODO: Refactor to only use the questions actually in the survey
1014
- """Create the Python code representation of a survey."""
1015
- header_lines = [
1016
- "from edsl.scenarios.Scenario import Scenario",
1017
- "from edsl.scenarios.ScenarioList import ScenarioList",
1018
- ]
1019
- lines = ["\n".join(header_lines)]
1020
- names = []
1021
- for index, scenario in enumerate(self):
1022
- lines.append(f"scenario_{index} = " + repr(scenario))
1023
- names.append(f"scenario_{index}")
1024
- lines.append(f"scenarios = ScenarioList([{', '.join(names)}])")
1025
- return lines
1026
-
1027
- @classmethod
1028
- def example(cls, randomize: bool = False) -> ScenarioList:
1029
- """
1030
- Return an example ScenarioList instance.
1031
-
1032
- :params randomize: If True, use Scenario's randomize method to randomize the values.
1033
- """
1034
- return cls([Scenario.example(randomize), Scenario.example(randomize)])
1035
-
1036
- def rich_print(self) -> None:
1037
- """Display an object as a table."""
1038
- from rich.table import Table
1039
-
1040
- table = Table(title="ScenarioList")
1041
- table.add_column("Index", style="bold")
1042
- table.add_column("Scenario")
1043
- for i, s in enumerate(self):
1044
- table.add_row(str(i), s.rich_print())
1045
- return table
1046
-
1047
- def __getitem__(self, key: Union[int, slice]) -> Any:
1048
- """Return the item at the given index.
1049
-
1050
- Example:
1051
- >>> s = ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5}), Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1052
- >>> s[0]
1053
- Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})
1054
-
1055
- >>> s[:1]
1056
- ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1057
-
1058
- """
1059
- if isinstance(key, slice):
1060
- return ScenarioList(super().__getitem__(key))
1061
- elif isinstance(key, int):
1062
- return super().__getitem__(key)
1063
- else:
1064
- return self.to_dict(add_edsl_version=False)[key]
1065
-
1066
- def to_agent_list(self):
1067
- """Convert the ScenarioList to an AgentList.
1068
-
1069
- Example:
1070
-
1071
- >>> s = ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5}), Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1072
- >>> s.to_agent_list()
1073
- AgentList([Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5}), Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5})])
1074
- """
1075
- from edsl.agents.AgentList import AgentList
1076
- from edsl.agents.Agent import Agent
1077
-
1078
- return AgentList([Agent(traits=s.data) for s in self])
1079
-
1080
- def chunk(
1081
- self,
1082
- field,
1083
- num_words: Optional[int] = None,
1084
- num_lines: Optional[int] = None,
1085
- include_original=False,
1086
- hash_original=False,
1087
- ) -> "ScenarioList":
1088
- """Chunk the scenarios based on a field.
1089
-
1090
- Example:
1091
-
1092
- >>> s = ScenarioList([Scenario({'text': 'The quick brown fox jumps over the lazy dog.'})])
1093
- >>> s.chunk('text', num_words=3)
1094
- ScenarioList([Scenario({'text': 'The quick brown', 'text_chunk': 0}), Scenario({'text': 'fox jumps over', 'text_chunk': 1}), Scenario({'text': 'the lazy dog.', 'text_chunk': 2})])
1095
- """
1096
- new_scenarios = []
1097
- for scenario in self:
1098
- replacement_scenarios = scenario.chunk(
1099
- field,
1100
- num_words=num_words,
1101
- num_lines=num_lines,
1102
- include_original=include_original,
1103
- hash_original=hash_original,
1104
- )
1105
- new_scenarios.extend(replacement_scenarios)
1106
- return ScenarioList(new_scenarios)
1107
-
1108
-
1109
- if __name__ == "__main__":
1110
- import doctest
1111
-
1112
- doctest.testmod(optionflags=doctest.ELLIPSIS)
1
+ """A list of Scenarios to be used in a survey."""
2
+
3
+ from __future__ import annotations
4
+ from typing import (
5
+ Any,
6
+ Optional,
7
+ Union,
8
+ List,
9
+ Callable,
10
+ Literal,
11
+ TYPE_CHECKING,
12
+ )
13
+
14
+ try:
15
+ from typing import TypeAlias
16
+ except ImportError:
17
+ from typing_extensions import TypeAlias
18
+
19
+ import csv
20
+ import random
21
+ from io import StringIO
22
+ import inspect
23
+ from collections import UserList, defaultdict
24
+ from collections.abc import Iterable
25
+
26
+ if TYPE_CHECKING:
27
+ from urllib.parse import ParseResult
28
+ from edsl.results.Dataset import Dataset
29
+ from edsl.jobs.Jobs import Jobs
30
+ from edsl.surveys.Survey import Survey
31
+ from edsl.questions.QuestionBase import QuestionBase
32
+
33
+
34
+ from simpleeval import EvalWithCompoundTypes, NameNotDefined # type: ignore
35
+
36
+ from tabulate import tabulate_formats
37
+
38
+ from edsl.Base import Base
39
+ from edsl.utilities.remove_edsl_version import remove_edsl_version
40
+
41
+ from edsl.scenarios.Scenario import Scenario
42
+ from edsl.scenarios.ScenarioListPdfMixin import ScenarioListPdfMixin
43
+ from edsl.scenarios.ScenarioListExportMixin import ScenarioListExportMixin
44
+ from edsl.utilities.naming_utilities import sanitize_string
45
+ from edsl.utilities.is_valid_variable_name import is_valid_variable_name
46
+ from edsl.exceptions.scenarios import ScenarioError
47
+
48
+ from edsl.scenarios.directory_scanner import DirectoryScanner
49
+
50
+
51
+ class ScenarioListMixin(ScenarioListPdfMixin, ScenarioListExportMixin):
52
+ pass
53
+
54
+
55
+ if TYPE_CHECKING:
56
+ from edsl.results.Dataset import Dataset
57
+
58
+ TableFormat: TypeAlias = Literal[
59
+ "plain",
60
+ "simple",
61
+ "github",
62
+ "grid",
63
+ "fancy_grid",
64
+ "pipe",
65
+ "orgtbl",
66
+ "rst",
67
+ "mediawiki",
68
+ "html",
69
+ "latex",
70
+ "latex_raw",
71
+ "latex_booktabs",
72
+ "tsv",
73
+ ]
74
+
75
+
76
+ class ScenarioList(Base, UserList, ScenarioListMixin):
77
+ """Class for creating a list of scenarios to be used in a survey."""
78
+
79
+ __documentation__ = (
80
+ "https://docs.expectedparrot.com/en/latest/scenarios.html#scenariolist"
81
+ )
82
+
83
+ def __init__(
84
+ self, data: Optional[list] = None, codebook: Optional[dict[str, str]] = None
85
+ ):
86
+ """Initialize the ScenarioList class."""
87
+ if data is not None:
88
+ super().__init__(data)
89
+ else:
90
+ super().__init__([])
91
+ self.codebook = codebook or {}
92
+
93
+ def unique(self) -> ScenarioList:
94
+ """Return a list of unique scenarios.
95
+
96
+ >>> s = ScenarioList([Scenario({'a': 1}), Scenario({'a': 1}), Scenario({'a': 2})])
97
+ >>> s.unique()
98
+ ScenarioList([Scenario({'a': 1}), Scenario({'a': 2})])
99
+ """
100
+ return ScenarioList(list(set(self)))
101
+
102
+ @property
103
+ def has_jinja_braces(self) -> bool:
104
+ """Check if the ScenarioList has Jinja braces."""
105
+ return any([scenario.has_jinja_braces for scenario in self])
106
+
107
+ def _convert_jinja_braces(self) -> ScenarioList:
108
+ """Convert Jinja braces to Python braces."""
109
+ return ScenarioList([scenario._convert_jinja_braces() for scenario in self])
110
+
111
+ def give_valid_names(self, existing_codebook: dict = None) -> ScenarioList:
112
+ """Give valid names to the scenario keys, using an existing codebook if provided.
113
+
114
+ Args:
115
+ existing_codebook (dict, optional): Existing mapping of original keys to valid names.
116
+ Defaults to None.
117
+
118
+ Returns:
119
+ ScenarioList: A new ScenarioList with valid variable names and updated codebook.
120
+
121
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
122
+ >>> s.give_valid_names()
123
+ ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
124
+ >>> s = ScenarioList([Scenario({'are you there John?': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
125
+ >>> s.give_valid_names()
126
+ ScenarioList([Scenario({'john': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
127
+ >>> s.give_valid_names({'are you there John?': 'custom_name'})
128
+ ScenarioList([Scenario({'custom_name': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
129
+ """
130
+ codebook = existing_codebook.copy() if existing_codebook else {}
131
+ new_scenarios = []
132
+
133
+ for scenario in self:
134
+ new_scenario = {}
135
+ for key in scenario:
136
+ if is_valid_variable_name(key):
137
+ new_scenario[key] = scenario[key]
138
+ continue
139
+
140
+ if key in codebook:
141
+ new_key = codebook[key]
142
+ else:
143
+ new_key = sanitize_string(key)
144
+ if not is_valid_variable_name(new_key):
145
+ new_key = f"var_{len(codebook)}"
146
+ codebook[key] = new_key
147
+
148
+ new_scenario[new_key] = scenario[key]
149
+
150
+ new_scenarios.append(Scenario(new_scenario))
151
+
152
+ return ScenarioList(new_scenarios, codebook)
153
+
154
+ def unpivot(
155
+ self,
156
+ id_vars: Optional[List[str]] = None,
157
+ value_vars: Optional[List[str]] = None,
158
+ ) -> ScenarioList:
159
+ """
160
+ Unpivot the ScenarioList, allowing for id variables to be specified.
161
+
162
+ Parameters:
163
+ id_vars (list): Fields to use as identifier variables (kept in each entry)
164
+ value_vars (list): Fields to unpivot. If None, all fields not in id_vars will be used.
165
+
166
+ Example:
167
+ >>> s = ScenarioList([
168
+ ... Scenario({'id': 1, 'year': 2020, 'a': 10, 'b': 20}),
169
+ ... Scenario({'id': 2, 'year': 2021, 'a': 15, 'b': 25})
170
+ ... ])
171
+ >>> s.unpivot(id_vars=['id', 'year'], value_vars=['a', 'b'])
172
+ ScenarioList([Scenario({'id': 1, 'year': 2020, 'variable': 'a', 'value': 10}), Scenario({'id': 1, 'year': 2020, 'variable': 'b', 'value': 20}), Scenario({'id': 2, 'year': 2021, 'variable': 'a', 'value': 15}), Scenario({'id': 2, 'year': 2021, 'variable': 'b', 'value': 25})])
173
+ """
174
+ if id_vars is None:
175
+ id_vars = []
176
+ if value_vars is None:
177
+ value_vars = [field for field in self[0].keys() if field not in id_vars]
178
+
179
+ new_scenarios = []
180
+ for scenario in self:
181
+ for var in value_vars:
182
+ new_scenario = {id_var: scenario[id_var] for id_var in id_vars}
183
+ new_scenario["variable"] = var
184
+ new_scenario["value"] = scenario[var]
185
+ new_scenarios.append(Scenario(new_scenario))
186
+
187
+ return ScenarioList(new_scenarios)
188
+
189
+ def sem_filter(self, language_predicate: str) -> ScenarioList:
190
+ """Filter the ScenarioList based on a language predicate.
191
+
192
+ :param language_predicate: The language predicate to use.
193
+
194
+ Inspired by:
195
+ @misc{patel2024semanticoperators,
196
+ title={Semantic Operators: A Declarative Model for Rich, AI-based Analytics Over Text Data},
197
+ author={Liana Patel and Siddharth Jha and Parth Asawa and Melissa Pan and Carlos Guestrin and Matei Zaharia},
198
+ year={2024},
199
+ eprint={2407.11418},
200
+ archivePrefix={arXiv},
201
+ primaryClass={cs.DB},
202
+ url={https://arxiv.org/abs/2407.11418},
203
+ }
204
+ """
205
+ from edsl import QuestionYesNo
206
+
207
+ new_scenario_list = self.duplicate()
208
+ q = QuestionYesNo(
209
+ question_text=language_predicate, question_name="binary_outcome"
210
+ )
211
+ results = q.by(new_scenario_list).run(verbose=False)
212
+ new_scenario_list = new_scenario_list.add_list(
213
+ "criteria", results.select("binary_outcome").to_list()
214
+ )
215
+ return new_scenario_list.filter("criteria == 'Yes'").drop("criteria")
216
+
217
+ def pivot(
218
+ self,
219
+ id_vars: List[str] = None,
220
+ var_name="variable",
221
+ value_name="value",
222
+ ) -> ScenarioList:
223
+ """
224
+ Pivot the ScenarioList from long to wide format.
225
+
226
+ Parameters:
227
+ id_vars (list): Fields to use as identifier variables
228
+ var_name (str): Name of the variable column (default: 'variable')
229
+ value_name (str): Name of the value column (default: 'value')
230
+
231
+ Example:
232
+ >>> s = ScenarioList([
233
+ ... Scenario({'id': 1, 'year': 2020, 'variable': 'a', 'value': 10}),
234
+ ... Scenario({'id': 1, 'year': 2020, 'variable': 'b', 'value': 20}),
235
+ ... Scenario({'id': 2, 'year': 2021, 'variable': 'a', 'value': 15}),
236
+ ... Scenario({'id': 2, 'year': 2021, 'variable': 'b', 'value': 25})
237
+ ... ])
238
+ >>> s.pivot(id_vars=['id', 'year'])
239
+ ScenarioList([Scenario({'id': 1, 'year': 2020, 'a': 10, 'b': 20}), Scenario({'id': 2, 'year': 2021, 'a': 15, 'b': 25})])
240
+ """
241
+ pivoted_dict = {}
242
+
243
+ for scenario in self:
244
+ # Create a tuple of id values to use as a key
245
+ id_key = tuple(scenario[id_var] for id_var in id_vars)
246
+
247
+ # If this combination of id values hasn't been seen before, initialize it
248
+ if id_key not in pivoted_dict:
249
+ pivoted_dict[id_key] = {id_var: scenario[id_var] for id_var in id_vars}
250
+
251
+ # Add the variable-value pair to the dict
252
+ variable = scenario[var_name]
253
+ value = scenario[value_name]
254
+ pivoted_dict[id_key][variable] = value
255
+
256
+ # Convert the dict of dicts to a list of Scenarios
257
+ pivoted_scenarios = [
258
+ Scenario(dict(zip(id_vars, id_key), **values))
259
+ for id_key, values in pivoted_dict.items()
260
+ ]
261
+
262
+ return ScenarioList(pivoted_scenarios)
263
+
264
+ def group_by(
265
+ self, id_vars: List[str], variables: List[str], func: Callable
266
+ ) -> ScenarioList:
267
+ """
268
+ Group the ScenarioList by id_vars and apply a function to the specified variables.
269
+
270
+ :param id_vars: Fields to use as identifier variables
271
+ :param variables: Fields to group and aggregate
272
+ :param func: Function to apply to the grouped variables
273
+
274
+ Returns:
275
+ ScenarioList: A new ScenarioList with the grouped and aggregated results
276
+
277
+ Example:
278
+ >>> def avg_sum(a, b):
279
+ ... return {'avg_a': sum(a) / len(a), 'sum_b': sum(b)}
280
+ >>> s = ScenarioList([
281
+ ... Scenario({'group': 'A', 'year': 2020, 'a': 10, 'b': 20}),
282
+ ... Scenario({'group': 'A', 'year': 2021, 'a': 15, 'b': 25}),
283
+ ... Scenario({'group': 'B', 'year': 2020, 'a': 12, 'b': 22}),
284
+ ... Scenario({'group': 'B', 'year': 2021, 'a': 17, 'b': 27})
285
+ ... ])
286
+ >>> s.group_by(id_vars=['group'], variables=['a', 'b'], func=avg_sum)
287
+ ScenarioList([Scenario({'group': 'A', 'avg_a': 12.5, 'sum_b': 45}), Scenario({'group': 'B', 'avg_a': 14.5, 'sum_b': 49})])
288
+ """
289
+ # Check if the function is compatible with the specified variables
290
+ func_params = inspect.signature(func).parameters
291
+ if len(func_params) != len(variables):
292
+ raise ScenarioError(
293
+ f"Function {func.__name__} expects {len(func_params)} arguments, but {len(variables)} variables were provided"
294
+ )
295
+
296
+ # Group the scenarios
297
+ grouped: dict[str, list] = defaultdict(lambda: defaultdict(list))
298
+ for scenario in self:
299
+ key = tuple(scenario[id_var] for id_var in id_vars)
300
+ for var in variables:
301
+ grouped[key][var].append(scenario[var])
302
+
303
+ # Apply the function to each group
304
+ result = []
305
+ for key, group in grouped.items():
306
+ try:
307
+ aggregated = func(*[group[var] for var in variables])
308
+ except Exception as e:
309
+ raise ScenarioError(f"Error applying function to group {key}: {str(e)}")
310
+
311
+ if not isinstance(aggregated, dict):
312
+ raise ScenarioError(
313
+ f"Function {func.__name__} must return a dictionary"
314
+ )
315
+
316
+ new_scenario = dict(zip(id_vars, key))
317
+ new_scenario.update(aggregated)
318
+ result.append(Scenario(new_scenario))
319
+
320
+ return ScenarioList(result)
321
+
322
+ @property
323
+ def parameters(self) -> set:
324
+ """Return the set of parameters in the ScenarioList
325
+
326
+ Example:
327
+
328
+ >>> s = ScenarioList([Scenario({'a': 1}), Scenario({'b': 2})])
329
+ >>> s.parameters == {'a', 'b'}
330
+ True
331
+ """
332
+ if len(self) == 0:
333
+ return set()
334
+
335
+ return set.union(*[set(s.keys()) for s in self])
336
+
337
+ def __hash__(self) -> int:
338
+ """Return the hash of the ScenarioList.
339
+
340
+ >>> s = ScenarioList.example()
341
+ >>> hash(s)
342
+ 1262252885757976162
343
+ """
344
+ from edsl.utilities.utilities import dict_hash
345
+
346
+ return dict_hash(self.to_dict(sort=True, add_edsl_version=False))
347
+
348
+ def __eq__(self, other: Any) -> bool:
349
+ return hash(self) == hash(other)
350
+
351
+ def __repr__(self):
352
+ return f"ScenarioList({self.data})"
353
+
354
+ def __mul__(self, other: ScenarioList) -> ScenarioList:
355
+ """Takes the cross product of two ScenarioLists.
356
+
357
+ >>> s1 = ScenarioList.from_list("a", [1, 2])
358
+ >>> s2 = ScenarioList.from_list("b", [3, 4])
359
+ >>> s1 * s2
360
+ ScenarioList([Scenario({'a': 1, 'b': 3}), Scenario({'a': 1, 'b': 4}), Scenario({'a': 2, 'b': 3}), Scenario({'a': 2, 'b': 4})])
361
+ """
362
+ from itertools import product
363
+
364
+ new_sl = []
365
+ for s1, s2 in list(product(self, other)):
366
+ new_sl.append(s1 + s2)
367
+ return ScenarioList(new_sl)
368
+
369
+ def times(self, other: ScenarioList) -> ScenarioList:
370
+ """Takes the cross product of two ScenarioLists.
371
+
372
+ Example:
373
+
374
+ >>> s1 = ScenarioList([Scenario({'a': 1}), Scenario({'a': 2})])
375
+ >>> s2 = ScenarioList([Scenario({'b': 1}), Scenario({'b': 2})])
376
+ >>> s1.times(s2)
377
+ ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2}), Scenario({'a': 2, 'b': 1}), Scenario({'a': 2, 'b': 2})])
378
+ """
379
+ return self.__mul__(other)
380
+
381
+ def shuffle(self, seed: Optional[str] = None) -> ScenarioList:
382
+ """Shuffle the ScenarioList.
383
+
384
+ >>> s = ScenarioList.from_list("a", [1,2,3,4])
385
+ >>> s.shuffle(seed = "1234")
386
+ ScenarioList([Scenario({'a': 1}), Scenario({'a': 4}), Scenario({'a': 3}), Scenario({'a': 2})])
387
+ """
388
+ sl = self.duplicate()
389
+ if seed:
390
+ random.seed(seed)
391
+ random.shuffle(sl.data)
392
+ return sl
393
+
394
+ def sample(self, n: int, seed: Optional[str] = None) -> ScenarioList:
395
+ """Return a random sample from the ScenarioList
396
+
397
+ >>> s = ScenarioList.from_list("a", [1,2,3,4,5,6])
398
+ >>> s.sample(3, seed = "edsl")
399
+ ScenarioList([Scenario({'a': 2}), Scenario({'a': 1}), Scenario({'a': 3})])
400
+ """
401
+ if seed:
402
+ random.seed(seed)
403
+
404
+ sl = self.duplicate()
405
+ return ScenarioList(random.sample(sl.data, n))
406
+
407
+ def expand(self, expand_field: str, number_field: bool = False) -> ScenarioList:
408
+ """Expand the ScenarioList by a field.
409
+
410
+ :param expand_field: The field to expand.
411
+ :param number_field: Whether to add a field with the index of the value
412
+
413
+ Example:
414
+
415
+ >>> s = ScenarioList( [ Scenario({'a':1, 'b':[1,2]}) ] )
416
+ >>> s.expand('b')
417
+ ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
418
+ >>> s.expand('b', number_field=True)
419
+ ScenarioList([Scenario({'a': 1, 'b': 1, 'b_number': 1}), Scenario({'a': 1, 'b': 2, 'b_number': 2})])
420
+ """
421
+ new_scenarios = []
422
+ for scenario in self:
423
+ values = scenario[expand_field]
424
+ if not isinstance(values, Iterable) or isinstance(values, str):
425
+ values = [values]
426
+ for index, value in enumerate(values):
427
+ new_scenario = scenario.copy()
428
+ new_scenario[expand_field] = value
429
+ if number_field:
430
+ new_scenario[expand_field + "_number"] = index + 1
431
+ new_scenarios.append(new_scenario)
432
+ return ScenarioList(new_scenarios)
433
+
434
+ def concatenate(self, fields: List[str], separator: str = ";") -> ScenarioList:
435
+ """Concatenate specified fields into a single field.
436
+
437
+ :param fields: The fields to concatenate.
438
+ :param separator: The separator to use.
439
+
440
+ Returns:
441
+ ScenarioList: A new ScenarioList with concatenated fields.
442
+
443
+ Example:
444
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2, 'c': 3}), Scenario({'a': 4, 'b': 5, 'c': 6})])
445
+ >>> s.concatenate(['a', 'b', 'c'])
446
+ ScenarioList([Scenario({'concat_a_b_c': '1;2;3'}), Scenario({'concat_a_b_c': '4;5;6'})])
447
+ """
448
+ new_scenarios = []
449
+ for scenario in self:
450
+ new_scenario = scenario.copy()
451
+ concat_values = []
452
+ for field in fields:
453
+ if field in new_scenario:
454
+ concat_values.append(str(new_scenario[field]))
455
+ del new_scenario[field]
456
+
457
+ new_field_name = f"concat_{'_'.join(fields)}"
458
+ new_scenario[new_field_name] = separator.join(concat_values)
459
+ new_scenarios.append(new_scenario)
460
+
461
+ return ScenarioList(new_scenarios)
462
+
463
+ def unpack_dict(
464
+ self, field: str, prefix: Optional[str] = None, drop_field: bool = False
465
+ ) -> ScenarioList:
466
+ """Unpack a dictionary field into separate fields.
467
+
468
+ :param field: The field to unpack.
469
+ :param prefix: An optional prefix to add to the new fields.
470
+ :param drop_field: Whether to drop the original field.
471
+
472
+ Example:
473
+
474
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': {'c': 2, 'd': 3}})])
475
+ >>> s.unpack_dict('b')
476
+ ScenarioList([Scenario({'a': 1, 'b': {'c': 2, 'd': 3}, 'c': 2, 'd': 3})])
477
+ >>> s.unpack_dict('b', prefix='new_')
478
+ ScenarioList([Scenario({'a': 1, 'b': {'c': 2, 'd': 3}, 'new_c': 2, 'new_d': 3})])
479
+ """
480
+ new_scenarios = []
481
+ for scenario in self:
482
+ new_scenario = scenario.copy()
483
+ for key, value in scenario[field].items():
484
+ if prefix:
485
+ new_scenario[prefix + key] = value
486
+ else:
487
+ new_scenario[key] = value
488
+ if drop_field:
489
+ new_scenario.pop(field)
490
+ new_scenarios.append(new_scenario)
491
+ return ScenarioList(new_scenarios)
492
+
493
+ def transform(
494
+ self, field: str, func: Callable, new_name: Optional[str] = None
495
+ ) -> ScenarioList:
496
+ """Transform a field using a function.
497
+
498
+ :param field: The field to transform.
499
+ :param func: The function to apply to the field.
500
+ :param new_name: An optional new name for the transformed field.
501
+
502
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
503
+ >>> s.transform('b', lambda x: x + 1)
504
+ ScenarioList([Scenario({'a': 1, 'b': 3}), Scenario({'a': 1, 'b': 2})])
505
+
506
+ """
507
+ new_scenarios = []
508
+ for scenario in self:
509
+ new_scenario = scenario.copy()
510
+ new_scenario[new_name or field] = func(scenario[field])
511
+ new_scenarios.append(new_scenario)
512
+ return ScenarioList(new_scenarios)
513
+
514
+ def mutate(
515
+ self, new_var_string: str, functions_dict: Optional[dict[str, Callable]] = None
516
+ ) -> ScenarioList:
517
+ """
518
+ Return a new ScenarioList with a new variable added.
519
+
520
+ :param new_var_string: A string with the new variable assignment.
521
+ :param functions_dict: A dictionary of functions to use in the assignment.
522
+
523
+ Example:
524
+
525
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
526
+ >>> s.mutate("c = a + b")
527
+ ScenarioList([Scenario({'a': 1, 'b': 2, 'c': 3}), Scenario({'a': 1, 'b': 1, 'c': 2})])
528
+
529
+ """
530
+ if "=" not in new_var_string:
531
+ raise ScenarioError(
532
+ f"Mutate requires an '=' in the string, but '{new_var_string}' doesn't have one."
533
+ )
534
+ raw_var_name, expression = new_var_string.split("=", 1)
535
+ var_name = raw_var_name.strip()
536
+ from edsl.utilities.utilities import is_valid_variable_name
537
+
538
+ if not is_valid_variable_name(var_name):
539
+ raise ScenarioError(f"{var_name} is not a valid variable name.")
540
+
541
+ # create the evaluator
542
+ functions_dict = functions_dict or {}
543
+
544
+ def create_evaluator(scenario) -> EvalWithCompoundTypes:
545
+ return EvalWithCompoundTypes(names=scenario, functions=functions_dict)
546
+
547
+ def new_scenario(old_scenario: Scenario, var_name: str) -> Scenario:
548
+ evaluator = create_evaluator(old_scenario)
549
+ value = evaluator.eval(expression)
550
+ new_s = old_scenario.copy()
551
+ new_s[var_name] = value
552
+ return new_s
553
+
554
+ try:
555
+ new_data = [new_scenario(s, var_name) for s in self]
556
+ except Exception as e:
557
+ raise ScenarioError(f"Error in mutate. Exception:{e}")
558
+
559
+ return ScenarioList(new_data)
560
+
561
+ def order_by(self, *fields: str, reverse: bool = False) -> ScenarioList:
562
+ """Order the scenarios by one or more fields.
563
+
564
+ :param fields: The fields to order by.
565
+ :param reverse: Whether to reverse the order.
566
+ Example:
567
+
568
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 1, 'b': 1})])
569
+ >>> s.order_by('b', 'a')
570
+ ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
571
+ """
572
+
573
+ def get_sort_key(scenario: Any) -> tuple:
574
+ return tuple(scenario[field] for field in fields)
575
+
576
+ return ScenarioList(sorted(self, key=get_sort_key, reverse=reverse))
577
+
578
+ def duplicate(self) -> ScenarioList:
579
+ """Return a copy of the ScenarioList.
580
+
581
+ >>> sl = ScenarioList.example()
582
+ >>> sl_copy = sl.duplicate()
583
+ >>> sl == sl_copy
584
+ True
585
+ >>> sl is sl_copy
586
+ False
587
+ """
588
+ return ScenarioList([scenario.copy() for scenario in self])
589
+
590
+ def filter(self, expression: str) -> ScenarioList:
591
+ """
592
+ Filter a list of scenarios based on an expression.
593
+
594
+ :param expression: The expression to filter by.
595
+
596
+ Example:
597
+
598
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
599
+ >>> s.filter("b == 2")
600
+ ScenarioList([Scenario({'a': 1, 'b': 2})])
601
+ """
602
+ sl = self.duplicate()
603
+ base_keys = set(self[0].keys())
604
+ keys = set()
605
+ for scenario in sl:
606
+ keys.update(scenario.keys())
607
+ if keys != base_keys:
608
+ import warnings
609
+
610
+ warnings.warn(
611
+ "Ragged ScenarioList detected (different keys for different scenario entries). This may cause unexpected behavior."
612
+ )
613
+
614
+ def create_evaluator(scenario: Scenario):
615
+ """Create an evaluator for the given result.
616
+ The 'combined_dict' is a mapping of all values for that Result object.
617
+ """
618
+ return EvalWithCompoundTypes(names=scenario)
619
+
620
+ try:
621
+ # iterates through all the results and evaluates the expression
622
+ new_data = []
623
+ for scenario in sl:
624
+ if create_evaluator(scenario).eval(expression):
625
+ new_data.append(scenario)
626
+ except NameNotDefined as e:
627
+ available_fields = ", ".join(self.data[0].keys() if self.data else [])
628
+ raise ScenarioError(
629
+ f"Error in filter: '{e}'\n"
630
+ f"The expression '{expression}' refers to a field that does not exist.\n"
631
+ f"Scenario: {scenario}\n"
632
+ f"Available fields: {available_fields}\n"
633
+ "Check your filter expression or consult the documentation: "
634
+ "https://docs.expectedparrot.com/en/latest/scenarios.html#module-edsl.scenarios.Scenario"
635
+ ) from None
636
+ except Exception as e:
637
+ raise ScenarioError(f"Error in filter. Exception:{e}")
638
+
639
+ return ScenarioList(new_data)
640
+
641
+ def from_urls(
642
+ self, urls: list[str], field_name: Optional[str] = "text"
643
+ ) -> ScenarioList:
644
+ """Create a ScenarioList from a list of URLs.
645
+
646
+ :param urls: A list of URLs.
647
+ :param field_name: The name of the field to store the text from the URLs.
648
+
649
+ """
650
+ return ScenarioList([Scenario.from_url(url, field_name) for url in urls])
651
+
652
+ def select(self, *fields: str) -> ScenarioList:
653
+ """
654
+ Selects scenarios with only the references fields.
655
+
656
+ :param fields: The fields to select.
657
+
658
+ Example:
659
+
660
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
661
+ >>> s.select('a')
662
+ ScenarioList([Scenario({'a': 1}), Scenario({'a': 1})])
663
+ """
664
+ from edsl.scenarios.scenario_selector import ScenarioSelector
665
+
666
+ return ScenarioSelector(self).select(*fields)
667
+
668
+ def drop(self, *fields: str) -> ScenarioList:
669
+ """Drop fields from the scenarios.
670
+
671
+ Example:
672
+
673
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
674
+ >>> s.drop('a')
675
+ ScenarioList([Scenario({'b': 1}), Scenario({'b': 2})])
676
+ """
677
+ sl = self.duplicate()
678
+ return ScenarioList([scenario.drop(fields) for scenario in sl])
679
+
680
+ def keep(self, *fields: str) -> ScenarioList:
681
+ """Keep only the specified fields in the scenarios.
682
+
683
+ :param fields: The fields to keep.
684
+
685
+ Example:
686
+
687
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 1}), Scenario({'a': 1, 'b': 2})])
688
+ >>> s.keep('a')
689
+ ScenarioList([Scenario({'a': 1}), Scenario({'a': 1})])
690
+ """
691
+ sl = self.duplicate()
692
+ return ScenarioList([scenario.keep(fields) for scenario in sl])
693
+
694
+ @classmethod
695
+ def from_list(
696
+ cls, name: str, values: list, func: Optional[Callable] = None
697
+ ) -> ScenarioList:
698
+ """Create a ScenarioList from a list of values.
699
+
700
+ :param name: The name of the field.
701
+ :param values: The list of values.
702
+ :param func: An optional function to apply to the values.
703
+
704
+ Example:
705
+
706
+ >>> ScenarioList.from_list('name', ['Alice', 'Bob'])
707
+ ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
708
+ """
709
+ if not func:
710
+ func = lambda x: x
711
+ return cls([Scenario({name: func(value)}) for value in values])
712
+
713
+ def table(
714
+ self,
715
+ *fields: str,
716
+ tablefmt: Optional[TableFormat] = None,
717
+ pretty_labels: Optional[dict[str, str]] = None,
718
+ ) -> str:
719
+ """Return the ScenarioList as a table."""
720
+
721
+ from tabulate import tabulate_formats
722
+
723
+ if tablefmt is not None and tablefmt not in tabulate_formats:
724
+ raise ValueError(
725
+ f"Invalid table format: {tablefmt}",
726
+ f"Valid formats are: {tabulate_formats}",
727
+ )
728
+ return self.to_dataset().table(
729
+ *fields, tablefmt=tablefmt, pretty_labels=pretty_labels
730
+ )
731
+
732
+ def tree(self, node_list: Optional[List[str]] = None) -> str:
733
+ """Return the ScenarioList as a tree.
734
+
735
+ :param node_list: The list of nodes to include in the tree.
736
+ """
737
+ return self.to_dataset().tree(node_list)
738
+
739
+ def _summary(self) -> dict:
740
+ """Return a summary of the ScenarioList.
741
+
742
+ >>> ScenarioList.example()._summary()
743
+ {'scenarios': 2, 'keys': ['persona']}
744
+ """
745
+ d = {
746
+ "scenarios": len(self),
747
+ "keys": list(self.parameters),
748
+ }
749
+ return d
750
+
751
+ def reorder_keys(self, new_order: List[str]) -> ScenarioList:
752
+ """Reorder the keys in the scenarios.
753
+
754
+ :param new_order: The new order of the keys.
755
+
756
+ Example:
757
+
758
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': 2}), Scenario({'a': 3, 'b': 4})])
759
+ >>> s.reorder_keys(['b', 'a'])
760
+ ScenarioList([Scenario({'b': 2, 'a': 1}), Scenario({'b': 4, 'a': 3})])
761
+ >>> s.reorder_keys(['a', 'b', 'c'])
762
+ Traceback (most recent call last):
763
+ ...
764
+ AssertionError
765
+ """
766
+ assert set(new_order) == set(self.parameters)
767
+
768
+ new_scenarios = []
769
+ for scenario in self:
770
+ new_scenario = Scenario({key: scenario[key] for key in new_order})
771
+ new_scenarios.append(new_scenario)
772
+ return ScenarioList(new_scenarios)
773
+
774
+ def to_dataset(self) -> "Dataset":
775
+ """
776
+ Convert the ScenarioList to a Dataset.
777
+
778
+ >>> s = ScenarioList.from_list("a", [1,2,3])
779
+ >>> s.to_dataset()
780
+ Dataset([{'a': [1, 2, 3]}])
781
+ >>> s = ScenarioList.from_list("a", [1,2,3]).add_list("b", [4,5,6])
782
+ >>> s.to_dataset()
783
+ Dataset([{'a': [1, 2, 3]}, {'b': [4, 5, 6]}])
784
+ """
785
+ from edsl.results.Dataset import Dataset
786
+
787
+ keys = list(self[0].keys())
788
+ for scenario in self:
789
+ new_keys = list(scenario.keys())
790
+ if new_keys != keys:
791
+ keys = list(set(keys + new_keys))
792
+ data = [
793
+ {key: [scenario.get(key, None) for scenario in self.data]} for key in keys
794
+ ]
795
+ return Dataset(data)
796
+
797
+ def unpack(
798
+ self, field: str, new_names: Optional[List[str]] = None, keep_original=True
799
+ ) -> ScenarioList:
800
+ """Unpack a field into multiple fields.
801
+
802
+ Example:
803
+
804
+ >>> s = ScenarioList([Scenario({'a': 1, 'b': [2, True]}), Scenario({'a': 3, 'b': [3, False]})])
805
+ >>> s.unpack('b')
806
+ ScenarioList([Scenario({'a': 1, 'b': [2, True], 'b_0': 2, 'b_1': True}), Scenario({'a': 3, 'b': [3, False], 'b_0': 3, 'b_1': False})])
807
+ >>> s.unpack('b', new_names=['c', 'd'], keep_original=False)
808
+ ScenarioList([Scenario({'a': 1, 'c': 2, 'd': True}), Scenario({'a': 3, 'c': 3, 'd': False})])
809
+
810
+ """
811
+ new_names = new_names or [f"{field}_{i}" for i in range(len(self[0][field]))]
812
+ new_scenarios = []
813
+ for scenario in self:
814
+ new_scenario = scenario.copy()
815
+ if len(new_names) == 1:
816
+ new_scenario[new_names[0]] = scenario[field]
817
+ else:
818
+ for i, new_name in enumerate(new_names):
819
+ new_scenario[new_name] = scenario[field][i]
820
+
821
+ if not keep_original:
822
+ del new_scenario[field]
823
+ new_scenarios.append(new_scenario)
824
+ return ScenarioList(new_scenarios)
825
+
826
+ @classmethod
827
+ def from_list_of_tuples(self, *names: str, values: List[Tuple]) -> ScenarioList:
828
+ sl = ScenarioList.from_list(names[0], [value[0] for value in values])
829
+ for index, name in enumerate(names[1:]):
830
+ sl = sl.add_list(name, [value[index + 1] for value in values])
831
+ return sl
832
+
833
+ def add_list(self, name: str, values: List[Any]) -> ScenarioList:
834
+ """Add a list of values to a ScenarioList.
835
+
836
+ Example:
837
+
838
+ >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
839
+ >>> s.add_list('age', [30, 25])
840
+ ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
841
+ """
842
+ sl = self.duplicate()
843
+ if len(values) != len(sl):
844
+ raise ScenarioError(
845
+ f"Length of values ({len(values)}) does not match length of ScenarioList ({len(sl)})"
846
+ )
847
+ for i, value in enumerate(values):
848
+ sl[i][name] = value
849
+ return sl
850
+
851
+ @classmethod
852
+ def create_empty_scenario_list(cls, n: int) -> ScenarioList:
853
+ """Create an empty ScenarioList with n scenarios.
854
+
855
+ Example:
856
+
857
+ >>> ScenarioList.create_empty_scenario_list(3)
858
+ ScenarioList([Scenario({}), Scenario({}), Scenario({})])
859
+ """
860
+ return ScenarioList([Scenario({}) for _ in range(n)])
861
+
862
+ def add_value(self, name: str, value: Any) -> ScenarioList:
863
+ """Add a value to all scenarios in a ScenarioList.
864
+
865
+ Example:
866
+
867
+ >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
868
+ >>> s.add_value('age', 30)
869
+ ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 30})])
870
+ """
871
+ sl = self.duplicate()
872
+ for scenario in sl:
873
+ scenario[name] = value
874
+ return sl
875
+
876
+ def rename(self, replacement_dict: dict) -> ScenarioList:
877
+ """Rename the fields in the scenarios.
878
+
879
+ :param replacement_dict: A dictionary with the old names as keys and the new names as values.
880
+
881
+ Example:
882
+
883
+ >>> s = ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
884
+ >>> s.rename({'name': 'first_name', 'age': 'years'})
885
+ ScenarioList([Scenario({'first_name': 'Alice', 'years': 30}), Scenario({'first_name': 'Bob', 'years': 25})])
886
+
887
+ """
888
+
889
+ new_list = ScenarioList([])
890
+ for obj in self:
891
+ new_obj = obj.rename(replacement_dict)
892
+ new_list.append(new_obj)
893
+ return new_list
894
+
895
+ ## NEEDS TO BE FIXED
896
+ # def new_column_names(self, new_names: List[str]) -> ScenarioList:
897
+ # """Rename the fields in the scenarios.
898
+
899
+ # Example:
900
+
901
+ # >>> s = ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
902
+ # >>> s.new_column_names(['first_name', 'years'])
903
+ # ScenarioList([Scenario({'first_name': 'Alice', 'years': 30}), Scenario({'first_name': 'Bob', 'years': 25})])
904
+
905
+ # """
906
+ # new_list = ScenarioList([])
907
+ # for obj in self:
908
+ # new_obj = obj.new_column_names(new_names)
909
+ # new_list.append(new_obj)
910
+ # return new_list
911
+
912
+ @classmethod
913
+ def from_sqlite(cls, filepath: str, table: str):
914
+ """Create a ScenarioList from a SQLite database."""
915
+ import sqlite3
916
+
917
+ with sqlite3.connect(filepath) as conn:
918
+ cursor = conn.cursor()
919
+ cursor.execute(f"SELECT * FROM {table}")
920
+ columns = [description[0] for description in cursor.description]
921
+ data = cursor.fetchall()
922
+ return cls([Scenario(dict(zip(columns, row))) for row in data])
923
+
924
+ @classmethod
925
+ def from_latex(cls, tex_file_path: str):
926
+ with open(tex_file_path, "r") as file:
927
+ lines = file.readlines()
928
+
929
+ processed_lines = []
930
+ non_blank_lines = [
931
+ (i, line.strip()) for i, line in enumerate(lines) if line.strip()
932
+ ]
933
+
934
+ for index, (line_no, text) in enumerate(non_blank_lines):
935
+ entry = {
936
+ "line_no": line_no + 1, # Using 1-based index for line numbers
937
+ "text": text,
938
+ "line_before": non_blank_lines[index - 1][1] if index > 0 else None,
939
+ "line_after": (
940
+ non_blank_lines[index + 1][1]
941
+ if index < len(non_blank_lines) - 1
942
+ else None
943
+ ),
944
+ }
945
+ processed_lines.append(entry)
946
+
947
+ return ScenarioList([Scenario(entry) for entry in processed_lines])
948
+
949
+ @classmethod
950
+ def from_google_doc(cls, url: str) -> ScenarioList:
951
+ """Create a ScenarioList from a Google Doc.
952
+
953
+ This method downloads the Google Doc as a Word file (.docx), saves it to a temporary file,
954
+ and then reads it using the from_docx class method.
955
+
956
+ Args:
957
+ url (str): The URL to the Google Doc.
958
+
959
+ Returns:
960
+ ScenarioList: An instance of the ScenarioList class.
961
+
962
+ """
963
+ import tempfile
964
+ import requests
965
+ from docx import Document
966
+
967
+ if "/edit" in url:
968
+ doc_id = url.split("/d/")[1].split("/edit")[0]
969
+ else:
970
+ raise ValueError("Invalid Google Doc URL format.")
971
+
972
+ export_url = f"https://docs.google.com/document/d/{doc_id}/export?format=docx"
973
+
974
+ # Download the Google Doc as a Word file (.docx)
975
+ response = requests.get(export_url)
976
+ response.raise_for_status() # Ensure the request was successful
977
+
978
+ # Save the Word file to a temporary file
979
+ with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as temp_file:
980
+ temp_file.write(response.content)
981
+ temp_filename = temp_file.name
982
+
983
+ # Call the from_docx class method with the temporary file
984
+ return cls.from_docx(temp_filename)
985
+
986
+ @classmethod
987
+ def from_pandas(cls, df) -> ScenarioList:
988
+ """Create a ScenarioList from a pandas DataFrame.
989
+
990
+ Example:
991
+
992
+ >>> import pandas as pd
993
+ >>> df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 25], 'location': ['New York', 'Los Angeles']})
994
+ >>> ScenarioList.from_pandas(df)
995
+ ScenarioList([Scenario({'name': 'Alice', 'age': 30, 'location': 'New York'}), Scenario({'name': 'Bob', 'age': 25, 'location': 'Los Angeles'})])
996
+ """
997
+ return cls([Scenario(row) for row in df.to_dict(orient="records")])
998
+
999
+ @classmethod
1000
+ def from_wikipedia(cls, url: str, table_index: int = 0):
1001
+ """
1002
+ Extracts a table from a Wikipedia page.
1003
+
1004
+ Parameters:
1005
+ url (str): The URL of the Wikipedia page.
1006
+ table_index (int): The index of the table to extract (default is 0).
1007
+
1008
+ Returns:
1009
+ pd.DataFrame: A DataFrame containing the extracted table.
1010
+ # # Example usage
1011
+ # url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
1012
+ # df = from_wikipedia(url, 0)
1013
+
1014
+ # if not df.empty:
1015
+ # print(df.head())
1016
+ # else:
1017
+ # print("Failed to extract table.")
1018
+
1019
+
1020
+ """
1021
+ import pandas as pd
1022
+ import requests
1023
+ from requests.exceptions import RequestException
1024
+
1025
+ try:
1026
+ # Check if the URL is reachable
1027
+ response = requests.get(url)
1028
+ response.raise_for_status() # Raises HTTPError for bad responses
1029
+
1030
+ # Extract tables from the Wikipedia page
1031
+ tables = pd.read_html(url)
1032
+
1033
+ # Ensure the requested table index is within the range of available tables
1034
+ if table_index >= len(tables) or table_index < 0:
1035
+ raise IndexError(
1036
+ f"Table index {table_index} is out of range. This page has {len(tables)} table(s)."
1037
+ )
1038
+
1039
+ # Return the requested table as a DataFrame
1040
+ # return tables[table_index]
1041
+ return cls.from_pandas(tables[table_index])
1042
+
1043
+ except RequestException as e:
1044
+ print(f"Error fetching the URL: {e}")
1045
+ except ValueError as e:
1046
+ print(f"Error parsing tables: {e}")
1047
+ except IndexError as e:
1048
+ print(e)
1049
+ except Exception as e:
1050
+ print(f"An unexpected error occurred: {e}")
1051
+
1052
+ # Return an empty DataFrame in case of an error
1053
+ # return cls.from_pandas(pd.DataFrame())
1054
+
1055
+ def to_key_value(self, field: str, value=None) -> Union[dict, set]:
1056
+ """Return the set of values in the field.
1057
+
1058
+ :param field: The field to extract values from.
1059
+ :param value: An optional field to use as the value in the key-value pair.
1060
+
1061
+ Example:
1062
+
1063
+ >>> s = ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
1064
+ >>> s.to_key_value('name') == {'Alice', 'Bob'}
1065
+ True
1066
+ """
1067
+ if value is None:
1068
+ return {scenario[field] for scenario in self}
1069
+ else:
1070
+ return {scenario[field]: scenario[value] for scenario in self}
1071
+
1072
+ @classmethod
1073
+ def from_excel(
1074
+ cls, filename: str, sheet_name: Optional[str] = None
1075
+ ) -> ScenarioList:
1076
+ """Create a ScenarioList from an Excel file.
1077
+
1078
+ If the Excel file contains multiple sheets and no sheet_name is provided,
1079
+ the method will print the available sheets and require the user to specify one.
1080
+
1081
+ Example:
1082
+
1083
+ >>> import tempfile
1084
+ >>> import os
1085
+ >>> import pandas as pd
1086
+ >>> with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as f:
1087
+ ... df1 = pd.DataFrame({
1088
+ ... 'name': ['Alice', 'Bob'],
1089
+ ... 'age': [30, 25],
1090
+ ... 'location': ['New York', 'Los Angeles']
1091
+ ... })
1092
+ ... df2 = pd.DataFrame({
1093
+ ... 'name': ['Charlie', 'David'],
1094
+ ... 'age': [35, 40],
1095
+ ... 'location': ['Chicago', 'Boston']
1096
+ ... })
1097
+ ... with pd.ExcelWriter(f.name) as writer:
1098
+ ... df1.to_excel(writer, sheet_name='Sheet1', index=False)
1099
+ ... df2.to_excel(writer, sheet_name='Sheet2', index=False)
1100
+ ... temp_filename = f.name
1101
+ >>> scenario_list = ScenarioList.from_excel(temp_filename, sheet_name='Sheet1')
1102
+ >>> len(scenario_list)
1103
+ 2
1104
+ >>> scenario_list[0]['name']
1105
+ 'Alice'
1106
+ >>> scenario_list = ScenarioList.from_excel(temp_filename) # Should raise an error and list sheets
1107
+ Traceback (most recent call last):
1108
+ ...
1109
+ ValueError: Please provide a sheet name to load data from.
1110
+ """
1111
+ from edsl.scenarios.Scenario import Scenario
1112
+ import pandas as pd
1113
+
1114
+ # Get all sheets
1115
+ all_sheets = pd.read_excel(filename, sheet_name=None)
1116
+
1117
+ # If no sheet_name is provided and there is more than one sheet, print available sheets
1118
+ if sheet_name is None:
1119
+ if len(all_sheets) > 1:
1120
+ print("The Excel file contains multiple sheets:")
1121
+ for name in all_sheets.keys():
1122
+ print(f"- {name}")
1123
+ raise ValueError("Please provide a sheet name to load data from.")
1124
+ else:
1125
+ # If there is only one sheet, use it
1126
+ sheet_name = list(all_sheets.keys())[0]
1127
+
1128
+ # Load the specified or determined sheet
1129
+ df = pd.read_excel(filename, sheet_name=sheet_name)
1130
+
1131
+ observations = []
1132
+ for _, row in df.iterrows():
1133
+ observations.append(Scenario(row.to_dict()))
1134
+
1135
+ return cls(observations)
1136
+
1137
+ @classmethod
1138
+ def from_google_sheet(cls, url: str, sheet_name: str = None) -> ScenarioList:
1139
+ """Create a ScenarioList from a Google Sheet.
1140
+
1141
+ This method downloads the Google Sheet as an Excel file, saves it to a temporary file,
1142
+ and then reads it using the from_excel class method.
1143
+
1144
+ Args:
1145
+ url (str): The URL to the Google Sheet.
1146
+ sheet_name (str, optional): The name of the sheet to load. If None, the method will behave
1147
+ the same as from_excel regarding multiple sheets.
1148
+
1149
+ Returns:
1150
+ ScenarioList: An instance of the ScenarioList class.
1151
+
1152
+ """
1153
+ import pandas as pd
1154
+ import tempfile
1155
+ import requests
1156
+
1157
+ if "/edit" in url:
1158
+ sheet_id = url.split("/d/")[1].split("/edit")[0]
1159
+ else:
1160
+ raise ValueError("Invalid Google Sheet URL format.")
1161
+
1162
+ export_url = (
1163
+ f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
1164
+ )
1165
+
1166
+ # Download the Google Sheet as an Excel file
1167
+ response = requests.get(export_url)
1168
+ response.raise_for_status() # Ensure the request was successful
1169
+
1170
+ # Save the Excel file to a temporary file
1171
+ with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as temp_file:
1172
+ temp_file.write(response.content)
1173
+ temp_filename = temp_file.name
1174
+
1175
+ # Call the from_excel class method with the temporary file
1176
+ return cls.from_excel(temp_filename, sheet_name=sheet_name)
1177
+
1178
+ @classmethod
1179
+ def from_delimited_file(
1180
+ cls, source: Union[str, "ParseResult"], delimiter: str = ","
1181
+ ) -> ScenarioList:
1182
+ """Create a ScenarioList from a delimited file (CSV/TSV) or URL."""
1183
+ import requests
1184
+ from edsl.scenarios.Scenario import Scenario
1185
+ from urllib.parse import urlparse
1186
+ from urllib.parse import ParseResult
1187
+
1188
+ headers = {
1189
+ "Accept": "text/csv,application/csv,text/plain",
1190
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
1191
+ }
1192
+
1193
+ def is_url(source):
1194
+ try:
1195
+ result = urlparse(source)
1196
+ return all([result.scheme, result.netloc])
1197
+ except ValueError:
1198
+ return False
1199
+
1200
+ try:
1201
+ if isinstance(source, str) and is_url(source):
1202
+ response = requests.get(source, headers=headers)
1203
+ response.raise_for_status()
1204
+ file_obj = StringIO(response.text)
1205
+ elif isinstance(source, ParseResult):
1206
+ response = requests.get(source.geturl(), headers=headers)
1207
+ response.raise_for_status()
1208
+ file_obj = StringIO(response.text)
1209
+ else:
1210
+ file_obj = open(source, "r")
1211
+
1212
+ reader = csv.reader(file_obj, delimiter=delimiter)
1213
+ header = next(reader)
1214
+ observations = [Scenario(dict(zip(header, row))) for row in reader]
1215
+
1216
+ finally:
1217
+ file_obj.close()
1218
+
1219
+ return cls(observations)
1220
+
1221
+ # Convenience methods for specific file types
1222
+ @classmethod
1223
+ def from_csv(cls, source: Union[str, "ParseResult"]) -> ScenarioList:
1224
+ """Create a ScenarioList from a CSV file or URL."""
1225
+ return cls.from_delimited_file(source, delimiter=",")
1226
+
1227
+ def left_join(self, other: ScenarioList, by: Union[str, list[str]]) -> ScenarioList:
1228
+ """Perform a left join with another ScenarioList, following SQL join semantics.
1229
+
1230
+ Args:
1231
+ other: The ScenarioList to join with
1232
+ by: String or list of strings representing the key(s) to join on. Cannot be empty.
1233
+
1234
+ >>> s1 = ScenarioList([Scenario({'name': 'Alice', 'age': 30}), Scenario({'name': 'Bob', 'age': 25})])
1235
+ >>> s2 = ScenarioList([Scenario({'name': 'Alice', 'location': 'New York'}), Scenario({'name': 'Charlie', 'location': 'Los Angeles'})])
1236
+ >>> s3 = s1.left_join(s2, 'name')
1237
+ >>> s3 == ScenarioList([Scenario({'age': 30, 'location': 'New York', 'name': 'Alice'}), Scenario({'age': 25, 'location': None, 'name': 'Bob'})])
1238
+ True
1239
+ """
1240
+ from edsl.scenarios.scenario_join import ScenarioJoin
1241
+
1242
+ sj = ScenarioJoin(self, other)
1243
+ return sj.left_join(by)
1244
+
1245
+ @classmethod
1246
+ def from_tsv(cls, source: Union[str, "ParseResult"]) -> ScenarioList:
1247
+ """Create a ScenarioList from a TSV file or URL."""
1248
+ return cls.from_delimited_file(source, delimiter="\t")
1249
+
1250
+ def to_dict(self, sort: bool = False, add_edsl_version: bool = True) -> dict:
1251
+ """
1252
+ >>> s = ScenarioList([Scenario({'food': 'wood chips'}), Scenario({'food': 'wood-fired pizza'})])
1253
+ >>> s.to_dict()
1254
+ {'scenarios': [{'food': 'wood chips', 'edsl_version': '...', 'edsl_class_name': 'Scenario'}, {'food': 'wood-fired pizza', 'edsl_version': '...', 'edsl_class_name': 'Scenario'}], 'edsl_version': '...', 'edsl_class_name': 'ScenarioList'}
1255
+
1256
+ """
1257
+ if sort:
1258
+ data = sorted(self, key=lambda x: hash(x))
1259
+ else:
1260
+ data = self
1261
+ d = {"scenarios": [s.to_dict(add_edsl_version=add_edsl_version) for s in data]}
1262
+
1263
+ if add_edsl_version:
1264
+ from edsl import __version__
1265
+
1266
+ d["edsl_version"] = __version__
1267
+ d["edsl_class_name"] = self.__class__.__name__
1268
+ return d
1269
+
1270
+ def to(self, survey: Union["Survey", "QuestionBase"]) -> "Jobs":
1271
+ """Create a Jobs object from a ScenarioList and a Survey object.
1272
+
1273
+ :param survey: The Survey object to use for the Jobs object.
1274
+
1275
+ Example:
1276
+ >>> from edsl import Survey
1277
+ >>> from edsl.jobs.Jobs import Jobs
1278
+ >>> from edsl import ScenarioList
1279
+ >>> isinstance(ScenarioList.example().to(Survey.example()), Jobs)
1280
+ True
1281
+ """
1282
+ from edsl.surveys.Survey import Survey
1283
+ from edsl.questions.QuestionBase import QuestionBase
1284
+ from edsl.jobs.Jobs import Jobs
1285
+
1286
+ if isinstance(survey, QuestionBase):
1287
+ return Survey([survey]).by(self)
1288
+ else:
1289
+ return survey.by(self)
1290
+
1291
+ @classmethod
1292
+ def gen(cls, scenario_dicts_list: List[dict]) -> ScenarioList:
1293
+ """Create a `ScenarioList` from a list of dictionaries.
1294
+
1295
+ Example:
1296
+
1297
+ >>> ScenarioList.gen([{'name': 'Alice'}, {'name': 'Bob'}])
1298
+ ScenarioList([Scenario({'name': 'Alice'}), Scenario({'name': 'Bob'})])
1299
+
1300
+ """
1301
+ from edsl.scenarios.Scenario import Scenario
1302
+
1303
+ return cls([Scenario(s) for s in scenario_dicts_list])
1304
+
1305
+ @classmethod
1306
+ @remove_edsl_version
1307
+ def from_dict(cls, data) -> ScenarioList:
1308
+ """Create a `ScenarioList` from a dictionary."""
1309
+ from edsl.scenarios.Scenario import Scenario
1310
+
1311
+ return cls([Scenario.from_dict(s) for s in data["scenarios"]])
1312
+
1313
+ @classmethod
1314
+ def from_nested_dict(cls, data: dict) -> ScenarioList:
1315
+ """Create a `ScenarioList` from a nested dictionary.
1316
+
1317
+ >>> data = {"headline": ["Armistice Signed, War Over: Celebrations Erupt Across City"], "date": ["1918-11-11"], "author": ["Jane Smith"]}
1318
+ >>> ScenarioList.from_nested_dict(data)
1319
+ ScenarioList([Scenario({'headline': 'Armistice Signed, War Over: Celebrations Erupt Across City', 'date': '1918-11-11', 'author': 'Jane Smith'})])
1320
+
1321
+ """
1322
+ length_of_first_list = len(next(iter(data.values())))
1323
+ s = ScenarioList.create_empty_scenario_list(n=length_of_first_list)
1324
+
1325
+ if any(len(v) != length_of_first_list for v in data.values()):
1326
+ raise ValueError(
1327
+ "All lists in the dictionary must be of the same length.",
1328
+ )
1329
+ for key, list_of_values in data.items():
1330
+ s = s.add_list(key, list_of_values)
1331
+ return s
1332
+
1333
+ def code(self) -> str:
1334
+ """Create the Python code representation of a survey."""
1335
+ header_lines = [
1336
+ "from edsl.scenarios.Scenario import Scenario",
1337
+ "from edsl.scenarios.ScenarioList import ScenarioList",
1338
+ ]
1339
+ lines = ["\n".join(header_lines)]
1340
+ names = []
1341
+ for index, scenario in enumerate(self):
1342
+ lines.append(f"scenario_{index} = " + repr(scenario))
1343
+ names.append(f"scenario_{index}")
1344
+ lines.append(f"scenarios = ScenarioList([{', '.join(names)}])")
1345
+ return lines
1346
+
1347
+ @classmethod
1348
+ def example(cls, randomize: bool = False) -> ScenarioList:
1349
+ """
1350
+ Return an example ScenarioList instance.
1351
+
1352
+ :params randomize: If True, use Scenario's randomize method to randomize the values.
1353
+ """
1354
+ return cls([Scenario.example(randomize), Scenario.example(randomize)])
1355
+
1356
+ # def rich_print(self) -> None:
1357
+ # """Display an object as a table."""
1358
+ # from rich.table import Table
1359
+
1360
+ # table = Table(title="ScenarioList")
1361
+ # table.add_column("Index", style="bold")
1362
+ # table.add_column("Scenario")
1363
+ # for i, s in enumerate(self):
1364
+ # table.add_row(str(i), s.rich_print())
1365
+ # return table
1366
+
1367
+ def __getitem__(self, key: Union[int, slice]) -> Any:
1368
+ """Return the item at the given index.
1369
+
1370
+ Example:
1371
+ >>> s = ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5}), Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1372
+ >>> s[0]
1373
+ Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})
1374
+
1375
+ >>> s[:1]
1376
+ ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1377
+
1378
+ """
1379
+ if isinstance(key, slice):
1380
+ return ScenarioList(super().__getitem__(key))
1381
+ elif isinstance(key, int):
1382
+ return super().__getitem__(key)
1383
+ else:
1384
+ return self.to_dict(add_edsl_version=False)[key]
1385
+
1386
+ def to_agent_list(self):
1387
+ """Convert the ScenarioList to an AgentList.
1388
+
1389
+ Example:
1390
+
1391
+ >>> s = ScenarioList([Scenario({'age': 22, 'hair': 'brown', 'height': 5.5}), Scenario({'age': 22, 'hair': 'brown', 'height': 5.5})])
1392
+ >>> s.to_agent_list()
1393
+ AgentList([Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5}), Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5})])
1394
+ """
1395
+ from edsl.agents.AgentList import AgentList
1396
+ from edsl.agents.Agent import Agent
1397
+ import warnings
1398
+
1399
+ agents = []
1400
+ for scenario in self:
1401
+ new_scenario = scenario.copy().data
1402
+ if "name" in new_scenario:
1403
+ name = new_scenario.pop("name")
1404
+ proposed_agent_name = "agent_name"
1405
+ while proposed_agent_name not in new_scenario:
1406
+ proposed_agent_name += "_"
1407
+ warnings.warn(
1408
+ f"The 'name' field is reserved for the agent's name---putting this value in {proposed_agent_name}"
1409
+ )
1410
+ new_scenario[proposed_agent_name] = name
1411
+ new_agent = Agent(traits=new_scenario, name=name)
1412
+ if "agent_parameters" in new_scenario:
1413
+ agent_parameters = new_scenario.pop("agent_parameters")
1414
+ instruction = agent_parameters.get("instruction", None)
1415
+ name = agent_parameters.get("name", None)
1416
+ new_agent = Agent(
1417
+ traits=new_scenario, name=name, instruction=instruction
1418
+ )
1419
+ else:
1420
+ new_agent = Agent(traits=new_scenario)
1421
+
1422
+ agents.append(new_agent)
1423
+
1424
+ return AgentList(agents)
1425
+
1426
+ def chunk(
1427
+ self,
1428
+ field,
1429
+ num_words: Optional[int] = None,
1430
+ num_lines: Optional[int] = None,
1431
+ include_original=False,
1432
+ hash_original=False,
1433
+ ) -> "ScenarioList":
1434
+ """Chunk the scenarios based on a field.
1435
+
1436
+ Example:
1437
+
1438
+ >>> s = ScenarioList([Scenario({'text': 'The quick brown fox jumps over the lazy dog.'})])
1439
+ >>> s.chunk('text', num_words=3)
1440
+ ScenarioList([Scenario({'text': 'The quick brown', 'text_chunk': 0}), Scenario({'text': 'fox jumps over', 'text_chunk': 1}), Scenario({'text': 'the lazy dog.', 'text_chunk': 2})])
1441
+ """
1442
+ new_scenarios = []
1443
+ for scenario in self:
1444
+ replacement_scenarios = scenario.chunk(
1445
+ field,
1446
+ num_words=num_words,
1447
+ num_lines=num_lines,
1448
+ include_original=include_original,
1449
+ hash_original=hash_original,
1450
+ )
1451
+ new_scenarios.extend(replacement_scenarios)
1452
+ return ScenarioList(new_scenarios)
1453
+
1454
+
1455
+ if __name__ == "__main__":
1456
+ import doctest
1457
+
1458
+ doctest.testmod(optionflags=doctest.ELLIPSIS)