### Install AI.zymes with pip Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Installation.md Installs the AI.zymes package using pip. ```bash pip install aizymes ``` -------------------------------- ### Submit controller to run AI.zymes Source: https://github.com/bunzela/aizymes/blob/main/example_notebooks/Example_KSI.ipynb Submits the AI.zymes controller to start the design process. Includes commands to check job status and log output. ```python AIzymes.submit_controller() ``` ```bash !squeue --me # Use the command below to check the output from the running AI.zymes controller #!tail -n 50 Example_KSI/controller.log ``` -------------------------------- ### ESMFold Installation Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Available_Tools.md Instructions for installing ESMFold using pip. ```bash pip install transformers fair-esm ``` -------------------------------- ### Clone AI.zymes from GitHub Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Installation.md Clones the AI.zymes repository from GitHub. ```bash git clone https://github.com/bunzela/AIzymes.git ``` -------------------------------- ### AmberTools Installation Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Available_Tools.md Instructions for installing AmberTools using conda. ```bash conda install conda-forge::ambertools ``` -------------------------------- ### Install build tools Source: https://github.com/bunzela/aizymes/blob/main/src/make_pip_distribution.ipynb Installs the necessary tools for building and uploading Python packages. ```bash #!pip install build twine ``` -------------------------------- ### Import AI.zymes and Create Instance Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md This snippet shows how to import the AI.zymes library and create an instance of the AIzymes_MAIN class, setting the FOLDER_HOME directory. ```python # Import AI.zymes from aizymes import * # Create instance of AIzymes_MAIN AIzymes = AIzymes_MAIN(FOLDER_HOME = 'Example_KSI') ``` -------------------------------- ### Set up AI.zymes for Design Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md This snippet demonstrates the AIzymes.setup() function, which configures the necessary folder structure and input files for the design process. It includes various design, scoring, and job settings. ```python AIzymes.setup( # General Design Settings WT = "1ohp", LIGAND = "5TS", DESIGN = "11,14,15,18,38,54,55,58,63,65,80,82,84,97,99,101,112,114,116", PARENT_DES_MED = ['RosettaDesign', 'ESMfold','MDMin','RosettaRelax','ElectricFields'], DESIGN_METHODS = [[0.5,'SolubleMPNN', 'ESMfold','MDMin','RosettaRelax','ElectricFields'], [0.5,'RosettaDesign', 'ESMfold','MDMin','RosettaRelax','ElectricFields']], # General Scoring Settings SELECTED_SCORES = ["total","catalytic","interface","efield", "identical"], # General Job Settings MAX_JOBS = 72, MAX_GPUS = 4, MEMORY = 450, N_PARENT_JOBS = 144, MAX_DESIGNS = 5000, KBT_BOLTZMANN = [1.0, 0.5, 0.02], SUBMIT_PREFIX = "KSI_TEST", SYSTEM = "AIzymes.config", # RosettaDesign Settings CST_NAME = "5TS_enzdes_planar_tAB100", CST_DIST_CUTOFF = 40., # FieldTools settings FIELD_TARGET = ":5TS@C9 :5TS@H04", ) ``` -------------------------------- ### Check Controller Log and Design Scripts Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md These commands demonstrate how to check the progress and troubleshoot errors by viewing the controller log and listing the scripts for individual designs. ```bash !tail -n 50 {FOLDER_HOME}/controller.log !ls {FOLDER_HOME}/designs/0/scripts ``` -------------------------------- ### Add AI.zymes to PYTHONPATH Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Installation.md Appends the AI.zymes source directory to the PYTHONPATH in .bashrc. ```bash echo 'export PYTHONPATH="$PYTHONPATH:PATH_TO_AIZYMES/src/aizymes"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Set up AI.zymes for design Source: https://github.com/bunzela/aizymes/blob/main/example_notebooks/Example_KSI.ipynb Configures the AI.zymes instance with various design, scoring, and job settings, including specific parameters for RosettaDesign and FieldTools. ```python AIzymes.setup( # General Design Settings WT = "1ohp", LIGAND = "5TS", DESIGN = "11,14,15,18,38,54,55,58,63,65,80,82,84,97,99,101,112,114,116", PARENT_DES_MED = ['RosettaDesign','ESMfold','MDMin','RosettaRelax','ElectricFields'], DESIGN_METHODS = [[0.5,'SolubleMPNN','ESMfold','MDMin','RosettaRelax','ElectricFields'], [0.5,'RosettaDesign','ESMfold','MDMin','RosettaRelax','ElectricFields']], # General Scoring Settings SELECTED_SCORES = ["total","catalytic","interface","efield", "identical"], # General Job Settings MAX_JOBS = 72, MAX_GPUS = 4, MEMORY = 450, N_PARENT_JOBS = 144, MAX_DESIGNS = 2000, KBT_BOLTZMANN = [1.0, 0.5, 0.05], SUBMIT_PREFIX = "KSI_TEST", SYSTEM = "AIzymes.config", # RosettaDesign Settings CST_NAME = "5TS_enzdes_planar_tAB100", CST_DIST_CUTOFF = 40., # FieldTools settings FIELD_TARGET = ":5TS@C9 :5TS@H04", ) ``` -------------------------------- ### Create AI.zymes conda environment Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Installation.md Creates a new conda environment for AI.zymes using the environment.yml file. ```bash cd AIzymes conda env create -f environment.yml --name AIzymes ``` -------------------------------- ### Create an instance of the AI.zymes class Source: https://github.com/bunzela/aizymes/blob/main/example_notebooks/Example_KSI.ipynb Imports the AI.zymes library and creates an instance of the AIzymes_MAIN class, specifying the home folder for the project. ```python # Import AI.zymes from aizymes import * # Create instance of AIzymes_MAIN AIzymes = AIzymes_MAIN(FOLDER_HOME = 'Example_KSI') ``` -------------------------------- ### Print Statistics from AI.zymes Run Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md This snippet shows how to use AIzymes.print_statistics() to display key information from the all_scores.csv file, useful for troubleshooting. ```python AIzymes.print_statistics() ``` -------------------------------- ### Analysis tools to check AI.zymes Source: https://github.com/bunzela/aizymes/blob/main/example_notebooks/Example_KSI.ipynb Provides tools for analyzing the results of the AI.zymes run, including plotting scores and printing statistics. ```python AIzymes.plot(NORM = { 'final_score': [0.2, 0.7], 'total_score': [320, 380], 'catalytic_score': [-35, 0], 'interface_score': [20, 32], 'efield_score': [-40, 35], 'identical_score': [0, 1.05], }) ``` ```python AIzymes.tar_designs() ``` ```python AIzymes.print_statistics() ``` -------------------------------- ### Arabic Page Numbering Reset Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Resets page numbering to Arabic numerals and sets the starting page to 1. ```latex \clearpage\pagenumbering{arabic}\setcounter{page}{1} ``` -------------------------------- ### Update current conda environment Source: https://github.com/bunzela/aizymes/blob/main/src/docs/Installation.md Updates the current conda environment with packages from environment.yml. ```bash cd AIzymes conda env update -f environment.yml --prune ``` -------------------------------- ### Extract best structures after AI.zymes run Source: https://github.com/bunzela/aizymes/blob/main/example_notebooks/Example_KSI.ipynb Extracts the best performing protein structures after the AI.zymes design process has completed. ```python AIzymes.best_structures(SEQ_PER_ACTIVE_SITE=5, N_HITS=30) ``` -------------------------------- ### Extract Best Structures after AI.zymes Run Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md This snippet shows how to use AIzymes.best_structures() to extract the best performing structures from the AI.zymes run, which will be saved with their scores as prefixes. ```python AIzymes.best_structures() ``` -------------------------------- ### Plotting Analysis of AI.zymes Run Source: https://github.com/bunzela/aizymes/blob/main/src/docs/quick_start.md This snippet shows how to use AIzymes.plot() to visualize the evolution of scores over time, with specified normalization ranges for different score types. ```python AIzymes.plot(NORM = { 'total_score': [310, 380], 'catalytic_score': [-30, -4], 'interface_score': [20, 30], 'final_score': [-30, 0], 'efield_score': [-40, 30], 'identical_score': [0, 1.05], }) ``` -------------------------------- ### Create an Instance of the AI.zymes class Source: https://github.com/bunzela/aizymes/blob/main/src/docs/full_manual.md This code snippet demonstrates how to import the necessary modules and create an instance of the AIzymes class, initializing it with a specified home folder. ```python FOLDER_HOME = '/raven/ptmp/bunzela/AIzymes/TEST' import sys, os from AIzymes_015 import * AIzymes = AIzymes_MAIN(FOLDER_HOME = FOLDER_HOME) ``` -------------------------------- ### Submit controller to run AI.zymes Source: https://github.com/bunzela/aizymes/blob/main/src/docs/full_manual.md This code snippet shows how to submit the controller to run the AIzymes process. ```python AIzymes.submit_controller() ``` -------------------------------- ### Create Section LaTeX Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Reads a Markdown file and converts its content to LaTeX, supporting headers, code blocks, callouts, and images. ```python def create_section_latex(section, doc_tex): """ Reads a Markdown file (section.md) and converts it to LaTeX. Markdown headers become LaTeX sections. Code blocks (delimited by ```), GitHub-style callouts (e.g., > [!WARNING]), and images are supported. For the cover, unnumbered sections (\section*) are used so that it does not appear in the TOC. """ if section.lower() == "cover": return doc_tex filepath = f"{section}.md" if not os.path.exists(filepath): return doc_tex with open(filepath, "r", encoding="utf-8") as file: content = file.read() lines = content.splitlines() processed_lines = [] in_code_block = False i = 0 while i < len(lines): line = lines[i] if line.startswith("```"): if not in_code_block: in_code_block = True code_block_start = i code_lines = [] # <-- add this line i += 1 continue # Skip ``` else: in_code_block = False processed_lines.append(r"\vspace*{0.5\baselineskip}") processed_lines.append( r"\begin{lstlisting}[basicstyle=\color{black}\fontsize{9}{11}\selectfont\ttfamily, frame=single, rulecolor=\color{black}, breaklines=true]" ) processed_lines.extend(code_lines) processed_lines.append(r"\end{lstlisting}") processed_lines.append(r"\vspace*{0.5\baselineskip}") i += 1 continue # Handlen table if line.lstrip().startswith("**Tab."): table_lines = [] # Include the table header line (with caption info) table_lines.append(line.strip()) i += 1 # Collect subsequent lines that start with "|" (the actual table rows) while i < len(lines) and lines[i].lstrip().startswith("|"): table_lines.append(lines[i]) i += 1 table_markdown = "\n".join(table_lines) # Convert the collected markdown table to LaTeX and add it to processed_lines processed_lines.append(convert_markdown_table_to_latex(table_markdown)) continue # Skip further processing for this block if in_code_block: code_lines.append(line) i += 1 continue # Handle GitHub-style callouts if re.match(r'> \[!\w+\]', line): callout_lines = [] while i < len(lines) and lines[i].startswith(">"): callout_lines.append(lines[i][2:].rstrip()) i += 1 callout_text = "\n".join(callout_lines) match = re.match(r'\[!(\w+)\](.*)', callout_text, re.DOTALL) if match: box_type, message = match.groups() box_type = box_type.upper() box_styles = { "WARNING": (r"mpgAccentOrange!20!white", r"mpgAccentOrange!80!black"), "IMPORTANT": (r"mpgAccentGreen!20!white", r"mpgAccentGreen!80!black"), "NOTE": (r"mpgAccentBlue!20!white", r"mpgAccentBlue!80!black"), "TIP": (r"mpgAccentCyan!20!white", r"mpgAccentCyan!80!black"), } bg, border = box_styles.get(box_type, ("gray!10!white", "gray!80!black")) processed_lines.append( rf"\begin{{tcolorbox}}[colback={bg},colframe={border},title={box_type.capitalize()}]" ) processed_lines.append(parse_formatting(message.strip())) processed_lines.append(r"\end{tcolorbox}") continue # Handle markdown headers if line.startswith("# "): # ... (implementation not fully shown in provided snippet) pass i += 1 return doc_tex ``` -------------------------------- ### Python script for creating and uploading pip distribution Source: https://github.com/bunzela/aizymes/blob/main/src/make_pip_distribution.ipynb This script generates the pyproject.toml file, cleans previous build artifacts, builds the package, and uploads it to PyPI using twine. ```python import subprocess import getpass import twine import shutil import glob version = '0.1.12' pyproject = f'''[project] name = "aizymes" version = "{version}" description = "A modular enzyme design platform" authors = [{{ name = "Adrian Bunzel", email = "adrian.bunzel@mpi-marburg.mpg.de" }}] readme = "README.md" license-files = ["LICENSE.txt"] requires-python = ">=3.8" dependencies = [ "numpy", "pandas", "biopython", "scikit-learn", "matplotlib" ] [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta" [tool.setuptools] package-dir = {{"" = "src"}} [tool.setuptools.packages.find] where = ["src"] ''' with open('../pyproject.toml', 'w') as f: f.write(pyproject) # Remove dist, build, and .egg-info directories import shutil, glob for p in ['../dist','../build', *glob.glob('../*.egg-info')]: shutil.rmtree(p, ignore_errors=True) # Build the package subprocess.run(["python", "-m", "build"], cwd="..", stdout=subprocess.DEVNULL, check=True, text=True) # Upload to PyPI api_token = getpass.getpass("Enter your PyPI API token: ") subprocess.run(["twine", "upload", "-u", "__token__", "-p", api_token, "../dist/*"], check=True, text=True) print('xxx') ``` -------------------------------- ### LaTeX Preamble Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Defines the LaTeX document class, packages, colors, formatting, and styles for the document. ```latex \documentclass[10pt]{extarticle} \usepackage{etoolbox} \AtBeginEnvironment{tabular}{\fontsize{9}{11}\selectfont} \usepackage[most]{tcolorbox} \usepackage[colorlinks=true, linkcolor=black, urlcolor=blue]{hyperref} \usepackage{graphicx} \usepackage[utf8]{inputenc} \DeclareUnicodeCharacter{221B}{\ensuremath{\sqrt[3]{}}} % Map \xe2\x88\x9b to cube-root \usepackage{xcolor} \definecolor{mpgDarkGreen}{HTML}{005555} \definecolor{mpgLightGreen}{HTML}{006c66} \definecolor{mpgDarkGrey}{HTML}{777777} \definecolor{mpgAccentOrange}{HTML}{ef7c00} \definecolor{mpgAccentGreen}{HTML}{c6d325} \definecolor{mpgAccentBlue}{HTML}{29485d} \definecolor{mpgAccentCyan}{HTML}{00b1ea} \usepackage[a4paper, left=2.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm]{geometry} \usepackage{setspace} \setstretch{1.5} \usepackage{titlesec} \renewcommand{\figurename}{Fig.} \renewcommand{\thefigure}{\arabic{figure}\,\textbar} \usepackage{caption} \DeclareCaptionFont{figfont}{\fontsize{9}{11}\selectfont} \captionsetup[figure]{labelfont={bf,figfont}, textfont=figfont, labelsep=space} \usepackage{enumitem} % for description formatting \titleformat{\section} {\color{mpgDarkGreen}\normalfont\fontsize{16}{18}\selectfont\bfseries} {\thesection}{1em}{} \titleformat{\subsection} {\color{mpgLightGreen}\normalfont\fontsize{14}{16}\selectfont\bfseries} {\thesubsection}{1em}{} \titleformat{\subsubsection} {\color{mpgLightGreen}\normalfont\fontsize{12}{14}\selectfont\bfseries} {\thesubsubsection}{1em}{} \usepackage{listings} \lstset{ basicstyle=\color{black}\fontsize{9}{11}\selectfont\ttfamily, backgroundcolor=\color{gray!20}, frame=single, rulecolor=\color{black}, breaklines=true } \usepackage{pdfpages} \usepackage[sfdefault]{roboto} \renewcommand*\familydefault{\sfdefault} \setlength{\parindent}{0pt} \usepackage{hyperref} \usepackage{longtable} \usepackage{fancyhdr} \pagestyle{fancy} \fancyhf{} % clear all headers and footers \fancyhead[R]{\textsf{\nouppercase{\leftmark}}} \fancyfoot[C]{\textsf{\thepage}} \renewcommand{\headrulewidth}{0.4pt} \renewcommand{\footrulewidth}{0pt} % Make each new section start on a new page. \let\oldsection\section \renewcommand{\section}[1]{\clearpage\oldsection{#1}} \begin{document} ``` -------------------------------- ### Create Code LaTeX Section Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Processes Python files to extract docstrings and format them into a LaTeX 'Code' section. ```python def create_code_latex(doc_tex): """ Processes all Python files matching *_###.py and adds their documentation. Files in PRIORITY_SCRIPTS are processed first. """ code_parts = [r"\section{Code}"] all_files = [f for f in glob.glob(os.path.join("..", "aizymes", "*.py")) if re.search(r"_\d{3}\.py$", f)] print(all_files) priority_files = [f for f in all_files if f in PRIORITY_SCRIPTS] others = [f for f in all_files if f not in PRIORITY_SCRIPTS] ordered_priority = [p for p in PRIORITY_SCRIPTS if p in priority_files] ordered_files = ordered_priority + others for filepath in ordered_files: code_parts.append(extract_docstrings(filepath)) doc_tex += "\n".join(code_parts) return doc_tex ``` -------------------------------- ### Define Markdown Sections Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Specifies the order of markdown sections to be included in the document. ```python markdown_sections = ["installation", "quick_start", "available_tools", "introduction", "full_manual"] ``` -------------------------------- ### Extract best structures after AI.zymes run Source: https://github.com/bunzela/aizymes/blob/main/src/docs/full_manual.md This code snippet demonstrates how to extract the best structures after an AIzymes run has been completed. ```python AIzymes.best_structures() ``` -------------------------------- ### Analysis tools to check AI.zymes Source: https://github.com/bunzela/aizymes/blob/main/src/docs/full_manual.md These code snippets illustrate how to use analysis tools to check the results of an AIzymes run, including plotting and printing statistics. ```python AIzymes.plot(...) ``` ```python AIzymes.print_statistics() ``` -------------------------------- ### Markdown Formatting to LaTeX Conversion Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb This Python function converts markdown formatting (bold, italics, callouts, links, tabs) into LaTeX equivalents. ```python def parse_formatting(text): """ Convert Markdown bold (**text**), italics (*text*), and callouts to LaTeX. """ text = latex_escape(text) # Define replacement functions for our custom tokens. def tab_plain(match): left = match.group(1).rstrip() # Text before right = match.group(2).lstrip() # Text after # Use a fixed-width makebox (3.0cm), left-aligned, with no additional dots. return r'\makebox[' + str(tab_space) + r'cm][l]{' + left + r'} ' + right def tab_dots(match): left = match.group(1).rstrip() # Text before right = match.group(2).lstrip() # Text after # Use a fixed-width makebox (3.0cm) with \dotfill appended. return r'\makebox[' + str(tab_space) + r'cm][l]{' + left + r'\dotfill} ' + right # Process each line separately so we can catch our custom tokens. lines = text.splitlines() processed_lines = [] for line in lines: # First, process the token (with dotfill) if '' in line: line = re.sub(r'(.*?)(.*)', tab_dots, line) # Then, process the token (plain, no dotfill) if '' in line: line = re.sub(r'(.*?)(.*)', tab_plain, line) processed_lines.append(line) text = "\n".join(processed_lines) # Add chapter number text = text.replace("**Full Manual**", "**5. Full Manual**") # GitHub callouts callout_patterns = { "[!WARNING]": r"\\begin{tcolorbox}[colback=red!5!white,colframe=red!75!black,title=Warning]", "[!IMPORTANT]": r"\\begin{tcolorbox}[colback=yellow!10!white,colframe=yellow!60!black,title=Important]", "[!NOTE]": r"\\begin{tcolorbox}[colback=blue!5!white,colframe=blue!75!black,title=Note]", "[!TIP]": r"\\begin{tcolorbox}[colback=green!5!white,colframe=green!75!black,title=Tip]", } for marker, latex_box in callout_patterns.items(): if text.strip().startswith(f"> {marker}"): content = text.strip()[len(f"> {marker}"):].strip() content = latex_escape(content) content = re.sub(r'\*\*(.+?)\*\*', r'\\textbf{\1}', content) content = re.sub(r'\*(.+?)\*', r'\\textit{\1}', content) return f"{latex_box}\n{content}\n\\end{{tcolorbox}}" # Naked URLs → \href{url}{url} text = re.sub(r'(?... → smaller font #text = re.sub(r'(.+?)', r'{\\fontsize{8}{10}\\selectfont \1}', text) #
→ line break text = text.replace("
", r"\\") return text ``` -------------------------------- ### Format Text with Specific Headers Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Python function to convert docstring sections into LaTeX-formatted text, handling specific keywords and key-value items. ```python def format_text_with_specific_headers(text, keywords): """ Convert a docstring section into LaTeX-formatted text. When a line starts with one of the specified keywords (e.g. "Parameters:"), this function outputs the header in dark grey (mpgDarkGrey) and then collects subsequent lines as key–value items. Rules: - A line containing ": " starts a new item. - A nonblank line that does NOT contain ": " is appended as a continuation. - A blank line ends the collection. If items are collected, they are wrapped in a description environment with reduced spacing (locally set to 1.15) and appropriate enumitem options. """ lines = text.splitlines() result = [] i = 0 while i < len(lines): line = lines[i].strip() handled = False for keyword in keywords: if line.startswith(keyword + ":"): header_text = line.split(":")[0] header_line = ( r"\\par\\vspace*{0.5\\baselineskip}" r"\\noindent{\\color{mpgAccentBlue}\\textbf{" + header_text + r":}}" ) result.append(header_line) items = [] i += 1 while i < len(lines): current_line = lines[i].rstrip() # preserve trailing spaces for continuation stripped = current_line.strip() if not stripped: i += 1 break # blank line ends collection if ": " in stripped: parts = stripped.split(": ", 1) key_part = parse_formatting(parts[0].strip()) val_part = parse_formatting(parts[1].strip()) items.append( r"\\item[\\textcolor{mpgAccentBlue!75!white}{" + key_part + r"\\dotfill}] " + val_part ) else: if items: items[-1] += " " + parse_formatting(stripped) i += 1 if items: result.append(r"{\\setstretch{1.15}") result.append(r"\\begin{description}[noitemsep,topsep=0pt,parsep=0pt,labelwidth=5cm,leftmargin=!," r"labelindent=0pt,labelsep=0.2cm,itemsep=0pt]") result.extend(items) result.append(r"\\end{description}") result.append("}") handled = True break if not handled: result.append(parse_formatting(line)) i += 1 return "\n".join(result) ``` -------------------------------- ### Cover Page Inclusion Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Includes the cover page PDF and resets page numbering. ```latex \includepdf[pages=1]{cover.pdf} \clearpage \pagenumbering{roman} \setcounter{page}{1} ``` -------------------------------- ### Format Docstring Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Formats a Python docstring with specific headers. ```python def format_text_with_specific_headers(docstring, headers): # ... (implementation not fully shown in provided snippet) pass ``` -------------------------------- ### Import AI.zymes in Python Source: https://github.com/bunzela/aizymes/blob/main/README.md How to import the AI.zymes library for use in Python scripts. ```python from aizymes import * ``` -------------------------------- ### Table of Contents Generation Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Temporarily restores the original section command to generate the table of contents, then restores the modified section command. ```latex \clearpage\pagenumbering{roman}\setcounter{page}{1} % Temporarily restore the original section command for the TOC \let\sectionTemp=\section \let\section=\oldsection \clearpage {\setstretch{1.15}\tableofcontents} \clearpage \let\section=\sectionTemp ``` -------------------------------- ### Documentation Generator Script Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb This Python script scans for Python files, extracts docstrings and Markdown content, generates a LaTeX document, and compiles it into a PDF. ```python """ Documentation Generator using LaTeX This script: 1. Scans for Python files (with names matching *_###.py) and extracts module, function, and class docstrings. 2. Reads Markdown files for non-code sections. 3. Generates a LaTeX document combining these sections. 4. Compiles the LaTeX file to produce a final PDF. """ import ast import os import glob import re import subprocess import shutil tab_space = 3.5 # List of .py scripts that should be described first, in the given order. PRIORITY_SCRIPTS = [ "aizymes.py", "main_startup_002.py", "main_running_003.py", "setup_system_001.py" ] # Define folder and output file paths. combined_tex_path = "AIzymes_Manual.tex" pdf_path = os.path.join("..", "..", "AIzymes_Manual.pdf") generated_pdf = os.path.basename(pdf_path) ``` -------------------------------- ### LaTeX Compilation with pdflatex Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Python code to compile a LaTeX file into a PDF using pdflatex, including error handling for timeouts and compilation failures. ```python latex_executable = r'C:\Users\bunzelh\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe' cmd = [ latex_executable, '-output-directory', '.', '-interaction=nonstopmode', combined_tex_path ] try: result = subprocess.run( cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60 ) print("LaTeX compilation finished successfully.") except subprocess.TimeoutExpired: print("LaTeX compilation timed out!") except subprocess.CalledProcessError as err: print("LaTeX compilation failed with errors:") print(err.stderr) if os.path.exists(generated_pdf): shutil.copy(generated_pdf, pdf_path) print(f"Final PDF generated at {pdf_path}") else: print("PDF generation failed. Please check for errors during compilation.") ``` -------------------------------- ### Remove old generated files Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb A Python snippet to remove old generated PDF files if they exist. ```python for f in (generated_pdf, pdf_path): if os.path.exists(f): os.remove(f) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/bunzela/aizymes/blob/main/input_files/cst_out/extract_catres_orientation.ipynb Imports pandas for data manipulation and Bio.PDB for protein structure handling. ```python import os import pandas as pd from Bio.PDB import PDBParser, PDBIO, Select ``` -------------------------------- ### Print Top and Bottom Structures by Constraint Source: https://github.com/bunzela/aizymes/blob/main/input_files/cst_out/extract_catres_orientation.ipynb This code snippet iterates through different constraints (atom_pair_constraint, angle_constraint, dihedral_constraint) and prints the top 5 and bottom 5 structures based on each constraint's score. It also prints the combined PDB file name. ```python # Print the 5 best and 5 worst structures for each constraint constraints = ['atom_pair_constraint', 'angle_constraint', 'dihedral_constraint'] for constraint in constraints: print(f"\nTop 5 structures for {constraint}:") print(remark_df.nsmallest(5, constraint)) print(f"\nBottom 5 structures for {constraint}:") print(remark_df.nlargest(5, constraint)) print(f'Combined PDB file saved as {output_pdb}') ``` -------------------------------- ### Process and combine PDB files Source: https://github.com/bunzela/aizymes/blob/main/input_files/cst_out/extract_catres_orientation.ipynb Iterates through sorted structures, reads their scores, extracts relevant residues, and appends them to a single output PDB file with detailed remarks. ```python # Output PDB file output_pdb = '/links/grid/scratch/lmerlicek/design/Input/cst_out/catres_sorted_res99_planar_tAB50_cstopt_2_012.pdb' io = PDBIO() # Open the output file in write mode initially to clear any existing content with open(output_pdb, 'w') as f: f.write("") # List to store remark information remark_list = [] # Iterate over sorted PDB files i = 1 for index, row in df_sorted.iterrows(): row["index"] = int(row["index"]) pdb_file = next((file for file in os.listdir(f'{path}/best_structures') if file.endswith(f'_{row["index"]}.pdb')), None) pdb_file = f'/{path}/best_structures/{pdb_file}' if pdb_file else None if pdb_file is None: continue # Determine the score file path score_file_path = f'{path}/{row["index"]}/score_rosetta_relax.sc' if not os.path.exists(score_file_path): score_file_path = f'{path}/{row["index"]}/score_rosetta_design.sc' if not os.path.exists(score_file_path): continue # Read the scores scores = read_scores(score_file_path) if scores is None: continue structure = parser.get_structure(row["index"], pdb_file) # Extract ligand and catalytic residue select = LigandCatResSelect(chain_id='A', res_id=row['cat_resi'], ligand_name='5TS') io.set_structure(structure) # Append each structure as a new model with open(output_pdb, 'a') as f: f.write(f"REMARK 999 CATALYTIC SCORE: {row['catalytic_score']} STATE: {i} INDEX: {row['index']}\n") f.write(f"REMARK 999 ATOM PAIR CONSTRAINT: {scores.get('atom_pair_constraint', 'N/A')}\n") f.write(f"REMARK 999 ANGLE CONSTRAINT: {scores.get('angle_constraint', 'N/A')}\n") f.write(f"REMARK 999 DIHEDRAL CONSTRAINT: {scores.get('dihedral_constraint', 'N/A')}\n") io.save(f, select=select, write_end=False) f.write("TER\n") f.write("ENDMDL\n") # Store remark information in the list remark_list.append({ 'index': row['index'], 'state': i, 'catalytic_score': row['catalytic_score'], 'atom_pair_constraint': scores.get('atom_pair_constraint', 'N/A'), 'angle_constraint': scores.get('angle_constraint', 'N/A'), 'dihedral_constraint': scores.get('dihedral_constraint', 'N/A') }) i += 1 # Convert the remark list to a DataFrame remark_df = pd.DataFrame(remark_list) print(f'Combined PDB file saved as {output_pdb}') ``` -------------------------------- ### LaTeX Document Generation Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb This Python function processes markdown lines to generate LaTeX code, handling sections, subsections, subsubsections, and images with captions. ```python def generate_documentation(markdown_content): """ Convert markdown content to LaTeX format. """ doc_tex = "" lines = markdown_content.splitlines() i = 0 while i < len(lines): line = lines[i].strip() # Handle sections if line.startswith("# "): processed_lines.append(r"\section{" + parse_formatting(line[2:].strip()) + "}") elif line.startswith("## "): processed_lines.append(r"\subsection{" + parse_formatting(line[3:].strip()) + "}") elif line.startswith("### "): processed_lines.append(r"\subsubsection{" + parse_formatting(line[4:].strip()) + "}") # Handle markdown images elif line.startswith("![')}: match = re.match(r"!\\[(.*?)\\]\((.*?)\", line) if match: alt_text, image_path = match.groups() caption = "" # Check if the next line is a line containing the caption if i+1 < len(lines) and lines[i+1].strip().startswith("") and lines[i+1].strip().endswith(""): caption_match = re.search(r"(.*?)", lines[i+1].strip(), re.DOTALL) if caption_match: caption_raw = caption_match.group(1).strip() caption = re.sub(r'(?i)^(?:\*\*?)?\s*fig\.\s*\d+\s*|\s*\\s*', "", caption_raw) caption = "**" + caption i += 1 # Skip the caption line so it doesn't get processed again processed_lines.append(r"\\begin{figure}[htbp]") processed_lines.append(r"\\centering") processed_lines.append(r"\\includegraphics[width=16cm]{" + image_path + r"}") if caption: processed_lines.append(r"\\caption{"+ parse_formatting(caption) + r"}") else: processed_lines.append(r"\\caption{"+ parse_formatting(alt_text) + r"}") processed_lines.append(r"\\end{figure}") # Default: treat as plain paragraph else: processed_lines.append(parse_formatting(line)) i += 1 section_tex = "\n".join(processed_lines) doc_tex += section_tex return doc_tex ``` -------------------------------- ### Load and sort structures by catalytic score Source: https://github.com/bunzela/aizymes/blob/main/input_files/cst_out/extract_catres_orientation.ipynb Reads a CSV file containing scores, sorts the data by 'catalytic_score', and initializes a PDB parser. It also defines a custom selector for PDB residues. ```python # Read the CSV file path = "/net/bs-gridfs/export/grid/scratch/lmerlicek/design/LM_res99_PMPNN_planar_tAB50_cstopt_2_012" csv_file = f'{path}/all_scores.csv' df = pd.read_csv(csv_file) # Sort by catalytic score df_sorted = df.sort_values(by='catalytic_score') # Initialize PDB parser parser = PDBParser(QUIET=True) class LigandCatResSelect(Select): def __init__(self, chain_id, res_id, ligand_name): self.chain_id = chain_id self.res_id = res_id self.ligand_name = ligand_name def accept_residue(self, residue): if residue.id[0] == ' ' and residue.id[1] == self.res_id and residue.parent.id == self.chain_id: return True if residue.resname == self.ligand_name: return True return False ``` -------------------------------- ### End Document Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Marks the end of the LaTeX document. ```latex \end{document} ``` -------------------------------- ### Extract Docstrings Function Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Python function to extract docstrings from a Python file and format them for LaTeX. ```python def extract_docstrings(filepath): """ Extracts docstrings from a Python file and returns LaTeX-formatted content. The module becomes a subsection; functions and classes become subsubsections. (Functions have "()" appended.) """ filename = os.path.basename(filepath) formatted_filename = re.sub(r'_\d+\.py$', '', filename) doc_parts = [r"\\subsection{" + parse_formatting(f'{formatted_filename}.py') + r"}"] with open(filepath, "r", encoding="utf-8") as file: tree = ast.parse(file.read()) module_docstring = ast.get_docstring(tree) if module_docstring: formatted_docstring = format_text_with_specific_headers( module_docstring, ["Parameters", "Optional Parameters", "Returns", "Functions", "Classes", "Modules Required", "Usage"] ) doc_parts.append(formatted_docstring) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): doc_parts.append(r"\\subsubsection{" + parse_formatting(node.name + "()") + "}") docstring = ast.get_docstring(node) if docstring: formatted_docstring = format_text_with_specific_headers( docstring, ["Parameters", "Optional Parameters", "Returns", "Functions", "Classes", "Modules Required", "Usage"] ) doc_parts.append(formatted_docstring) elif isinstance(node, ast.ClassDef): doc_parts.append(r"\\subsubsection{" + parse_formatting(node.name) + "}") docstring = ast.get_docstring(node) ``` -------------------------------- ### LaTeX Escape Function Source: https://github.com/bunzela/aizymes/blob/main/src/docs/generate_documentation.ipynb Python function to escape special characters for LaTeX. ```python def latex_escape(text): """ Escape LaTeX special characters. """ replacements = { '&': r'&', '%': r'%', '$': r'$', '#': r'#', '_': r'_', '{': r'{', '}': r'}', '~': r'\textasciitilde{}', '^': r'\textasciicircum{}', '\\': r'\\textbackslash{}', '|': r'\textbar{}' } pattern = re.compile("|".join(re.escape(key) for key in replacements.keys())) return pattern.sub(lambda match: replacements[match.group()], text) ``` -------------------------------- ### Score reading function Source: https://github.com/bunzela/aizymes/blob/main/input_files/cst_out/extract_catres_orientation.ipynb A helper function to read scores from a Rosetta score file. ```python def read_scores(score_file_path): with open(score_file_path, "r") as f: scores = f.readlines() if len(scores) < 3: # if the timing is bad, the score file is not fully written. Check if len(scores) > 2! return None headers = scores[1].split() scores = scores[2].split() score_dict = {} for idx, header in enumerate(headers): if header in ['atom_pair_constraint', 'angle_constraint', 'dihedral_constraint']: score_dict[header] = float(scores[idx]) return score_dict ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.