### Install DenarioApp from source Source: https://github.com/astropilot-ai/denario/blob/master/docs/app.md Commands for setting up the development environment after cloning the repository. ```bash pip install -e . ``` ```bash uv sync ``` -------------------------------- ### Setup virtual environment for source build Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Creates and activates a virtual environment for local development. ```bash python3 -m venv Denario_env source Denario_env/bin/activate ``` -------------------------------- ### Launch DenarioApp Source: https://github.com/astropilot-ai/denario/blob/master/docs/app.md Start the GUI application using the built-in CLI command. ```bash denario run ``` -------------------------------- ### Install Denario via pip Source: https://github.com/astropilot-ai/denario/blob/master/README.md Standard installation method using a virtual environment and pip. ```bash python -m venv Denario_env source Denario_env/bin/activate pip install "denario[app]" ``` -------------------------------- ### Install Denario via pip Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Installs the package with GUI support. ```bash pip install "denario[app]" ``` -------------------------------- ### Install DenarioApp via pip Source: https://github.com/astropilot-ai/denario/blob/master/docs/app.md Use these commands to install the application package or the standalone GUI package. ```bash pip install "denario[app]" ``` ```bash pip install denario_app ``` -------------------------------- ### Install project in editable mode Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Installs the local project directory as an editable package. ```bash pip install -e . ``` -------------------------------- ### Clone and Build Denario from Source Source: https://github.com/astropilot-ai/denario/blob/master/README.md Commands to clone the repository and install the project using pip. ```bash git clone https://github.com/AstroPilot-AI/Denario.git cd Denario ``` ```bash python3 -m venv Denario_env source Denario_env/bin/activate ``` ```bash pip install -e . ``` -------------------------------- ### Install Denario via uv Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Adds the package as a dependency using uv. ```bash uv add denario[app] ``` -------------------------------- ### Configure Denario models for Vertex AI Source: https://github.com/astropilot-ai/denario/blob/master/docs/llm_api_keys/vertex-ai-setup.md Example of specifying Gemini models when calling the get_results method in Denario. ```python den.get_results(engineer_model='gemini-2.5-pro', researcher_model='gemini-2.5-pro') ``` -------------------------------- ### Rerunning Denario analysis from the beginning Source: https://github.com/astropilot-ai/denario/blob/master/docs/troubleshooting.md Restart the module from the start when encountering unrecoverable bugs or data reading issues. ```python from denario import Denario # Follow the research plan, write and execute code, make plots, and summarize the results den.get_results(engineer_model='gemini-2.5-pro', researcher_model='gemini-2.5-pro') ``` -------------------------------- ### Initialize Denario Project Source: https://github.com/astropilot-ai/denario/blob/master/docs/get_started.md Set up the Denario instance and define the data description for the project. ```python from denario import Denario den = Denario(project_dir="project_dir") prompt = """ Analyze the experimental data stored in data.csv using sklearn and pandas. This data includes time-series measurements from a particle detector. """ den.set_data_description(prompt) ``` -------------------------------- ### Initialize Denario Project Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Set up the Denario instance by specifying the project directory path. ```python from denario import Denario project_dir = "/path/to/project/folder" # replace with the path to your project folder den = Denario(project_dir=project_dir) ``` -------------------------------- ### Initialize environment with uv Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Initializes a project with Python 3.12 and activates the virtual environment. ```bash uv init --python 3.12 source .venv/bin/activate ``` -------------------------------- ### Sync project with uv Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Synchronizes dependencies and environment using uv. ```bash uv sync ``` -------------------------------- ### Run DenarioApp from source Source: https://github.com/astropilot-ai/denario/blob/master/docs/app.md Alternative methods to execute the application when running from a local source clone. ```bash denario run ``` ```bash streamlit run src/denario_app/app.py ``` -------------------------------- ### Build and Sync with uv Source: https://github.com/astropilot-ai/denario/blob/master/README.md Commands to manage dependencies and environment using the uv package manager. ```bash uv sync ``` ```bash source .venv/bin/activate ``` -------------------------------- ### Define API keys in a .env file Source: https://github.com/astropilot-ai/denario/blob/master/docs/llm_api_keys/storing-api-keys.md Create a .env file in the project directory to store API keys for the current environment. ```bash GOOGLE_API_KEY=your_gemini_api_key GOOGLE_APPLICATION_CREDENTIALS=path/to/gemini.json OPENAI_API_KEY=your_openai_api_key PERPLEXITY_API_KEY=your_perplexity_api_key ANTHROPIC_API_KEY=your_anthropic_api_key FUTURE_HOUSE_API_KEY=your_fh_key ``` -------------------------------- ### Set and Retrieve Project Idea Source: https://github.com/astropilot-ai/denario/blob/master/examples/idea_check.ipynb Configures the project idea and retrieves it for further processing. ```python # den.set_idea(project_dir+"/input_files/idea.md") ``` ```python den.set_idea() ``` ```python idea = den.research.idea ``` ```python print(idea) ``` -------------------------------- ### Build Docker image from source Source: https://github.com/astropilot-ai/denario/blob/master/docs/docker.md Build a local image using the development Dockerfile. ```bash docker build -f docker/Dockerfile.dev -t denario_src . ``` -------------------------------- ### Create virtual environment with venv Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Initializes a new virtual environment named Denario_env. ```bash python3 -m venv Denario_env ``` -------------------------------- ### Configure FutureHouse Client Source: https://github.com/astropilot-ai/denario/blob/master/examples/idea_check.ipynb Initializes the FutureHouse client using an API key from environment variables. ```python from futurehouse_client import FutureHouseClient, JobNames from futurehouse_client.models import ( TaskRequest, ) import os fhkey = os.getenv("FUTURE_HOUSE_API_KEY") ``` -------------------------------- ### Run with Docker Compose Source: https://github.com/astropilot-ai/denario/blob/master/docs/docker.md Use Docker Compose to manage container execution and volume settings. ```bash docker compose up ``` ```bash docker compose run --rm denario ``` ```bash docker compose run --rm denario bash ``` -------------------------------- ### Activate virtual environment Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Activates the previously created virtual environment. ```bash source Denario_env/bin/activate ``` -------------------------------- ### Set and display research idea Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/research_idea.ipynb Initializes the research project with a detailed markdown string and displays the current configuration. ```python den.set_idea(idea = r""" Compare 1D CNN and FCNN neural net architecture for non-linear matter power spectrum emulators in LCDM. Input parameters include the cosmological parameters as well as the redshift at which the power spectrum is requested. We want to find the architecture that is both as accurate as possible and as fast as possible to compute. Constraints: - use classy_sz for computing P(k,z) to generate the data. - Cosmological parameters are omega_b, omega_cdm, H0, logA, n_s. - The k-range of interest is kmin = 1e-4 [1/Mpc] to kmax = 10 [1/Mpc]. - The z-range of interest is zmin = 0 to zmax = 3. - P(k) at z should always be plotted/processed in log-log scale. - Training set should have at least 50k spectra. - The training/testing data should be created in a different step as training the neural nets. - The step to train the neural nets should only be for training. Plotting and performances should be done in another step. """) den.show_idea() ``` -------------------------------- ### Initialize Denario Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/denario_oscillator_full_run.ipynb Instantiate the Denario class to begin the research process. ```python from denario import Denario den = Denario() ``` -------------------------------- ### Run local Docker image Source: https://github.com/astropilot-ai/denario/blob/master/docs/docker.md Execute the locally built image with volume mounting for live code updates. ```bash docker run --rm \ -p 8501:8501 \ -v "$(pwd)":/app \ denario_src ``` ```bash docker run -it --rm \ -v "$(pwd)":/app \ denario_src bash ``` -------------------------------- ### Set Google Application Credentials environment variable Source: https://github.com/astropilot-ai/denario/blob/master/docs/llm_api_keys/vertex-ai-setup.md Command to point the environment variable to the service account JSON key file. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/gemini.json ``` -------------------------------- ### Initialize and Generate Paper Source: https://github.com/astropilot-ai/denario/blob/master/docs/troubleshooting.md Use this snippet to initiate the paper generation process with specific journal styles and LLM configurations. ```python from denario import Denario, Journal # Write a paper with [APS (Physical Review Journals)](https://journals.aps.org/) style den.get_paper(journal=Journal.AAS, llm='gemini-2.5-flash', add_citations=False) ``` -------------------------------- ### Run Denario with Docker Source: https://github.com/astropilot-ai/denario/blob/master/README.md Commands for pulling, running, and building the Denario Docker image. ```bash docker pull pablovd/denario:latest ``` ```bash docker run -p 8501:8501 --rm pablovd/denario:latest ``` ```bash docker run --rm -it pablovd/denario:latest bash ``` ```bash docker build -f docker/Dockerfile.dev -t denario_src . ``` -------------------------------- ### Create and activate environment with conda Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Creates a conda environment with Python 3.12 and activates it. ```bash conda create -n Denario_env python==3.12 conda activate Denario_env ``` -------------------------------- ### End-to-end Denario Research Workflow Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/EtE_Gemini_fast.ipynb Initializes the Denario project, sets data descriptions, and executes the full research pipeline using Gemini models. ```python # add these two lines if you are working on a python notebook # these are just required to deal with async calls import nest_asyncio nest_asyncio.apply() from denario import Denario, Journal # set Denario and project folder folder = 'Project3' den = Denario(project_dir=folder) # set data description. The file Project3/input.md contains the data description den.set_data_description(f"{folder}/input.md") # Generate a research idea from the input text den.get_idea_fast(llm='gemini-2.5-flash', verbose=False) # Check if idea is novel or not den.check_idea(llm='gemini-2.5-flash') # Generate a research plan to carry out the idea den.get_method_fast(llm="gemini-2.5-pro", verbose=False) # Follow the research plan, write and execute code, make plots, and summarize the results den.get_results(engineer_model='gemini-2.5-pro', researcher_model='gemini-2.5-pro') # Write a paper with [APS (Physical Review Journals)](https://journals.aps.org/) style den.get_paper(journal=Journal.AAS, llm='gemini-2.5-flash', add_citations=False) ``` -------------------------------- ### Prepare Validation Prompt Source: https://github.com/astropilot-ai/denario/blob/master/examples/idea_check.ipynb Constructs the prompt to query existing literature regarding the project idea. ```python fh_client = FutureHouseClient( api_key=fhkey, ) check_idea_prompt = rf""" Has anyone worked on or explored the following idea? {idea} Answer: Related previous work: """ ``` -------------------------------- ### Initialize and Generate Paper Draft Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/write_paper.ipynb Configures the Denario instance with a project directory and triggers the paper generation process using a specified journal format and LLM. ```python # add these two lines if you are working on a python notebook # these are just required to deal with async calls import nest_asyncio nest_asyncio.apply() from denario import Denario, Journal # set Denario; the project folder is Project2 and inside it there are the files idea.md, methods.md, results.md, and a # folder called plots with all the plots folder = "Project2" astro_pilot = Denario(project_dir=folder) # Write the paper; using the AAS format and without adding citations astro_pilot.get_paper(journal=Journal.AAS, llm='gemini-2.5-flash', add_citations=False) ``` -------------------------------- ### Run Docker container Source: https://github.com/astropilot-ai/denario/blob/master/docs/docker.md Commands to execute the Denario GUI or access the container interactively. ```bash docker run -p 8501:8501 --rm pablovd/denario:latest ``` ```bash docker run --rm -it pablovd/denario:latest bash ``` ```bash docker run --rm \ -p 8501:8501 \ -v $(pwd)/project:/app/project \ -v $(pwd).env/app/.env \ denario_src ``` -------------------------------- ### Activate uv virtual environment Source: https://github.com/astropilot-ai/denario/blob/master/docs/install.md Activates the virtual environment created by uv. ```bash source .venv/bin/activate ``` -------------------------------- ### Execution logs and output Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Sample console output generated during the execution of the idea check process. ```text WARNING: All log messages before absl::InitializeLog() is called are written to STDERR E0000 00:00:1758990951.795471 53440736 alts_credentials.cc:93] ALTS creds ignored. Not running on GCP and untrusted ALTS is not enabled. ``` ```text Output: Addressing idea novelty: round 0 ``` ```text Output: Analyzing novelty: 0%| | 0/5 [00:05 Sum(lambda_j * x_ij) - theta * x_io <= 0 # # Rewritten for linprog: theta * x_io - Sum(lambda_j * x_ij) >= 0 # # This is for each input. Here, one input. # # A_ub matrix rows: # # [x_io, -x_1, -x_2, ..., -x_N] (for the input constraint, but linprog expects <=, so multiply by -1) # # Let's structure for linprog: # # theta * x_io - sum(lambda_j * x_j) >= 0 => sum(lambda_j * x_j) - theta * x_io <= 0 # A_ub_input_rows = np.hstack([ # -x_o.reshape(-1, 1), # Coeff for theta (negative because x_o is on RHS of theta) # inputs_arr.T # Coeffs for lambdas # ]) # Shape: (num_inputs, num_dmus + 1) # b_ub_input_rows = np.zeros(inputs_arr.shape[1]) # # # 2. Sum(lambda_j * y_rj) >= y_ro => y_ro - Sum(lambda_j * y_rj) <= 0 # # A_ub matrix rows: # # [0, -y_1, -y_2, ..., -y_N] # A_ub_output_rows = np.hstack([ # np.zeros((outputs_arr.shape[1], 1)), # Coeff for theta # -outputs_arr.T # Coeffs for lambdas (negative because original is >=) # ]) # Shape: (num_outputs, num_dmus + 1) # b_ub_output_rows = -y_o # # A_ub = np.vstack([A_ub_input_rows, A_ub_output_rows]) # b_ub = np.concatenate([b_ub_input_rows, b_ub_output_rows]) # # # Equality constraints (Aeq x = beq) # # Sum(lambda_j) = 1 # # A_eq = [0, 1, 1, ..., 1] # A_eq = np.ones((1, num_dmus + 1)) # A_eq[0, 0] = 0 # b_eq = np.array([1]) # # # Bounds for variables: # # theta >= 0 (implicitly, can be set to (None, None) or (0, None) or (0,1] if input oriented) # # lambda_j >= 0 # bounds = [(None, None)] + [(0, None)] * num_dmus # Theta can be unbounded or (0,1] for input-oriented. # # (0,1] might be better for input-oriented theta. # # Let's use (0,None) for theta, as some formulations allow >1 for super-efficiency if input > peer sum. # # For standard efficiency, theta <=1. LP solver will find smallest positive. # bounds[0] = (0,1) # Theta for input-oriented efficiency score is <=1 # # res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs') # 'highs' is default in newer scipy # # if res.success: # return res.fun # This is theta # else: # # print(f"Optimization failed for DMU {dmu_idx}: {res.message}") # return np.nan ``` -------------------------------- ### Set research data description Source: https://github.com/astropilot-ai/denario/blob/master/examples/enhance_input.ipynb Define the research topic using a raw string containing arXiv URLs and register it with the Denario instance. ```python input_description = r""" We are in the context of fuzzy dark matter (FDM) models, also known as ultralight or scalar dark matter, a particular dark matter (DM) candidate (see https://arxiv.org/pdf/1610.08297). The idea to develop is to calculate whether or not FDM can explain some of the properties of Little Red Dots (LRDs) which have been recently discovered by JWST. LRDs are astrophysical objects with very peculiar properties. Little red dots (LRDs) are a newly identified class of broad-line active galactic nuclei (AGN) with a distinctive v-shape spectrum characterized by red optical and blue UV continuum emission. Their high abundance at redshifts of z∼6−8 and decline at lower redshifts suggest a transient origin. Most likely, they are the cradle of supermassive black holes (see https://arxiv.org/pdf/2509.02664). We ask to focus on the possibility that the large mass inferred for the Black Hole (BH) could be produced by the accretion of a FDM solitonic core. For example in this paper here https://arxiv.org/abs/2508.21748 presents a tentative measurement of the BH mass and also on the ratio of BH mass with the stellar mass, this ratio has to be larger than 2. Such a ''naked'' black hole, together with its near-pristine environment, indicates that this LRD is a massive black hole seed caught in its earliest accretion phase, with a lot of surrounding gas. We would like to explore possibilities in the context of FDM models, both at the level of DM accretion rates/times, or dynamical effects. For example, see https://arxiv.org/abs/1908.04790. """ den.set_data_description(data_description = input_description) ``` -------------------------------- ### Display Generated Paper PDF Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/write_paper.ipynb Uses IPython to render the generated PDF file within a scrollable frame in a notebook. ```python from IPython.display import IFrame # show PDF in a scrollable frame (width, height in pixels) IFrame("Project2/paper/paper_v2_no_citations.pdf", width=800, height=600) ``` -------------------------------- ### Load Dataset into DataFrame Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Initial loading of the CSV file into a pandas DataFrame for inspection. ```python # Example: # df_raw = pd.read_csv(DATA_PATH) # print("Data loaded successfully.") # print(f"Raw dataset shape: {df_raw.shape}") ``` -------------------------------- ### Generate Research Methodology Source: https://github.com/astropilot-ai/denario/blob/master/docs/get_started.md Generate research methodologies using standard or fast workflows. ```python den.get_method() ``` ```python den.get_method_fast() ``` -------------------------------- ### Compute Results Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/denario_oscillator_full_run.ipynb Execute the methodology to perform computations and generate plots. ```python den.get_results() den.show_results() ``` -------------------------------- ### BibTeX Citation Entries Source: https://github.com/astropilot-ai/denario/blob/master/README.md Use these BibTeX entries to cite the Denario research paper and software in academic publications. ```bibtex @article{villaescusanavarro2025denarioprojectdeepknowledge, title={The Denario project: Deep knowledge AI agents for scientific discovery}, author={Francisco Villaescusa-Navarro and Boris Bolliet and Pablo Villanueva-Domingo and Adrian E. Bayer and Aidan Acquah and Chetana Amancharla and Almog Barzilay-Siegal and Pablo Bermejo and Camille Bilodeau and Pablo Cárdenas Ramírez and Miles Cranmer and Urbano L. França and ChangHoon Hahn and Yan-Fei Jiang and Raul Jimenez and Jun-Young Lee and Antonio Lerario and Osman Mamun and Thomas Meier and Anupam A. Ojha and Pavlos Protopapas and Shimanto Roy and David N. Spergel and Pedro Tarancón-Álvarez and Ujjwal Tiwari and Matteo Viel and Digvijay Wadekar and Chi Wang and Bonny Y. Wang and Licong Xu and Yossi Yovel and Shuwen Yue and Wen-Han Zhou and Qiyao Zhu and Jiajun Zou and Íñigo Zubeldia}, year={2025}, eprint={2510.26887}, archivePrefix={arXiv}, primaryClass={cs.AI}, url={https://arxiv.org/abs/2510.26887}, } @software{Denario_2025, author = {Pablo Villanueva-Domingo, Francisco Villaescusa-Navarro, Boris Bolliet}, title = {Denario: Modular Multi-Agent System for Scientific Research Assistance}, year = {2025}, url = {https://github.com/AstroPilot-AI/Denario}, note = {Available at https://github.com/AstroPilot-AI/Denario}, version = {latest} } @software{CMBAGENT_2025, author = {Boris Bolliet}, title = {CMBAGENT: Open-Source Multi-Agent System for Science}, year = {2025}, url = {https://github.com/CMBAgents/cmbagent}, note = {Available at https://github.com/CMBAgents/cmbagent}, version = {latest} } ``` -------------------------------- ### Recompile LaTeX Documents Source: https://github.com/astropilot-ai/denario/blob/master/docs/troubleshooting.md Commands to manually recompile LaTeX files when automatic generation encounters syntax errors or missing references. ```sh xelatex paper_v2_no_citations.tex xelatex paper_v2_no_citations.tex ``` ```sh xelatex paper_v4_final.tex bibtex paper_v4_final xelatex paper_v4_final.tex xelatex paper_v4_final.tex ``` -------------------------------- ### Execute idea check Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Runs the agentic module to check the idea defined in the project's idea.md file using the specified LLM and Semantic Scholar mode. ```python # beyond the Project1/input.md file, the module requires a file called Project1/idea.md, that contains the actual idea to check # run the agentic module (it will go through a maximum of 7 iterations to find relevant papers) den.check_idea(mode = 'semantic_scholar', llm='gemini-2.5-flash', max_iterations=7) ``` -------------------------------- ### Generate EDA Summary Statistics Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Calculates descriptive statistics for IR, LB, and LB Rate grouped by year and age, then saves the results to a CSV file. ```python # Example: # eda_summary_list = [] # for year_val in df_dea_data['Year'].unique(): # for age_group_val in df_dea_data['AgeGroup'].unique(): # stratum_data = df_dea_data[(df_dea_data['Year'] == year_val) & (df_dea_data['AgeGroup'] == age_group_val)] # if stratum_data.empty: # continue # num_clinics = stratum_data['ClinicId'].nunique() # stats_ir = stratum_data['Input_IntendedRetrievals'].agg(['mean', 'median', 'min', 'max', 'std']).to_dict() # stats_lb = stratum_data['Output_LiveBirths'].agg(['mean', 'median', 'min', 'max', 'std']).to_dict() # stats_lbrate = stratum_data['Data_Value_num'].agg(['mean', 'median']).to_dict() # Original percentage # # eda_summary_list.append({ # 'Year': year_val, 'AgeGroup': age_group_val, 'NumClinics': num_clinics, # 'Mean_IR': stats_ir['mean'], 'Median_IR': stats_ir['median'], 'Min_IR': stats_ir['min'], 'Max_IR': stats_ir['max'], 'Std_IR': stats_ir['std'], # 'Mean_LB': stats_lb['mean'], 'Median_LB': stats_lb['median'], 'Min_LB': stats_lb['min'], 'Max_LB': stats_lb['max'], 'Std_LB': stats_lb['std'], # 'Mean_LBRate': stats_lbrate['mean'], 'Median_LBRate': stats_lbrate['median'] # }) # eda_summary_df = pd.DataFrame(eda_summary_list) # eda_summary_df.to_csv(os.path.join(EDA_DIR, 'eda_summary_statistics_by_stratum.csv'), index=False) # print("EDA summary statistics saved.") # print("\nEDA Summary Statistics by Stratum:") # print(eda_summary_df) # This is the table to be included in the methods section ``` -------------------------------- ### Generate Research Ideas Source: https://github.com/astropilot-ai/denario/blob/master/docs/get_started.md Generate research ideas using standard or fast workflows. ```python den.get_idea() ``` ```python den.get_idea_fast() ``` -------------------------------- ### Set Research Idea Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Configure the research idea to be checked. The set_idea method can be called with a file path or without arguments to use the default configuration. ```python # den.set_idea(project_dir+"/input_files/idea.md") ``` ```python den.set_idea() ``` -------------------------------- ### Generate and display research idea Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/research_idea.ipynb Executes the fast research idea generation process and displays the resulting output. ```python den.get_idea_fast(verbose=False) den.show_idea() ``` -------------------------------- ### Access and Print Research Idea Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Retrieve the current research idea from the research object and display it. ```python idea = den.research.idea ``` ```python print(idea) ``` -------------------------------- ### Execute Validation Task Source: https://github.com/astropilot-ai/denario/blob/master/examples/idea_check.ipynb Submits the validation task to the FutureHouse client and retrieves the results. ```python task_data = TaskRequest( name=JobNames.from_string("owl"), query=check_idea_prompt, ) ``` ```python task_response = fh_client.run_tasks_until_done(task_data) ``` ```python print(task_response[0].answer) ``` ```python print(task_response[0].formatted_answer) ``` -------------------------------- ### Perform Temporal Analysis of Mean Efficiency Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Pivots the efficiency summary data to compare mean efficiency scores across years for each age group. ```python # Example: # temporal_analysis = efficiency_summary_df.pivot_table( # index='AgeGroup', # columns='Year', # values='Mean_Efficiency' # ) # temporal_analysis.to_csv(os.path.join(DEA_RESULTS_DIR, 'temporal_mean_efficiency_by_agegroup.csv')) # print("\nTemporal Analysis of Mean Efficiency by Age Group:") # print(temporal_analysis) ``` -------------------------------- ### Retrieve Keywords Source: https://github.com/astropilot-ai/denario/blob/master/examples/get_keywords.ipynb Retrieves a specified number of keywords from input text based on a defined keyword type. ```python den.get_keywords(input_text=text, n_keywords=8, kw_type = 'aaai') ``` -------------------------------- ### Calculate DEA Efficiency Scores by Stratum Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Iterates through Year and AgeGroup strata to compute efficiency scores, handling insufficient DMUs and zero-output cases. ```python # Example of loop and parallel execution: # all_results = [] # unique_strata = df_dea_data[['Year', 'AgeGroup']].drop_duplicates() # # for index, row in unique_strata.iterrows(): # year = row['Year'] # age_group = row['AgeGroup'] # stratum_df = df_dea_data[(df_dea_data['Year'] == year) & (df_dea_data['AgeGroup'] == age_group)].copy() # # if len(stratum_df) < 2: # Need at least 2 DMUs for comparison, ideally more # print(f"Skipping stratum Year {year}, AgeGroup {age_group} due to insufficient DMUs ({len(stratum_df)}).") # # Assign NaN or 1 to single DMUs if any (a single DMU is always efficient) # if len(stratum_df) == 1: # stratum_df['EfficiencyScore'] = 1.0 # all_results.append(stratum_df) # continue # # inputs_arr = stratum_df['Input_IntendedRetrievals'].values.reshape(-1, 1) # outputs_arr = stratum_df['Output_LiveBirths'].values.reshape(-1, 1) # # # Handle cases where all outputs are zero for a stratum # if np.all(outputs_arr == 0): # print(f"All outputs are zero for stratum Year {year}, AgeGroup {age_group}. Assigning NaN to efficiency scores.") # stratum_df['EfficiencyScore'] = np.nan # all_results.append(stratum_df) # continue # # # If an output is 0 for a DMU, it can cause issues if it's the only one producing that output. # # Small positive value (epsilon) can be added to outputs if they are zero, # # but this changes the data. Standard DEA handles zero outputs if other DMUs have positive outputs. # # If an output is essential and a DMU has zero of it, it will likely be inefficient. # # num_dmus = len(stratum_df) # # tasks = [(inputs_arr, outputs_arr, i) for i in range(num_dmus)] # # # Use with Pool for context management (auto-closes pool) # # with multiprocessing.Pool(processes=min(os.cpu_count(), 128)) as pool: # # efficiency_scores = pool.starmap(solve_dea_bcc_input_oriented_wrapper, tasks) # Need a wrapper if func is not top-level # # # For simplicity here, sequential execution (replace with parallel for actual run) # efficiency_scores = [] # for i in range(num_dmus): # # If solve_dea_bcc_input_oriented is defined within this script, it might need to be passed or made global for multiprocessing. # # Or use a helper function that can be pickled. # score = solve_dea_bcc_input_oriented(inputs_arr, outputs_arr, i) # efficiency_scores.append(score) # # stratum_df['EfficiencyScore'] = efficiency_scores # all_results.append(stratum_df) # print(f"DEA scores calculated for Year {year}, AgeGroup {age_group}.") # # final_dea_results_df = pd.concat(all_results, ignore_index=True) # final_dea_results_df.to_csv(os.path.join(DEA_RESULTS_DIR, 'clinic_efficiency_scores.csv'), index=False) # print("All DEA efficiency scores calculated and saved.") ``` -------------------------------- ### Execute Idea Validation Source: https://github.com/astropilot-ai/denario/blob/master/examples/idea_check.ipynb Runs the agentic module to check a research idea defined in the project's idea.md file using a specified LLM. ```python # beyond the Project1/input.md file, the module requires a file called Project1/idea.md, that contains the actual idea to check # run the agentic module (it will go through a maximum of 7 iterations to find relevant papers) astro_pilot.check_idea(llm='gemini-2.5-flash', max_iterations=7) ``` -------------------------------- ### Save Prepared DEA Data Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Exports the cleaned dataframe to a CSV file for subsequent analysis. ```python # Example: # df_dea_data.to_csv(os.path.join(EDA_DIR, 'prepared_dea_input_output_data.csv'), index=False) # print("Prepared DEA data saved.") ``` -------------------------------- ### Filter Metrics for DEA Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Filters the primary dataframe for specific live birth rate metrics and age breakout categories. ```python # Example: # target_question_lb_rate = "% Live Births per Intended Retrieval" # Verify this exact string # age_breakout_category = "Age group of patient" # Verify this exact string # # df_metrics = df[ # (df['Question'].str.contains(target_question_lb_rate, case=False, na=False)) & # (df['Breakout_Category'] == age_breakout_category) # ].copy() # print(f"Filtered for relevant metrics and age breakouts. Shape: {df_metrics.shape}") ``` -------------------------------- ### Filter for Own-Egg Cycles Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Filter records to include only patients using their own eggs. ```python # Example: # own_egg_type_string = "Patients using their own eggs" # Verify this exact string from data exploration # df = df[df['Type'] == own_egg_type_string].copy() # print(f"Data filtered for own-egg cycles. Shape: {df.shape}") ``` -------------------------------- ### Display Validation Results Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/idea_check.ipynb Print the results of the idea check to view the literature analysis. ```python print(answer) ``` -------------------------------- ### Generate Research Idea Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/denario_oscillator_full_run.ipynb Generate and display a research idea based on the provided data specification. ```python den.get_idea() den.show_idea() ``` -------------------------------- ### Generate Research Paper Source: https://github.com/astropilot-ai/denario/blob/master/docs/examples/denario_oscillator_full_run.ipynb Generate a LaTeX article using the computed results, specifying a journal style. ```python from denario import Journal den.get_paper(journal=Journal.APS) ``` -------------------------------- ### Extract Keywords from Text Source: https://github.com/astropilot-ai/denario/blob/master/examples/get_keywords.ipynb Use the get_keywords method to identify relevant keywords from input text, specifying the keyword type and count. ```python den.get_keywords(input_text=text, n_keywords=8, kw_type = 'unesco') ``` -------------------------------- ### Aggregate Efficiency Scores by Stratum Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Calculates descriptive statistics for efficiency scores grouped by year and age group, saving the results to a CSV file. ```python # Example: # efficiency_summary_list = [] # for year_val in final_dea_results_df['Year'].unique(): # for age_group_val in final_dea_results_df['AgeGroup'].unique(): # stratum_scores = final_dea_results_df[ # (final_dea_results_df['Year'] == year_val) & # (final_dea_results_df['AgeGroup'] == age_group_val) # ]['EfficiencyScore'].dropna() # # if stratum_scores.empty: # continue # # desc_stats = stratum_scores.agg(['mean', 'median', 'min', 'max', 'std']).to_dict() # num_efficient = (stratum_scores >= 0.9999).sum() # Using a threshold for float precision # pct_efficient = (num_efficient / len(stratum_scores)) * 100 if len(stratum_scores) > 0 else 0 # # efficiency_summary_list.append({ # 'Year': year_val, 'AgeGroup': age_group_val, # 'Num_DMUs_in_Stratum': len(stratum_scores), # 'Mean_Efficiency': desc_stats['mean'], 'Median_Efficiency': desc_stats['median'], # 'Min_Efficiency': desc_stats['min'], 'Max_Efficiency': desc_stats['max'], # Max should be 1 # 'Std_Efficiency': desc_stats['std'], # 'Num_Efficient_Clinics': num_efficient, 'Pct_Efficient_Clinics': pct_efficient # }) # # efficiency_summary_df = pd.DataFrame(efficiency_summary_list) # efficiency_summary_df.to_csv(os.path.join(DEA_RESULTS_DIR, 'efficiency_score_summary_by_stratum.csv'), index=False) # print("Efficiency score summary statistics saved.") # print("\nEfficiency Score Summary by Stratum:") # print(efficiency_summary_df) ``` -------------------------------- ### Access AAS Keywords Source: https://github.com/astropilot-ai/denario/blob/master/examples/get_keywords.ipynb Retrieve the full list of AAS keywords directly from the research object or via the show_keywords method. ```python den.research.keywords ``` ```python den.show_keywords() ``` -------------------------------- ### Filter Dataset by Reporting Year Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Restrict the dataset to the years 2020, 2021, and 2022. ```python # Example: # years_of_interest = [2020, 2021, 2022] # df = df_raw[df_raw['Year'].isin(years_of_interest)].copy() # print(f"Data filtered for years {years_of_interest}. Shape: {df.shape}") ``` -------------------------------- ### Extract AAS Keywords Source: https://github.com/astropilot-ai/denario/blob/master/examples/get_keywords.ipynb Execute the keyword extraction process by specifying the input text, the number of keywords, and the keyword type. ```python den.get_keywords(input_text=text, n_keywords=8, kw_type = 'aas') ``` -------------------------------- ### Clean DEA Dataset Source: https://github.com/astropilot-ai/denario/blob/master/examples/Project2/input_files/methods.md Removes rows with missing or non-positive input values to ensure data validity for DEA models. ```python # Example: # initial_rows = len(df_dea_data) # df_dea_data.dropna(subset=['Input_IntendedRetrievals', 'Output_LiveBirths'], inplace=True) # df_dea_data = df_dea_data[df_dea_data['Input_IntendedRetrievals'] > 0] # # If Output_LiveBirths can be zero, this is okay. If not, filter: # # df_dea_data = df_dea_data[df_dea_data['Output_LiveBirths'] > 0] # rows_after_cleaning = len(df_dea_data) # print(f"Removed {initial_rows - rows_after_cleaning} rows due to missing/invalid inputs/outputs for DEA.") # print(f"Final prepared DEA dataset shape: {df_dea_data.shape}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.