edsl 0.1.38__py3-none-any.whl → 0.1.38.dev1__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 (86) hide show
  1. edsl/Base.py +34 -63
  2. edsl/BaseDiff.py +7 -7
  3. edsl/__init__.py +1 -2
  4. edsl/__version__.py +1 -1
  5. edsl/agents/Agent.py +11 -23
  6. edsl/agents/AgentList.py +23 -86
  7. edsl/agents/Invigilator.py +7 -18
  8. edsl/agents/InvigilatorBase.py +19 -0
  9. edsl/agents/PromptConstructor.py +4 -5
  10. edsl/auto/SurveyCreatorPipeline.py +1 -1
  11. edsl/auto/utilities.py +1 -1
  12. edsl/base/Base.py +13 -3
  13. edsl/config.py +0 -8
  14. edsl/conjure/AgentConstructionMixin.py +160 -0
  15. edsl/conjure/Conjure.py +62 -0
  16. edsl/conjure/InputData.py +659 -0
  17. edsl/conjure/InputDataCSV.py +48 -0
  18. edsl/conjure/InputDataMixinQuestionStats.py +182 -0
  19. edsl/conjure/InputDataPyRead.py +91 -0
  20. edsl/conjure/InputDataSPSS.py +8 -0
  21. edsl/conjure/InputDataStata.py +8 -0
  22. edsl/conjure/QuestionOptionMixin.py +76 -0
  23. edsl/conjure/QuestionTypeMixin.py +23 -0
  24. edsl/conjure/RawQuestion.py +65 -0
  25. edsl/conjure/SurveyResponses.py +7 -0
  26. edsl/conjure/__init__.py +9 -0
  27. edsl/conjure/examples/placeholder.txt +0 -0
  28. edsl/{utilities → conjure}/naming_utilities.py +1 -1
  29. edsl/conjure/utilities.py +201 -0
  30. edsl/coop/coop.py +7 -77
  31. edsl/data/Cache.py +17 -45
  32. edsl/data/CacheEntry.py +3 -8
  33. edsl/data/RemoteCacheSync.py +19 -0
  34. edsl/enums.py +0 -2
  35. edsl/exceptions/agents.py +0 -4
  36. edsl/inference_services/GoogleService.py +15 -7
  37. edsl/inference_services/registry.py +0 -2
  38. edsl/jobs/Jobs.py +559 -110
  39. edsl/jobs/buckets/TokenBucket.py +0 -3
  40. edsl/jobs/interviews/Interview.py +7 -7
  41. edsl/jobs/runners/JobsRunnerAsyncio.py +28 -156
  42. edsl/jobs/runners/JobsRunnerStatus.py +196 -194
  43. edsl/jobs/tasks/TaskHistory.py +19 -27
  44. edsl/language_models/LanguageModel.py +90 -52
  45. edsl/language_models/ModelList.py +14 -67
  46. edsl/language_models/registry.py +4 -57
  47. edsl/notebooks/Notebook.py +8 -7
  48. edsl/prompts/Prompt.py +3 -8
  49. edsl/questions/QuestionBase.py +30 -38
  50. edsl/questions/QuestionBaseGenMixin.py +1 -1
  51. edsl/questions/QuestionBasePromptsMixin.py +17 -0
  52. edsl/questions/QuestionExtract.py +4 -3
  53. edsl/questions/QuestionFunctional.py +3 -10
  54. edsl/questions/derived/QuestionTopK.py +0 -2
  55. edsl/questions/question_registry.py +6 -36
  56. edsl/results/Dataset.py +15 -146
  57. edsl/results/DatasetExportMixin.py +217 -231
  58. edsl/results/DatasetTree.py +4 -134
  59. edsl/results/Result.py +16 -31
  60. edsl/results/Results.py +65 -159
  61. edsl/scenarios/FileStore.py +13 -187
  62. edsl/scenarios/Scenario.py +18 -73
  63. edsl/scenarios/ScenarioList.py +76 -251
  64. edsl/surveys/MemoryPlan.py +1 -1
  65. edsl/surveys/Rule.py +5 -1
  66. edsl/surveys/RuleCollection.py +1 -1
  67. edsl/surveys/Survey.py +19 -25
  68. edsl/surveys/SurveyFlowVisualizationMixin.py +9 -67
  69. edsl/surveys/instructions/ChangeInstruction.py +7 -9
  70. edsl/surveys/instructions/Instruction.py +7 -21
  71. edsl/templates/error_reporting/interview_details.html +3 -3
  72. edsl/templates/error_reporting/interviews.html +9 -18
  73. edsl/utilities/utilities.py +0 -15
  74. {edsl-0.1.38.dist-info → edsl-0.1.38.dev1.dist-info}/METADATA +1 -2
  75. {edsl-0.1.38.dist-info → edsl-0.1.38.dev1.dist-info}/RECORD +77 -71
  76. edsl/exceptions/cache.py +0 -5
  77. edsl/inference_services/PerplexityService.py +0 -163
  78. edsl/jobs/JobsChecks.py +0 -147
  79. edsl/jobs/JobsPrompts.py +0 -268
  80. edsl/jobs/JobsRemoteInferenceHandler.py +0 -239
  81. edsl/results/CSSParameterizer.py +0 -108
  82. edsl/results/TableDisplay.py +0 -198
  83. edsl/results/table_display.css +0 -78
  84. edsl/scenarios/ScenarioJoin.py +0 -127
  85. {edsl-0.1.38.dist-info → edsl-0.1.38.dev1.dist-info}/LICENSE +0 -0
  86. {edsl-0.1.38.dist-info → edsl-0.1.38.dev1.dist-info}/WHEEL +0 -0
@@ -0,0 +1,160 @@
1
+ import random
2
+ from typing import Generator, List, Optional, Union, Callable
3
+ from edsl.agents.Agent import Agent
4
+ from edsl.agents.AgentList import AgentList
5
+ from edsl.questions import QuestionBase
6
+ from edsl.results.Results import Results
7
+
8
+
9
+ class AgentConstructionMixin:
10
+ def agent(self, index) -> Agent:
11
+ """Return an agent constructed from the data.
12
+
13
+ :param index: The index of the agent to construct.
14
+
15
+ >>> from edsl.conjure.InputData import InputDataABC
16
+ >>> id = InputDataABC.example()
17
+ >>> id.agent(0)
18
+ Agent(traits = {'morning': '1', 'feeling': '3'}, codebook = {'morning': 'how are you doing this morning?', 'feeling': 'how are you feeling?'})
19
+
20
+
21
+ """
22
+ responses = [responses[index] for responses in self.raw_data]
23
+ traits = {qn: r for qn, r in zip(self.question_names, responses)}
24
+
25
+ a = Agent(traits=traits, codebook=self.names_to_texts)
26
+
27
+ def construct_answer_dict_function(traits: dict) -> Callable:
28
+ def func(self, question: "QuestionBase", scenario=None):
29
+ return traits.get(question.question_name, None)
30
+
31
+ return func
32
+
33
+ a.add_direct_question_answering_method(construct_answer_dict_function(traits))
34
+ return a
35
+
36
+ def _agents(self, indices) -> Generator[Agent, None, None]:
37
+ """Return a generator of agents, one for each index."""
38
+ for idx in indices:
39
+ yield self.agent(idx)
40
+
41
+ def to_agent_list(
42
+ self,
43
+ indices: Optional[List] = None,
44
+ sample_size: int = None,
45
+ seed: str = "edsl",
46
+ remove_direct_question_answering_method: bool = True,
47
+ ) -> AgentList:
48
+ """Return an AgentList from the data.
49
+
50
+ :param indices: The indices of the agents to include.
51
+ :param sample_size: The number of agents to sample.
52
+ :param seed: The seed for the random number generator.
53
+
54
+ >>> from edsl.conjure.InputData import InputDataABC
55
+ >>> id = InputDataABC.example()
56
+ >>> al = id.to_agent_list()
57
+ >>> len(al) == id.num_observations
58
+ True
59
+ >>> al = id.to_agent_list(indices = [0, 1, 2])
60
+ Traceback (most recent call last):
61
+ ...
62
+ ValueError: Index 2 is greater than the number of agents 2.
63
+ """
64
+ if indices and (sample_size or seed != "edsl"):
65
+ raise ValueError(
66
+ "You cannot pass both indices and sample_size/seed, as these are mutually exclusive."
67
+ )
68
+
69
+ if indices:
70
+ if len(indices) == 0:
71
+ raise ValueError("Indices must be a non-empty list.")
72
+ if max(indices) >= self.num_observations:
73
+ raise ValueError(
74
+ f"Index {max(indices)} is greater than the number of agents {self.num_observations}."
75
+ )
76
+ if min(indices) < 0:
77
+ raise ValueError(f"Index {min(indices)} is less than 0.")
78
+
79
+ if indices is None:
80
+ if sample_size is None:
81
+ indices = range(self.num_observations)
82
+ else:
83
+ if sample_size > self.num_observations:
84
+ raise ValueError(
85
+ f"Sample size {sample_size} is greater than the number of agents {self.num_observations}."
86
+ )
87
+ random.seed(seed)
88
+ indices = random.sample(range(self.num_observations), sample_size)
89
+
90
+ agents = list(self._agents(indices))
91
+ if remove_direct_question_answering_method:
92
+ for a in agents:
93
+ a.remove_direct_question_answering_method()
94
+ return AgentList(agents)
95
+
96
+ def to_results(
97
+ self,
98
+ indices: Optional[List] = None,
99
+ sample_size: int = None,
100
+ seed: str = "edsl",
101
+ dryrun=False,
102
+ disable_remote_cache: bool = False,
103
+ disable_remote_inference: bool = False,
104
+ ) -> Union[Results, None]:
105
+ """Return the results of the survey.
106
+
107
+ :param indices: The indices of the agents to include.
108
+ :param sample_size: The number of agents to sample.
109
+ :param seed: The seed for the random number generator.
110
+ :param dryrun: If True, the survey will not be run, but the time to run it will be printed.
111
+
112
+ >>> from edsl.conjure.InputData import InputDataABC
113
+ >>> id = InputDataABC.example()
114
+ >>> r = id.to_results(disable_remote_cache = True, disable_remote_inference = True)
115
+ >>> len(r) == id.num_observations
116
+ True
117
+ """
118
+ agent_list = self.to_agent_list(
119
+ indices=indices,
120
+ sample_size=sample_size,
121
+ seed=seed,
122
+ remove_direct_question_answering_method=False,
123
+ )
124
+ DRYRUN_SAMPLE = 30
125
+ survey = self.to_survey()
126
+ if dryrun:
127
+ import time
128
+
129
+ start = time.time()
130
+ _ = survey.by(agent_list.sample(DRYRUN_SAMPLE)).run(
131
+ disable_remote_cache=disable_remote_cache,
132
+ disable_remote_inference=disable_remote_inference,
133
+ )
134
+ end = time.time()
135
+ print(f"Time to run {DRYRUN_SAMPLE} agents (s): {round(end - start, 2)}")
136
+ time_per_agent = (end - start) / DRYRUN_SAMPLE
137
+ full_sample_time = time_per_agent * len(agent_list)
138
+ if full_sample_time < 60:
139
+ print(
140
+ f"Full sample will take about {round(full_sample_time, 2)} seconds."
141
+ )
142
+ if full_sample_time > 60 and full_sample_time < 3600:
143
+ print(
144
+ f"Full sample will take about {round(full_sample_time / 60, 2)} minutes."
145
+ )
146
+ if full_sample_time > 3600:
147
+ print(
148
+ f"Full sample will take about {round(full_sample_time / 3600, 2)} hours."
149
+ )
150
+ return None
151
+ return survey.by(agent_list).run(
152
+ disable_remote_cache=disable_remote_cache,
153
+ disable_remote_inference=disable_remote_inference,
154
+ )
155
+
156
+
157
+ if __name__ == "__main__":
158
+ import doctest
159
+
160
+ doctest.testmod(optionflags=doctest.ELLIPSIS)
@@ -0,0 +1,62 @@
1
+ from typing import List, Optional, Dict, Callable
2
+
3
+
4
+ class Conjure:
5
+ def __new__(cls, datafile_name: str, *args, **kwargs):
6
+ if datafile_name.endswith(".csv"):
7
+ from edsl.conjure.InputDataCSV import InputDataCSV
8
+
9
+ return InputDataCSV(datafile_name, *args, **kwargs)
10
+ elif datafile_name.endswith(".sav"):
11
+ from edsl.conjure.InputDataSPSS import InputDataSPSS
12
+
13
+ return InputDataSPSS(datafile_name, *args, **kwargs)
14
+ elif datafile_name.endswith(".dta"):
15
+ from edsl.conjure.InputDataStata import InputDataStata
16
+
17
+ return InputDataStata(datafile_name, *args, **kwargs)
18
+ else:
19
+ raise ValueError("Unsupported file type")
20
+
21
+ def __init__(
22
+ self,
23
+ datafile_name: str,
24
+ config: Optional[dict] = None,
25
+ naming_function: Optional[Callable] = None,
26
+ raw_data: Optional[List] = None,
27
+ question_names: Optional[List[str]] = None,
28
+ question_texts: Optional[List[str]] = None,
29
+ answer_codebook: Optional[Dict] = None,
30
+ question_types: Optional[List[str]] = None,
31
+ question_options: Optional[List] = None,
32
+ order_options=False,
33
+ question_name_repair_func: Callable = None,
34
+ ):
35
+ # The __init__ method in Conjure won't be called because __new__ returns a different class instance.
36
+ pass
37
+
38
+ @classmethod
39
+ def example(cls):
40
+ from edsl.conjure.InputData import InputDataABC
41
+
42
+ return InputDataABC.example()
43
+
44
+
45
+ if __name__ == "__main__":
46
+ pass
47
+ # import glob
48
+
49
+ # for file in glob.glob("examples/*"):
50
+ # if file.endswith(".txt"):
51
+ # continue
52
+ # print("\n\n")
53
+ # print("Now processing:", file)
54
+ # conjure_instance = Conjure(file)
55
+ # print(conjure_instance)
56
+ # conjure_instance.to_results(dryrun=True)
57
+ # print("\n\n")
58
+
59
+ # # c = Conjure("mayors.sav")
60
+ # # al = c.to_agent_list()
61
+ # # s = c.to_survey()
62
+ # # r = c.results()