edsl 0.1.37.dev5__py3-none-any.whl → 0.1.37.dev6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. edsl/Base.py +303 -303
  2. edsl/BaseDiff.py +260 -260
  3. edsl/TemplateLoader.py +24 -24
  4. edsl/__init__.py +48 -48
  5. edsl/__version__.py +1 -1
  6. edsl/agents/Agent.py +855 -855
  7. edsl/agents/AgentList.py +350 -350
  8. edsl/agents/Invigilator.py +222 -222
  9. edsl/agents/InvigilatorBase.py +284 -284
  10. edsl/agents/PromptConstructor.py +353 -353
  11. edsl/agents/__init__.py +3 -3
  12. edsl/agents/descriptors.py +99 -99
  13. edsl/agents/prompt_helpers.py +129 -129
  14. edsl/auto/AutoStudy.py +117 -117
  15. edsl/auto/StageBase.py +230 -230
  16. edsl/auto/StageGenerateSurvey.py +178 -178
  17. edsl/auto/StageLabelQuestions.py +125 -125
  18. edsl/auto/StagePersona.py +61 -61
  19. edsl/auto/StagePersonaDimensionValueRanges.py +88 -88
  20. edsl/auto/StagePersonaDimensionValues.py +74 -74
  21. edsl/auto/StagePersonaDimensions.py +69 -69
  22. edsl/auto/StageQuestions.py +73 -73
  23. edsl/auto/SurveyCreatorPipeline.py +21 -21
  24. edsl/auto/utilities.py +224 -224
  25. edsl/base/Base.py +289 -289
  26. edsl/config.py +149 -149
  27. edsl/conjure/AgentConstructionMixin.py +160 -160
  28. edsl/conjure/Conjure.py +62 -62
  29. edsl/conjure/InputData.py +659 -659
  30. edsl/conjure/InputDataCSV.py +48 -48
  31. edsl/conjure/InputDataMixinQuestionStats.py +182 -182
  32. edsl/conjure/InputDataPyRead.py +91 -91
  33. edsl/conjure/InputDataSPSS.py +8 -8
  34. edsl/conjure/InputDataStata.py +8 -8
  35. edsl/conjure/QuestionOptionMixin.py +76 -76
  36. edsl/conjure/QuestionTypeMixin.py +23 -23
  37. edsl/conjure/RawQuestion.py +65 -65
  38. edsl/conjure/SurveyResponses.py +7 -7
  39. edsl/conjure/__init__.py +9 -9
  40. edsl/conjure/naming_utilities.py +263 -263
  41. edsl/conjure/utilities.py +201 -201
  42. edsl/conversation/Conversation.py +290 -290
  43. edsl/conversation/car_buying.py +58 -58
  44. edsl/conversation/chips.py +95 -95
  45. edsl/conversation/mug_negotiation.py +81 -81
  46. edsl/conversation/next_speaker_utilities.py +93 -93
  47. edsl/coop/PriceFetcher.py +54 -54
  48. edsl/coop/__init__.py +2 -2
  49. edsl/coop/coop.py +958 -958
  50. edsl/coop/utils.py +131 -131
  51. edsl/data/Cache.py +527 -527
  52. edsl/data/CacheEntry.py +228 -228
  53. edsl/data/CacheHandler.py +149 -149
  54. edsl/data/RemoteCacheSync.py +97 -97
  55. edsl/data/SQLiteDict.py +292 -292
  56. edsl/data/__init__.py +4 -4
  57. edsl/data/orm.py +10 -10
  58. edsl/data_transfer_models.py +73 -73
  59. edsl/enums.py +173 -173
  60. edsl/exceptions/BaseException.py +21 -21
  61. edsl/exceptions/__init__.py +54 -54
  62. edsl/exceptions/agents.py +38 -38
  63. edsl/exceptions/configuration.py +16 -16
  64. edsl/exceptions/coop.py +10 -10
  65. edsl/exceptions/data.py +14 -14
  66. edsl/exceptions/general.py +34 -34
  67. edsl/exceptions/jobs.py +33 -33
  68. edsl/exceptions/language_models.py +63 -63
  69. edsl/exceptions/prompts.py +15 -15
  70. edsl/exceptions/questions.py +91 -91
  71. edsl/exceptions/results.py +29 -29
  72. edsl/exceptions/scenarios.py +22 -22
  73. edsl/exceptions/surveys.py +37 -37
  74. edsl/inference_services/AnthropicService.py +87 -87
  75. edsl/inference_services/AwsBedrock.py +120 -120
  76. edsl/inference_services/AzureAI.py +217 -217
  77. edsl/inference_services/DeepInfraService.py +18 -18
  78. edsl/inference_services/GoogleService.py +156 -156
  79. edsl/inference_services/GroqService.py +20 -20
  80. edsl/inference_services/InferenceServiceABC.py +147 -147
  81. edsl/inference_services/InferenceServicesCollection.py +97 -97
  82. edsl/inference_services/MistralAIService.py +123 -123
  83. edsl/inference_services/OllamaService.py +18 -18
  84. edsl/inference_services/OpenAIService.py +224 -224
  85. edsl/inference_services/TestService.py +89 -89
  86. edsl/inference_services/TogetherAIService.py +170 -170
  87. edsl/inference_services/models_available_cache.py +118 -118
  88. edsl/inference_services/rate_limits_cache.py +25 -25
  89. edsl/inference_services/registry.py +39 -39
  90. edsl/inference_services/write_available.py +10 -10
  91. edsl/jobs/Answers.py +56 -56
  92. edsl/jobs/Jobs.py +1347 -1347
  93. edsl/jobs/__init__.py +1 -1
  94. edsl/jobs/buckets/BucketCollection.py +63 -63
  95. edsl/jobs/buckets/ModelBuckets.py +65 -65
  96. edsl/jobs/buckets/TokenBucket.py +248 -248
  97. edsl/jobs/interviews/Interview.py +661 -661
  98. edsl/jobs/interviews/InterviewExceptionCollection.py +99 -99
  99. edsl/jobs/interviews/InterviewExceptionEntry.py +186 -186
  100. edsl/jobs/interviews/InterviewStatistic.py +63 -63
  101. edsl/jobs/interviews/InterviewStatisticsCollection.py +25 -25
  102. edsl/jobs/interviews/InterviewStatusDictionary.py +78 -78
  103. edsl/jobs/interviews/InterviewStatusLog.py +92 -92
  104. edsl/jobs/interviews/ReportErrors.py +66 -66
  105. edsl/jobs/interviews/interview_status_enum.py +9 -9
  106. edsl/jobs/runners/JobsRunnerAsyncio.py +338 -338
  107. edsl/jobs/runners/JobsRunnerStatus.py +332 -332
  108. edsl/jobs/tasks/QuestionTaskCreator.py +242 -242
  109. edsl/jobs/tasks/TaskCreators.py +64 -64
  110. edsl/jobs/tasks/TaskHistory.py +442 -442
  111. edsl/jobs/tasks/TaskStatusLog.py +23 -23
  112. edsl/jobs/tasks/task_status_enum.py +163 -163
  113. edsl/jobs/tokens/InterviewTokenUsage.py +27 -27
  114. edsl/jobs/tokens/TokenUsage.py +34 -34
  115. edsl/language_models/KeyLookup.py +30 -30
  116. edsl/language_models/LanguageModel.py +706 -706
  117. edsl/language_models/ModelList.py +102 -102
  118. edsl/language_models/RegisterLanguageModelsMeta.py +184 -184
  119. edsl/language_models/__init__.py +3 -3
  120. edsl/language_models/fake_openai_call.py +15 -15
  121. edsl/language_models/fake_openai_service.py +61 -61
  122. edsl/language_models/registry.py +137 -137
  123. edsl/language_models/repair.py +156 -156
  124. edsl/language_models/unused/ReplicateBase.py +83 -83
  125. edsl/language_models/utilities.py +64 -64
  126. edsl/notebooks/Notebook.py +259 -259
  127. edsl/notebooks/__init__.py +1 -1
  128. edsl/prompts/Prompt.py +357 -357
  129. edsl/prompts/__init__.py +2 -2
  130. edsl/questions/AnswerValidatorMixin.py +289 -289
  131. edsl/questions/QuestionBase.py +656 -656
  132. edsl/questions/QuestionBaseGenMixin.py +161 -161
  133. edsl/questions/QuestionBasePromptsMixin.py +234 -234
  134. edsl/questions/QuestionBudget.py +227 -227
  135. edsl/questions/QuestionCheckBox.py +359 -359
  136. edsl/questions/QuestionExtract.py +183 -183
  137. edsl/questions/QuestionFreeText.py +114 -114
  138. edsl/questions/QuestionFunctional.py +159 -159
  139. edsl/questions/QuestionList.py +231 -231
  140. edsl/questions/QuestionMultipleChoice.py +286 -286
  141. edsl/questions/QuestionNumerical.py +153 -153
  142. edsl/questions/QuestionRank.py +324 -324
  143. edsl/questions/Quick.py +41 -41
  144. edsl/questions/RegisterQuestionsMeta.py +71 -71
  145. edsl/questions/ResponseValidatorABC.py +174 -174
  146. edsl/questions/SimpleAskMixin.py +73 -73
  147. edsl/questions/__init__.py +26 -26
  148. edsl/questions/compose_questions.py +98 -98
  149. edsl/questions/decorators.py +21 -21
  150. edsl/questions/derived/QuestionLikertFive.py +76 -76
  151. edsl/questions/derived/QuestionLinearScale.py +87 -87
  152. edsl/questions/derived/QuestionTopK.py +91 -91
  153. edsl/questions/derived/QuestionYesNo.py +82 -82
  154. edsl/questions/descriptors.py +413 -413
  155. edsl/questions/prompt_templates/question_budget.jinja +13 -13
  156. edsl/questions/prompt_templates/question_checkbox.jinja +32 -32
  157. edsl/questions/prompt_templates/question_extract.jinja +11 -11
  158. edsl/questions/prompt_templates/question_free_text.jinja +3 -3
  159. edsl/questions/prompt_templates/question_linear_scale.jinja +11 -11
  160. edsl/questions/prompt_templates/question_list.jinja +17 -17
  161. edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -33
  162. edsl/questions/prompt_templates/question_numerical.jinja +36 -36
  163. edsl/questions/question_registry.py +147 -147
  164. edsl/questions/settings.py +12 -12
  165. edsl/questions/templates/budget/answering_instructions.jinja +7 -7
  166. edsl/questions/templates/budget/question_presentation.jinja +7 -7
  167. edsl/questions/templates/checkbox/answering_instructions.jinja +10 -10
  168. edsl/questions/templates/checkbox/question_presentation.jinja +22 -22
  169. edsl/questions/templates/extract/answering_instructions.jinja +7 -7
  170. edsl/questions/templates/likert_five/answering_instructions.jinja +10 -10
  171. edsl/questions/templates/likert_five/question_presentation.jinja +11 -11
  172. edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -5
  173. edsl/questions/templates/linear_scale/question_presentation.jinja +5 -5
  174. edsl/questions/templates/list/answering_instructions.jinja +3 -3
  175. edsl/questions/templates/list/question_presentation.jinja +5 -5
  176. edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -9
  177. edsl/questions/templates/multiple_choice/question_presentation.jinja +11 -11
  178. edsl/questions/templates/numerical/answering_instructions.jinja +6 -6
  179. edsl/questions/templates/numerical/question_presentation.jinja +6 -6
  180. edsl/questions/templates/rank/answering_instructions.jinja +11 -11
  181. edsl/questions/templates/rank/question_presentation.jinja +15 -15
  182. edsl/questions/templates/top_k/answering_instructions.jinja +8 -8
  183. edsl/questions/templates/top_k/question_presentation.jinja +22 -22
  184. edsl/questions/templates/yes_no/answering_instructions.jinja +6 -6
  185. edsl/questions/templates/yes_no/question_presentation.jinja +11 -11
  186. edsl/results/Dataset.py +293 -293
  187. edsl/results/DatasetExportMixin.py +717 -717
  188. edsl/results/DatasetTree.py +145 -145
  189. edsl/results/Result.py +450 -450
  190. edsl/results/Results.py +1071 -1071
  191. edsl/results/ResultsDBMixin.py +238 -238
  192. edsl/results/ResultsExportMixin.py +43 -43
  193. edsl/results/ResultsFetchMixin.py +33 -33
  194. edsl/results/ResultsGGMixin.py +121 -121
  195. edsl/results/ResultsToolsMixin.py +98 -98
  196. edsl/results/Selector.py +135 -135
  197. edsl/results/__init__.py +2 -2
  198. edsl/results/tree_explore.py +115 -115
  199. edsl/scenarios/FileStore.py +458 -458
  200. edsl/scenarios/Scenario.py +546 -546
  201. edsl/scenarios/ScenarioHtmlMixin.py +64 -64
  202. edsl/scenarios/ScenarioList.py +1112 -1112
  203. edsl/scenarios/ScenarioListExportMixin.py +52 -52
  204. edsl/scenarios/ScenarioListPdfMixin.py +261 -261
  205. edsl/scenarios/__init__.py +4 -4
  206. edsl/shared.py +1 -1
  207. edsl/study/ObjectEntry.py +173 -173
  208. edsl/study/ProofOfWork.py +113 -113
  209. edsl/study/SnapShot.py +80 -80
  210. edsl/study/Study.py +528 -528
  211. edsl/study/__init__.py +4 -4
  212. edsl/surveys/DAG.py +148 -148
  213. edsl/surveys/Memory.py +31 -31
  214. edsl/surveys/MemoryPlan.py +244 -244
  215. edsl/surveys/Rule.py +330 -330
  216. edsl/surveys/RuleCollection.py +387 -387
  217. edsl/surveys/Survey.py +1795 -1795
  218. edsl/surveys/SurveyCSS.py +261 -261
  219. edsl/surveys/SurveyExportMixin.py +259 -259
  220. edsl/surveys/SurveyFlowVisualizationMixin.py +121 -121
  221. edsl/surveys/SurveyQualtricsImport.py +284 -284
  222. edsl/surveys/__init__.py +3 -3
  223. edsl/surveys/base.py +53 -53
  224. edsl/surveys/descriptors.py +56 -56
  225. edsl/surveys/instructions/ChangeInstruction.py +47 -47
  226. edsl/surveys/instructions/Instruction.py +51 -51
  227. edsl/surveys/instructions/InstructionCollection.py +77 -77
  228. edsl/templates/error_reporting/base.html +23 -23
  229. edsl/templates/error_reporting/exceptions_by_model.html +34 -34
  230. edsl/templates/error_reporting/exceptions_by_question_name.html +16 -16
  231. edsl/templates/error_reporting/exceptions_by_type.html +16 -16
  232. edsl/templates/error_reporting/interview_details.html +115 -115
  233. edsl/templates/error_reporting/interviews.html +9 -9
  234. edsl/templates/error_reporting/overview.html +4 -4
  235. edsl/templates/error_reporting/performance_plot.html +1 -1
  236. edsl/templates/error_reporting/report.css +73 -73
  237. edsl/templates/error_reporting/report.html +117 -117
  238. edsl/templates/error_reporting/report.js +25 -25
  239. edsl/tools/__init__.py +1 -1
  240. edsl/tools/clusters.py +192 -192
  241. edsl/tools/embeddings.py +27 -27
  242. edsl/tools/embeddings_plotting.py +118 -118
  243. edsl/tools/plotting.py +112 -112
  244. edsl/tools/summarize.py +18 -18
  245. edsl/utilities/SystemInfo.py +28 -28
  246. edsl/utilities/__init__.py +22 -22
  247. edsl/utilities/ast_utilities.py +25 -25
  248. edsl/utilities/data/Registry.py +6 -6
  249. edsl/utilities/data/__init__.py +1 -1
  250. edsl/utilities/data/scooter_results.json +1 -1
  251. edsl/utilities/decorators.py +77 -77
  252. edsl/utilities/gcp_bucket/cloud_storage.py +96 -96
  253. edsl/utilities/interface.py +627 -627
  254. edsl/utilities/repair_functions.py +28 -28
  255. edsl/utilities/restricted_python.py +70 -70
  256. edsl/utilities/utilities.py +409 -409
  257. {edsl-0.1.37.dev5.dist-info → edsl-0.1.37.dev6.dist-info}/LICENSE +21 -21
  258. {edsl-0.1.37.dev5.dist-info → edsl-0.1.37.dev6.dist-info}/METADATA +1 -1
  259. edsl-0.1.37.dev6.dist-info/RECORD +283 -0
  260. edsl-0.1.37.dev5.dist-info/RECORD +0 -283
  261. {edsl-0.1.37.dev5.dist-info → edsl-0.1.37.dev6.dist-info}/WHEEL +0 -0
edsl/results/Results.py CHANGED
@@ -1,1071 +1,1071 @@
1
- """
2
- The Results object is the result of running a survey.
3
- It is not typically instantiated directly, but is returned by the run method of a `Job` object.
4
- """
5
-
6
- from __future__ import annotations
7
- import json
8
- import random
9
- from collections import UserList, defaultdict
10
- from typing import Optional, Callable, Any, Type, Union, List, TYPE_CHECKING
11
-
12
- if TYPE_CHECKING:
13
- from edsl import Survey, Cache, AgentList, ModelList, ScenarioList
14
- from edsl.results.Result import Result
15
- from edsl.jobs.tasks.TaskHistory import TaskHistory
16
-
17
- from simpleeval import EvalWithCompoundTypes
18
-
19
- from edsl.exceptions.results import (
20
- ResultsError,
21
- ResultsBadMutationstringError,
22
- ResultsColumnNotFoundError,
23
- ResultsInvalidNameError,
24
- ResultsMutateError,
25
- ResultsFilterError,
26
- ResultsDeserializationError,
27
- )
28
-
29
- from edsl.results.ResultsExportMixin import ResultsExportMixin
30
- from edsl.results.ResultsToolsMixin import ResultsToolsMixin
31
- from edsl.results.ResultsDBMixin import ResultsDBMixin
32
- from edsl.results.ResultsGGMixin import ResultsGGMixin
33
- from edsl.results.ResultsFetchMixin import ResultsFetchMixin
34
-
35
- from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
36
- from edsl.utilities.utilities import dict_hash
37
-
38
-
39
- from edsl.Base import Base
40
-
41
-
42
- class Mixins(
43
- ResultsExportMixin,
44
- ResultsDBMixin,
45
- ResultsFetchMixin,
46
- ResultsGGMixin,
47
- ResultsToolsMixin,
48
- ):
49
- def print_long(self, max_rows: int = None) -> None:
50
- """Print the results in long format.
51
-
52
- >>> from edsl.results import Results
53
- >>> r = Results.example()
54
- >>> r.select('how_feeling').print_long(max_rows = 2)
55
- ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━┓
56
- ┃ Result index ┃ Key ┃ Value ┃
57
- ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━┩
58
- │ 0 │ how_feeling │ OK │
59
- │ 1 │ how_feeling │ Great │
60
- └──────────────┴─────────────┴───────┘
61
- """
62
- from edsl.utilities.interface import print_results_long
63
-
64
- print_results_long(self, max_rows=max_rows)
65
-
66
-
67
- class Results(UserList, Mixins, Base):
68
- """
69
- This class is a UserList of Result objects.
70
-
71
- It is instantiated with a `Survey` and a list of `Result` objects.
72
- It can be manipulated in various ways with select, filter, mutate, etc.
73
- It also has a list of created_columns, which are columns that have been created with `mutate` and are not part of the original data.
74
- """
75
-
76
- known_data_types = [
77
- "answer",
78
- "scenario",
79
- "agent",
80
- "model",
81
- "prompt",
82
- "raw_model_response",
83
- "iteration",
84
- "question_text",
85
- "question_options",
86
- "question_type",
87
- "comment",
88
- "generated_tokens",
89
- ]
90
-
91
- def __init__(
92
- self,
93
- survey: Optional[Survey] = None,
94
- data: Optional[list[Result]] = None,
95
- created_columns: Optional[list[str]] = None,
96
- cache: Optional[Cache] = None,
97
- job_uuid: Optional[str] = None,
98
- total_results: Optional[int] = None,
99
- task_history: Optional[TaskHistory] = None,
100
- ):
101
- """Instantiate a `Results` object with a survey and a list of `Result` objects.
102
-
103
- :param survey: A Survey object.
104
- :param data: A list of Result objects.
105
- :param created_columns: A list of strings that are created columns.
106
- :param job_uuid: A string representing the job UUID.
107
- :param total_results: An integer representing the total number of results.
108
- """
109
- super().__init__(data)
110
- from edsl.data.Cache import Cache
111
- from edsl.jobs.tasks.TaskHistory import TaskHistory
112
-
113
- self.survey = survey
114
- self.created_columns = created_columns or []
115
- self._job_uuid = job_uuid
116
- self._total_results = total_results
117
- self.cache = cache or Cache()
118
-
119
- self.task_history = task_history or TaskHistory(interviews=[])
120
-
121
- if hasattr(self, "_add_output_functions"):
122
- self._add_output_functions()
123
-
124
- def leaves(self):
125
- leaves = []
126
- for result in self:
127
- leaves.extend(result.leaves())
128
- return leaves
129
-
130
- def tree(
131
- self,
132
- fold_attributes: Optional[List[str]] = None,
133
- drop: Optional[List[str]] = None,
134
- open_file=True,
135
- ) -> dict:
136
- """Return the results as a tree."""
137
- from edsl.results.tree_explore import FoldableHTMLTableGenerator
138
-
139
- if drop is None:
140
- drop = []
141
-
142
- valid_attributes = [
143
- "model",
144
- "scenario",
145
- "agent",
146
- "answer",
147
- "question",
148
- "iteration",
149
- ]
150
- if fold_attributes is None:
151
- fold_attributes = []
152
-
153
- for attribute in fold_attributes:
154
- if attribute not in valid_attributes:
155
- raise ValueError(
156
- f"Invalid fold attribute: {attribute}; must be in {valid_attributes}"
157
- )
158
- data = self.leaves()
159
- generator = FoldableHTMLTableGenerator(data)
160
- tree = generator.tree(fold_attributes=fold_attributes, drop=drop)
161
- html_content = generator.generate_html(tree, fold_attributes)
162
- import tempfile
163
- from edsl.utilities.utilities import is_notebook
164
-
165
- from IPython.display import display, HTML
166
-
167
- if is_notebook():
168
- import html
169
- from IPython.display import display, HTML
170
-
171
- height = 1000
172
- width = 1000
173
- escaped_output = html.escape(html_content)
174
- # escaped_output = rendered_html
175
- iframe = f""""
176
- <iframe srcdoc="{ escaped_output }" style="width: {width}px; height: {height}px;"></iframe>
177
- """
178
- display(HTML(iframe))
179
- return None
180
-
181
- with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
182
- f.write(html_content.encode())
183
- print(f"HTML file has been generated: {f.name}")
184
-
185
- if open_file:
186
- import webbrowser
187
- import time
188
-
189
- time.sleep(1) # Wait for 1 second
190
- # webbrowser.open(f.name)
191
- import os
192
-
193
- filename = f.name
194
- webbrowser.open(f"file://{os.path.abspath(filename)}")
195
-
196
- else:
197
- return html_content
198
-
199
- def code(self):
200
- raise NotImplementedError
201
-
202
- def __getitem__(self, i):
203
- if isinstance(i, int):
204
- return self.data[i]
205
-
206
- if isinstance(i, slice):
207
- return self.__class__(survey=self.survey, data=self.data[i])
208
-
209
- if isinstance(i, str):
210
- return self.to_dict()[i]
211
-
212
- raise TypeError("Invalid argument type")
213
-
214
- def _update_results(self) -> None:
215
- from edsl import Agent, Scenario
216
- from edsl.language_models import LanguageModel
217
- from edsl.results import Result
218
-
219
- if self._job_uuid and len(self.data) < self._total_results:
220
- results = [
221
- Result(
222
- agent=Agent.from_dict(json.loads(r.agent)),
223
- scenario=Scenario.from_dict(json.loads(r.scenario)),
224
- model=LanguageModel.from_dict(json.loads(r.model)),
225
- iteration=1,
226
- answer=json.loads(r.answer),
227
- )
228
- for r in CRUD.read_results(self._job_uuid)
229
- ]
230
- self.data = results
231
-
232
- def __add__(self, other: Results) -> Results:
233
- """Add two Results objects together.
234
- They must have the same survey and created columns.
235
- :param other: A Results object.
236
-
237
- Example:
238
-
239
- >>> r = Results.example()
240
- >>> r2 = Results.example()
241
- >>> r3 = r + r2
242
- """
243
- if self.survey != other.survey:
244
- raise ResultsError(
245
- "The surveys are not the same so the the results cannot be added together."
246
- )
247
- if self.created_columns != other.created_columns:
248
- raise ResultsError(
249
- "The created columns are not the same so they cannot be added together."
250
- )
251
-
252
- return Results(
253
- survey=self.survey,
254
- data=self.data + other.data,
255
- created_columns=self.created_columns,
256
- )
257
-
258
- def __repr__(self) -> str:
259
- import reprlib
260
-
261
- return f"Results(data = {reprlib.repr(self.data)}, survey = {repr(self.survey)}, created_columns = {self.created_columns})"
262
-
263
- def _repr_html_(self) -> str:
264
- from IPython.display import HTML
265
-
266
- json_str = json.dumps(self.to_dict()["data"], indent=4)
267
- return f"<pre>{json_str}</pre>"
268
-
269
- def _to_dict(self, sort=False):
270
- from edsl.data.Cache import Cache
271
-
272
- if sort:
273
- data = sorted([result for result in self.data], key=lambda x: hash(x))
274
- else:
275
- data = [result for result in self.data]
276
- return {
277
- "data": [result.to_dict() for result in data],
278
- "survey": self.survey.to_dict(),
279
- "created_columns": self.created_columns,
280
- "cache": Cache() if not hasattr(self, "cache") else self.cache.to_dict(),
281
- "task_history": self.task_history.to_dict(),
282
- }
283
-
284
- def compare(self, other_results):
285
- """
286
- Compare two Results objects and return the differences.
287
- """
288
- hashes_0 = [hash(result) for result in self]
289
- hashes_1 = [hash(result) for result in other_results]
290
-
291
- in_self_but_not_other = set(hashes_0).difference(set(hashes_1))
292
- in_other_but_not_self = set(hashes_1).difference(set(hashes_0))
293
-
294
- indicies_self = [hashes_0.index(h) for h in in_self_but_not_other]
295
- indices_other = [hashes_1.index(h) for h in in_other_but_not_self]
296
- return {
297
- "a_not_b": [self[i] for i in indicies_self],
298
- "b_not_a": [other_results[i] for i in indices_other],
299
- }
300
-
301
- @property
302
- def has_unfixed_exceptions(self):
303
- return self.task_history.has_unfixed_exceptions
304
-
305
- @add_edsl_version
306
- def to_dict(self) -> dict[str, Any]:
307
- """Convert the Results object to a dictionary.
308
-
309
- The dictionary can be quite large, as it includes all of the data in the Results object.
310
-
311
- Example: Illustrating just the keys of the dictionary.
312
-
313
- >>> r = Results.example()
314
- >>> r.to_dict().keys()
315
- dict_keys(['data', 'survey', 'created_columns', 'cache', 'task_history', 'edsl_version', 'edsl_class_name'])
316
- """
317
- return self._to_dict()
318
-
319
- def __hash__(self) -> int:
320
- return dict_hash(self._to_dict(sort=True))
321
-
322
- @property
323
- def hashes(self) -> set:
324
- return set(hash(result) for result in self.data)
325
-
326
- def sample(self, n: int) -> Results:
327
- """Return a random sample of the results.
328
-
329
- :param n: The number of samples to return.
330
-
331
- >>> from edsl.results import Results
332
- >>> r = Results.example()
333
- >>> len(r.sample(2))
334
- 2
335
- """
336
- indices = None
337
-
338
- for entry in self:
339
- key, values = list(entry.items())[0]
340
- if indices is None: # gets the indices for the first time
341
- indices = list(range(len(values)))
342
- sampled_indices = random.sample(indices, n)
343
- if n > len(indices):
344
- raise ResultsError(
345
- f"Cannot sample {n} items from a list of length {len(indices)}."
346
- )
347
- entry[key] = [values[i] for i in sampled_indices]
348
-
349
- return self
350
-
351
- @classmethod
352
- @remove_edsl_version
353
- def from_dict(cls, data: dict[str, Any]) -> Results:
354
- """Convert a dictionary to a Results object.
355
-
356
- :param data: A dictionary representation of a Results object.
357
-
358
- Example:
359
-
360
- >>> r = Results.example()
361
- >>> d = r.to_dict()
362
- >>> r2 = Results.from_dict(d)
363
- >>> r == r2
364
- True
365
- """
366
- from edsl import Survey, Cache
367
- from edsl.results.Result import Result
368
- from edsl.jobs.tasks.TaskHistory import TaskHistory
369
-
370
- try:
371
- results = cls(
372
- survey=Survey.from_dict(data["survey"]),
373
- data=[Result.from_dict(r) for r in data["data"]],
374
- created_columns=data.get("created_columns", None),
375
- cache=(
376
- Cache.from_dict(data.get("cache")) if "cache" in data else Cache()
377
- ),
378
- task_history=TaskHistory.from_dict(data.get("task_history")),
379
- )
380
- except Exception as e:
381
- raise ResultsDeserializationError(f"Error in Results.from_dict: {e}")
382
- return results
383
-
384
- ######################
385
- ## Convenience methods
386
- ## & Report methods
387
- ######################
388
- @property
389
- def _key_to_data_type(self) -> dict[str, str]:
390
- """
391
- Return a mapping of keys (how_feeling, status, etc.) to strings representing data types.
392
-
393
- Objects such as Agent, Answer, Model, Scenario, etc.
394
- - Uses the key_to_data_type property of the Result class.
395
- - Includes any columns that the user has created with `mutate`
396
- """
397
- d: dict = {}
398
- for result in self.data:
399
- d.update(result.key_to_data_type)
400
- for column in self.created_columns:
401
- d[column] = "answer"
402
-
403
- return d
404
-
405
- @property
406
- def _data_type_to_keys(self) -> dict[str, str]:
407
- """
408
- Return a mapping of strings representing data types (objects such as Agent, Answer, Model, Scenario, etc.) to keys (how_feeling, status, etc.)
409
- - Uses the key_to_data_type property of the Result class.
410
- - Includes any columns that the user has created with `mutate`
411
-
412
- Example:
413
-
414
- >>> r = Results.example()
415
- >>> r._data_type_to_keys
416
- defaultdict(...
417
- """
418
- d: dict = defaultdict(set)
419
- for result in self.data:
420
- for key, value in result.key_to_data_type.items():
421
- d[value] = d[value].union(set({key}))
422
- for column in self.created_columns:
423
- d["answer"] = d["answer"].union(set({column}))
424
- return d
425
-
426
- @property
427
- def columns(self) -> list[str]:
428
- """Return a list of all of the columns that are in the Results.
429
-
430
- Example:
431
-
432
- >>> r = Results.example()
433
- >>> r.columns
434
- ['agent.agent_instruction', ...]
435
- """
436
- column_names = [f"{v}.{k}" for k, v in self._key_to_data_type.items()]
437
- return sorted(column_names)
438
-
439
- @property
440
- def answer_keys(self) -> dict[str, str]:
441
- """Return a mapping of answer keys to question text.
442
-
443
- Example:
444
-
445
- >>> r = Results.example()
446
- >>> r.answer_keys
447
- {'how_feeling': 'How are you this {{ period }}?', 'how_feeling_yesterday': 'How were you feeling yesterday {{ period }}?'}
448
- """
449
- from edsl.utilities.utilities import shorten_string
450
-
451
- if not self.survey:
452
- raise ResultsError("Survey is not defined so no answer keys are available.")
453
-
454
- answer_keys = self._data_type_to_keys["answer"]
455
- answer_keys = {k for k in answer_keys if "_comment" not in k}
456
- questions_text = [
457
- self.survey.get_question(k).question_text for k in answer_keys
458
- ]
459
- short_question_text = [shorten_string(q, 80) for q in questions_text]
460
- initial_dict = dict(zip(answer_keys, short_question_text))
461
- sorted_dict = {key: initial_dict[key] for key in sorted(initial_dict)}
462
- return sorted_dict
463
-
464
- @property
465
- def agents(self) -> AgentList:
466
- """Return a list of all of the agents in the Results.
467
-
468
- Example:
469
-
470
- >>> r = Results.example()
471
- >>> r.agents
472
- AgentList([Agent(traits = {'status': 'Joyful'}), Agent(traits = {'status': 'Joyful'}), Agent(traits = {'status': 'Sad'}), Agent(traits = {'status': 'Sad'})])
473
- """
474
- from edsl import AgentList
475
-
476
- return AgentList([r.agent for r in self.data])
477
-
478
- @property
479
- def models(self) -> ModelList:
480
- """Return a list of all of the models in the Results.
481
-
482
- Example:
483
-
484
- >>> r = Results.example()
485
- >>> r.models[0]
486
- Model(model_name = ...)
487
- """
488
- from edsl import ModelList
489
-
490
- return ModelList([r.model for r in self.data])
491
-
492
- @property
493
- def scenarios(self) -> ScenarioList:
494
- """Return a list of all of the scenarios in the Results.
495
-
496
- Example:
497
-
498
- >>> r = Results.example()
499
- >>> r.scenarios
500
- ScenarioList([Scenario({'period': 'morning'}), Scenario({'period': 'afternoon'}), Scenario({'period': 'morning'}), Scenario({'period': 'afternoon'})])
501
- """
502
- from edsl import ScenarioList
503
-
504
- return ScenarioList([r.scenario for r in self.data])
505
-
506
- @property
507
- def agent_keys(self) -> list[str]:
508
- """Return a set of all of the keys that are in the Agent data.
509
-
510
- Example:
511
-
512
- >>> r = Results.example()
513
- >>> r.agent_keys
514
- ['agent_instruction', 'agent_name', 'status']
515
- """
516
- return sorted(self._data_type_to_keys["agent"])
517
-
518
- @property
519
- def model_keys(self) -> list[str]:
520
- """Return a set of all of the keys that are in the LanguageModel data.
521
-
522
- >>> r = Results.example()
523
- >>> r.model_keys
524
- ['frequency_penalty', 'logprobs', 'max_tokens', 'model', 'presence_penalty', 'temperature', 'top_logprobs', 'top_p']
525
- """
526
- return sorted(self._data_type_to_keys["model"])
527
-
528
- @property
529
- def scenario_keys(self) -> list[str]:
530
- """Return a set of all of the keys that are in the Scenario data.
531
-
532
- >>> r = Results.example()
533
- >>> r.scenario_keys
534
- ['period']
535
- """
536
- return sorted(self._data_type_to_keys["scenario"])
537
-
538
- @property
539
- def question_names(self) -> list[str]:
540
- """Return a list of all of the question names.
541
-
542
- Example:
543
-
544
- >>> r = Results.example()
545
- >>> r.question_names
546
- ['how_feeling', 'how_feeling_yesterday']
547
- """
548
- if self.survey is None:
549
- return []
550
- return sorted(list(self.survey.question_names))
551
-
552
- @property
553
- def all_keys(self) -> list[str]:
554
- """Return a set of all of the keys that are in the Results.
555
-
556
- Example:
557
-
558
- >>> r = Results.example()
559
- >>> r.all_keys
560
- ['agent_instruction', 'agent_name', 'frequency_penalty', 'how_feeling', 'how_feeling_yesterday', 'logprobs', 'max_tokens', 'model', 'period', 'presence_penalty', 'status', 'temperature', 'top_logprobs', 'top_p']
561
- """
562
- answer_keys = set(self.answer_keys)
563
- all_keys = (
564
- answer_keys.union(self.agent_keys)
565
- .union(self.scenario_keys)
566
- .union(self.model_keys)
567
- )
568
- return sorted(list(all_keys))
569
-
570
- def first(self) -> Result:
571
- """Return the first observation in the results.
572
-
573
- Example:
574
-
575
- >>> r = Results.example()
576
- >>> r.first()
577
- Result(agent...
578
- """
579
- return self.data[0]
580
-
581
- def answer_truncate(self, column: str, top_n=5, new_var_name=None) -> Results:
582
- """Create a new variable that truncates the answers to the top_n.
583
-
584
- :param column: The column to truncate.
585
- :param top_n: The number of top answers to keep.
586
- :param new_var_name: The name of the new variable. If None, it is the original name + '_truncated'.
587
-
588
-
589
-
590
- """
591
- if new_var_name is None:
592
- new_var_name = column + "_truncated"
593
- answers = list(self.select(column).tally().keys())
594
-
595
- def f(x):
596
- if x in answers[:top_n]:
597
- return x
598
- else:
599
- return "Other"
600
-
601
- return self.recode(column, recode_function=f, new_var_name=new_var_name)
602
-
603
- def recode(
604
- self, column: str, recode_function: Optional[Callable], new_var_name=None
605
- ) -> Results:
606
- """
607
- Recode a column in the Results object.
608
-
609
- >>> r = Results.example()
610
- >>> r.recode('how_feeling', recode_function = lambda x: 1 if x == 'Great' else 0).select('how_feeling', 'how_feeling_recoded')
611
- Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling_recoded': [0, 1, 0, 0]}])
612
- """
613
-
614
- if new_var_name is None:
615
- new_var_name = column + "_recoded"
616
- new_data = []
617
- for result in self.data:
618
- new_result = result.copy()
619
- value = new_result.get_value("answer", column)
620
- # breakpoint()
621
- new_result["answer"][new_var_name] = recode_function(value)
622
- new_data.append(new_result)
623
-
624
- # print("Created new variable", new_var_name)
625
- return Results(
626
- survey=self.survey,
627
- data=new_data,
628
- created_columns=self.created_columns + [new_var_name],
629
- )
630
-
631
- def add_column(self, column_name: str, values: list) -> Results:
632
- """Adds columns to Results
633
-
634
- >>> r = Results.example()
635
- >>> r.add_column('a', [1,2,3, 4]).select('a')
636
- Dataset([{'answer.a': [1, 2, 3, 4]}])
637
- """
638
-
639
- assert len(values) == len(
640
- self.data
641
- ), "The number of values must match the number of results."
642
- new_results = self.data.copy()
643
- for i, result in enumerate(new_results):
644
- result["answer"][column_name] = values[i]
645
- return Results(
646
- survey=self.survey,
647
- data=new_results,
648
- created_columns=self.created_columns + [column_name],
649
- )
650
-
651
- def add_columns_from_dict(self, columns: List[dict]) -> Results:
652
- """Adds columns to Results from a list of dictionaries.
653
-
654
- >>> r = Results.example()
655
- >>> r.add_columns_from_dict([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a':3, 'b':2}, {'a':3, 'b':2}]).select('a', 'b')
656
- Dataset([{'answer.a': [1, 3, 3, 3]}, {'answer.b': [2, 4, 2, 2]}])
657
- """
658
- keys = list(columns[0].keys())
659
- for key in keys:
660
- values = [d[key] for d in columns]
661
- self = self.add_column(key, values)
662
- return self
663
-
664
- @staticmethod
665
- def _create_evaluator(
666
- result: Result, functions_dict: Optional[dict] = None
667
- ) -> EvalWithCompoundTypes:
668
- """Create an evaluator for the expression.
669
-
670
- >>> from unittest.mock import Mock
671
- >>> result = Mock()
672
- >>> result.combined_dict = {'how_feeling': 'OK'}
673
-
674
- >>> evaluator = Results._create_evaluator(result = result, functions_dict = {})
675
- >>> evaluator.eval("how_feeling == 'OK'")
676
- True
677
-
678
- >>> result.combined_dict = {'answer': {'how_feeling': 'OK'}}
679
- >>> evaluator = Results._create_evaluator(result = result, functions_dict = {})
680
- >>> evaluator.eval("answer.how_feeling== 'OK'")
681
- True
682
-
683
- Note that you need to refer to the answer dictionary in the expression.
684
-
685
- >>> evaluator.eval("how_feeling== 'OK'")
686
- Traceback (most recent call last):
687
- ...
688
- simpleeval.NameNotDefined: 'how_feeling' is not defined for expression 'how_feeling== 'OK''
689
- """
690
- if functions_dict is None:
691
- functions_dict = {}
692
- evaluator = EvalWithCompoundTypes(
693
- names=result.combined_dict, functions=functions_dict
694
- )
695
- evaluator.functions.update(int=int, float=float)
696
- return evaluator
697
-
698
- def mutate(
699
- self, new_var_string: str, functions_dict: Optional[dict] = None
700
- ) -> Results:
701
- """
702
- Creates a value in the Results object as if has been asked as part of the survey.
703
-
704
- :param new_var_string: A string that is a valid Python expression.
705
- :param functions_dict: A dictionary of functions that can be used in the expression. The keys are the function names and the values are the functions themselves.
706
-
707
- It splits the new_var_string at the "=" and uses simple_eval
708
-
709
- Example:
710
-
711
- >>> r = Results.example()
712
- >>> r.mutate('how_feeling_x = how_feeling + "x"').select('how_feeling_x')
713
- Dataset([{'answer.how_feeling_x': ...
714
- """
715
- # extract the variable name and the expression
716
- if "=" not in new_var_string:
717
- raise ResultsBadMutationstringError(
718
- f"Mutate requires an '=' in the string, but '{new_var_string}' doesn't have one."
719
- )
720
- raw_var_name, expression = new_var_string.split("=", 1)
721
- var_name = raw_var_name.strip()
722
- from edsl.utilities.utilities import is_valid_variable_name
723
-
724
- if not is_valid_variable_name(var_name):
725
- raise ResultsInvalidNameError(f"{var_name} is not a valid variable name.")
726
-
727
- # create the evaluator
728
- functions_dict = functions_dict or {}
729
-
730
- def new_result(old_result: "Result", var_name: str) -> "Result":
731
- evaluator = self._create_evaluator(old_result, functions_dict)
732
- value = evaluator.eval(expression)
733
- new_result = old_result.copy()
734
- new_result["answer"][var_name] = value
735
- return new_result
736
-
737
- try:
738
- new_data = [new_result(result, var_name) for result in self.data]
739
- except Exception as e:
740
- raise ResultsMutateError(f"Error in mutate. Exception:{e}")
741
-
742
- return Results(
743
- survey=self.survey,
744
- data=new_data,
745
- created_columns=self.created_columns + [var_name],
746
- )
747
-
748
- def rename(self, old_name: str, new_name: str) -> Results:
749
- """Rename an answer column in a Results object.
750
-
751
- >>> s = Results.example()
752
- >>> s.rename('how_feeling', 'how_feeling_new').select('how_feeling_new')
753
- Dataset([{'answer.how_feeling_new': ['OK', 'Great', 'Terrible', 'OK']}])
754
-
755
- # TODO: Should we allow renaming of scenario fields as well? Probably.
756
-
757
- """
758
-
759
- for obs in self.data:
760
- obs["answer"][new_name] = obs["answer"][old_name]
761
- del obs["answer"][old_name]
762
-
763
- return self
764
-
765
- def shuffle(self, seed: Optional[str] = "edsl") -> Results:
766
- """Shuffle the results.
767
-
768
- Example:
769
-
770
- >>> r = Results.example()
771
- >>> r.shuffle(seed = 1)[0]
772
- Result(...)
773
- """
774
- if seed != "edsl":
775
- seed = random.seed(seed)
776
-
777
- new_data = self.data.copy()
778
- random.shuffle(new_data)
779
- return Results(survey=self.survey, data=new_data, created_columns=None)
780
-
781
- def sample(
782
- self,
783
- n: Optional[int] = None,
784
- frac: Optional[float] = None,
785
- with_replacement: bool = True,
786
- seed: Optional[str] = "edsl",
787
- ) -> Results:
788
- """Sample the results.
789
-
790
- :param n: An integer representing the number of samples to take.
791
- :param frac: A float representing the fraction of samples to take.
792
- :param with_replacement: A boolean representing whether to sample with replacement.
793
- :param seed: An integer representing the seed for the random number generator.
794
-
795
- Example:
796
-
797
- >>> r = Results.example()
798
- >>> len(r.sample(2))
799
- 2
800
- """
801
- if seed != "edsl":
802
- random.seed(seed)
803
-
804
- if n is None and frac is None:
805
- raise Exception("You must specify either n or frac.")
806
-
807
- if n is not None and frac is not None:
808
- raise Exception("You cannot specify both n and frac.")
809
-
810
- if frac is not None and n is None:
811
- n = int(frac * len(self.data))
812
-
813
- if with_replacement:
814
- new_data = random.choices(self.data, k=n)
815
- else:
816
- new_data = random.sample(self.data, n)
817
-
818
- return Results(survey=self.survey, data=new_data, created_columns=None)
819
-
820
- def select(self, *columns: Union[str, list[str]]) -> Results:
821
- """
822
- Select data from the results and format it.
823
-
824
- :param columns: A list of strings, each of which is a column name. The column name can be a single key, e.g. "how_feeling", or a dot-separated string, e.g. "answer.how_feeling".
825
-
826
- Example:
827
-
828
- >>> results = Results.example()
829
- >>> results.select('how_feeling')
830
- Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}])
831
-
832
- >>> results.select('how_feeling', 'model', 'how_feeling')
833
- Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'model.model': ['...', '...', '...', '...']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}])
834
-
835
- >>> from edsl import Results; r = Results.example(); r.select('answer.how_feeling_y')
836
- Dataset([{'answer.how_feeling_yesterday': ['Great', 'Good', 'OK', 'Terrible']}])
837
- """
838
-
839
- from edsl.results.Selector import Selector
840
-
841
- if len(self) == 0:
842
- raise Exception("No data to select from---the Results object is empty.")
843
-
844
- selector = Selector(
845
- known_data_types=self.known_data_types,
846
- data_type_to_keys=self._data_type_to_keys,
847
- key_to_data_type=self._key_to_data_type,
848
- fetch_list_func=self._fetch_list,
849
- columns=self.columns,
850
- )
851
- return selector.select(*columns)
852
-
853
- def sort_by(self, *columns: str, reverse: bool = False) -> Results:
854
- import warnings
855
-
856
- warnings.warn(
857
- "sort_by is deprecated. Use order_by instead.", DeprecationWarning
858
- )
859
- return self.order_by(*columns, reverse=reverse)
860
-
861
- def _parse_column(self, column: str) -> tuple[str, str]:
862
- if "." in column:
863
- return column.split(".")
864
- return self._key_to_data_type[column], column
865
-
866
- def order_by(self, *columns: str, reverse: bool = False) -> Results:
867
- """Sort the results by one or more columns.
868
-
869
- :param columns: One or more column names as strings.
870
- :param reverse: A boolean that determines whether to sort in reverse order.
871
-
872
- Each column name can be a single key, e.g. "how_feeling", or a dot-separated string, e.g. "answer.how_feeling".
873
-
874
- Example:
875
-
876
- >>> r = Results.example()
877
- >>> r.sort_by('how_feeling', reverse=False).select('how_feeling').print()
878
- ┏━━━━━━━━━━━━━━┓
879
- ┃ answer ┃
880
- ┃ .how_feeling ┃
881
- ┡━━━━━━━━━━━━━━┩
882
- │ Great │
883
- ├──────────────┤
884
- │ OK │
885
- ├──────────────┤
886
- │ OK │
887
- ├──────────────┤
888
- │ Terrible │
889
- └──────────────┘
890
- >>> r.sort_by('how_feeling', reverse=True).select('how_feeling').print()
891
- ┏━━━━━━━━━━━━━━┓
892
- ┃ answer ┃
893
- ┃ .how_feeling ┃
894
- ┡━━━━━━━━━━━━━━┩
895
- │ Terrible │
896
- ├──────────────┤
897
- │ OK │
898
- ├──────────────┤
899
- │ OK │
900
- ├──────────────┤
901
- │ Great │
902
- └──────────────┘
903
- """
904
-
905
- def to_numeric_if_possible(v):
906
- try:
907
- return float(v)
908
- except:
909
- return v
910
-
911
- def sort_key(item):
912
- key_components = []
913
- for col in columns:
914
- data_type, key = self._parse_column(col)
915
- value = item.get_value(data_type, key)
916
- key_components.append(to_numeric_if_possible(value))
917
- return tuple(key_components)
918
-
919
- new_data = sorted(self.data, key=sort_key, reverse=reverse)
920
- return Results(survey=self.survey, data=new_data, created_columns=None)
921
-
922
- def filter(self, expression: str) -> Results:
923
- """
924
- Filter based on the given expression and returns the filtered `Results`.
925
-
926
- :param expression: A string expression that evaluates to a boolean. The expression is applied to each element in `Results` to determine whether it should be included in the filtered results.
927
-
928
- The `expression` parameter is a string that must resolve to a boolean value when evaluated against each element in `Results`.
929
- This expression is used to determine which elements to include in the returned `Results`.
930
-
931
- Example usage: Create an example `Results` instance and apply filters to it:
932
-
933
- >>> r = Results.example()
934
- >>> r.filter("how_feeling == 'Great'").select('how_feeling').print()
935
- ┏━━━━━━━━━━━━━━┓
936
- ┃ answer ┃
937
- ┃ .how_feeling ┃
938
- ┡━━━━━━━━━━━━━━┩
939
- │ Great │
940
- └──────────────┘
941
-
942
- Example usage: Using an OR operator in the filter expression.
943
-
944
- >>> r = Results.example().filter("how_feeling = 'Great'").select('how_feeling').print()
945
- Traceback (most recent call last):
946
- ...
947
- edsl.exceptions.results.ResultsFilterError: You must use '==' instead of '=' in the filter expression.
948
- ...
949
-
950
- >>> r.filter("how_feeling == 'Great' or how_feeling == 'Terrible'").select('how_feeling').print()
951
- ┏━━━━━━━━━━━━━━┓
952
- ┃ answer ┃
953
- ┃ .how_feeling ┃
954
- ┡━━━━━━━━━━━━━━┩
955
- │ Great │
956
- ├──────────────┤
957
- │ Terrible │
958
- └──────────────┘
959
- """
960
-
961
- def has_single_equals(string):
962
- if "!=" in string:
963
- return False
964
- if "=" in string and not (
965
- "==" in string or "<=" in string or ">=" in string
966
- ):
967
- return True
968
-
969
- if has_single_equals(expression):
970
- raise ResultsFilterError(
971
- "You must use '==' instead of '=' in the filter expression."
972
- )
973
-
974
- try:
975
- # iterates through all the results and evaluates the expression
976
- new_data = []
977
- for result in self.data:
978
- evaluator = self._create_evaluator(result)
979
- result.check_expression(expression) # check expression
980
- if evaluator.eval(expression):
981
- new_data.append(result)
982
-
983
- except ValueError as e:
984
- raise ResultsFilterError(
985
- f"Error in filter. Exception:{e}",
986
- f"The expression you provided was: {expression}",
987
- "See https://docs.expectedparrot.com/en/latest/results.html#filtering-results for more details.",
988
- )
989
- except Exception as e:
990
- raise ResultsFilterError(
991
- f"""Error in filter. Exception:{e}.""",
992
- f"""The expression you provided was: {expression}.""",
993
- """Please make sure that the expression is a valid Python expression that evaluates to a boolean.""",
994
- """For example, 'how_feeling == "Great"' is a valid expression, as is 'how_feeling in ["Great", "Terrible"]'., """,
995
- """However, 'how_feeling = "Great"' is not a valid expression.""",
996
- """See https://docs.expectedparrot.com/en/latest/results.html#filtering-results for more details.""",
997
- )
998
-
999
- if len(new_data) == 0:
1000
- import warnings
1001
-
1002
- warnings.warn("No results remain after applying the filter.")
1003
-
1004
- return Results(survey=self.survey, data=new_data, created_columns=None)
1005
-
1006
- @classmethod
1007
- def example(cls, randomize: bool = False) -> Results:
1008
- """Return an example `Results` object.
1009
-
1010
- Example usage:
1011
-
1012
- >>> r = Results.example()
1013
-
1014
- :param debug: if False, uses actual API calls
1015
- """
1016
- from edsl.jobs.Jobs import Jobs
1017
- from edsl.data.Cache import Cache
1018
-
1019
- c = Cache()
1020
- job = Jobs.example(randomize=randomize)
1021
- results = job.run(
1022
- cache=c,
1023
- stop_on_exception=True,
1024
- skip_retry=True,
1025
- raise_validation_errors=True,
1026
- disable_remote_cache=True,
1027
- disable_remote_inference=True,
1028
- )
1029
- return results
1030
-
1031
- def rich_print(self):
1032
- """Display an object as a table."""
1033
- pass
1034
-
1035
- def __str__(self):
1036
- data = self.to_dict()["data"]
1037
- return json.dumps(data, indent=4)
1038
-
1039
- def show_exceptions(self, traceback=False):
1040
- """Print the exceptions."""
1041
- if hasattr(self, "task_history"):
1042
- self.task_history.show_exceptions(traceback)
1043
- else:
1044
- print("No exceptions to show.")
1045
-
1046
- def score(self, f: Callable) -> list:
1047
- """Score the results using in a function.
1048
-
1049
- :param f: A function that takes values from a Resul object and returns a score.
1050
-
1051
- >>> r = Results.example()
1052
- >>> def f(status): return 1 if status == 'Joyful' else 0
1053
- >>> r.score(f)
1054
- [1, 1, 0, 0]
1055
- """
1056
- return [r.score(f) for r in self.data]
1057
-
1058
-
1059
- def main(): # pragma: no cover
1060
- """Call the OpenAI API credits."""
1061
- from edsl.results.Results import Results
1062
-
1063
- results = Results.example(debug=True)
1064
- print(results.filter("how_feeling == 'Great'").select("how_feeling"))
1065
- print(results.mutate("how_feeling_x = how_feeling + 'x'").select("how_feeling_x"))
1066
-
1067
-
1068
- if __name__ == "__main__":
1069
- import doctest
1070
-
1071
- doctest.testmod(optionflags=doctest.ELLIPSIS)
1
+ """
2
+ The Results object is the result of running a survey.
3
+ It is not typically instantiated directly, but is returned by the run method of a `Job` object.
4
+ """
5
+
6
+ from __future__ import annotations
7
+ import json
8
+ import random
9
+ from collections import UserList, defaultdict
10
+ from typing import Optional, Callable, Any, Type, Union, List, TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from edsl import Survey, Cache, AgentList, ModelList, ScenarioList
14
+ from edsl.results.Result import Result
15
+ from edsl.jobs.tasks.TaskHistory import TaskHistory
16
+
17
+ from simpleeval import EvalWithCompoundTypes
18
+
19
+ from edsl.exceptions.results import (
20
+ ResultsError,
21
+ ResultsBadMutationstringError,
22
+ ResultsColumnNotFoundError,
23
+ ResultsInvalidNameError,
24
+ ResultsMutateError,
25
+ ResultsFilterError,
26
+ ResultsDeserializationError,
27
+ )
28
+
29
+ from edsl.results.ResultsExportMixin import ResultsExportMixin
30
+ from edsl.results.ResultsToolsMixin import ResultsToolsMixin
31
+ from edsl.results.ResultsDBMixin import ResultsDBMixin
32
+ from edsl.results.ResultsGGMixin import ResultsGGMixin
33
+ from edsl.results.ResultsFetchMixin import ResultsFetchMixin
34
+
35
+ from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
36
+ from edsl.utilities.utilities import dict_hash
37
+
38
+
39
+ from edsl.Base import Base
40
+
41
+
42
+ class Mixins(
43
+ ResultsExportMixin,
44
+ ResultsDBMixin,
45
+ ResultsFetchMixin,
46
+ ResultsGGMixin,
47
+ ResultsToolsMixin,
48
+ ):
49
+ def print_long(self, max_rows: int = None) -> None:
50
+ """Print the results in long format.
51
+
52
+ >>> from edsl.results import Results
53
+ >>> r = Results.example()
54
+ >>> r.select('how_feeling').print_long(max_rows = 2)
55
+ ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━┓
56
+ ┃ Result index ┃ Key ┃ Value ┃
57
+ ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━┩
58
+ │ 0 │ how_feeling │ OK │
59
+ │ 1 │ how_feeling │ Great │
60
+ └──────────────┴─────────────┴───────┘
61
+ """
62
+ from edsl.utilities.interface import print_results_long
63
+
64
+ print_results_long(self, max_rows=max_rows)
65
+
66
+
67
+ class Results(UserList, Mixins, Base):
68
+ """
69
+ This class is a UserList of Result objects.
70
+
71
+ It is instantiated with a `Survey` and a list of `Result` objects.
72
+ It can be manipulated in various ways with select, filter, mutate, etc.
73
+ It also has a list of created_columns, which are columns that have been created with `mutate` and are not part of the original data.
74
+ """
75
+
76
+ known_data_types = [
77
+ "answer",
78
+ "scenario",
79
+ "agent",
80
+ "model",
81
+ "prompt",
82
+ "raw_model_response",
83
+ "iteration",
84
+ "question_text",
85
+ "question_options",
86
+ "question_type",
87
+ "comment",
88
+ "generated_tokens",
89
+ ]
90
+
91
+ def __init__(
92
+ self,
93
+ survey: Optional[Survey] = None,
94
+ data: Optional[list[Result]] = None,
95
+ created_columns: Optional[list[str]] = None,
96
+ cache: Optional[Cache] = None,
97
+ job_uuid: Optional[str] = None,
98
+ total_results: Optional[int] = None,
99
+ task_history: Optional[TaskHistory] = None,
100
+ ):
101
+ """Instantiate a `Results` object with a survey and a list of `Result` objects.
102
+
103
+ :param survey: A Survey object.
104
+ :param data: A list of Result objects.
105
+ :param created_columns: A list of strings that are created columns.
106
+ :param job_uuid: A string representing the job UUID.
107
+ :param total_results: An integer representing the total number of results.
108
+ """
109
+ super().__init__(data)
110
+ from edsl.data.Cache import Cache
111
+ from edsl.jobs.tasks.TaskHistory import TaskHistory
112
+
113
+ self.survey = survey
114
+ self.created_columns = created_columns or []
115
+ self._job_uuid = job_uuid
116
+ self._total_results = total_results
117
+ self.cache = cache or Cache()
118
+
119
+ self.task_history = task_history or TaskHistory(interviews=[])
120
+
121
+ if hasattr(self, "_add_output_functions"):
122
+ self._add_output_functions()
123
+
124
+ def leaves(self):
125
+ leaves = []
126
+ for result in self:
127
+ leaves.extend(result.leaves())
128
+ return leaves
129
+
130
+ def tree(
131
+ self,
132
+ fold_attributes: Optional[List[str]] = None,
133
+ drop: Optional[List[str]] = None,
134
+ open_file=True,
135
+ ) -> dict:
136
+ """Return the results as a tree."""
137
+ from edsl.results.tree_explore import FoldableHTMLTableGenerator
138
+
139
+ if drop is None:
140
+ drop = []
141
+
142
+ valid_attributes = [
143
+ "model",
144
+ "scenario",
145
+ "agent",
146
+ "answer",
147
+ "question",
148
+ "iteration",
149
+ ]
150
+ if fold_attributes is None:
151
+ fold_attributes = []
152
+
153
+ for attribute in fold_attributes:
154
+ if attribute not in valid_attributes:
155
+ raise ValueError(
156
+ f"Invalid fold attribute: {attribute}; must be in {valid_attributes}"
157
+ )
158
+ data = self.leaves()
159
+ generator = FoldableHTMLTableGenerator(data)
160
+ tree = generator.tree(fold_attributes=fold_attributes, drop=drop)
161
+ html_content = generator.generate_html(tree, fold_attributes)
162
+ import tempfile
163
+ from edsl.utilities.utilities import is_notebook
164
+
165
+ from IPython.display import display, HTML
166
+
167
+ if is_notebook():
168
+ import html
169
+ from IPython.display import display, HTML
170
+
171
+ height = 1000
172
+ width = 1000
173
+ escaped_output = html.escape(html_content)
174
+ # escaped_output = rendered_html
175
+ iframe = f""""
176
+ <iframe srcdoc="{ escaped_output }" style="width: {width}px; height: {height}px;"></iframe>
177
+ """
178
+ display(HTML(iframe))
179
+ return None
180
+
181
+ with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
182
+ f.write(html_content.encode())
183
+ print(f"HTML file has been generated: {f.name}")
184
+
185
+ if open_file:
186
+ import webbrowser
187
+ import time
188
+
189
+ time.sleep(1) # Wait for 1 second
190
+ # webbrowser.open(f.name)
191
+ import os
192
+
193
+ filename = f.name
194
+ webbrowser.open(f"file://{os.path.abspath(filename)}")
195
+
196
+ else:
197
+ return html_content
198
+
199
+ def code(self):
200
+ raise NotImplementedError
201
+
202
+ def __getitem__(self, i):
203
+ if isinstance(i, int):
204
+ return self.data[i]
205
+
206
+ if isinstance(i, slice):
207
+ return self.__class__(survey=self.survey, data=self.data[i])
208
+
209
+ if isinstance(i, str):
210
+ return self.to_dict()[i]
211
+
212
+ raise TypeError("Invalid argument type")
213
+
214
+ def _update_results(self) -> None:
215
+ from edsl import Agent, Scenario
216
+ from edsl.language_models import LanguageModel
217
+ from edsl.results import Result
218
+
219
+ if self._job_uuid and len(self.data) < self._total_results:
220
+ results = [
221
+ Result(
222
+ agent=Agent.from_dict(json.loads(r.agent)),
223
+ scenario=Scenario.from_dict(json.loads(r.scenario)),
224
+ model=LanguageModel.from_dict(json.loads(r.model)),
225
+ iteration=1,
226
+ answer=json.loads(r.answer),
227
+ )
228
+ for r in CRUD.read_results(self._job_uuid)
229
+ ]
230
+ self.data = results
231
+
232
+ def __add__(self, other: Results) -> Results:
233
+ """Add two Results objects together.
234
+ They must have the same survey and created columns.
235
+ :param other: A Results object.
236
+
237
+ Example:
238
+
239
+ >>> r = Results.example()
240
+ >>> r2 = Results.example()
241
+ >>> r3 = r + r2
242
+ """
243
+ if self.survey != other.survey:
244
+ raise ResultsError(
245
+ "The surveys are not the same so the the results cannot be added together."
246
+ )
247
+ if self.created_columns != other.created_columns:
248
+ raise ResultsError(
249
+ "The created columns are not the same so they cannot be added together."
250
+ )
251
+
252
+ return Results(
253
+ survey=self.survey,
254
+ data=self.data + other.data,
255
+ created_columns=self.created_columns,
256
+ )
257
+
258
+ def __repr__(self) -> str:
259
+ import reprlib
260
+
261
+ return f"Results(data = {reprlib.repr(self.data)}, survey = {repr(self.survey)}, created_columns = {self.created_columns})"
262
+
263
+ def _repr_html_(self) -> str:
264
+ from IPython.display import HTML
265
+
266
+ json_str = json.dumps(self.to_dict()["data"], indent=4)
267
+ return f"<pre>{json_str}</pre>"
268
+
269
+ def _to_dict(self, sort=False):
270
+ from edsl.data.Cache import Cache
271
+
272
+ if sort:
273
+ data = sorted([result for result in self.data], key=lambda x: hash(x))
274
+ else:
275
+ data = [result for result in self.data]
276
+ return {
277
+ "data": [result.to_dict() for result in data],
278
+ "survey": self.survey.to_dict(),
279
+ "created_columns": self.created_columns,
280
+ "cache": Cache() if not hasattr(self, "cache") else self.cache.to_dict(),
281
+ "task_history": self.task_history.to_dict(),
282
+ }
283
+
284
+ def compare(self, other_results):
285
+ """
286
+ Compare two Results objects and return the differences.
287
+ """
288
+ hashes_0 = [hash(result) for result in self]
289
+ hashes_1 = [hash(result) for result in other_results]
290
+
291
+ in_self_but_not_other = set(hashes_0).difference(set(hashes_1))
292
+ in_other_but_not_self = set(hashes_1).difference(set(hashes_0))
293
+
294
+ indicies_self = [hashes_0.index(h) for h in in_self_but_not_other]
295
+ indices_other = [hashes_1.index(h) for h in in_other_but_not_self]
296
+ return {
297
+ "a_not_b": [self[i] for i in indicies_self],
298
+ "b_not_a": [other_results[i] for i in indices_other],
299
+ }
300
+
301
+ @property
302
+ def has_unfixed_exceptions(self):
303
+ return self.task_history.has_unfixed_exceptions
304
+
305
+ @add_edsl_version
306
+ def to_dict(self) -> dict[str, Any]:
307
+ """Convert the Results object to a dictionary.
308
+
309
+ The dictionary can be quite large, as it includes all of the data in the Results object.
310
+
311
+ Example: Illustrating just the keys of the dictionary.
312
+
313
+ >>> r = Results.example()
314
+ >>> r.to_dict().keys()
315
+ dict_keys(['data', 'survey', 'created_columns', 'cache', 'task_history', 'edsl_version', 'edsl_class_name'])
316
+ """
317
+ return self._to_dict()
318
+
319
+ def __hash__(self) -> int:
320
+ return dict_hash(self._to_dict(sort=True))
321
+
322
+ @property
323
+ def hashes(self) -> set:
324
+ return set(hash(result) for result in self.data)
325
+
326
+ def sample(self, n: int) -> Results:
327
+ """Return a random sample of the results.
328
+
329
+ :param n: The number of samples to return.
330
+
331
+ >>> from edsl.results import Results
332
+ >>> r = Results.example()
333
+ >>> len(r.sample(2))
334
+ 2
335
+ """
336
+ indices = None
337
+
338
+ for entry in self:
339
+ key, values = list(entry.items())[0]
340
+ if indices is None: # gets the indices for the first time
341
+ indices = list(range(len(values)))
342
+ sampled_indices = random.sample(indices, n)
343
+ if n > len(indices):
344
+ raise ResultsError(
345
+ f"Cannot sample {n} items from a list of length {len(indices)}."
346
+ )
347
+ entry[key] = [values[i] for i in sampled_indices]
348
+
349
+ return self
350
+
351
+ @classmethod
352
+ @remove_edsl_version
353
+ def from_dict(cls, data: dict[str, Any]) -> Results:
354
+ """Convert a dictionary to a Results object.
355
+
356
+ :param data: A dictionary representation of a Results object.
357
+
358
+ Example:
359
+
360
+ >>> r = Results.example()
361
+ >>> d = r.to_dict()
362
+ >>> r2 = Results.from_dict(d)
363
+ >>> r == r2
364
+ True
365
+ """
366
+ from edsl import Survey, Cache
367
+ from edsl.results.Result import Result
368
+ from edsl.jobs.tasks.TaskHistory import TaskHistory
369
+
370
+ try:
371
+ results = cls(
372
+ survey=Survey.from_dict(data["survey"]),
373
+ data=[Result.from_dict(r) for r in data["data"]],
374
+ created_columns=data.get("created_columns", None),
375
+ cache=(
376
+ Cache.from_dict(data.get("cache")) if "cache" in data else Cache()
377
+ ),
378
+ task_history=TaskHistory.from_dict(data.get("task_history")),
379
+ )
380
+ except Exception as e:
381
+ raise ResultsDeserializationError(f"Error in Results.from_dict: {e}")
382
+ return results
383
+
384
+ ######################
385
+ ## Convenience methods
386
+ ## & Report methods
387
+ ######################
388
+ @property
389
+ def _key_to_data_type(self) -> dict[str, str]:
390
+ """
391
+ Return a mapping of keys (how_feeling, status, etc.) to strings representing data types.
392
+
393
+ Objects such as Agent, Answer, Model, Scenario, etc.
394
+ - Uses the key_to_data_type property of the Result class.
395
+ - Includes any columns that the user has created with `mutate`
396
+ """
397
+ d: dict = {}
398
+ for result in self.data:
399
+ d.update(result.key_to_data_type)
400
+ for column in self.created_columns:
401
+ d[column] = "answer"
402
+
403
+ return d
404
+
405
+ @property
406
+ def _data_type_to_keys(self) -> dict[str, str]:
407
+ """
408
+ Return a mapping of strings representing data types (objects such as Agent, Answer, Model, Scenario, etc.) to keys (how_feeling, status, etc.)
409
+ - Uses the key_to_data_type property of the Result class.
410
+ - Includes any columns that the user has created with `mutate`
411
+
412
+ Example:
413
+
414
+ >>> r = Results.example()
415
+ >>> r._data_type_to_keys
416
+ defaultdict(...
417
+ """
418
+ d: dict = defaultdict(set)
419
+ for result in self.data:
420
+ for key, value in result.key_to_data_type.items():
421
+ d[value] = d[value].union(set({key}))
422
+ for column in self.created_columns:
423
+ d["answer"] = d["answer"].union(set({column}))
424
+ return d
425
+
426
+ @property
427
+ def columns(self) -> list[str]:
428
+ """Return a list of all of the columns that are in the Results.
429
+
430
+ Example:
431
+
432
+ >>> r = Results.example()
433
+ >>> r.columns
434
+ ['agent.agent_instruction', ...]
435
+ """
436
+ column_names = [f"{v}.{k}" for k, v in self._key_to_data_type.items()]
437
+ return sorted(column_names)
438
+
439
+ @property
440
+ def answer_keys(self) -> dict[str, str]:
441
+ """Return a mapping of answer keys to question text.
442
+
443
+ Example:
444
+
445
+ >>> r = Results.example()
446
+ >>> r.answer_keys
447
+ {'how_feeling': 'How are you this {{ period }}?', 'how_feeling_yesterday': 'How were you feeling yesterday {{ period }}?'}
448
+ """
449
+ from edsl.utilities.utilities import shorten_string
450
+
451
+ if not self.survey:
452
+ raise ResultsError("Survey is not defined so no answer keys are available.")
453
+
454
+ answer_keys = self._data_type_to_keys["answer"]
455
+ answer_keys = {k for k in answer_keys if "_comment" not in k}
456
+ questions_text = [
457
+ self.survey.get_question(k).question_text for k in answer_keys
458
+ ]
459
+ short_question_text = [shorten_string(q, 80) for q in questions_text]
460
+ initial_dict = dict(zip(answer_keys, short_question_text))
461
+ sorted_dict = {key: initial_dict[key] for key in sorted(initial_dict)}
462
+ return sorted_dict
463
+
464
+ @property
465
+ def agents(self) -> AgentList:
466
+ """Return a list of all of the agents in the Results.
467
+
468
+ Example:
469
+
470
+ >>> r = Results.example()
471
+ >>> r.agents
472
+ AgentList([Agent(traits = {'status': 'Joyful'}), Agent(traits = {'status': 'Joyful'}), Agent(traits = {'status': 'Sad'}), Agent(traits = {'status': 'Sad'})])
473
+ """
474
+ from edsl import AgentList
475
+
476
+ return AgentList([r.agent for r in self.data])
477
+
478
+ @property
479
+ def models(self) -> ModelList:
480
+ """Return a list of all of the models in the Results.
481
+
482
+ Example:
483
+
484
+ >>> r = Results.example()
485
+ >>> r.models[0]
486
+ Model(model_name = ...)
487
+ """
488
+ from edsl import ModelList
489
+
490
+ return ModelList([r.model for r in self.data])
491
+
492
+ @property
493
+ def scenarios(self) -> ScenarioList:
494
+ """Return a list of all of the scenarios in the Results.
495
+
496
+ Example:
497
+
498
+ >>> r = Results.example()
499
+ >>> r.scenarios
500
+ ScenarioList([Scenario({'period': 'morning'}), Scenario({'period': 'afternoon'}), Scenario({'period': 'morning'}), Scenario({'period': 'afternoon'})])
501
+ """
502
+ from edsl import ScenarioList
503
+
504
+ return ScenarioList([r.scenario for r in self.data])
505
+
506
+ @property
507
+ def agent_keys(self) -> list[str]:
508
+ """Return a set of all of the keys that are in the Agent data.
509
+
510
+ Example:
511
+
512
+ >>> r = Results.example()
513
+ >>> r.agent_keys
514
+ ['agent_instruction', 'agent_name', 'status']
515
+ """
516
+ return sorted(self._data_type_to_keys["agent"])
517
+
518
+ @property
519
+ def model_keys(self) -> list[str]:
520
+ """Return a set of all of the keys that are in the LanguageModel data.
521
+
522
+ >>> r = Results.example()
523
+ >>> r.model_keys
524
+ ['frequency_penalty', 'logprobs', 'max_tokens', 'model', 'presence_penalty', 'temperature', 'top_logprobs', 'top_p']
525
+ """
526
+ return sorted(self._data_type_to_keys["model"])
527
+
528
+ @property
529
+ def scenario_keys(self) -> list[str]:
530
+ """Return a set of all of the keys that are in the Scenario data.
531
+
532
+ >>> r = Results.example()
533
+ >>> r.scenario_keys
534
+ ['period']
535
+ """
536
+ return sorted(self._data_type_to_keys["scenario"])
537
+
538
+ @property
539
+ def question_names(self) -> list[str]:
540
+ """Return a list of all of the question names.
541
+
542
+ Example:
543
+
544
+ >>> r = Results.example()
545
+ >>> r.question_names
546
+ ['how_feeling', 'how_feeling_yesterday']
547
+ """
548
+ if self.survey is None:
549
+ return []
550
+ return sorted(list(self.survey.question_names))
551
+
552
+ @property
553
+ def all_keys(self) -> list[str]:
554
+ """Return a set of all of the keys that are in the Results.
555
+
556
+ Example:
557
+
558
+ >>> r = Results.example()
559
+ >>> r.all_keys
560
+ ['agent_instruction', 'agent_name', 'frequency_penalty', 'how_feeling', 'how_feeling_yesterday', 'logprobs', 'max_tokens', 'model', 'period', 'presence_penalty', 'status', 'temperature', 'top_logprobs', 'top_p']
561
+ """
562
+ answer_keys = set(self.answer_keys)
563
+ all_keys = (
564
+ answer_keys.union(self.agent_keys)
565
+ .union(self.scenario_keys)
566
+ .union(self.model_keys)
567
+ )
568
+ return sorted(list(all_keys))
569
+
570
+ def first(self) -> Result:
571
+ """Return the first observation in the results.
572
+
573
+ Example:
574
+
575
+ >>> r = Results.example()
576
+ >>> r.first()
577
+ Result(agent...
578
+ """
579
+ return self.data[0]
580
+
581
+ def answer_truncate(self, column: str, top_n=5, new_var_name=None) -> Results:
582
+ """Create a new variable that truncates the answers to the top_n.
583
+
584
+ :param column: The column to truncate.
585
+ :param top_n: The number of top answers to keep.
586
+ :param new_var_name: The name of the new variable. If None, it is the original name + '_truncated'.
587
+
588
+
589
+
590
+ """
591
+ if new_var_name is None:
592
+ new_var_name = column + "_truncated"
593
+ answers = list(self.select(column).tally().keys())
594
+
595
+ def f(x):
596
+ if x in answers[:top_n]:
597
+ return x
598
+ else:
599
+ return "Other"
600
+
601
+ return self.recode(column, recode_function=f, new_var_name=new_var_name)
602
+
603
+ def recode(
604
+ self, column: str, recode_function: Optional[Callable], new_var_name=None
605
+ ) -> Results:
606
+ """
607
+ Recode a column in the Results object.
608
+
609
+ >>> r = Results.example()
610
+ >>> r.recode('how_feeling', recode_function = lambda x: 1 if x == 'Great' else 0).select('how_feeling', 'how_feeling_recoded')
611
+ Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling_recoded': [0, 1, 0, 0]}])
612
+ """
613
+
614
+ if new_var_name is None:
615
+ new_var_name = column + "_recoded"
616
+ new_data = []
617
+ for result in self.data:
618
+ new_result = result.copy()
619
+ value = new_result.get_value("answer", column)
620
+ # breakpoint()
621
+ new_result["answer"][new_var_name] = recode_function(value)
622
+ new_data.append(new_result)
623
+
624
+ # print("Created new variable", new_var_name)
625
+ return Results(
626
+ survey=self.survey,
627
+ data=new_data,
628
+ created_columns=self.created_columns + [new_var_name],
629
+ )
630
+
631
+ def add_column(self, column_name: str, values: list) -> Results:
632
+ """Adds columns to Results
633
+
634
+ >>> r = Results.example()
635
+ >>> r.add_column('a', [1,2,3, 4]).select('a')
636
+ Dataset([{'answer.a': [1, 2, 3, 4]}])
637
+ """
638
+
639
+ assert len(values) == len(
640
+ self.data
641
+ ), "The number of values must match the number of results."
642
+ new_results = self.data.copy()
643
+ for i, result in enumerate(new_results):
644
+ result["answer"][column_name] = values[i]
645
+ return Results(
646
+ survey=self.survey,
647
+ data=new_results,
648
+ created_columns=self.created_columns + [column_name],
649
+ )
650
+
651
+ def add_columns_from_dict(self, columns: List[dict]) -> Results:
652
+ """Adds columns to Results from a list of dictionaries.
653
+
654
+ >>> r = Results.example()
655
+ >>> r.add_columns_from_dict([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a':3, 'b':2}, {'a':3, 'b':2}]).select('a', 'b')
656
+ Dataset([{'answer.a': [1, 3, 3, 3]}, {'answer.b': [2, 4, 2, 2]}])
657
+ """
658
+ keys = list(columns[0].keys())
659
+ for key in keys:
660
+ values = [d[key] for d in columns]
661
+ self = self.add_column(key, values)
662
+ return self
663
+
664
+ @staticmethod
665
+ def _create_evaluator(
666
+ result: Result, functions_dict: Optional[dict] = None
667
+ ) -> EvalWithCompoundTypes:
668
+ """Create an evaluator for the expression.
669
+
670
+ >>> from unittest.mock import Mock
671
+ >>> result = Mock()
672
+ >>> result.combined_dict = {'how_feeling': 'OK'}
673
+
674
+ >>> evaluator = Results._create_evaluator(result = result, functions_dict = {})
675
+ >>> evaluator.eval("how_feeling == 'OK'")
676
+ True
677
+
678
+ >>> result.combined_dict = {'answer': {'how_feeling': 'OK'}}
679
+ >>> evaluator = Results._create_evaluator(result = result, functions_dict = {})
680
+ >>> evaluator.eval("answer.how_feeling== 'OK'")
681
+ True
682
+
683
+ Note that you need to refer to the answer dictionary in the expression.
684
+
685
+ >>> evaluator.eval("how_feeling== 'OK'")
686
+ Traceback (most recent call last):
687
+ ...
688
+ simpleeval.NameNotDefined: 'how_feeling' is not defined for expression 'how_feeling== 'OK''
689
+ """
690
+ if functions_dict is None:
691
+ functions_dict = {}
692
+ evaluator = EvalWithCompoundTypes(
693
+ names=result.combined_dict, functions=functions_dict
694
+ )
695
+ evaluator.functions.update(int=int, float=float)
696
+ return evaluator
697
+
698
+ def mutate(
699
+ self, new_var_string: str, functions_dict: Optional[dict] = None
700
+ ) -> Results:
701
+ """
702
+ Creates a value in the Results object as if has been asked as part of the survey.
703
+
704
+ :param new_var_string: A string that is a valid Python expression.
705
+ :param functions_dict: A dictionary of functions that can be used in the expression. The keys are the function names and the values are the functions themselves.
706
+
707
+ It splits the new_var_string at the "=" and uses simple_eval
708
+
709
+ Example:
710
+
711
+ >>> r = Results.example()
712
+ >>> r.mutate('how_feeling_x = how_feeling + "x"').select('how_feeling_x')
713
+ Dataset([{'answer.how_feeling_x': ...
714
+ """
715
+ # extract the variable name and the expression
716
+ if "=" not in new_var_string:
717
+ raise ResultsBadMutationstringError(
718
+ f"Mutate requires an '=' in the string, but '{new_var_string}' doesn't have one."
719
+ )
720
+ raw_var_name, expression = new_var_string.split("=", 1)
721
+ var_name = raw_var_name.strip()
722
+ from edsl.utilities.utilities import is_valid_variable_name
723
+
724
+ if not is_valid_variable_name(var_name):
725
+ raise ResultsInvalidNameError(f"{var_name} is not a valid variable name.")
726
+
727
+ # create the evaluator
728
+ functions_dict = functions_dict or {}
729
+
730
+ def new_result(old_result: "Result", var_name: str) -> "Result":
731
+ evaluator = self._create_evaluator(old_result, functions_dict)
732
+ value = evaluator.eval(expression)
733
+ new_result = old_result.copy()
734
+ new_result["answer"][var_name] = value
735
+ return new_result
736
+
737
+ try:
738
+ new_data = [new_result(result, var_name) for result in self.data]
739
+ except Exception as e:
740
+ raise ResultsMutateError(f"Error in mutate. Exception:{e}")
741
+
742
+ return Results(
743
+ survey=self.survey,
744
+ data=new_data,
745
+ created_columns=self.created_columns + [var_name],
746
+ )
747
+
748
+ def rename(self, old_name: str, new_name: str) -> Results:
749
+ """Rename an answer column in a Results object.
750
+
751
+ >>> s = Results.example()
752
+ >>> s.rename('how_feeling', 'how_feeling_new').select('how_feeling_new')
753
+ Dataset([{'answer.how_feeling_new': ['OK', 'Great', 'Terrible', 'OK']}])
754
+
755
+ # TODO: Should we allow renaming of scenario fields as well? Probably.
756
+
757
+ """
758
+
759
+ for obs in self.data:
760
+ obs["answer"][new_name] = obs["answer"][old_name]
761
+ del obs["answer"][old_name]
762
+
763
+ return self
764
+
765
+ def shuffle(self, seed: Optional[str] = "edsl") -> Results:
766
+ """Shuffle the results.
767
+
768
+ Example:
769
+
770
+ >>> r = Results.example()
771
+ >>> r.shuffle(seed = 1)[0]
772
+ Result(...)
773
+ """
774
+ if seed != "edsl":
775
+ seed = random.seed(seed)
776
+
777
+ new_data = self.data.copy()
778
+ random.shuffle(new_data)
779
+ return Results(survey=self.survey, data=new_data, created_columns=None)
780
+
781
+ def sample(
782
+ self,
783
+ n: Optional[int] = None,
784
+ frac: Optional[float] = None,
785
+ with_replacement: bool = True,
786
+ seed: Optional[str] = "edsl",
787
+ ) -> Results:
788
+ """Sample the results.
789
+
790
+ :param n: An integer representing the number of samples to take.
791
+ :param frac: A float representing the fraction of samples to take.
792
+ :param with_replacement: A boolean representing whether to sample with replacement.
793
+ :param seed: An integer representing the seed for the random number generator.
794
+
795
+ Example:
796
+
797
+ >>> r = Results.example()
798
+ >>> len(r.sample(2))
799
+ 2
800
+ """
801
+ if seed != "edsl":
802
+ random.seed(seed)
803
+
804
+ if n is None and frac is None:
805
+ raise Exception("You must specify either n or frac.")
806
+
807
+ if n is not None and frac is not None:
808
+ raise Exception("You cannot specify both n and frac.")
809
+
810
+ if frac is not None and n is None:
811
+ n = int(frac * len(self.data))
812
+
813
+ if with_replacement:
814
+ new_data = random.choices(self.data, k=n)
815
+ else:
816
+ new_data = random.sample(self.data, n)
817
+
818
+ return Results(survey=self.survey, data=new_data, created_columns=None)
819
+
820
+ def select(self, *columns: Union[str, list[str]]) -> Results:
821
+ """
822
+ Select data from the results and format it.
823
+
824
+ :param columns: A list of strings, each of which is a column name. The column name can be a single key, e.g. "how_feeling", or a dot-separated string, e.g. "answer.how_feeling".
825
+
826
+ Example:
827
+
828
+ >>> results = Results.example()
829
+ >>> results.select('how_feeling')
830
+ Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}])
831
+
832
+ >>> results.select('how_feeling', 'model', 'how_feeling')
833
+ Dataset([{'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'model.model': ['...', '...', '...', '...']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}, {'answer.how_feeling': ['OK', 'Great', 'Terrible', 'OK']}])
834
+
835
+ >>> from edsl import Results; r = Results.example(); r.select('answer.how_feeling_y')
836
+ Dataset([{'answer.how_feeling_yesterday': ['Great', 'Good', 'OK', 'Terrible']}])
837
+ """
838
+
839
+ from edsl.results.Selector import Selector
840
+
841
+ if len(self) == 0:
842
+ raise Exception("No data to select from---the Results object is empty.")
843
+
844
+ selector = Selector(
845
+ known_data_types=self.known_data_types,
846
+ data_type_to_keys=self._data_type_to_keys,
847
+ key_to_data_type=self._key_to_data_type,
848
+ fetch_list_func=self._fetch_list,
849
+ columns=self.columns,
850
+ )
851
+ return selector.select(*columns)
852
+
853
+ def sort_by(self, *columns: str, reverse: bool = False) -> Results:
854
+ import warnings
855
+
856
+ warnings.warn(
857
+ "sort_by is deprecated. Use order_by instead.", DeprecationWarning
858
+ )
859
+ return self.order_by(*columns, reverse=reverse)
860
+
861
+ def _parse_column(self, column: str) -> tuple[str, str]:
862
+ if "." in column:
863
+ return column.split(".")
864
+ return self._key_to_data_type[column], column
865
+
866
+ def order_by(self, *columns: str, reverse: bool = False) -> Results:
867
+ """Sort the results by one or more columns.
868
+
869
+ :param columns: One or more column names as strings.
870
+ :param reverse: A boolean that determines whether to sort in reverse order.
871
+
872
+ Each column name can be a single key, e.g. "how_feeling", or a dot-separated string, e.g. "answer.how_feeling".
873
+
874
+ Example:
875
+
876
+ >>> r = Results.example()
877
+ >>> r.sort_by('how_feeling', reverse=False).select('how_feeling').print()
878
+ ┏━━━━━━━━━━━━━━┓
879
+ ┃ answer ┃
880
+ ┃ .how_feeling ┃
881
+ ┡━━━━━━━━━━━━━━┩
882
+ │ Great │
883
+ ├──────────────┤
884
+ │ OK │
885
+ ├──────────────┤
886
+ │ OK │
887
+ ├──────────────┤
888
+ │ Terrible │
889
+ └──────────────┘
890
+ >>> r.sort_by('how_feeling', reverse=True).select('how_feeling').print()
891
+ ┏━━━━━━━━━━━━━━┓
892
+ ┃ answer ┃
893
+ ┃ .how_feeling ┃
894
+ ┡━━━━━━━━━━━━━━┩
895
+ │ Terrible │
896
+ ├──────────────┤
897
+ │ OK │
898
+ ├──────────────┤
899
+ │ OK │
900
+ ├──────────────┤
901
+ │ Great │
902
+ └──────────────┘
903
+ """
904
+
905
+ def to_numeric_if_possible(v):
906
+ try:
907
+ return float(v)
908
+ except:
909
+ return v
910
+
911
+ def sort_key(item):
912
+ key_components = []
913
+ for col in columns:
914
+ data_type, key = self._parse_column(col)
915
+ value = item.get_value(data_type, key)
916
+ key_components.append(to_numeric_if_possible(value))
917
+ return tuple(key_components)
918
+
919
+ new_data = sorted(self.data, key=sort_key, reverse=reverse)
920
+ return Results(survey=self.survey, data=new_data, created_columns=None)
921
+
922
+ def filter(self, expression: str) -> Results:
923
+ """
924
+ Filter based on the given expression and returns the filtered `Results`.
925
+
926
+ :param expression: A string expression that evaluates to a boolean. The expression is applied to each element in `Results` to determine whether it should be included in the filtered results.
927
+
928
+ The `expression` parameter is a string that must resolve to a boolean value when evaluated against each element in `Results`.
929
+ This expression is used to determine which elements to include in the returned `Results`.
930
+
931
+ Example usage: Create an example `Results` instance and apply filters to it:
932
+
933
+ >>> r = Results.example()
934
+ >>> r.filter("how_feeling == 'Great'").select('how_feeling').print()
935
+ ┏━━━━━━━━━━━━━━┓
936
+ ┃ answer ┃
937
+ ┃ .how_feeling ┃
938
+ ┡━━━━━━━━━━━━━━┩
939
+ │ Great │
940
+ └──────────────┘
941
+
942
+ Example usage: Using an OR operator in the filter expression.
943
+
944
+ >>> r = Results.example().filter("how_feeling = 'Great'").select('how_feeling').print()
945
+ Traceback (most recent call last):
946
+ ...
947
+ edsl.exceptions.results.ResultsFilterError: You must use '==' instead of '=' in the filter expression.
948
+ ...
949
+
950
+ >>> r.filter("how_feeling == 'Great' or how_feeling == 'Terrible'").select('how_feeling').print()
951
+ ┏━━━━━━━━━━━━━━┓
952
+ ┃ answer ┃
953
+ ┃ .how_feeling ┃
954
+ ┡━━━━━━━━━━━━━━┩
955
+ │ Great │
956
+ ├──────────────┤
957
+ │ Terrible │
958
+ └──────────────┘
959
+ """
960
+
961
+ def has_single_equals(string):
962
+ if "!=" in string:
963
+ return False
964
+ if "=" in string and not (
965
+ "==" in string or "<=" in string or ">=" in string
966
+ ):
967
+ return True
968
+
969
+ if has_single_equals(expression):
970
+ raise ResultsFilterError(
971
+ "You must use '==' instead of '=' in the filter expression."
972
+ )
973
+
974
+ try:
975
+ # iterates through all the results and evaluates the expression
976
+ new_data = []
977
+ for result in self.data:
978
+ evaluator = self._create_evaluator(result)
979
+ result.check_expression(expression) # check expression
980
+ if evaluator.eval(expression):
981
+ new_data.append(result)
982
+
983
+ except ValueError as e:
984
+ raise ResultsFilterError(
985
+ f"Error in filter. Exception:{e}",
986
+ f"The expression you provided was: {expression}",
987
+ "See https://docs.expectedparrot.com/en/latest/results.html#filtering-results for more details.",
988
+ )
989
+ except Exception as e:
990
+ raise ResultsFilterError(
991
+ f"""Error in filter. Exception:{e}.""",
992
+ f"""The expression you provided was: {expression}.""",
993
+ """Please make sure that the expression is a valid Python expression that evaluates to a boolean.""",
994
+ """For example, 'how_feeling == "Great"' is a valid expression, as is 'how_feeling in ["Great", "Terrible"]'., """,
995
+ """However, 'how_feeling = "Great"' is not a valid expression.""",
996
+ """See https://docs.expectedparrot.com/en/latest/results.html#filtering-results for more details.""",
997
+ )
998
+
999
+ if len(new_data) == 0:
1000
+ import warnings
1001
+
1002
+ warnings.warn("No results remain after applying the filter.")
1003
+
1004
+ return Results(survey=self.survey, data=new_data, created_columns=None)
1005
+
1006
+ @classmethod
1007
+ def example(cls, randomize: bool = False) -> Results:
1008
+ """Return an example `Results` object.
1009
+
1010
+ Example usage:
1011
+
1012
+ >>> r = Results.example()
1013
+
1014
+ :param debug: if False, uses actual API calls
1015
+ """
1016
+ from edsl.jobs.Jobs import Jobs
1017
+ from edsl.data.Cache import Cache
1018
+
1019
+ c = Cache()
1020
+ job = Jobs.example(randomize=randomize)
1021
+ results = job.run(
1022
+ cache=c,
1023
+ stop_on_exception=True,
1024
+ skip_retry=True,
1025
+ raise_validation_errors=True,
1026
+ disable_remote_cache=True,
1027
+ disable_remote_inference=True,
1028
+ )
1029
+ return results
1030
+
1031
+ def rich_print(self):
1032
+ """Display an object as a table."""
1033
+ pass
1034
+
1035
+ def __str__(self):
1036
+ data = self.to_dict()["data"]
1037
+ return json.dumps(data, indent=4)
1038
+
1039
+ def show_exceptions(self, traceback=False):
1040
+ """Print the exceptions."""
1041
+ if hasattr(self, "task_history"):
1042
+ self.task_history.show_exceptions(traceback)
1043
+ else:
1044
+ print("No exceptions to show.")
1045
+
1046
+ def score(self, f: Callable) -> list:
1047
+ """Score the results using in a function.
1048
+
1049
+ :param f: A function that takes values from a Resul object and returns a score.
1050
+
1051
+ >>> r = Results.example()
1052
+ >>> def f(status): return 1 if status == 'Joyful' else 0
1053
+ >>> r.score(f)
1054
+ [1, 1, 0, 0]
1055
+ """
1056
+ return [r.score(f) for r in self.data]
1057
+
1058
+
1059
+ def main(): # pragma: no cover
1060
+ """Call the OpenAI API credits."""
1061
+ from edsl.results.Results import Results
1062
+
1063
+ results = Results.example(debug=True)
1064
+ print(results.filter("how_feeling == 'Great'").select("how_feeling"))
1065
+ print(results.mutate("how_feeling_x = how_feeling + 'x'").select("how_feeling_x"))
1066
+
1067
+
1068
+ if __name__ == "__main__":
1069
+ import doctest
1070
+
1071
+ doctest.testmod(optionflags=doctest.ELLIPSIS)