edsl 0.1.38.dev1__py3-none-any.whl → 0.1.38.dev3__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 (263) hide show
  1. edsl/Base.py +303 -303
  2. edsl/BaseDiff.py +260 -260
  3. edsl/TemplateLoader.py +24 -24
  4. edsl/__init__.py +49 -48
  5. edsl/__version__.py +1 -1
  6. edsl/agents/Agent.py +858 -855
  7. edsl/agents/AgentList.py +362 -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 +279 -289
  26. edsl/config.py +149 -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 +961 -958
  35. edsl/coop/utils.py +131 -131
  36. edsl/data/Cache.py +530 -527
  37. edsl/data/CacheEntry.py +228 -228
  38. edsl/data/CacheHandler.py +149 -149
  39. edsl/data/RemoteCacheSync.py +97 -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 +173 -173
  45. edsl/exceptions/BaseException.py +21 -21
  46. edsl/exceptions/__init__.py +54 -54
  47. edsl/exceptions/agents.py +42 -38
  48. edsl/exceptions/cache.py +5 -0
  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 +156 -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/TestService.py +89 -89
  72. edsl/inference_services/TogetherAIService.py +170 -170
  73. edsl/inference_services/models_available_cache.py +118 -118
  74. edsl/inference_services/rate_limits_cache.py +25 -25
  75. edsl/inference_services/registry.py +39 -39
  76. edsl/inference_services/write_available.py +10 -10
  77. edsl/jobs/Answers.py +56 -56
  78. edsl/jobs/Jobs.py +1358 -1347
  79. edsl/jobs/__init__.py +1 -1
  80. edsl/jobs/buckets/BucketCollection.py +63 -63
  81. edsl/jobs/buckets/ModelBuckets.py +65 -65
  82. edsl/jobs/buckets/TokenBucket.py +251 -248
  83. edsl/jobs/interviews/Interview.py +661 -661
  84. edsl/jobs/interviews/InterviewExceptionCollection.py +99 -99
  85. edsl/jobs/interviews/InterviewExceptionEntry.py +186 -186
  86. edsl/jobs/interviews/InterviewStatistic.py +63 -63
  87. edsl/jobs/interviews/InterviewStatisticsCollection.py +25 -25
  88. edsl/jobs/interviews/InterviewStatusDictionary.py +78 -78
  89. edsl/jobs/interviews/InterviewStatusLog.py +92 -92
  90. edsl/jobs/interviews/ReportErrors.py +66 -66
  91. edsl/jobs/interviews/interview_status_enum.py +9 -9
  92. edsl/jobs/runners/JobsRunnerAsyncio.py +361 -338
  93. edsl/jobs/runners/JobsRunnerStatus.py +332 -332
  94. edsl/jobs/tasks/QuestionTaskCreator.py +242 -242
  95. edsl/jobs/tasks/TaskCreators.py +64 -64
  96. edsl/jobs/tasks/TaskHistory.py +451 -442
  97. edsl/jobs/tasks/TaskStatusLog.py +23 -23
  98. edsl/jobs/tasks/task_status_enum.py +163 -163
  99. edsl/jobs/tokens/InterviewTokenUsage.py +27 -27
  100. edsl/jobs/tokens/TokenUsage.py +34 -34
  101. edsl/language_models/KeyLookup.py +30 -30
  102. edsl/language_models/LanguageModel.py +708 -706
  103. edsl/language_models/ModelList.py +109 -102
  104. edsl/language_models/RegisterLanguageModelsMeta.py +184 -184
  105. edsl/language_models/__init__.py +3 -3
  106. edsl/language_models/fake_openai_call.py +15 -15
  107. edsl/language_models/fake_openai_service.py +61 -61
  108. edsl/language_models/registry.py +137 -137
  109. edsl/language_models/repair.py +156 -156
  110. edsl/language_models/unused/ReplicateBase.py +83 -83
  111. edsl/language_models/utilities.py +64 -64
  112. edsl/notebooks/Notebook.py +258 -259
  113. edsl/notebooks/__init__.py +1 -1
  114. edsl/prompts/Prompt.py +357 -357
  115. edsl/prompts/__init__.py +2 -2
  116. edsl/questions/AnswerValidatorMixin.py +289 -289
  117. edsl/questions/QuestionBase.py +660 -656
  118. edsl/questions/QuestionBaseGenMixin.py +161 -161
  119. edsl/questions/QuestionBasePromptsMixin.py +217 -234
  120. edsl/questions/QuestionBudget.py +227 -227
  121. edsl/questions/QuestionCheckBox.py +359 -359
  122. edsl/questions/QuestionExtract.py +183 -183
  123. edsl/questions/QuestionFreeText.py +114 -114
  124. edsl/questions/QuestionFunctional.py +166 -159
  125. edsl/questions/QuestionList.py +231 -231
  126. edsl/questions/QuestionMultipleChoice.py +286 -286
  127. edsl/questions/QuestionNumerical.py +153 -153
  128. edsl/questions/QuestionRank.py +324 -324
  129. edsl/questions/Quick.py +41 -41
  130. edsl/questions/RegisterQuestionsMeta.py +71 -71
  131. edsl/questions/ResponseValidatorABC.py +174 -174
  132. edsl/questions/SimpleAskMixin.py +73 -73
  133. edsl/questions/__init__.py +26 -26
  134. edsl/questions/compose_questions.py +98 -98
  135. edsl/questions/decorators.py +21 -21
  136. edsl/questions/derived/QuestionLikertFive.py +76 -76
  137. edsl/questions/derived/QuestionLinearScale.py +87 -87
  138. edsl/questions/derived/QuestionTopK.py +93 -91
  139. edsl/questions/derived/QuestionYesNo.py +82 -82
  140. edsl/questions/descriptors.py +413 -413
  141. edsl/questions/prompt_templates/question_budget.jinja +13 -13
  142. edsl/questions/prompt_templates/question_checkbox.jinja +32 -32
  143. edsl/questions/prompt_templates/question_extract.jinja +11 -11
  144. edsl/questions/prompt_templates/question_free_text.jinja +3 -3
  145. edsl/questions/prompt_templates/question_linear_scale.jinja +11 -11
  146. edsl/questions/prompt_templates/question_list.jinja +17 -17
  147. edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -33
  148. edsl/questions/prompt_templates/question_numerical.jinja +36 -36
  149. edsl/questions/question_registry.py +147 -147
  150. edsl/questions/settings.py +12 -12
  151. edsl/questions/templates/budget/answering_instructions.jinja +7 -7
  152. edsl/questions/templates/budget/question_presentation.jinja +7 -7
  153. edsl/questions/templates/checkbox/answering_instructions.jinja +10 -10
  154. edsl/questions/templates/checkbox/question_presentation.jinja +22 -22
  155. edsl/questions/templates/extract/answering_instructions.jinja +7 -7
  156. edsl/questions/templates/likert_five/answering_instructions.jinja +10 -10
  157. edsl/questions/templates/likert_five/question_presentation.jinja +11 -11
  158. edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -5
  159. edsl/questions/templates/linear_scale/question_presentation.jinja +5 -5
  160. edsl/questions/templates/list/answering_instructions.jinja +3 -3
  161. edsl/questions/templates/list/question_presentation.jinja +5 -5
  162. edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -9
  163. edsl/questions/templates/multiple_choice/question_presentation.jinja +11 -11
  164. edsl/questions/templates/numerical/answering_instructions.jinja +6 -6
  165. edsl/questions/templates/numerical/question_presentation.jinja +6 -6
  166. edsl/questions/templates/rank/answering_instructions.jinja +11 -11
  167. edsl/questions/templates/rank/question_presentation.jinja +15 -15
  168. edsl/questions/templates/top_k/answering_instructions.jinja +8 -8
  169. edsl/questions/templates/top_k/question_presentation.jinja +22 -22
  170. edsl/questions/templates/yes_no/answering_instructions.jinja +6 -6
  171. edsl/questions/templates/yes_no/question_presentation.jinja +11 -11
  172. edsl/results/Dataset.py +293 -293
  173. edsl/results/DatasetExportMixin.py +717 -717
  174. edsl/results/DatasetTree.py +145 -145
  175. edsl/results/Result.py +456 -450
  176. edsl/results/Results.py +1071 -1071
  177. edsl/results/ResultsDBMixin.py +238 -238
  178. edsl/results/ResultsExportMixin.py +43 -43
  179. edsl/results/ResultsFetchMixin.py +33 -33
  180. edsl/results/ResultsGGMixin.py +121 -121
  181. edsl/results/ResultsToolsMixin.py +98 -98
  182. edsl/results/Selector.py +135 -135
  183. edsl/results/__init__.py +2 -2
  184. edsl/results/tree_explore.py +115 -115
  185. edsl/scenarios/FileStore.py +458 -458
  186. edsl/scenarios/Scenario.py +544 -546
  187. edsl/scenarios/ScenarioHtmlMixin.py +64 -64
  188. edsl/scenarios/ScenarioList.py +1112 -1112
  189. edsl/scenarios/ScenarioListExportMixin.py +52 -52
  190. edsl/scenarios/ScenarioListPdfMixin.py +261 -261
  191. edsl/scenarios/__init__.py +4 -4
  192. edsl/shared.py +1 -1
  193. edsl/study/ObjectEntry.py +173 -173
  194. edsl/study/ProofOfWork.py +113 -113
  195. edsl/study/SnapShot.py +80 -80
  196. edsl/study/Study.py +528 -528
  197. edsl/study/__init__.py +4 -4
  198. edsl/surveys/DAG.py +148 -148
  199. edsl/surveys/Memory.py +31 -31
  200. edsl/surveys/MemoryPlan.py +244 -244
  201. edsl/surveys/Rule.py +326 -330
  202. edsl/surveys/RuleCollection.py +387 -387
  203. edsl/surveys/Survey.py +1787 -1795
  204. edsl/surveys/SurveyCSS.py +261 -261
  205. edsl/surveys/SurveyExportMixin.py +259 -259
  206. edsl/surveys/SurveyFlowVisualizationMixin.py +121 -121
  207. edsl/surveys/SurveyQualtricsImport.py +284 -284
  208. edsl/surveys/__init__.py +3 -3
  209. edsl/surveys/base.py +53 -53
  210. edsl/surveys/descriptors.py +56 -56
  211. edsl/surveys/instructions/ChangeInstruction.py +49 -47
  212. edsl/surveys/instructions/Instruction.py +53 -51
  213. edsl/surveys/instructions/InstructionCollection.py +77 -77
  214. edsl/templates/error_reporting/base.html +23 -23
  215. edsl/templates/error_reporting/exceptions_by_model.html +34 -34
  216. edsl/templates/error_reporting/exceptions_by_question_name.html +16 -16
  217. edsl/templates/error_reporting/exceptions_by_type.html +16 -16
  218. edsl/templates/error_reporting/interview_details.html +115 -115
  219. edsl/templates/error_reporting/interviews.html +9 -9
  220. edsl/templates/error_reporting/overview.html +4 -4
  221. edsl/templates/error_reporting/performance_plot.html +1 -1
  222. edsl/templates/error_reporting/report.css +73 -73
  223. edsl/templates/error_reporting/report.html +117 -117
  224. edsl/templates/error_reporting/report.js +25 -25
  225. edsl/tools/__init__.py +1 -1
  226. edsl/tools/clusters.py +192 -192
  227. edsl/tools/embeddings.py +27 -27
  228. edsl/tools/embeddings_plotting.py +118 -118
  229. edsl/tools/plotting.py +112 -112
  230. edsl/tools/summarize.py +18 -18
  231. edsl/utilities/SystemInfo.py +28 -28
  232. edsl/utilities/__init__.py +22 -22
  233. edsl/utilities/ast_utilities.py +25 -25
  234. edsl/utilities/data/Registry.py +6 -6
  235. edsl/utilities/data/__init__.py +1 -1
  236. edsl/utilities/data/scooter_results.json +1 -1
  237. edsl/utilities/decorators.py +77 -77
  238. edsl/utilities/gcp_bucket/cloud_storage.py +96 -96
  239. edsl/utilities/interface.py +627 -627
  240. edsl/{conjure → utilities}/naming_utilities.py +263 -263
  241. edsl/utilities/repair_functions.py +28 -28
  242. edsl/utilities/restricted_python.py +70 -70
  243. edsl/utilities/utilities.py +409 -409
  244. {edsl-0.1.38.dev1.dist-info → edsl-0.1.38.dev3.dist-info}/LICENSE +21 -21
  245. {edsl-0.1.38.dev1.dist-info → edsl-0.1.38.dev3.dist-info}/METADATA +1 -1
  246. edsl-0.1.38.dev3.dist-info/RECORD +269 -0
  247. edsl/conjure/AgentConstructionMixin.py +0 -160
  248. edsl/conjure/Conjure.py +0 -62
  249. edsl/conjure/InputData.py +0 -659
  250. edsl/conjure/InputDataCSV.py +0 -48
  251. edsl/conjure/InputDataMixinQuestionStats.py +0 -182
  252. edsl/conjure/InputDataPyRead.py +0 -91
  253. edsl/conjure/InputDataSPSS.py +0 -8
  254. edsl/conjure/InputDataStata.py +0 -8
  255. edsl/conjure/QuestionOptionMixin.py +0 -76
  256. edsl/conjure/QuestionTypeMixin.py +0 -23
  257. edsl/conjure/RawQuestion.py +0 -65
  258. edsl/conjure/SurveyResponses.py +0 -7
  259. edsl/conjure/__init__.py +0 -9
  260. edsl/conjure/examples/placeholder.txt +0 -0
  261. edsl/conjure/utilities.py +0 -201
  262. edsl-0.1.38.dev1.dist-info/RECORD +0 -283
  263. {edsl-0.1.38.dev1.dist-info → edsl-0.1.38.dev3.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(add_edsl_version=False)["data"], indent=4)
267
+ return f"<pre>{json_str}</pre>"
268
+
269
+ def to_dict(self, sort=False, add_edsl_version=False) -> dict[str, Any]:
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
+
277
+ d = {
278
+ "data": [
279
+ result.to_dict(add_edsl_version=add_edsl_version) for result in data
280
+ ],
281
+ "survey": self.survey.to_dict(add_edsl_version=add_edsl_version),
282
+ "created_columns": self.created_columns,
283
+ "cache": (
284
+ Cache()
285
+ if not hasattr(self, "cache")
286
+ else self.cache.to_dict(add_edsl_version=add_edsl_version)
287
+ ),
288
+ "task_history": self.task_history.to_dict(),
289
+ }
290
+ if add_edsl_version:
291
+ from edsl import __version__
292
+
293
+ d["edsl_version"] = __version__
294
+ d["edsl_class_name"] = "Results"
295
+
296
+ return d
297
+
298
+ def compare(self, other_results):
299
+ """
300
+ Compare two Results objects and return the differences.
301
+ """
302
+ hashes_0 = [hash(result) for result in self]
303
+ hashes_1 = [hash(result) for result in other_results]
304
+
305
+ in_self_but_not_other = set(hashes_0).difference(set(hashes_1))
306
+ in_other_but_not_self = set(hashes_1).difference(set(hashes_0))
307
+
308
+ indicies_self = [hashes_0.index(h) for h in in_self_but_not_other]
309
+ indices_other = [hashes_1.index(h) for h in in_other_but_not_self]
310
+ return {
311
+ "a_not_b": [self[i] for i in indicies_self],
312
+ "b_not_a": [other_results[i] for i in indices_other],
313
+ }
314
+
315
+ @property
316
+ def has_unfixed_exceptions(self):
317
+ return self.task_history.has_unfixed_exceptions
318
+
319
+ def __hash__(self) -> int:
320
+ return dict_hash(self.to_dict(sort=True, add_edsl_version=False))
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)