edsl 0.1.46__py3-none-any.whl → 0.1.47__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.
edsl/auto/utilities.py DELETED
@@ -1,218 +0,0 @@
1
- from textwrap import dedent
2
- import random
3
- from typing import List, TypeVar, Generator, Optional
4
- from edsl.auto.StageBase import StageBase
5
- from edsl.utilities.naming_utilities import sanitize_string
6
- from edsl import Agent, Survey, Model, Cache, AgentList
7
- from edsl import QuestionFreeText, Scenario
8
- from edsl import QuestionMultipleChoice, Scenario, Agent, ScenarioList
9
-
10
- StageClassType = TypeVar("StageClassType", bound=StageBase)
11
-
12
-
13
- def gen_pipeline(stages_list: List[StageClassType]) -> StageBase:
14
- """Takes as input a list of Stage classes & returns a pipeline of instantiated stages.
15
- A pipeline is a linked list of stages where each stage has a next_stage attribute.
16
-
17
- """
18
- pipeline = stages_list[0]()
19
- last_stage = pipeline
20
- for stage in stages_list[1:]:
21
- while last_stage.next_stage is not None: # find the end of the pipeline
22
- last_stage = last_stage.next_stage
23
- stage_to_add = stage()
24
- last_stage.next_stage = stage_to_add
25
- return pipeline
26
-
27
-
28
- q_eligibility = QuestionMultipleChoice(
29
- question_text=dedent(
30
- """\
31
- Consider this set of question: '{{ questions }}'.
32
- Consider this persona: '{{ persona }}'.
33
- Would this persona be able to answer all of these questions?
34
- """
35
- ),
36
- question_options=["No", "Yes"],
37
- question_name="eligibility",
38
- )
39
-
40
-
41
- def agent_list_eligibility(
42
- agent_list: AgentList,
43
- survey: Optional[Survey] = None,
44
- model: Optional[Model] = None,
45
- cache: Optional[Cache] = None,
46
- ) -> List[bool]:
47
- """
48
- Returns whether each agent in a list is elgible for a survey i.e., can answer every question.
49
-
50
- >>> from edsl.language_models import LanguageModel
51
- >>> m = LanguageModel.example(canned_response = "1", test_model = True)
52
- >>> agent_list_eligibility(AgentList.example())
53
- [True, True]
54
- >>> agent_list_eligibility(AgentList.example().add_trait('persona', 2*["Cool dude"]), survey = Survey.example(), model = m)
55
- [True, True]
56
- """
57
- if survey is None:
58
- return [True] * len(agent_list)
59
- if "persona" not in agent_list.all_traits:
60
- raise ValueError(
61
- f"Each agent needs to have a persona attribute; traits are {agent_list.all_traits}"
62
- )
63
- sl = agent_list.select("persona").to_scenario_list()
64
- sl.add_value("questions", [q.question_text for q in survey._questions])
65
- results = q_eligibility.by(sl).by(model).run(cache=cache)
66
- return [r == "Yes" for r in results.select("eligibility").to_list()]
67
-
68
-
69
- def agent_eligibility(
70
- agent: Agent,
71
- survey: Survey,
72
- model: Optional[Model] = None,
73
- cache: Optional[Cache] = None,
74
- ) -> bool:
75
- """NB: This could be parallelized.
76
-
77
- >>> from edsl.language_models import LanguageModel
78
- >>> m = LanguageModel.example(canned_response = "1", test_model = True)
79
- >>> agent_eligibility(agent = Agent.example().add_trait({'persona': "Persona"}), survey = Survey.example(), model = m)
80
- True
81
-
82
- """
83
- model = model or Model()
84
-
85
- questions = [q.question_text for q in survey._questions]
86
- persona = agent.traits["persona"]
87
- return (
88
- q_eligibility(model=model, questions=questions, persona=persona, cache=cache)
89
- == "Yes"
90
- )
91
-
92
-
93
- def gen_agent_traits(dimension_dict: dict, seed_value: Optional[str] = None):
94
- """
95
- >>> dimension_dict = {'attitude':['positive', 'negative']}
96
- >>> ag = gen_agent_traits(dimension_dict)
97
- >>> a = next(ag)
98
- >>> a == {'attitude': 'positive'} or a == {'attitude': 'negative'}
99
- True
100
- >>> len([next(ag) for _ in range(100)])
101
- 100
102
- """
103
- if seed_value is None:
104
- seed_value = "edsl"
105
-
106
- random.seed(seed_value)
107
-
108
- while True:
109
- new_agent_traits = {}
110
- for key, list_of_values in dimension_dict.items():
111
- new_agent_traits[key] = random.choice(list_of_values)
112
- yield new_agent_traits
113
-
114
-
115
- def agent_generator(
116
- persona: str,
117
- dimension_dict: dict,
118
- model: Optional[Model] = None,
119
- cache: Optional["Cache"] = None,
120
- ) -> Generator["Results", None, None]:
121
- """
122
- >>> from edsl.language_models import LanguageModel
123
- >>> m = LanguageModel.example(canned_response = "This is a cool dude.", test_model = True)
124
- >>> ag = agent_generator(persona = "Base person", dimension_dict = {'attitude':['Positive', 'Negative']}, model = m)
125
- >>> next(ag).select('new_agent_persona').first()
126
- 'This is a cool dude.'
127
- >>> next(ag).select('new_agent_persona').first()
128
- 'This is a cool dude.'
129
- """
130
-
131
- if model is None:
132
- model = Model()
133
-
134
- q = QuestionFreeText(
135
- question_text=dedent(
136
- """\
137
- Consider this persona: '{{ persona }}'.
138
- Now imagine writing a new persona with these traits:
139
- '{{ new_agent_traits }}'
140
- Please write this persona as a narrative.
141
- """
142
- ),
143
- question_name="new_agent_persona",
144
- )
145
- agent_trait_generator = gen_agent_traits(dimension_dict)
146
- codebook = {sanitize_string(k): k for k in dimension_dict.keys()}
147
- while True:
148
- new_agent_traits = next(agent_trait_generator)
149
- yield q(
150
- persona=persona,
151
- new_agent_traits=new_agent_traits,
152
- codebook=codebook,
153
- just_answer=False,
154
- cache=cache,
155
- model=model,
156
- )
157
-
158
-
159
- def create_agents(
160
- agent_generator: Generator["Results", None, None],
161
- survey: Optional[Survey] = None,
162
- num_agents=11,
163
- ) -> AgentList:
164
- """
165
- >>> from edsl.language_models import LanguageModel
166
- >>> m = LanguageModel.example(canned_response = "This is a cool dude.", test_model = True)
167
- >>> ag = agent_generator(persona = "Base person", dimension_dict = {'attitude':['Positive', 'Negative']}, model = m)
168
- >>> new_agent_list = create_agents(agent_generator = ag)
169
- >>> new_agent_list
170
-
171
- """
172
- agent_list = AgentList([])
173
-
174
- MAX_ITERATIONS_MULTIPLIER = 2
175
- iterations = 0
176
-
177
- while len(agent_list) < num_agents:
178
- iterations += 1
179
- candidate_agent = next(agent_generator)
180
- codebook = candidate_agent.select("codebook").to_list()[0]
181
-
182
- koobedoc = {v: k for k, v in codebook.items()}
183
- persona = candidate_agent.select("new_agent_persona").to_list()[0]
184
- traits = candidate_agent.select("new_agent_traits").to_list()[0]
185
- new_traits = {koobedoc[key]: value for key, value in traits.items()} | {
186
- "persona": persona
187
- }
188
- agent = Agent(traits=new_traits, codebook=codebook)
189
- if survey is not None:
190
- if agent_eligibility(agent, survey):
191
- agent_list.append(agent)
192
- else:
193
- print("Agent not eligible")
194
- else:
195
- agent_list.append(agent)
196
-
197
- if iterations > MAX_ITERATIONS_MULTIPLIER * num_agents:
198
- raise Exception("Too many failures")
199
-
200
- return agent_list
201
-
202
-
203
- if __name__ == "__main__":
204
- import doctest
205
-
206
- doctest.testmod()
207
- # from edsl.language_models import LanguageModel
208
-
209
- # m = LanguageModel.example(canned_response="This is a cool dude.", test_model=True)
210
- # ag = agent_generator(
211
- # persona="Base person",
212
- # dimension_dict={"attitude": ["Positive", "Negative"]},
213
- # model=m,
214
- # )
215
- # example = [next(ag).select("new_agent_persona").first() for _ in range(10)]
216
- # dimension_dict = {"attitude": ["positive", "negative"]}
217
- # ag = gen_agent_traits(dimension_dict)
218
- # example = [next(ag) for _ in range(100)]
edsl/base/Base.py DELETED
@@ -1,279 +0,0 @@
1
- """Base class for all classes in the package. It provides rich printing and persistence of objects."""
2
-
3
- from abc import ABC, abstractmethod, ABCMeta
4
- import gzip
5
- import io
6
- import json
7
- from typing import Any, Optional, Union
8
- from uuid import UUID
9
- from IPython.display import display
10
- from rich.console import Console
11
-
12
-
13
- class RichPrintingMixin:
14
- """Mixin for rich printing and persistence of objects."""
15
-
16
- def _for_console(self):
17
- """Return a string representation of the object for console printing."""
18
- with io.StringIO() as buf:
19
- console = Console(file=buf, record=True)
20
- table = self.rich_print()
21
- console.print(table)
22
- return console.export_text()
23
-
24
- def __str__(self):
25
- """Return a string representation of the object for console printing."""
26
- return self._for_console()
27
-
28
- def print(self):
29
- """Print the object to the console."""
30
- from edsl.utilities.utilities import is_notebook
31
-
32
- if is_notebook():
33
- display(self.rich_print())
34
- else:
35
- from rich.console import Console
36
-
37
- console = Console()
38
- console.print(self.rich_print())
39
-
40
-
41
- class PersistenceMixin:
42
- """Mixin for saving and loading objects to and from files."""
43
-
44
- def push(
45
- self,
46
- description: Optional[str] = None,
47
- visibility: Optional[str] = "unlisted",
48
- ):
49
- """Post the object to coop."""
50
- from edsl.coop import Coop
51
-
52
- c = Coop()
53
- return c.create(self, description, visibility)
54
-
55
- @classmethod
56
- def pull(cls, id_or_url: Union[str, UUID], exec_profile=None):
57
- """Pull the object from coop."""
58
- from edsl.coop import Coop
59
-
60
- if id_or_url.startswith("http"):
61
- uuid_value = id_or_url.split("/")[-1]
62
- else:
63
- uuid_value = id_or_url
64
-
65
- c = Coop()
66
-
67
- return c._get_base(cls, uuid_value, exec_profile=exec_profile)
68
-
69
- @classmethod
70
- def delete(cls, id_or_url: Union[str, UUID]):
71
- """Delete the object from coop."""
72
- from edsl.coop import Coop
73
-
74
- c = Coop()
75
- return c._delete_base(cls, id_or_url)
76
-
77
- @classmethod
78
- def patch(
79
- cls,
80
- id_or_url: Union[str, UUID],
81
- description: Optional[str] = None,
82
- value: Optional[Any] = None,
83
- visibility: Optional[str] = None,
84
- ):
85
- """
86
- Patch an uploaded objects attributes.
87
- - `description` changes the description of the object on Coop
88
- - `value` changes the value of the object on Coop. **has to be an EDSL object**
89
- - `visibility` changes the visibility of the object on Coop
90
- """
91
- from edsl.coop import Coop
92
-
93
- c = Coop()
94
- return c._patch_base(cls, id_or_url, description, value, visibility)
95
-
96
- @classmethod
97
- def search(cls, query):
98
- """Search for objects on coop."""
99
- from edsl.coop import Coop
100
-
101
- c = Coop()
102
- return c.search(cls, query)
103
-
104
- def save(self, filename, compress=True):
105
- """Save the object to a file as zippped JSON.
106
-
107
- >>> obj.save("obj.json.gz")
108
-
109
- """
110
- if filename.endswith("json.gz"):
111
- import warnings
112
-
113
- warnings.warn(
114
- "Do not apply the file extensions. The filename should not end with 'json.gz'."
115
- )
116
- filename = filename[:-7]
117
- if filename.endswith("json"):
118
- filename = filename[:-4]
119
- warnings.warn(
120
- "Do not apply the file extensions. The filename should not end with 'json'."
121
- )
122
-
123
- if compress:
124
- with gzip.open(filename + ".json.gz", "wb") as f:
125
- f.write(json.dumps(self.to_dict()).encode("utf-8"))
126
- else:
127
- with open(filename + ".json", "w") as f:
128
- f.write(json.dumps(self.to_dict()))
129
-
130
- @staticmethod
131
- def open_compressed_file(filename):
132
- with gzip.open(filename, "rb") as f:
133
- file_contents = f.read()
134
- file_contents_decoded = file_contents.decode("utf-8")
135
- d = json.loads(file_contents_decoded)
136
- return d
137
-
138
- @staticmethod
139
- def open_regular_file(filename):
140
- with open(filename, "r") as f:
141
- d = json.loads(f.read())
142
- return d
143
-
144
- @classmethod
145
- def load(cls, filename):
146
- """Load the object from a file.
147
-
148
- >>> obj = cls.load("obj.json.gz")
149
-
150
- """
151
-
152
- if filename.endswith("json.gz"):
153
- d = cls.open_compressed_file(filename)
154
- elif filename.endswith("json"):
155
- d = cls.open_regular_file(filename)
156
- else:
157
- try:
158
- d = cls.open_compressed_file(filename)
159
- except:
160
- d = cls.open_regular_file(filename)
161
- finally:
162
- raise ValueError("File must be a json or json.gz file")
163
-
164
- return cls.from_dict(d)
165
-
166
-
167
- class RegisterSubclassesMeta(ABCMeta):
168
- """Metaclass for registering subclasses."""
169
-
170
- _registry = {}
171
-
172
- def __init__(cls, name, bases, nmspc):
173
- """Register the class in the registry upon creation."""
174
- super(RegisterSubclassesMeta, cls).__init__(name, bases, nmspc)
175
- if cls.__name__ != "Base":
176
- RegisterSubclassesMeta._registry[cls.__name__] = cls
177
-
178
- @staticmethod
179
- def get_registry():
180
- """Return the registry of subclasses."""
181
- return dict(RegisterSubclassesMeta._registry)
182
-
183
-
184
- class DiffMethodsMixin:
185
- def __sub__(self, other):
186
- """Return the difference between two objects."""
187
- from edsl.BaseDiff import BaseDiff
188
-
189
- return BaseDiff(self, other)
190
-
191
-
192
- class Base(
193
- RichPrintingMixin,
194
- PersistenceMixin,
195
- DiffMethodsMixin,
196
- ABC,
197
- metaclass=RegisterSubclassesMeta,
198
- ):
199
- """Base class for all classes in the package."""
200
-
201
- # def __getitem__(self, key):
202
- # return getattr(self, key)
203
-
204
- # @abstractmethod
205
- # def _repr_html_(self) -> str:
206
- # raise NotImplementedError("This method is not implemented yet.")
207
-
208
- # @abstractmethod
209
- # def _repr_(self) -> str:
210
- # raise NotImplementedError("This method is not implemented yet.")
211
-
212
- def keys(self):
213
- """Return the keys of the object."""
214
- _keys = list(self.to_dict().keys())
215
- if "edsl_version" in _keys:
216
- _keys.remove("edsl_version")
217
- if "edsl_class_name" in _keys:
218
- _keys.remove("edsl_class_name")
219
- return _keys
220
-
221
- def values(self):
222
- """Return the values of the object."""
223
- data = self.to_dict()
224
- keys = self.keys()
225
- return {data[key] for key in keys}
226
-
227
- def _repr_html_(self):
228
- from edsl.utilities.utilities import data_to_html
229
-
230
- return data_to_html(self.to_dict())
231
-
232
- def __eq__(self, other):
233
- """Return whether two objects are equal."""
234
- import inspect
235
-
236
- if not isinstance(other, self.__class__):
237
- return False
238
- if "sort" in inspect.signature(self.to_dict).parameters:
239
- return self.to_dict(sort=True) == other.to_dict(sort=True)
240
- else:
241
- return self.to_dict() == other.to_dict()
242
-
243
- @abstractmethod
244
- def example():
245
- """This method should be implemented by subclasses."""
246
- raise NotImplementedError("This method is not implemented yet.")
247
-
248
- @abstractmethod
249
- def rich_print():
250
- """This method should be implemented by subclasses."""
251
- raise NotImplementedError("This method is not implemented yet.")
252
-
253
- @abstractmethod
254
- def to_dict():
255
- """This method should be implemented by subclasses."""
256
- raise NotImplementedError("This method is not implemented yet.")
257
-
258
- @abstractmethod
259
- def from_dict():
260
- """This method should be implemented by subclasses."""
261
- raise NotImplementedError("This method is not implemented yet.")
262
-
263
- @abstractmethod
264
- def code():
265
- """This method should be implemented by subclasses."""
266
- raise NotImplementedError("This method is not implemented yet.")
267
-
268
- def show_methods(self, show_docstrings=True):
269
- """Show the methods of the object."""
270
- public_methods_with_docstrings = [
271
- (method, getattr(self, method).__doc__)
272
- for method in dir(self)
273
- if callable(getattr(self, method)) and not method.startswith("_")
274
- ]
275
- if show_docstrings:
276
- for method, documentation in public_methods_with_docstrings:
277
- print(f"{method}: {documentation}")
278
- else:
279
- return [x[0] for x in public_methods_with_docstrings]
File without changes
File without changes