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