Purpose
Scenarios allow you create variations and versions of questions efficiently. For example, we could create a question “How much do you enjoy {{ scenario.activity }}?” and use scenarios to replace the parameter activity with running or reading or other activities. Similarly, we could create a question “What do you see in this image? {{ scenario.image }}” and use scenarios to replace the parameter image with different images.How it works
Adding scenarios to a question–or to multiple questions at once in a survey–causes it to be administered multiple times, once for each scenario, with the parameter(s) replaced by the value(s) in the scenario. This allows us to administer different versions of a question together, either asynchronously (by default) or according to survey rules that we can specify (e.g., skip/stop logic), without having to create each version of a question manually.Metadata
Scenarios are also a convenient way to keep track of metadata or other information relating to a survey that is important to an analysis of the results. For example, say we are using scenarios to parameterize question texts with pieces of {{ scenario.content }} from a dataset. In the scenarios that we create for the content parameter we could also include key/value pairs for metadata about the content, such as the {{ scenario.author }}, {{ scenario.publication_date }}, or {{ scenario.source }}. This will automatically include the data in the survey results but without requiring us to also parameterize the question texts those fields. This allows us to analyze the responses in the context of the metadata and avoid having to match up the data with the metadata post-survey. Please see more details on this feature in examples below.Constructing a Scenario
To use a scenario, we start by creating a question that takes a parameter in double braces:key | value |
---|---|
activity | running |
ScenarioList
If multiple values will be used with a question or survey, we can create a list of Scenario objects that will be passed to the question or survey together. For example, here we create a list of scenarios and inspect them:activity |
---|
running |
reading |
Special method for creating scenarios
We can use the general purpose from_source() method to create a ScenarioList from a variety of data source types. For example, the following code will create the same scenario list as above: Each source type has its own set of parameters that can be passed to it:- “csv”
- “dataframe”
- “delimited_file”
- “dict”
- “directory”
- “dta”
- “excel”
- “google_doc”
- “google_sheet”
- “json”
- “latex”
- “list”
- “list_of_tuples”
- “pandas”
- “parquet”
- “pdf”
- “png”
- “pdf_to_image”
- “text”
- “tsv”
- “sqlite”
- “urls”
- “wikipedia”
Using a scenario
We use a Scenario or ScenarioList by adding it to a question or survey of questions, either when we are constructing questions or when running them. If we add scenarios to a question when running a survey (using the by() method), the scenario contents replace the parameters in the question text at runtime, and are stored in a separate column of the results. If we add scenarios to a question when constructing a survey (using the loop() method), the scenario contents become part of the question text and there is no separate column of the results for the scenarios. The most common situation is to add a scenario to a question when running it. This is done by passing the Scenario or ScenarioList object to the by() method of a question or survey and then chaining the run() method. For example, here we call the by() method on the example question created above and pass a scenario list when we run it:scenario.activity | answer.enjoy |
---|---|
running | Somewhat |
sleeping | Very much |
Looping
We use the loop() method to add scenarios to a question when constructing a survey. This method takes a ScenarioList and returns a list of new questions for each scenario that was passed. We can optionally include the scenario key in the question name as well as the question text. This allows us to control the question names when the new questions are created; otherwise a number is automatically added to the original question name in order to ensure uniqueness. For example:answer.enjoy_reading | answer.enjoy_running |
---|---|
Very much | Somewhat |
Note:The loop() method cannot be used with image or PDF scenarios, as these are not evaluated when the question is constructed. Instead, use the by() method to add these types of scenarios when running a survey (see image scenario examples below).
Multiple parameters
We can also create a Scenario for multiple parameters at once:scenario.unit | scenario.distance | answer.counting |
---|---|---|
inches | mile | There are 63,360 inches in a mile. |
Scenarios for question options
In the above examples we created scenarios in the question_text. We can also create a Scenario for question_options, e.g., in a multiple choice, checkbox, linear scale or other question type that requires them. Note that we do not include the scenario. prefix when using sceanrios for question options.answer.capital_of_france |
---|
Paris |
Scenario methods
There are a variety of methods for working with scenarios and scenario lists, including: concatenate, concatenate_to_list, concatenate_to_set, condense, drop, duplicate expand, filter, keep, mutate, order_by, rename, sample, shuffle, times, tranform, unpack_dict These methods can be used to manipulate scenarios and scenario lists in various ways, such as sampling a subset of scenarios, shuffling the order of scenarios, concatenating scenarios together, filtering scenarios based on certain criteria, and more. Examples of some of these methods are provided below.Combining Scenarios
We can combine multiple scenarios into a single Scenario object:key | value |
---|---|
food | drink |
apple | water |
food | drink | color | shape |
---|---|---|---|
apple | nan | nan | nan |
nan | water | nan | nan |
nan | nan | nan | red |
nan | nan | circle | nan |
food | drink | color | shape |
---|---|---|---|
apple | nan | nan | red |
apple | nan | circle | nan |
nan | water | nan | red |
nan | water | circle | nan |
Concatenating scenarios
There are several ScenarioList methods for concatenating scenarios. The method concatenate() can be used to concatenate specified fields into a single string field; the default separator is a semicolon:c | concat_a_b |
---|---|
3 | 1;2 |
6 | 4;5 |
c | concat_a_b |
---|---|
3 | 1,2 |
6 | 4,5 |
c | concat_a_b |
---|---|
3 | [1,2] |
6 | [4,5] |
c | concat_a_b |
---|---|
3 | {1,2} |
6 | {4,5} |
category | color | item |
---|---|---|
fruit | red | [‘apple’, ‘cherry’] |
fruit | yellow | [‘banana’] |
vegetable | green | [‘spinach’] |
scenario_0 | scenario_1 | scenario_2 |
---|---|---|
{‘id’: 1, ‘text’: ‘First’} | {‘id’: 2, ‘text’: ‘Second’} | {‘id’: 3, ‘text’: ‘Third’} |
item_0 | item_1 | item_2 |
---|---|---|
{‘id’: 1, ‘text’: ‘First’} | {‘id’: 2, ‘text’: ‘Second’} | {‘id’: 3, ‘text’: ‘Third’} |
Creating scenarios from a dataset
There are a variety of methods for creating and working with scenarios generated from datasets and different data types.Turning results into scenarios
The method to_scenario_list() can be used to turn the results of a survey into a list of scenarios. Example usage: Say we have some results from a survey where we asked agents to choose a random number between 1 and 1000:agent.persona | answer.random |
---|---|
Child | 7 |
Magician | 472 |
Olympic breakdancer | 529 |
persona | random |
---|---|
Child | 7 |
Magician | 472 |
Olympic breakdancer | 529 |
PDFs as textual scenarios
The ScenarioList method from_source(“pdf”, “path/to/pdf”) is a convenient way to extract information from large files. It allows you to read in a PDF and automatically create a list of textual scenarios for the individual pages of the file. Each scenario has the following keys which can be used as parameters in a question or stored as metadata, and renamed as desired: filename, page, text:Image scenarios
A Scenario can be generated from an image by passing the filepath as the value (the same as a PDF, as shown above). This is done by using the FileStore module to store the image and then passing the FileStore object to a Scenario. Example usage:answer.identify | answer.colors |
---|---|
The animal in the picture is a parrot. | [‘gray’, ‘green’, ‘yellow’, ‘pink’, ‘blue’, ‘black’] |
Note:You must use a vision model in order to run questions with images. We recommend testing whether a model can reliably identify your images before running a survey with them. You can also use the models page to check available models’ performance with test questions, including images.
Creating a scenario list from a list
Example usage:item |
---|
color |
food |
animal |
Creating a scenario list from a dictionary
Example usage:item |
---|
color |
food |
animal |
Creating a scenario list from a Wikipedia table
Example usage:Rank | Title | Studios | Worldwide gross | Year |
---|---|---|---|---|
1 | Titanic | Paramount Pictures/20th Century Fox | $1,843,201,268 | 1997 |
2 | Star Wars: Episode I - The Phantom Menace | 20th Century Fox | $924,317,558 | 1999 |
3 | Jurassic Park | Universal Pictures | $914,691,118 | 1993 |
4 | Independence Day | 20th Century Fox | $817,400,891 | 1996 |
5 | The Lion King | Walt Disney Studios | $763,455,561 | 1994 |
6 | Forrest Gump | Paramount Pictures | $677,387,716 | 1994 |
7 | The Sixth Sense | Walt Disney Studios | $672,806,292 | 1999 |
8 | The Lost World: Jurassic Park | Universal Pictures | $618,638,999 | 1997 |
9 | Men in Black | Sony Pictures/Columbia Pictures | $589,390,539 | 1997 |
10 | Armageddon | Walt Disney Studios | $553,709,788 | 1998 |
11 | Terminator 2: Judgment Day | TriStar Pictures | $519,843,345 | 1991 |
12 | Ghost | Paramount Pictures | $505,702,588 | 1990 |
13 | Aladdin | Walt Disney Studios | $504,050,219 | 1992 |
14 | Twister | Warner Bros./Universal Pictures | $494,471,524 | 1996 |
15 | Toy Story 2 | Walt Disney Studios | $485,015,179 | 1999 |
16 | Saving Private Ryan | DreamWorks Pictures/Paramount Pictures | $481,840,909 | 1998 |
17 | Home Alone | 20th Century Fox | $476,684,675 | 1990 |
18 | The Matrix | Warner Bros. | $463,517,383 | 1999 |
19 | Pretty Woman | Walt Disney Studios | $463,406,268 | 1990 |
20 | Mission: Impossible | Paramount Pictures | $457,696,359 | 1996 |
21 | Tarzan | Walt Disney Studios | $448,191,819 | 1999 |
22 | Mrs. Doubtfire | 20th Century Fox | $441,286,195 | 1993 |
23 | Dances with Wolves | Orion Pictures | $424,208,848 | 1990 |
24 | The Mummy | Universal Pictures | $415,933,406 | 1999 |
25 | The Bodyguard | Warner Bros. | $411,006,740 | 1992 |
26 | Robin Hood: Prince of Thieves | Warner Bros. | $390,493,908 | 1991 |
27 | Godzilla | TriStar Pictures | $379,014,294 | 1998 |
28 | True Lies | 20th Century Fox | $378,882,411 | 1994 |
29 | Toy Story | Walt Disney Studios | $373,554,033 | 1995 |
30 | There’s Something About Mary | 20th Century Fox | $369,884,651 | 1998 |
31 | The Fugitive | Warner Bros. | $368,875,760 | 1993 |
32 | Die Hard with a Vengeance | 20th Century Fox/Cinergi Pictures | $366,101,666 | 1995 |
33 | Notting Hill | PolyGram Filmed Entertainment | $363,889,678 | 1999 |
34 | A Bug’s Life | Walt Disney Studios | $363,398,565 | 1998 |
35 | The World Is Not Enough | Metro-Goldwyn-Mayer Pictures | $361,832,400 | 1999 |
36 | Home Alone 2: Lost in New York | 20th Century Fox | $358,994,850 | 1992 |
37 | American Beauty | DreamWorks Pictures | $356,296,601 | 1999 |
38 | Apollo 13 | Universal Pictures/Imagine Entertainment | $355,237,933 | 1995 |
39 | Basic Instinct | TriStar Pictures | $352,927,224 | 1992 |
40 | GoldenEye | MGM/United Artists | $352,194,034 | 1995 |
41 | The Mask | New Line Cinema | $351,583,407 | 1994 |
42 | Speed | 20th Century Fox | $350,448,145 | 1994 |
43 | Deep Impact | Paramount Pictures/DreamWorks Pictures | $349,464,664 | 1998 |
44 | Beauty and the Beast | Walt Disney Studios | $346,317,207 | 1991 |
45 | Pocahontas | Walt Disney Studios | $346,079,773 | 1995 |
46 | The Flintstones | Universal Pictures | $341,631,208 | 1994 |
47 | Batman Forever | Warner Bros. | $336,529,144 | 1995 |
48 | The Rock | Walt Disney Studios | $335,062,621 | 1996 |
49 | Tomorrow Never Dies | MGM/United Artists | $333,011,068 | 1997 |
50 | Seven | New Line Cinema | $327,311,859 | 1995 |
Title | Leads |
---|---|
A Bug’s Life | Dave Foley, Kevin Spacey, Julia Louis-Dreyfus, Hayden Panettiere, Phyllis Diller, Richard Kind, David Hyde Pierce |
Aladdin | Mena Massoud, Naomi Scott, Will Smith |
American Beauty | Kevin Spacey, Annette Bening, Thora Birch, Mena Suvari, Wes Bentley, Chris Cooper |
Apollo 13 | Tom Hanks, Kevin Bacon, Bill Paxton |
Armageddon | Bruce Willis, Billy Bob Thornton, Liv Tyler, Ben Affleck |
Basic Instinct | Michael Douglas, Sharon Stone |
Batman Forever | Val Kilmer, Tommy Lee Jones, Jim Carrey, Nicole Kidman, Chris O’Donnell |
Beauty and the Beast | Emma Watson, Dan Stevens, Luke Evans, Kevin Kline, Josh Gad |
Dances with Wolves | Kevin Costner, Mary McDonnell, Graham Greene, Rodney A. Grant |
Deep Impact | Téa Leoni, Morgan Freeman, Elijah Wood, Robert Duvall |
Die Hard with a Vengeance | Bruce Willis, Samuel L. Jackson, Jeremy Irons |
Forrest Gump | Tom Hanks, Robin Wright, Gary Sinise, Mykelti Williamson, Sally Field |
Ghost | Patrick Swayze, Demi Moore, Whoopi Goldberg |
Godzilla | Matthew Broderick, Jean Reno, Bryan Cranston, Aaron Taylor-Johnson, Elizabeth Olsen, Kyle Chandler, Vera Farmiga, Millie Bobby Brown |
GoldenEye | Pierce Brosnan, Sean Bean, Izabella Scorupco, Famke Janssen |
Home Alone | Macaulay Culkin, Joe Pesci, Daniel Stern, Catherine O’Hara, John Heard |
Home Alone 2: Lost in New York | Macaulay Culkin, Joe Pesci, Daniel Stern, Catherine O’Hara, John Heard |
Independence Day | Will Smith, Bill Pullman, Jeff Goldblum |
Jurassic Park | Sam Neill, Laura Dern, Jeff Goldblum, Richard Attenborough |
Men in Black | Tommy Lee Jones, Will Smith |
Mission: Impossible | Tom Cruise, Ving Rhames, Simon Pegg, Rebecca Ferguson, Jeremy Renner |
Mrs. Doubtfire | Robin Williams, Sally Field, Pierce Brosnan, Lisa Jakub, Matthew Lawrence, Mara Wilson |
Notting Hill | Julia Roberts, Hugh Grant |
Pocahontas | Irene Bedard, Mel Gibson, Judy Kuhn, David Ogden Stiers, Russell Means, Christian Bale |
Pretty Woman | Richard Gere, Julia Roberts |
Robin Hood: Prince of Thieves | Kevin Costner, Morgan Freeman, Mary Elizabeth Mastrantonio, Christian Slater, Alan Rickman |
Saving Private Ryan | Tom Hanks, Matt Damon, Tom Sizemore, Edward Burns, Barry Pepper, Adam Goldberg, Vin Diesel, Giovanni Ribisi, Jeremy Davies |
Seven | Brad Pitt, Morgan Freeman, Gwyneth Paltrow |
Speed | Keanu Reeves, Sandra Bullock, Dennis Hopper |
Star Wars: Episode I - The Phantom Menace | Liam Neeson, Ewan McGregor, Natalie Portman, Jake Lloyd |
Tarzan | Johnny Weissmuller, Maureen O’Sullivan |
Terminator 2: Judgment Day | Arnold Schwarzenegger, Linda Hamilton, Edward Furlong, Robert Patrick |
The Bodyguard | Kevin Costner, Whitney Houston |
The Flintstones | John Goodman, Elizabeth Perkins, Rick Moranis, Rosie O’Donnell |
The Fugitive | Harrison Ford, Tommy Lee Jones |
The Lion King | Matthew Broderick, James Earl Jones, Jeremy Irons, Moira Kelly, Nathan Lane, Ernie Sabella, Rowan Atkinson, Whoopi Goldberg |
The Lost World: Jurassic Park | Jeff Goldblum, Julianne Moore, Pete Postlethwaite |
The Mask | Jim Carrey, Cameron Diaz |
The Matrix | Keanu Reeves, Laurence Fishburne, Carrie-Anne Moss |
The Mummy | Brendan Fraser, Rachel Weisz, John Hannah, Arnold Vosloo |
The Rock | Sean Connery, Nicolas Cage, Ed Harris |
The Sixth Sense | Bruce Willis, Haley Joel Osment, Toni Collette, Olivia Williams |
The World Is Not Enough | Pierce Brosnan, Sophie Marceau, Denise Richards, Robert Carlyle |
There’s Something About Mary | Cameron Diaz, Ben Stiller, Matt Dillon |
Titanic | Leonardo DiCaprio, Kate Winslet |
Tomorrow Never Dies | Pierce Brosnan, Michelle Yeoh, Jonathan Pryce, Teri Hatcher |
Toy Story | Tom Hanks, Tim Allen |
Toy Story 2 | Tom Hanks, Tim Allen, Joan Cusack |
True Lies | Arnold Schwarzenegger, Jamie Lee Curtis |
Twister | Helen Hunt, Bill Paxton |
Creating a scenario list from a CSV
The ScenarioList method from_source(“csv”, “<filepath>.csv”) creates a list of scenarios from a CSV file. The method reads the CSV file and creates a scenario for each row in the file, with the keys as the column names and the values as the row values. For example, say we have a CSV file containing the following data:Message | User | Source | Date |
---|---|---|---|
I can’t log in… | Alice | Customer support | 2022-01-01 |
I need help with my bill… | Bob | Phone | 2022-01-02 |
I have a safety concern… | Charlie | 2022-01-03 | |
I need help with a product… | David | Chat | 2022-01-04 |
What is the message? | Who is the user? | What is the source? | What is the date? |
---|---|---|---|
I can’t log in… | Alice | Customer support | 2022-01-01 |
I need help with my bill… | Bob | Phone | 2022-01-02 |
I have a safety concern… | Charlie | 2022-01-03 | |
I need help with a product… | David | Chat | 2022-01-04 |
message | user | source | date |
---|---|---|---|
I can’t log in… | Alice | Customer support | 2022-01-01 |
I need help with my bill… | Bob | Phone | 2022-01-02 |
I have a safety concern… | Charlie | 2022-01-03 | |
I need help with a product… | David | Chat | 2022-01-04 |
Methods for un/pivoting and grouping scenarios
There are a variety of methods for modifying scenarios and scenario lists.Unpivoting a scenario list
The ScenarioList method unpivot() can be used to unpivot a scenario list based on one or more specified identifiers. It takes a list of id_vars which are the names of the key/value pairs to keep in each new scenario, and a list of value_vars which are the names of the key/value pairs to unpivot. For example, say we have a scenario list for the above CSV file:user | variable | value |
---|---|---|
Alice | source | Customer support |
Alice | date | 2022-01-01 |
Alice | message | I can’t log in… |
Bob | source | Phone |
Bob | date | 2022-01-02 |
Bob | message | I need help with my bill… |
Charlie | source | |
Charlie | date | 2022-01-03 |
Charlie | message | I have a safety concern… |
David | source | Chat |
David | date | 2022-01-04 |
David | message | I need help with a product… |
Pivoting a scenario list
We can call the pivot() method to reverse the unpivot operation:user | source | date | message |
---|---|---|---|
Alice | Customer support | 2022-01-01 | I can’t log in… |
Bob | Phone | 2022-01-02 | I need help with my bill… |
Charlie | 2022-01-03 | I have a safety concern… | |
David | Chat | 2022-01-04 | I need help with a product… |
Grouping scenarios
The group_by() method can be used to group scenarios by one or more specified keys and apply a function to the values of the specified variables. Example usage:group | avg_a | sum_b |
---|---|---|
A | 12.5 | 45 |
B | 14.5 | 49 |
Data labeling tasks
Scenarios are particularly useful for conducting data labeling or data coding tasks, where the task can be designed as a survey of questions about each piece of data in a dataset. For example, say we have a dataset of text messages that we want to sort by topic. We can perform this task by using a language model to answer questions such as “What is the primary topic of this message: {{ scenario.message }}?” or “Does this message mention a safety issue? {{ scenario.message }}”, where each text message is inserted in the message placeholder of the question text. Here we use scenarios to conduct the task:message | safety | topic |
---|---|---|
I can’t log in… | No | Login issue |
I need help with a product… | No | Product support |
I need help with my bill… | No | Billing |
I have a safety concern… | Yes | Safety |
Adding metadata
If we have metadata about the messages that we want to keep track of, we can add it to the scenarios as well. This will create additional columns for the metadata in the results dataset, but without the need to include it in our question texts. Here we modify the above example to use a dataset of messages with metadata. Note that the question texts are unchanged:user | source | message | date | topic | safety |
---|---|---|---|---|---|
Alice | Customer support | I can’t log in… | 2022-01-01 | Login issue | No |
Bob | Phone | I need help with my bill… | 2022-01-02 | Billing | No |
Charlie | I have a safety concern… | 2022-01-03 | Safety | Yes | |
David | Chat | I need help with a product… | 2022-01-04 | Product support | No |
Slicing/chunking content into scenarios
We can use the Scenario method chunk() to slice a text scenario into a ScenarioList based on num_words or num_lines. Example usage:my_text | my_text_chunk | my_text_original |
---|---|---|
This is a long text. | 0 | 4aec42eda32b7f32bde8be6a6bc11125 |
Pages and pages, oh my! | 1 | 4aec42eda32b7f32bde8be6a6bc11125 |
I need to chunk it. | 2 | 4aec42eda32b7f32bde8be6a6bc11125 |
Using f-strings with scenarios
It is possible to use scenarios and f-strings together in a question. An f-string must be evaluated when a question is constructed, whereas a scenario is either evaluated when a question is run (using the by method) or when a question is constructed (using the loop method). For example, here we use an f-string to create different versions of a question that also takes a parameter {{ scenario.activity }}, together with a list of scenarios to replace the parameter when the question is run. We optionally include the f-string in the question name in addition to the question text in order to control the unique identifiers for the questions, which are needed in order to pass the questions that are created to a Survey. (If you do not include the f-string in the question name, a number is automatically appended to each question name to ensure uniqueness.) Then we use the show_prompts() method to examine the user prompts that are created when the scenarios are added to the questions:user_prompt | system_prompt |
---|---|
How much do you enjoy running? | |
How much do you hate running? | |
How much do you love running? | |
How much do you enjoy reading? | |
How much do you hate reading? | |
How much do you love reading? |
Special methods
Special methods are available for generating or modifying scenarios using web searches: The from_prompt method allows you to create scenarios from a prompt, which can be useful for generating scenarios based on user input or other dynamic sources:Scenario class
Bases:class edsl.scenarios.Scenario(data: Dict[str, Any] | Mapping[str, Any] | None = None, name: str | None = None) [source]
Base
, UserDict
A dictionary-like object that stores key-value pairs for parameterizing questions.
A Scenario inherits from both the EDSL Base class and Python’s UserDict, allowing it to function as a dictionary while providing additional functionality. Scenarios are used to parameterize questions by providing variable data that can be referenced within question templates using Jinja syntax.
Scenarios can be created directly with dictionary data or constructed from various sources using class methods (from_file, from_url, from_pdf, etc.). They support operations like addition (combining scenarios) and multiplication (creating cross products with other scenarios or scenario lists).
data (dict): The underlying dictionary data. name (str, optional): A name for the scenario.Attributes:
Create a simple scenario: >>> s = Scenario({“product”: “coffee”, “price”: 4.99}) Combine scenarios: >>> s1 = Scenario({“product”: “coffee”}) >>> s2 = Scenario({“price”: 4.99}) >>> s3 = s1 + s2 >>> s3 Scenario({‘product’: ‘coffee’, ‘price’: 4.99}) Create a scenario from a file: >>> import tempfile >>> with tempfile.NamedTemporaryFile(mode=’w’, suffix=’.txt’, delete=False) as f: … _ = f.write(“Hello World”) … data_path = f.name >>> s = Scenario.from_file(data_path, “document”) >>> import os >>> os.unlink(data_path) # Clean up temp fileExamples:
Initialize a new Scenario.**init(data: Dict[str, Any] | Mapping[str, Any] | None = None, name: str | None = None) [source]
Args:data: A dictionary of key-value pairs for parameterizing questions. Any dictionary-like object that can be converted to a dict is accepted. name: An optional name for the scenario to aid in identification.
Raises:ScenarioError: If the data cannot be converted to a dictionary.
Examples:
Splits a text field into chunks of a specified size, creating a ScenarioList. This method takes a field containing text and divides it into smaller chunks based on either word count or line count. It’s particularly useful for processing large text documents in manageable pieces, such as for summarization, analysis, or when working with models that have token limits.**chunk(field: str, num_words: int | None = None, num_lines: int | None = None, include_original: bool = False, hash_original: bool = False) → ScenarioList [source]
Args:field: The key name of the field in the Scenario to split. num_words: The number of words to include in each chunk. Mutually exclusive
Returns:A ScenarioList containing multiple Scenarios, each with a chunk of the original text. Each Scenario includes the chunk text, chunk index, character count, and word count.
Raises:ValueError: If neither num_words nor num_lines is specified, or if both are. KeyError: If the specified field doesn’t exist in the Scenario.
Examples:
Notes:
- Either num_words or num_lines must be specified, but not both
- Each chunk is assigned a sequential index in the ‘text_chunk’ field
- Character and word counts for each chunk are included
- When include_original is True, the original text is preserved in each chunk
- The hash_original option is useful to save space while maintaining traceability
Chunks a text field into smaller chunks of a specified size, creating a ScenarioList. This method takes a field containing text and divides it into smaller chunks based on either word count or line count. It’s particularly useful for processing large text documents in manageable pieces, such as for summarization, analysis, or when working with models that have token limits.chunk_text(field: str, chunk_size_field: str, unit: str = ‘word’, include_original: bool = False, hash_original: bool = False) → ScenarioList [source ]
Generate Python code to recreate this scenario.code() → List[str] [source]
Returns:A list of strings representing Python code lines that can be executed to recreate this scenario.
Examples:
Drop a subset of keys from a scenario. This method delegates to ScenarioSelector for the actual dropping logic. It supports both individual string arguments and collection arguments for backward compatibility.drop(**args: str | Iterable[str]*) → Scenario [source ]
Args:*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to drop.
Returns:A new Scenario containing all keys except the dropped ones.
Raises:ValueError: If no arguments are provided.
Examples:
Returns an example Scenario instance.classmethod example(randomize: bool = False) → Scenario [source ]
Args:randomize: If True, adds a random string to the value of the example key to ensure uniqueness.
Returns:A Scenario instance with example data suitable for testing or demonstration.
Examples:
firecrawl = <edsl.scenarios.firecrawl_scenario.FirecrawlRequest object> [source]
Creates a Scenario from a dictionary, with special handling for FileStore objects. This method creates a Scenario using the provided dictionary. It has special handling for dictionary values that represent serialized FileStore objects, which it will deserialize back into proper FileStore instances.classmethod from_dict(d: Dict[str, Any]) → Scenario [source ]
Args:d: A dictionary to convert to a Scenario.
Returns:A new Scenario containing the provided dictionary data.
Examples:
Notes:
- Any dictionary values that match the FileStore format will be converted to FileStore objects
- The method detects FileStore objects by looking for “base64_string” and “path” keys
- EDSL version information is automatically removed by the @remove_edsl_version decorator
- This method is commonly used when deserializing scenarios from JSON or other formats
Creates a Scenario containing text extracted from a Microsoft Word document. This method extracts text and structure from a DOCX file and creates a Scenario containing this information. It uses the DocxScenario class to handle the extraction process and maintain document structure where possible.classmethod from_docx(docx_path: str) → Scenario [source ]
Args:docx_path: Path to the DOCX file to extract content from.
Returns:A Scenario containing the file path and extracted text from the DOCX file.
Raises:FileNotFoundError: If the specified DOCX file does not exist. ImportError: If the python-docx library is not installed.
Examples:
Notes:
- The returned Scenario typically contains the file path and extracted text
- The extraction process attempts to maintain document structure
- Requires the python-docx library to be installed
Creates a Scenario containing a FileStore object from a file. This method creates a Scenario with a single key-value pair where the value is a FileStore object that encapsulates the specified file. The FileStore handles appropriate file loading, encoding, and extraction based on the file type.classmethod from_file(file_path: str, field_name: str) → Scenario [source ]
Args:file_path: Path to the file to be incorporated into the Scenario. field_name: Key name to use for storing the FileStore in the Scenario.
Returns:A Scenario containing a FileStore object linked to the specified file.
Raises:FileNotFoundError: If the specified file does not exist.
Examples:
Notes:
- The FileStore object handles various file formats differently
- FileStore provides methods to access file content, extract text, and manage file operations appropriate to the file type
Creates a Scenario containing both HTML content and extracted text from a URL. This method fetches HTML content from a URL, extracts readable text from it, and creates a Scenario containing the original URL, the raw HTML, and the extracted text. Unlike from_url, this method preserves the raw HTML content.classmethod from_html(url: str, field_name: str | None = None) → Scenario [source ]
Args:url: URL to fetch HTML content from. field_name: Key name to use for the extracted text in the Scenario. If not provided, defaults to “text”.
Returns:A Scenario containing the URL, raw HTML, and extracted text.
Raises:requests.exceptions.RequestException: If the URL cannot be accessed.
Examples:Create a scenario from HTML content (requires network access): s = Scenario.from_html(”https://example.com”) # Returns a Scenario with “url”, “html”, and “text” fields s = Scenario.from_html(”https://example.com”, field_name=”content”) # Returns a Scenario with “url”, “html”, and “content” fields
Notes:
- Uses BeautifulSoup for HTML parsing when available
- Stores both the raw HTML and the extracted text
- Provides a more comprehensive representation than from_url
- Useful when the HTML structure or specific elements are needed
Creates a Scenario containing an image file as a FileStore object. This method creates a Scenario with a single key-value pair where the value is a FileStore object that encapsulates the specified image file. The image is stored as a base64-encoded string, allowing it to be easily serialized and transmitted.classmethod from_image(image_path: str, image_name: str | None = None) → Scenario [source ]
Args:image_path: Path to the image file to be incorporated into the Scenario. image_name: Key name to use for storing the FileStore in the Scenario. If not provided, uses the filename without extension.
Returns:A Scenario containing a FileStore object with the image data.
Raises:FileNotFoundError: If the specified image file does not exist.
Examples:
import osAssuming an image file exists
if os.path.exists(“image.jpg”): … s = Scenario.from_image(“image.jpg”) … s_named = Scenario.from_image(“image.jpg”, “picture”)
Notes:
- The resulting FileStore can be displayed in notebooks or used in questions
- Supported image formats include JPG, PNG, GIF, etc.
- The image is stored as a base64-encoded string for portability
Creates a Scenario containing text extracted from a PDF file. This method extracts text and metadata from a PDF file and creates a Scenario containing this information. It uses the PdfExtractor class which provides access to text content, metadata, and structure from PDF files.classmethod from_pdf(pdf_path: str) → Scenario [source ]
Args:pdf_path: Path to the PDF file to extract content from.
Returns:A Scenario containing extracted text and metadata from the PDF.
Raises:FileNotFoundError: If the specified PDF file does not exist. ImportError: If the required PDF extraction libraries are not installed.
Examples:
Notes:
- The returned Scenario contains various keys with PDF content and metadata
- PDF extraction requires the PyMuPDF library
- The extraction process parses the PDF to maintain structure where possible
Converts each page of a PDF into an image and creates a Scenario containing them. This method takes a PDF file, converts each page to an image in the specified format, and creates a Scenario containing the original file path and FileStore objects for each page image. This is particularly useful for visualizing PDF content or for image-based processing of PDF documents.classmethod from_pdf_to_image(pdf_path: str, image_format: str = ‘jpeg’) → Scenario [source ]
Args:pdf_path: Path to the PDF file to convert to images. image_format: Format of the output images (default is ‘jpeg’). Other formats include ‘png’, ‘tiff’, etc.
Returns:A Scenario containing the original PDF file path and FileStore objects for each page image, with keys like “page_0”, “page_1”, etc.
Raises:FileNotFoundError: If the specified PDF file does not exist. ImportError: If pdf2image is not installed.
Examples:
Notes:
- Requires the pdf2image library which depends on poppler
- Creates a separate image for each page of the PDF
- Images are stored in FileStore objects for easy display and handling
- Images are created in a temporary directory which is automatically cleaned up
Creates a Scenario from the content of a URL. This method fetches content from a web URL and creates a Scenario containing the URL and the extracted text. When available, BeautifulSoup is used for better HTML parsing and text extraction, otherwise a basic requests approach is used.classmethod from_url(url: str, field_name: str | None = ‘text’, testing: bool = False) → Scenario [source ]
Args:url: The URL to fetch content from. field_name: The key name to use for storing the extracted text in the Scenario. Defaults to “text”. testing: If True, uses a simplified requests method instead of BeautifulSoup. This is primarily for testing purposes.
Returns:A Scenario containing the URL and extracted text.
Raises:requests.exceptions.RequestException: If the URL cannot be accessed.
Examples:Create a scenario from a URL (requires network access): s = Scenario.from_url(”https://example.com”, testing=True) # Returns a Scenario with “url” and “text” fields s = Scenario.from_url(”https://example.com”, field_name=”content”, testing=True) # Returns a Scenario with “url”, “html”, and “content” fields
Notes:
- The method attempts to use BeautifulSoup and fake_useragent for better HTML parsing and to mimic a real browser.
- If these packages are not available, it falls back to basic requests.
- When using BeautifulSoup, it extracts text from paragraph and heading tags.
Returns information about FileStore objects present in this Scenario. This method is useful for determining how many signed URLs need to be generated and what file extensions/types are present before calling save_to_gcs_bucket().get_filestore_info() → Dict[str, Any] [source]
Returns:dict: Information about FileStore objects containing:
- total_count: Total number of FileStore objects
- filestore_keys: List of scenario keys that contain FileStore objects
- file_extensions: Dictionary mapping keys to file extensions
- file_types: Dictionary mapping keys to MIME types
- is_filestore_scenario: Boolean indicating if this Scenario was created from a FileStore
- summary: Human-readable summary of files
Return whether the scenario has jinja braces. This matters for rendering.property has_jinja_braces*: bool* [source]
Keep a subset of keys from a scenario (alias for select). This method delegates to ScenarioSelector for the actual selection logic. It is functionally identical to select() but provides more intuitive naming.keep(**args: str | Iterable[str]*) → Scenario [source ]
Args:*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to keep.
Returns:A new Scenario containing only the kept keys and their values.
Raises:KeyError: If any of the specified keys don’t exist in the scenario. ValueError: If no arguments are provided.
Examples:Using a list (backward compatible): >>> s = Scenario({“food”: “wood chips”, “drink”: “water”}) >>> s.keep([“food”]) Scenario({‘food’: ‘wood chips’}) Using individual string arguments: >>> s = Scenario({“food”: “wood chips”, “drink”: “water”, “dessert”: “cookies”}) >>> s.keep(“food”, “drink”) Scenario({‘food’: ‘wood chips’, ‘drink’: ‘water’})
Rename all keys of a scenario using a list of new names.new_column_names(new_names: List[str]) → Scenario [source ]
Args:new_names: A list of new key names. Must have the same length as the number of keys in the scenario.
Returns:A new Scenario with keys renamed according to the provided list.
Raises:ValueError: If the length of new_names doesn’t match the number of keys.
Examples:
Offload base64-encoded content from the scenario by replacing ‘base64_string’ fields with ‘offloaded’. This reduces memory usage. This method delegates to ScenarioOffloader for the actual offloading logic. It handles three types of base64 content: 1. Direct base64_string in the scenario (from FileStore.to_dict()) 2. FileStore objects containing base64 content 3. Dictionary values containing base64_string fieldsoffload(inplace: bool = False) → Scenario [source ]
Args:inplace: If True, modify the current scenario. If False, return a new one.
Returns:The modified scenario (either self or a new instance).
Examples:Basic offloading: >>> s = Scenario({“base64_string”: “SGVsbG8gV29ybGQ=”, “name”: “test”}) >>> offloaded = s.offload() >>> offloaded[“base64_string”] ‘offloaded’ >>> offloaded[“name”] ‘test’ In-place offloading: >>> s = Scenario({“base64_string”: “SGVsbG8gV29ybGQ=”, “name”: “test”}) >>> result = s.offload(inplace=True) >>> result is s True >>> s[“base64_string”] ‘offloaded’
Open a URL field from the scenario in the default web browser.open_url(position: int = 0) → None [source]
Args:position: The index of the URL to open (0-based). Defaults to 0 for the first URL.
Raises:ValueError: If no URL fields are found in the scenario, or if the position is out of range.
Examples:
Rename the keys of a scenario.rename(old_name_or_replacement_dict: str | Dict[str, str], new_name: str | None = None) → Scenario [source ]
Args:old_name_or_replacement_dict: Either a dictionary mapping old keys to new keys, or a string representing the old key name. new_name: The new name for the key. Required if old_name_or_replacement_dict is a string, ignored if it’s a dictionary.
Returns:A new Scenario with renamed keys.
Raises:TypeError: If old_name_or_replacement_dict is a string but new_name is None.
Examples:Using a dictionary: >>> s = Scenario({“food”: “wood chips”}) >>> s.rename({“food”: “food_preference”}) Scenario({‘food_preference’: ‘wood chips’}) Using individual arguments: >>> s = Scenario({“food”: “wood chips”}) >>> s.rename(“food”, “snack”) Scenario({‘snack’: ‘wood chips’})
Replicate a scenario n times to return a ScenarioList.replicate(n: int) → ScenarioList [source ]
Args:n: The number of times to replicate the scenario. Must be non-negative.
Returns:A ScenarioList containing n copies of this scenario.
Raises:ValueError: If n is negative.
Examples:
Saves FileStore objects contained within this Scenario to a Google Cloud Storage bucket. This method finds all FileStore objects in the Scenario and uploads them to GCS using the provided signed URL(s). If the Scenario itself was created from a FileStore (has base64_string as a top-level key), it uploads that content directly.save_to_gcs_bucket(signed_url_or_dict: str | Dict[str, str]) → Dict[str, Any] [source]
Args:signed_url_or_dict: Either:
- str: Single signed URL (for single FileStore or Scenario from FileStore)
- dict: Mapping of scenario keys to signed URLs for multiple FileStore objects e.g., {“video”: “signed_url_1”, “image”: “signed_url_2”}
Returns:dict: Summary of upload operations performed
Raises:ValueError: If no uploadable content found or content is offloaded requests.RequestException: If any upload fails
Select a subset of keys from a scenario. This method delegates to ScenarioSelector for the actual selection logic. It supports both individual string arguments and collection arguments for backward compatibility.select(**args: str | Iterable[str]*) → Scenario [source ]
Args:*args: Either a single collection of keys (for backward compatibility) or individual string arguments for keys to select.
Returns:A new Scenario containing only the selected keys and their values.
Raises:KeyError: If any of the specified keys don’t exist in the scenario. ValueError: If no arguments are provided.
Examples:Using a list (backward compatible): >>> s = Scenario({“food”: “wood chips”, “drink”: “water”}) >>> s.select([“food”]) Scenario({‘food’: ‘wood chips’}) Using individual string arguments: >>> s = Scenario({“food”: “wood chips”, “drink”: “water”, “dessert”: “cookies”}) >>> s.select(“food”, “drink”) Scenario({‘food’: ‘wood chips’, ‘drink’: ‘water’}) Single string argument: >>> s.select(“food”) Scenario({‘food’: ‘wood chips’})
Display a scenario as a formatted table.table(tablefmt: str = ‘grid’) → str [source]
Args:tablefmt: The table format to use. Common options include “grid”, “simple”, “pipe”, “orgtbl”, “rst”, “mediawiki”, “html”, “latex”.
Returns:A string representation of the scenario formatted as a table.
Examples:
Send the scenario to a question or survey for execution.to(question_or_survey: ‘Question’ | ‘Survey’) → Jobs [source]
Args:question_or_survey: A Question or Survey object to parameterize with this scenario.
Returns:A Jobs object that can be run to execute the question or survey with this scenario.
Examples:
Convert a scenario to a dataset.to_dataset() → Dataset [source]
Convert a scenario to a dictionary.to_dict(add_edsl_version: bool = True, offload_base64: bool = False) → Dict[str, Any] [source]
Args:add_edsl_version: If True, adds the EDSL version to the returned dictionary. offload_base64: If True, replaces any base64_string fields with ‘offloaded’ to reduce memory usage. Example:
ScenarioList class
Bases:class edsl.scenarios.ScenarioList(data: list | None = None, codebook: dict[str, str] | None = None, data_class: type | None = <class ‘list’>) [source]
MutableSequence
, Base
[source], ScenarioListOperationsMixin
A collection of Scenario objects with advanced operations for manipulation and analysis.
ScenarioList provides specialized functionality for working with collections of Scenario objects. It inherits from MutableSequence to provide standard list operations, from Base to integrate with EDSL’s object model, and from ScenarioListOperationsMixin to provide powerful data manipulation capabilities.
Attributes:
data (list): The underlying list containing Scenario objects. codebook (dict): Optional metadata describing the fields in the scenarios.
Initialize a new ScenarioList with optional data and codebook.init(data: list | None = None, codebook: dict[str, str] | None = None, data_class: type | None = <class ‘list’>) [source]
Add a list of values to a ScenarioList. Example:add_list(name: str, values: List[Any]) → ScenarioList [source ]
Add a value to all scenarios in a ScenarioList. Example:add_value(name: str, value: Any) → ScenarioList [source ]
Apply a function to a field and return a new ScenarioList.apply(func: Callable, field: str, new_name: str | None, replace: bool = False) → ScenarioList [source ]
Get the scenario at the specified index position. >>> sl = ScenarioList.from_list(“a”, [1, 2, 3]) >>> sl.at(0) Scenario({‘a’: 1}) >>> sl.at(-1) Scenario({‘a’: 3})at(index: int) → Scenario [source ]
Augment the ScenarioList with Wikipedia content.augment_with_wikipedia(search_key: str, content_only: bool = True, key_name: str = ‘wikipedia_content’) → ScenarioList [source ]
Create a chart from the results.chart() [source]
Chunk the scenarios based on a field.chunk(field, num_words: int | None = None, num_lines: int | None = None, include_original=False, hash_original=False) → ScenarioList [source ]
Examples:
Return TSV representation of this object for clipboard operations. This method is called by the clipboard() method in the base class to provide a custom format for copying objects to the system clipboard. Returns: str: Tab-separated values representation of the objectclipboard_data() → str [source]
Create the Python code representation of a survey.code() → str [source]
Collapse by grouping on all fields except the specified one. Delegates to ScenarioListTransformer.collapse.collapse(field: str, separator: str | None = None, prefix: str = ”, postfix: str = ”, add_count: bool = False) → ScenarioList [source ]
Concatenate specified fields into a single string field. Delegates to ScenarioListTransformer.concatenate for implementation.concatenate(fields: List[str], separator: str = ’;’, prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]
Concatenate specified fields into a single list field. Delegates to ScenarioListTransformer.concatenate_to_list for implementation.concatenate_to_list(fields: List[str], prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]
Concatenate specified fields into a single set field. Delegates to ScenarioListTransformer.concatenate_to_set for implementation.concatenate_to_set(fields: List[str], prefix: str = ”, postfix: str = ”, new_field_name: str | None = None) → ScenarioList [source ]
Create a copy of this ScenarioList. Returns: A new ScenarioList with copies of the same scenarioscopy() [source]
Create a new ScenarioList with comparisons between scenarios. Delegates to ScenarioListTransformer.create_comparisons.create_comparisons(bidirectional: bool = False, num_options: int = 2, option_prefix: str = ‘option_’, use_alphabet: bool = False) → ScenarioList [source ]
Generate random product profiles for conjoint analysis from attribute definitions. This method uses the current ScenarioList (which should contain attribute definitions) to create random product profiles by sampling from the attribute levels. Each scenario in the current list should represent one attribute with its possible levels.create_conjoint_comparisons(attribute_field: str = ‘attribute’, levels_field: str = ‘levels’, count: int = 1, random_seed: int | None = None) → ScenarioList [source ])
Args:attribute_field: Field name containing the attribute names (default: ‘attribute’) levels_field: Field name containing the list of levels (default: ‘levels’) count: Number of product profiles to generate (default: 1) random_seed: Optional seed for reproducible random sampling
Returns:ScenarioList containing randomly generated product profiles
Examples:
Raises:ScenarioError: If the current ScenarioList doesn’t have the required fields ValueError: If count is not positive
Create an empty ScenarioList with n scenarios.create_empty_scenario_list(n: int) → ScenarioList [source ]
Args:n: The number of empty scenarios to create
Examples:
Drop fields from the scenarios. Example:drop(*fields: str) → ScenarioList [source ]
Return a copy of the ScenarioList using streaming to avoid loading everything into memory.duplicate() → ScenarioList [source ]
Memory-efficient comparison of two ScenarioLists.equals(other: Any) → bool [source]
Return an example ScenarioList instance. Params randomize: If True, use Scenario’s randomize method to randomize the values.classmethod example(randomize: bool = False) → ScenarioList [source ]
Expand the ScenarioList by a field. Parameters:expand(expand_field: str, number_field: bool = False) → ScenarioList [source ]
- expand_field – The field to expand.
- number_field – Whether to add a field with the index of the value
Fill None/NaN values in all scenarios with a specified value. This method is equivalent to pandas’ df.fillna() functionality, allowing you to replace None, NaN, or other null-like values across all scenarios in the list.fillna(value: Any = ”, inplace: bool = False) → ScenarioList [source ]
Args:value: The value to use for filling None/NaN values. Defaults to empty string “”. inplace: If True, modify the original ScenarioList. If False (default), return a new ScenarioList with filled values.
Returns:ScenarioList: A new ScenarioList with filled values, or self if inplace=True
Examples:
Filter a list of scenarios based on an expression. Delegates to ScenarioListTransformer.filter.filter(expression: str) → ScenarioList [source ]
firecrawl = <edsl.scenarios.firecrawl_scenario.FirecrawlRequest object> [source]
Expand a field containing dictionaries into separate fields. This method takes a field that contains a list of dictionaries and expands it into multiple fields, one for each key in the dictionaries. This is useful when working with nested data structures or results from extraction operations.flatten(field: str, keep_original: bool = False) → Dataset [source]
Parameters:field: The field containing dictionaries to flatten keep_original: Whether to retain the original field in the result
Returns:A new Dataset with the dictionary keys expanded into separate fields
Notes:
- Each key in the dictionaries becomes a new field with name pattern “.”
- All dictionaries in the field must have compatible structures
- If a dictionary is missing a key, the corresponding value will be None
- Non-dictionary values in the field will cause a warning
Examples:
Execute a target multiple times, feeding each iteration’s output into the next.for_n(target: ‘Question’ | ‘Survey’ | ‘Job’, iterations: int) → Jobs [source]
Parameters
targetQuestion | Survey | Job The object to be executed on each round. A freshduplicate()
of target is taken for every iteration so that state is not shared between runs.
iterationsint
How many times to run target.
Returns
Jobs AJobs
instance containing the results of the final iteration.
Create a ScenarioList from a CSV file or URL.classmethod from_csv(source: str | ‘ParseResult’, has_header: bool = True, encoding: str = ‘utf-8’, **kwargs) → ScenarioList [source ]
Args:source: Path to a local file or URL to a remote file. has_header: Whether the file has a header row (default is True). encoding: The file encoding to use (default is ‘utf-8’). **kwargs: Additional parameters for csv reader.
Returns:ScenarioList: An instance of the ScenarioList class.
Create a ScenarioList from a delimited file (CSV/TSV) or URL.classmethod from_delimited_file(source: str | ‘ParseResult’, delimiter: str = ’,’, encoding: str = ‘utf-8’, **kwargs) → ScenarioList [source ]
Args:source: Path to a local file or URL to a remote file. delimiter: The delimiter character used in the file (default is ‘,’). encoding: The file encoding to use (default is ‘utf-8’). **kwargs: Additional parameters for csv reader.
Returns:ScenarioList: An instance of the ScenarioList class.
Create a ScenarioList from a dictionary.classmethod from_dict(data: dict) → ScenarioList [source ]
Create a ScenarioList of Scenario objects from files in a directory. This method scans a directory and creates a Scenario object for each file found, where each Scenario contains a FileStore object under the specified key. Optionally filters files based on a wildcard pattern. If no path is provided, the current working directory is used.classmethod from_directory(path: str | None = None, recursive: bool = False, key_name: str = ‘content’) → ScenarioList [source ]
Args:path: The directory path to scan, optionally including a wildcard pattern. If None, uses the current working directory. Examples: - “/path/to/directory” - scans all files in the directory - “/path/to/directory/.py” - scans only Python files in the directory - “.txt” - scans only text files in the current working directory recursive: Whether to scan subdirectories recursively. Defaults to False. key_name: The key to use for the FileStore object in each Scenario. Defaults to “content”.
Returns:A ScenarioList containing Scenario objects for all matching files, where each Scenario has a FileStore object under the specified key.
Raises:FileNotFoundError: If the specified directory does not exist.
Examples:
Create a ScenarioList from a list of values with a specified field name.classmethod from_list(field_name: str, values: list, use_indexes: bool = False) → ScenarioList [source]
Create a ScenarioList from a nested dictionary.classmethod from_nested_dict(data: dict) → ScenarioList [source]
classmethod from_prompt(description: str, name: str | None = ‘item’, target_number: int = 10, verbose=False)[source]
Create a ScenarioList from a list of search terms, using Wikipedia. Args: search_terms: A list of search terms.classmethod from_search_terms(search_terms: List[str]) → ScenarioList [source]
Create a ScenarioList from a specified source type. This method serves as the main entry point for creating ScenarioList objects, providing a unified interface for various data sources. Args: source_type: The type of source to create a ScenarioList from. Valid values include: ‘urls’, ‘directory’, ‘csv’, ‘tsv’, ‘excel’, ‘pdf’, ‘pdf_to_image’, and others. *args: Positional arguments to pass to the source-specific method. **kwargs: Keyword arguments to pass to the source-specific method. Returns: A ScenarioList object created from the specified source. Examples:classmethod from_source(source_type: str, *args, **kwargs) → ScenarioList [source]
classmethod from_urls(urls: list[str], field_name: str | None = ‘text’) → ScenarioList [source]
Create a ScenarioList from a list of dictionaries. Example:classmethod gen(scenario_dicts_list: List[dict]) → ScenarioList [source]
Internal method to get tabular data in a standard format. Args: remove_prefix: Whether to remove the prefix from column names pretty_labels: Dictionary mapping original column names to pretty labels Returns: Tuple containing (header_row, data_rows)get_tabular_data(remove_prefix: bool = False, pretty_labels: dict | None = None) → Tuple[List[str], List[List]][source]
Create visualizations using R’s ggplot2 library. This method provides a bridge to R’s powerful ggplot2 visualization library, allowing you to create sophisticated plots directly from EDSL data structures.ggplot2(ggplot_code: str, shape: str = ‘wide’, sql: str | None = None, remove_prefix: bool = True, debug: bool = False, height: float = 4, width: float = 6, factor_orders: dict | None = None)[source]
Parameters:ggplot_code: R code string containing ggplot2 commands shape: Data shape to use (“wide” or “long”) sql: Optional SQL query to transform data before visualization remove_prefix: Whether to remove prefixes (like “answer.”) from column names debug: Whether to display debugging information height: Plot height in inches width: Plot width in inches factor_orders: Dictionary mapping factor variables to their desired order
Returns:A plot object that renders in Jupyter notebooks
Notes:
- Requires R and the ggplot2 package to be installed
- Data is automatically converted to a format suitable for ggplot2
- The ggplot2 code should reference column names as they appear after any transformations from the shape and remove_prefix parameters
Give valid names to the scenario keys, using an existing codebook if provided. Args: existing_codebook (dict, optional): Existing mapping of original keys to valid names. Defaults to None. Returns: ScenarioList: A new ScenarioList with valid variable names and updated codebook.give_valid_names(existing_codebook: dict = None) → ScenarioList [source]
Group the ScenarioList by id_vars and apply a function. Delegates to ScenarioListTransformer.group_by.group_by(id_vars: List[str], variables: List[str], func: Callable) → ScenarioList [source]
Check if any Scenario in the list contains values with Jinja template braces. This property checks all Scenarios in the list to determine if any contain string values with Jinja template syntax (). This is important for rendering templates and avoiding conflicts with other templating systems.property has_jinja_braces*: bool*[source]
Returns:True if any Scenario contains values with Jinja braces, False otherwise.
Examples:
html(filename: str | None = None, cta: str = ‘Open in browser’, return_link: bool = False)[source]
Perform an inner join with another ScenarioList, following SQL join semantics. Args: other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty. Returns: A new ScenarioList containing only scenarios that have matches in both ScenarioListsinner_join(other: ScenarioList, by: str | list[str]) → ScenarioList [source]
Insert value at index.insert(index, value)[source]
is_serializable()[source]
Make this class compatible with dict.items() by accessing first scenario items. This ensures the class works as a drop-in replacement for UserList in code that expects a dictionary-like interface. Returns: items view from the first scenario object if available, empty list otherwiseitems()[source]
Keep only the specified fields in the scenarios. Parameters: fields – The fields to keep. Example:keep(*fields: str) → ScenarioList[source]
Perform a left join with another ScenarioList, following SQL join semantics. Args: other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty.left_join(other: ScenarioList, by: str | list[str]) → ScenarioList source
Turn the results into a tabular format. Parameters: remove_prefix – Whether to remove the prefix from the column names.make_tabular(remove_prefix: bool, pretty_labels: dict | None = None) → tuple[list, List[list]] source
Return a new ScenarioList with a new variable added. Delegates to ScenarioListTransformer.mutate.mutate(new_var_string: str, functions_dict: dict[str, Callable] | None = None) → ScenarioList source
Return the number of observations in the dataset.num_observations()[source]
Offloads base64-encoded content from all scenarios in the list by replacing ‘base64_string’ fields with ‘offloaded’. This reduces memory usage.offload(inplace: bool = False) → ScenarioList source
Args:inplace (bool): If True, modify the current scenario list. If False, return a new one.
Returns:ScenarioList: The modified scenario list (either self or a new instance).
Order the scenarios by one or more fields. Delegates to ScenarioListTransformer.order_by.order_by(*fields: str, reverse: bool = False) → ScenarioList source
Return the set of parameters in the ScenarioList Example:property parameters*: set*[source]
Pivot the ScenarioList from long to wide format. Delegates to ScenarioListTransformer.pivot.pivot(id_vars: List[str] = None, var_name=‘variable’, value_name=‘value’) → ScenarioList source
Print the results in a long format. >>> from edsl.results import Results >>> r = Results.example() >>> r.select(‘how_feeling’).print_long() answer.how_feeling: OK answer.how_feeling: Great answer.how_feeling: Terrible answer.how_feeling: OKprint_long()[source]
Return the set of keys that are present in the dataset. Parameters:relevant_columns(data_type: str | None = None, remove_prefix: bool = False) → list[source]
- data_type – The data type to filter by.
- remove_prefix – Whether to remove the prefix from the column names.
Returns a new Dataset with the prefix removed from all column names. The prefix is defined as everything before the first dot (.) in the column name. If removing prefixes would result in duplicate column names, an exception is raised.remove_prefix()[source]
Returns:Dataset: A new Dataset with prefixes removed from column names
Raises:ValueError: If removing prefixes would result in duplicate column names
Examples:
Rename the fields in the scenarios. Parameters: replacement_dict – A dictionary with the old names as keys and the new names as values. Example:rename(replacement_dict: dict) → ScenarioList [source ]
Reorder the keys in the scenarios. Delegates to ScenarioListTransformer.reorder_keys.reorder_keys(new_order: List[str]) → ScenarioList [source ]
Replace the field names in the scenarios with a new list of names.replace_names(new_names: list) → ScenarioList [source ]
Parameters:new_names – A list of new field names to use.
Examples:
Create new scenarios with values replaced according to the provided replacement dictionary.replace_values(replacements: dict) → ScenarioList [source ]
Args:replacements (dict): Dictionary of values to replace {old_value: new_value}
Returns:ScenarioList: A new ScenarioList with replaced values
Examples:
Generates a report of the results by iterating through rows.report(*fields: str | None, top_n: int | None = None, header_fields: List[str] | None = None, divider: bool = True, return_string: bool = False, format: str = ‘markdown’, filename: str | None = None) → str | Document | None [source ]
Args:*fields: The fields to include in the report. If none provided, all fields are used. top_n: Optional limit on the number of observations to include. header_fields: Optional list of fields to include in the main header instead of as sections. divider: If True, adds a horizontal rule between observations (markdown only). return_string: If True, returns the markdown string. If False (default in notebooks), only displays the markdown without returning. format: Output format - either “markdown” or “docx”. filename: If provided and format is “docx”, saves the document to this file.
Returns:Depending on format and return_string: - For markdown: A string if return_string is True, otherwise None (displays in notebook) - For docx: A docx.Document object, or None if filename is provided (saves to file)
Examples:
Generates a report using a Jinja2 template for each row in the dataset. This method renders a user-provided Jinja2 template for each observation in the dataset, with template variables populated from the row data. This allows for completely customized report formatting using pandoc for advanced output formats.report_from_template(template: str, *fields: str | None, top_n: int | None = None, remove_prefix: bool = True, return_string: bool = False, format: str = ‘text’, filename: str | None = None, separator: str = ‘\n\n’, observation_title_template: str | None = None, explode: bool = False, filestore: bool = False) → str | Document | List | FileStore | None [source ]
Args:template: Jinja2 template string to render for each row *fields: The fields to include in template context. If none provided, all fields are used. top_n: Optional limit on the number of observations to include. remove_prefix: Whether to remove type prefixes (e.g., “answer.”) from field names in template context. return_string: If True, returns the rendered content. If False (default in notebooks), only displays the content without returning. format: Output format - one of “text”, “html”, “pdf”, or “docx”. Formats other than “text” require pandoc. filename: If provided, saves the rendered content to this file. For exploded output, this becomes a template (e.g., “report_{index}.html”). separator: String to use between rendered templates for each row (ignored when explode=True). observation_title_template: Optional Jinja2 template for observation titles. Defaults to “Observation ” where index is 1-based. Template has access to all row data plus ‘index’ and ‘index0’ variables. explode: If True, creates separate files for each observation instead of one combined file. filestore: If True, wraps the generated file(s) in FileStore object(s). If no filename is provided, creates temporary files. For exploded output, returns a list of FileStore objects.
Returns:Depending on explode, format, return_string, and filestore: - For text format: String content or None (if displayed in notebook) - For html format: HTML string content or None (if displayed in notebook) - For docx format: Document object or None (if saved to file) - For pdf format: PDF bytes or None (if saved to file) - If explode=True: List of created filenames (when filename provided) or list of documents/content - If filestore=True: FileStore object(s) containing the generated file(s)
Notes:
- Pandoc is required for HTML, PDF, and DOCX output formats
- Templates are treated as Markdown for all non-text formats
- PDF output uses XeLaTeX engine through pandoc
- HTML output includes standalone document structure
Examples:
Perform a right join with another ScenarioList, following SQL join semantics.right_join(other: ScenarioList, by: str | list[str]) → ScenarioList [source ]
Args:other: The ScenarioList to join with by: String or list of strings representing the key(s) to join on. Cannot be empty.
Returns:A new ScenarioList containing all right scenarios with matching left data added
Return a random sample from the ScenarioListsample(n: int, seed: str | None = None) → ScenarioList [source ]
Select only specified fields from all scenarios in the list. This method applies the select operation to each scenario in the list, returning a new ScenarioList where each scenario contains only the specified fields.select(*fields: str) → ScenarioList [source ]
Args:*fields: Field names to select from each scenario.
Returns:A new ScenarioList with each scenario containing only the selected fields.
Raises:KeyError: If any specified field doesn’t exist in any scenario.
Examples:
Shuffle the ScenarioList.shuffle(seed: str | None = None) → ScenarioList [source ]
Execute SQL queries on the dataset. This powerful method allows you to use SQL to query and transform your data, combining the expressiveness of SQL with EDSL’s data structures. It works by creating an in-memory SQLite database from your data and executing the query against it.sql(query: str, transpose: bool = None, transpose_by: str = None, remove_prefix: bool = True, shape: str = ‘wide’) → Dataset [source ]
Parameters:query: SQL query string to execute transpose: Whether to transpose the resulting table (rows become columns) transpose_by: Column to use as the new index when transposing remove_prefix: Whether to remove type prefixes (e.g., “answer.”) from column names shape: Data shape to use (“wide” or “long”)
- “wide”: Default tabular format with columns for each field
- “long”: Melted format with key-value pairs, useful for certain queries
Returns:A Dataset object containing the query results
Notes:
- The data is stored in a table named “self” in the SQLite database
- In wide format, column names include their type prefix unless remove_prefix=True
- In long format, the data is melted into columns: row_number, key, value, data_type
- Complex objects like lists and dictionaries are converted to strings
Examples:
Concatenate a string to a field across all Scenarios. Applies the same behavior asstring_cat(key: str, addend: str, position: str = ‘suffix’, inplace: bool = False) → ScenarioList [source ]
Scenario.string_cat
to each Scenario in the list. By default, returns a new ScenarioList
; set inplace=True
to modify this list.
Args:
key: The key whose value will be concatenated in each Scenario. addend: The string to concatenate to the existing value. position: Either “suffix” (default) or “prefix”. inplace: If True, modify scenarios in place and return self.
Returns:
A ScenarioList
with updated Scenarios.
Raises:
KeyError: If key
is missing in any Scenario. TypeError: If any value under key
is not a string. ValueError: If position
is not “suffix” or “prefix”.
Sum the values of a field across all scenarios.sum(field: str) → int [source ]
Return the ScenarioList as a table.table(*fields: str, tablefmt: Literal[‘plain’, ‘simple’, ‘github’, ‘grid’, ‘fancy_grid’, ‘pipe’, ‘orgtbl’, ‘rst’, ‘mediawiki’, ‘html’, ‘latex’, ‘latex_raw’, ‘latex_booktabs’, ‘tsv’] | None = ‘rich’, pretty_labels: dict[str, str] | None = None) → str [source ]
Add a duplicate of an existing scenario with optional value replacements. This method duplicates the scenario at index (defaulttack_on(replacements: dict[str, Any], index: int = -1) → ScenarioList [source ]
-1
which refers to the last scenario), applies the key/value pairs provided in replacements, and returns a new ScenarioList with the modified scenario appended.
Args:
replacements: Mapping of field names to new values to overwrite in the cloned
scenario.
index: Index of the scenario to duplicate. Supports negative indexing just
like normal Python lists (-1
is the last item).
Returns:
ScenarioList: A new ScenarioList containing all original scenarios plus the newly created one.
Raises:
ScenarioError: If the ScenarioList is empty, index is out of range, or if
any key in replacements does not exist in the reference scenario.
Count frequency distributions of values in specified fields. This method tallies the occurrence of unique values within one or more fields, similar to a GROUP BY and COUNT in SQL. When multiple fields are provided, it performs cross-tabulation across those fields.tally(*fields: str | None, top_n: int | None = None, output=‘Dataset’) → dict | Dataset [source ]
Parameters:*fields: Field names to tally. If none provided, uses all available fields. top_n: Optional limit to return only the top N most frequent values. output: Format for results, either “Dataset” (recommended) or “dict”.
Returns:By default, returns a Dataset with columns for the field(s) and a ‘count’ column. If output=”dict”, returns a dictionary mapping values to counts.
Notes:
- For single fields, returns counts of each unique value
- For multiple fields, returns counts of each unique combination of values
- Results are sorted in descending order by count
- Fields can be specified with or without their type prefix
Examples:
Takes the cross product of two ScenarioLists. Example:times(other: ScenarioList) → ScenarioList [source ]
Create a Jobs object from a ScenarioList and a Survey object. Parameters: survey – The Survey object to use for the Jobs object. Example: >>> from edsl import Survey, Jobs, ScenarioList # doctest: +SKIP >>> isinstance(ScenarioList.example().to(Survey.example()), Jobs) # doctest: +SKIP Trueto(survey: ‘Survey’ | ‘QuestionBase’) → Jobs [source ]
Create an AgentBlueprint from this ScenarioList. Args: seed: Optional seed for deterministic permutation order. cycle: Whether to continue cycling through permutations indefinitely. dimension_name_field: Field name to read the dimension name from. dimension_values_field: Field name to read the dimension values from. dimension_description_field: Optional field name for the dimension description.to_agent_blueprint(*, seed: int | None = None, cycle: bool = True, dimension_name_field: str = ‘dimension’, dimension_values_field: str = ‘dimension_values’, dimension_description_field: str | None = None) [source ]
Convert the results to a list of dictionaries, one per agent. Parameters: remove_prefix – Whether to remove the prefix from the column names.to_agent_list(remove_prefix: bool = True) [source ]
Convert all Scenario objects to traits of a single Agent. Delegates to ScenarioListTransformer.to_agent_traits.to_agent_traits(agent_name: str | None = None) → Agent [source ]
Export the results to a FileStore instance containing CSV data.to_csv(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None) → FileStore [source ]
Convert the ScenarioList to a Dataset.to_dataset() → Dataset [source ]
to_dict(sort: bool = False, add_edsl_version: bool = False) → dict [source ]
Convert the results to a list of dictionaries. Parameters: remove_prefix – Whether to remove the prefix from the column names.to_dicts(remove_prefix: bool = True) → list[dict] [source ]
Export the results to a FileStore instance containing DOCX data. Each row of the dataset will be rendered on its own page, with a 2-column table that lists the keys and associated values for that observation.to_docx(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None) → FileStore [source ]
Export the results to a FileStore instance containing Excel data.to_excel(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None, sheet_name: str | None = None) [source ]
Export the results to a FileStore instance containing JSONL data.to_jsonl(filename: str | None = None) [source ]
Return the set of values in the field. Parameters:to_key_value(field: str, value=None) → dict | set [source ]
- field – The field to extract values from.
- value – An optional field to use as the value in the key-value pair.
Convert the results to a list of lists. Parameters:to_list(flatten=False, remove_none=False, unzipped=False) → list[list] [source ]
- flatten – Whether to flatten the list of lists.
- remove_none – Whether to remove None values from the list.
Convert the results to a pandas DataFrame, ensuring that lists remain as lists. Args: remove_prefix: Whether to remove the prefix from the column names. lists_as_strings: Whether to convert lists to strings. Returns: A pandas DataFrame.to_pandas(remove_prefix: bool = False, lists_as_strings=False) [source ]
Convert the results to a Polars DataFrame. Args: remove_prefix: Whether to remove the prefix from the column names. lists_as_strings: Whether to convert lists to strings. Returns: A Polars DataFrame.to_polars(remove_prefix: bool = False, lists_as_strings=False) [source ]
Convert the ScenarioList to a ranked ScenarioList based on pairwise comparisons. Args: option_fields: List of scenario column names containing options to compare. answer_field: Name of the answer column containing the chosen option’s value. include_rank: If True, include a rank field on each returned Scenario. rank_field: Name of the rank field to include when include_rank is True. item_field: Field name used to store the ranked item value on each Scenario. Returns: ScenarioList ordered best-to-worst according to pairwise ranking.to_ranked_scenario_list(option_fields: Sequence[str], answer_field: str, include_rank: bool = True, rank_field: str = ‘rank’, item_field: str = ‘item’) → ScenarioList [source ]
Convert the results to a list of dictionaries, one per scenario. Parameters: remove_prefix – Whether to remove the prefix from the column names.to_scenario_list(remove_prefix: bool = True) → ScenarioList [source ]
Return a single Scenario whose values are lists across the list. The resulting Scenario contains every key that appears in any member of the list. For each key, the value is a list of that key’s values taken row-wise from the ScenarioList, padding with None when a row is missing the key.to_scenario_of_lists() → Scenario [source ]
Export the results to a SQLite database file.to_sqlite(filename: str | None = None, remove_prefix: bool = False, pretty_labels: dict | None = None, table_name: str = ‘results’, if_exists: str = ‘replace’) [source ]
to_survey() → Survey [source ]
Convert the ScenarioList to a ranked ScenarioList using TrueSkill algorithm. Args: option_fields: List of scenario column names containing options to compare. answer_field: Name of the answer column containing the ranking order. include_rank: If True, include a rank field on each returned Scenario. rank_field: Name of the rank field to include when include_rank is True. item_field: Field name used to store the ranked item value on each Scenario. mu_field: Field name for TrueSkill mu (skill estimate) value. sigma_field: Field name for TrueSkill sigma (uncertainty) value. conservative_rating_field: Field name for conservative rating (mu - 3*sigma). initial_mu: Initial skill rating (default 25.0). initial_sigma: Initial uncertainty (default 8.333). beta: Skill class width (defaults to initial_sigma/2). tau: Dynamics factor (defaults to initial_sigma/300).to_true_skill_ranked_list(option_fields: Sequence[str], answer_field: str, include_rank: bool = True, rank_field: str = ‘rank’, item_field: str = ‘item’, mu_field: str = ‘mu’, sigma_field: str = ‘sigma’, conservative_rating_field: str = ‘conservative_rating’, initial_mu: float = 25.0, initial_sigma: float = 8.333, beta: float = None, tau: float = None) → ScenarioList [source ]
ScenarioList ordered best-to-worst according to TrueSkill ranking.Returns:
Transform a field using a function. Delegates to ScenarioListTransformer.transform.transform(field: str, func: Callable, new_name: str | None = None) → ScenarioList [source ]
Transform the ScenarioList into a single Scenario with key/value pairs. This method transforms the ScenarioList by: 1. Using the value of the specified key_field from each Scenario as a new key 2. Automatically formatting the remaining values as “key: value, key: value” 3. Creating a single Scenario containing all the transformed key/value pairstransform_by_key(key_field: str) → Scenario [source ]
Args:key_field: The field name whose value will become the new key
Returns:A single Scenario with all the transformed key/value pairs
Examples:
tree(node_order: List[str] | None = None) [source ]Convert the results to a Tree. Args: node_order: The order of the nodes. Returns: A Tree object.
unique() → ScenarioList [source ]Return a new ScenarioList containing only unique Scenario objects. This method removes duplicate Scenario objects based on their hash values, which are determined by their content. Two Scenarios with identical key-value pairs will have the same hash and be considered duplicates.
Returns:A new ScenarioList containing only unique Scenario objects.
Examples:
Notes:
- The order of scenarios in the result is not guaranteed due to the use of sets
- Uniqueness is determined by the Scenario’s __hash__ method
- The original ScenarioList is not modified
- This implementation is memory efficient as it processes scenarios one at a time
Unpack a field into multiple fields. Delegates to ScenarioListTransformer.unpack.unpack(field: str, new_names: List[str] | None = None, keep_original=True) → ScenarioList [source ]
unpack_dict(field: str, prefix: str | None = None, drop_field: bool = False) → ScenarioList [source ]Unpack a dictionary field into separate fields. Delegates to ScenarioListTransformer.unpack_dict.
Unpack list columns into separate columns with provided names or numeric suffixes. For example, if a dataset contains: [{ ‘data’: [[1, 2, 3], [4, 5, 6]], ‘other’: [‘x’, ‘y’]}] After d.unpack_list(‘data’), it should become: [{ ‘other’: [‘x’, ‘y’], ‘data_1’: [1, 4], ‘data_2’: [2, 5], ‘data_3’: [3, 6]}]unpack_list(field: str, new_names: List[str] | None = None, keep_original: bool = True) → Dataset [source ]
Args:field: The field containing lists to unpack new_names: Optional list of names for the unpacked fields. If None, uses numeric suffixes. keep_original: If True, keeps the original field in the dataset
Returns:A new Dataset with unpacked columns
Examples:
from edsl.dataset import Dataset
Unpivot the ScenarioList, allowing for id variables. Delegates to ScenarioListTransformer.unpivot.unpivot(id_vars: List[str] | None = None, value_vars: List[str] | None = None) → ScenarioList [source ]
Zip two iterable fields in each Scenario into a dict under a new key. For every Scenario in the list, this method computeszip(field_a: str, field_b: str, new_name: str) → ScenarioList [source ]
dict(zip(scenario[field_a], scenario[field_b]))
and stores the result in a new key named new_name
. It returns a new ScenarioList containing the updated Scenarios.
Args:field_a: Name of the first iterable field whose values become dict keys. field_b: Name of the second iterable field whose values become dict values. new_name: Name of the new field to store the resulting dictionary under.
Returns:A new ScenarioList with the zipped dictionary added to each Scenario.
Raises:KeyError: If either field name does not exist in any Scenario. ScenarioError: If referenced fields are not iterable in any Scenario.
Examples: