edsl 0.1.38.dev3__py3-none-any.whl → 0.1.38.dev4__py3-none-any.whl

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