### Install LAMMPS via Ubuntu Package Manager Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Installs LAMMPS and its related documentation, examples, and development files using the Ubuntu package manager. It also installs the Python 3 bindings for LAMMPS and the shared library. ```bash sudo apt install lammps lammps-doc lammps-examples lammps-data python3-lammps liblammps0 liblammps-dev ``` -------------------------------- ### Install Groq Python Library Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/Providers/Groq.md Installs the Groq Python client library using pip. This is the first step to interact with the Groq API programmatically. ```shell pip install groq ``` -------------------------------- ### Install MCP and Chemistry Dependencies on Ubuntu Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md This bash script installs Python 3.11, the uv package manager, creates a project directory, sets up a virtual environment, and installs the MCP SDK along with essential chemistry libraries like numpy, pandas, and ase. ```bash sudo add-apt-repository ppa:deadsnakes/ppa -y sudo apt update sudo apt install -y python3.11 python3.11-venv python3.11-dev curl -LsSf https://astral.sh/uv/install.sh | sh source ~/.bashrc mkdir chem-mcp-server cd chem-mcp-server uv venv source .venv/bin/activate uv add "mcp[cli]" numpy pandas ase ``` -------------------------------- ### Verify MCP SDK Installation Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Checks if the MCP Python SDK has been installed correctly by displaying its help information and version number. ```Bash mcp --help mcp version ``` -------------------------------- ### Install Google Generative AI Library Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/Providers/Google.md Installs the Google Generative AI library using pip. This is a prerequisite for using the API. ```bash pip install -q -U google-generativeai ``` -------------------------------- ### ASE MCP Implementation Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Describes potential MCP resources, tools, and prompts for the Atomistic Simulation Environment (ASE), a Python library. Resources are ASE's Atoms objects. Tools involve running calculations and optimizations. Prompts guide DFT calculations and structure optimization. ```python Resources: Atoms objects, calculator configurations Tools: Create Atoms object, run calculation, get results, perform optimization Prompts: "Run a DFT calculation on {material}." "Optimize the structure of {cluster}." ``` -------------------------------- ### Install MCP Python SDK and CLI Tools Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Installs the MCP Python SDK and its command-line interface tools using pip within a virtual environment. This is a prerequisite for building MCP server bindings. ```Bash python3 -m venv mcp-chem-env source mcp-chem-env/bin/activate pip install "mcp[cli]" ``` -------------------------------- ### Install fastmcp and Dependencies Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Installs the fastmcp library and its dependencies using pip and uv. Ensure Python 3.10+ is installed and a virtual environment is active. ```Bash python3 -m venv venv source venv/bin/activate pip install uv uv pip install fastmcp ``` -------------------------------- ### List Installed Python Packages Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md A command to list all installed Python packages within a virtual environment, helpful for checking dependencies. ```bash uv pip list ``` -------------------------------- ### Start MCP Development Server (Bash) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md Starts the MCP development server for the chemistry tools. This command is run within the activated virtual environment and provides a web-based inspector for testing tools. ```Bash # In your activated virtual environment mcp dev chem_server.py ``` -------------------------------- ### Run Basic MCP Server Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Executes the Python script to start the basic MCP server in the background. ```Bash python chem_mcp_server.py & ``` -------------------------------- ### Install GROMACS and gmxapi Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Provides bash commands to install GROMACS and the `gmxapi` Python package on Ubuntu. This is a prerequisite for setting up a GROMACS MCP server. ```Bash sudo apt update sudo apt install -y gromacs python3-pip pip install gmxapi ``` -------------------------------- ### Gromacs MCP Implementation Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Details potential MCP resources, tools, and prompts for Gromacs, a molecular dynamics package. Resources include topology and trajectory files. Tools cover input preparation, simulation execution, and analysis. Prompts facilitate simulation setup and trajectory analysis. ```text Resources: Topology files, MDP files, trajectory files, analysis Tools: Prepare input, run simulation, monitor progress, analyze properties, visualize Prompts: "Simulate {protein}-{ligand} binding for {t}." "Calculate RMSD of {protein}." ``` -------------------------------- ### Verify LAMMPS Installation (dpkg) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Verifies the installation of LAMMPS and related packages using the `dpkg -l` command, which lists installed packages. The output is filtered to show only packages related to LAMMPS, providing details like package name, version, architecture, and a brief description. ```bash > dpkg -l | grep lammps ``` -------------------------------- ### Verify LAMMPS Installation (apt) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Checks the installed packages on an Ubuntu system to confirm that LAMMPS and its associated components are present. It uses `apt list --installed` and filters the output for packages containing 'lammps'. ```bash > apt list --installed | grep lammps ``` -------------------------------- ### ScanNonBond Example Reference Source: https://github.com/prokophapala/autocrunchcoder/blob/main/docs/NumIntegrationCL.md Reference to a script demonstrating the scanNonBond functionality, potentially for performance comparisons or examples. ```N/A pyCruncher2/scientific/gpu/run_scanNonBond.py ``` -------------------------------- ### LAMMPS MCP Implementation Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Illustrates potential MCP resources, tools, and prompts for LAMMPS, a classical molecular dynamics code. Resources include input scripts and trajectory files, while tools involve running simulations and querying status. Prompts guide LLM in setting up simulations. ```text Resources: Input scripts, trajectory files, energy/log files Tools: Run simulation, query status, retrieve data, modify parameters Prompts: "Run MD of {molecule} at {T} for {t} using {force_field}." ``` -------------------------------- ### Install MCP SDK and Dependencies Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Installs the necessary MCP Python SDK along with other required libraries like `anthropic` and `python-dotenv` using `uv` for package management. ```bash pip install uv uv pip install mcp anthropic python-dotenv ``` -------------------------------- ### Bash MCP Dependency Installation Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Provides commands to install necessary Python dependencies for MCP implementation, including `jsonschema`, `jsonrpcserver`, `openai`, and `requests`. ```Bash # Install required dependencies sudo apt update sudo apt install -y python3-jsonschema python3-jsonrpcserver pip install openai requests ``` -------------------------------- ### Install Python Packages and C++ Grammar Source: https://github.com/prokophapala/autocrunchcoder/blob/main/docs/dependency_graph_analyzer.md Installs necessary Python packages and clones/builds the tree-sitter C++ grammar for the dependency analyzer. ```Bash pip install tree-sitter git clone https://github.com/tree-sitter/tree-sitter-cpp cd tree-sitter-cpp make ``` -------------------------------- ### Biot-Savart Example Reference Source: https://github.com/prokophapala/autocrunchcoder/blob/main/docs/NumIntegrationCL.md Reference to a script demonstrating the Biot-Savart calculation, likely using the numerical integration framework. ```N/A pyCruncher2/scientific/gpu/run_biot_savart.py ``` -------------------------------- ### Plotting Examples in Maxima Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MaximaTutorial.md This section provides examples of plotting functions in Maxima. It shows how to plot 2D functions using `plot2d` and `wxplot2d`, including plotting multiple functions on the same graph. The code includes commented-out examples for plotting B-splines and Lorenz-like functions, with notes on interactive vs. batch execution. ```maxima /* Plotting B-splines (example from previous section) */ /* Define B1_1 and B1_2 for plotting */ B1_1(t_var) := bspline_basis(0,1,t_var); B1_2(t_var) := bspline_basis(1,1,t_var); /* plot2d([B1_1(t_val), B1_2(t_val)], [t_val, 0.0, 3.0], [legend, "B_0,1(t)", "B_1,1(t)"]); */ /* Note: Plotting commands execute and open a plot window or embed in interfaces like WxMaxima. In batch mode, they might save to a file if configured or do nothing visible. The actual plot command is commented out to prevent issues in non-graphical execution. To see plots, run Maxima interactively or use WxMaxima. */ /* Example from Lorenz-like functions in GaussianIntegrals.md */ /* block([w: 10.0], wxplot2d([L1x2, L0x4], [x, -0.2, 1.2], [legend, "L1x2", "L0x4"]) ); */ ``` -------------------------------- ### Install Project Dependencies (Shell) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/README.md This command installs all necessary Python packages for the project from a 'requirements.txt' file. Key dependencies include 'json', 'toml', and 'openai', with optional ones like 'google-generativeai', 'tree-sitter', and 'Maxima'. ```Shell pip install -r requirements.txt ``` -------------------------------- ### DeepSeek Integration: Basic Prompting Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/tests.md Tests the basic functionality of the AgentDeepSeek class by sending a prompt to the DeepSeek agent. This script is a foundational example for interacting with DeepSeek. ```Python import pytest from pyCruncher.agents.deepseek import AgentDeepSeek def test_deepseek_prompt(): agent = AgentDeepSeek() response = agent.prompt("Hello, DeepSeek!") assert "Hello" in response ``` -------------------------------- ### MCP Request Formatting Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md Demonstrates the structure of a JSON-RPC 2.0 message for an MCP request, specifying the method, parameters, and a unique identifier. ```JSON { "jsonrpc": "2.0", "method": "chemistry/calculate_energy", "params": { "molecule": "H2O", "method": "DFT", "basis_set": "6-31G*" }, "id": "req_123" } ``` -------------------------------- ### Check Python Version Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md A command to verify the installed Python version, useful for troubleshooting server startup issues. ```bash python3.11 --version ``` -------------------------------- ### Maxima Basic Interaction and Setup Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MaximaTutorial.md Demonstrates basic Maxima commands including clearing memory, variable assignment with and without output suppression, and simple arithmetic. It also shows how to run Maxima scripts. ```maxima > maxima -b GaussCoulombBoys.mac ``` ```maxima /* This is a comment */ kill(all)$ /* Clears memory, output suppressed */ a: 5; /* Assign 5 to 'a' and show output */ b: 10$ /* Assign 10 to 'b', suppress output */ a+b; ``` -------------------------------- ### Python: OpenCLBase Quick Start Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/OpenCLBase.md Demonstrates the basic usage of OpenCLBase for setting up OpenCL, loading a kernel, creating buffers, transferring data to the GPU, executing a kernel, and retrieving results. It shows how to initialize OpenCLBase, load a program, manage device buffers, set kernel parameters, and call a kernel with specified global and local work sizes. ```Python from pyBall.OCL.OpenCLBase import OpenCLBase import numpy as np ocl = OpenCLBase(nloc=64) ocl.load_program(kernel_path="path/to/kernels.cl") N = 100000 sizes = { 'pos': N*16, 'vel': N*16, 'force': N*16 } ocl.try_make_buffers(sizes) # creates pos_buff, vel_buff, force_buff (+ buffer_dict entries) pos = np.zeros((N,4), np.float32) vel = np.zeros((N,4), np.float32) force = np.zeros((N,4), np.float32)ocl.toGPU('pos_buff', pos); ocl.toGPU('vel_buff', vel) ocl.kernel_params = {'N': N, 'dt': 1e-3} args = ocl.generate_kernel_args('integrate') # [pos_buff, vel_buff, force_buff, N, dt] g = (ocl.roundUpGlobalSize(N),) ocl.prg.integrate(ocl.queue, g, (ocl.nloc,), *args) ocl.fromGPU('force_buff', force) ``` -------------------------------- ### JSON Output Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/Providers/DeepSeek.md Demonstrates how to enable and use the JSON Output feature for DeepSeek models. This involves setting the `response_format` parameter and guiding the model with prompts and examples to ensure valid JSON output. ```python import json from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.deepseek.com", ) system_prompt = """ The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format. EXAMPLE INPUT: Which is the highest mountain in the world? Mount Everest. EXAMPLE JSON OUTPUT: { "question": "Which is the highest mountain in the world?", "answer": "Mount Everest" } """ user_prompt = "Which is the longest river in the world? The Nile River." messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}] response = client.chat.completions.create( model="deepseek-coder", messages=messages, response_format={ 'type': 'json_object' } ) print(json.loads(response.choices[0].message.content)) ``` -------------------------------- ### Document Processing: LangChain with HuggingFaceEmbeddings and FAISS Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/tests.md Similar to the Ollama example, this script uses LangChain but with HuggingFaceEmbeddings and stores the embeddings in a FAISS index. It also demonstrates a RAG setup. ```Python import faiss from langchain_community.document_loaders import TextLoader from langchain_community.embeddings import HuggingFaceEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from pyCruncher.rag.faiss_retriever import FaissRetriever # Assuming this class handles FAISS integration # Load documents loader = TextLoader("path/to/your/document.txt") documents = loader.load() # Split documents into chunks text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) chunks = text_splitter.split_documents(documents) # Initialize embeddings model_name = "sentence-transformers/all-MiniLM-L6-v2" embeddings = HuggingFaceEmbeddings(model_name=model_name) # Create FAISS index (using a hypothetical FaissRetriever class) # retriever = FaissRetriever.from_documents(chunks, embeddings, index_path="./faiss_index") print("Document embeddings created and stored in FAISS index.") ``` -------------------------------- ### Setting up a Python MCP Server Environment Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md This snippet demonstrates the steps to set up a Python virtual environment for an MCP server, install dependencies, and run the server. It's crucial for resolving 'MCP Server Not Found' errors related to missing executables. ```bash # On the remote server python3 -m venv mcp-env source mcp-env/bin/activate pip install "mcp[cli]" python lammps_mcp_http_server.py ``` -------------------------------- ### Start MCP Server Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md This bash command activates the conda environment named 'lmp' which is assumed to contain the necessary LAMMPS installations and dependencies. It then executes the Python script 'lammps_mcp_server.py' to start the MCP server. ```Bash conda activate lmp # Ensure LAMMPS environment is active python lammps_mcp_server.py ``` -------------------------------- ### Validate maxima_simplify Tool (ratsimp) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Example of using the maxima_simplify tool with the 'ratsimp' method to simplify a rational expression. ```Maxima ratsimp((x^2 - 1)/(x-1)) ``` -------------------------------- ### Validate maxima_integrate Tool Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Example of using the maxima_integrate tool to compute the antiderivative of a given expression with respect to a specified variable. ```Maxima integrate(sin(x), x) ``` -------------------------------- ### Validate maxima_run_script Tool Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Example of using the maxima_run_script tool to execute a Maxima script. The script calculates and displays derivatives. ```Maxima display2d:false$ f:x^3 + y^2$ diff(f,x); diff(f,y); ``` -------------------------------- ### Validate maxima_diff Tool Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Example of using the maxima_diff tool to compute partial derivatives of an expression with respect to specified variables. ```Maxima expr: "x^3 + x*y + sin(z)" vars: ["x","y","z"] ``` -------------------------------- ### OpenAI Prompt Preparation with MCP Capabilities (Python) Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Deepseek.md Shows how to format MCP server capabilities into the structure required by OpenAI's API for tool use, including tool names, descriptions, and parameters. ```Python def prepare_openai_prompt(mcp_capabilities): tools = [{ "name": tool["name"], "description": tool["description"], "parameters": tool["parameters"] } for tool in mcp_capabilities["tools"]] return { "messages": [...], "tools": tools, "tool_choice": "auto" } ``` -------------------------------- ### Validate maxima_eval Tool Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Example of using the maxima_eval tool to evaluate a Maxima expression. It expects the factored form of the input. ```Maxima factor((x^2 - 1)); ``` -------------------------------- ### Get LAMMPS Version Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Retrieves the installed LAMMPS version. It checks for LAMMPS availability and accesses the version information through the provided context. ```Python import tempfile import os from mcp.server.fastmcp import Context # Assume LAMMPS_AVAILABLE and mcp are defined elsewhere # Assume Context and lifespan_context are available @mcp.resource("lammps://version") def get_lammps_version(ctx: Context) -> str: """Return the LAMMPS version""" if not LAMMPS_AVAILABLE: return "LAMMPS not available" lmp = ctx.request_context.lifespan_context.lmp version = lmp.version() return f"LAMMPS version: {version}" ``` -------------------------------- ### Run Maxima MCP SSE Server Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Starts the Maxima MCP server using SSE protocol on port 8011. This is an alternative to the recommended STDIO server. ```Shell python /home//git/AutoCrunchCoder/examples/MCP/mcp_server_maxima.py ``` -------------------------------- ### MCP Client Discovery and Request Formatting Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Demonstrates how an LLM client discovers capabilities (tools and resources) from an MCP server using a JSON-RPC 2.0 interface and how it formats subsequent tool call requests based on the discovered schema. This includes examples of the server's response detailing available tools and resources, and the client's request to call a specific tool with arguments. ```JSON { "jsonrpc": "2.0", "id": 1, "method": "offerings/list" } ``` ```JSON { "jsonrpc": "2.0", "id": 1, "result": { "tools": [ { "name": "calculate_energy", "description": "Calculates molecular energy using DFT", "parameters": { "type": "object", "properties": { "molecule": {"type": "string"}, "basis_set": {"type": "string"} } } } ], "resources": [ { "uri": "molecules://active_site", "description": "Active site coordinates from MD simulation" } ] } } ``` ```JSON { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "calculate_energy", "arguments": { "molecule": "H2O", "basis_set": "6-31G*" } } } ``` -------------------------------- ### Batch Script for Trigonometric Simplification Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Maxima.md Provides a batch script example for Autocrunchcoder to simplify trigonometric expressions. It uses `expand` and `trigreduce` functions to simplify the given expression. ```Maxima script = "display2d:false$ f:sin(x)^2 + cos(x)^2$ expand(f); trigreduce(f);" ``` -------------------------------- ### Get LAMMPS Version Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Retrieves the installed LAMMPS version. It checks if LAMMPS is available and then accesses the LAMMPS instance from the context to call its version() method. Returns 'LAMMPS not available' if the library is not found. ```Python import os import tempfile from contextvars import Context # Assuming FastMCP, Context, and LAMMPS_AVAILABLE are defined elsewhere # from your_mcp_library import FastMCP, Context # LAMMPS_AVAILABLE = True # or False # Placeholder for FastMCP and Context for demonstration class MockLifespanContext: def __init__(self, lmp): self.lmp = lmp class MockRequestContext: def __init__(self, lifespan_context): self.lifespan_context = lifespan_context class MockContext: def __init__(self, lmp): self.request_context = MockRequestContext(MockLifespanContext(lmp)) class MockLMP: def version(self): return "15 May 2023" def command(self, cmd): print(f"Executing: {cmd}") def get_natoms(self): return 100 def has_error(self): return False def get_last_error(self): return "" def get_thermo(self, thermo_key): if thermo_key == "pe": return -10.5 return 0.0 def file(self, filename): print(f"Running file: {filename}") class MockMCP: def __init__(self, name, lifespan): self.name = name self.lifespan = lifespan self.resources = {} self.tools = {} def resource(self, path): def decorator(func): self.resources[path] = func return func return decorator def tool(self): def decorator(func): self.tools[func.__name__] = func return func return decorator def run(self): print("MCP server running...") # Simulate running a resource/tool mock_lmp = MockLMP() mock_ctx = MockContext(mock_lmp) print(f"LAMMPS Version: {self.resources['lammps://version'](mock_ctx)}") script_content = """ units metal atom_style atomic lattice fcc 3.6 region box block 0 1 0 1 0 1 create_box 1 box create_atoms 1 box mass 1 63.546 pair_style eam pair_coeff * * /usr/share/lammps/potentials/cu_mm.eam run 0 """ print(f"Simulation Result: {self.tools['run_lammps_simulation'](mock_ctx, script_content)}") print(f"Energy Calculation: {self.tools['calculate_energy'](mock_ctx, 'Cu', 3.6)}") LAMMPS_AVAILABLE = True app_lifespan = None # Placeholder mcp = MockMCP("LAMMPS-MCP", lifespan=app_lifespan) @mcp.resource("lammps://version") def get_lammps_version(ctx: Context) -> str: """Return the LAMMPS version""" if not LAMMPS_AVAILABLE: return "LAMMPS not available" lmp = ctx.request_context.lifespan_context.lmp version = lmp.version() return f"LAMMPS version: {version}" ``` -------------------------------- ### Run Generic NumIntegrationCL Tests Source: https://github.com/prokophapala/autocrunchcoder/blob/main/docs/NumIntegrationCL.md Executes the end-to-end demo for the NumIntegrationCL framework, including generic tests and plotting. The output is redirected to a file named OUT-generic-integral. ```bash python -u -m pyCruncher2.scientific.gpu.test_num_integral_cl | tee OUT-generic-integral ``` -------------------------------- ### Avogadro MCP Implementation Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Gemini.md Presents potential MCP resources, tools, and prompts for Avogadro, a molecular editor. Resources are molecular structures in various formats. Tools include structure generation and optimization. Prompts guide molecule building and geometry optimization. ```text Resources: Molecular structures (various formats) Tools: Generate structure, optimize geometry, calculate properties, convert formats Prompts: "Build a molecule of {name}." "Optimize {molecule} with {force_field}." ``` -------------------------------- ### Python Demo Script Reference Source: https://github.com/prokophapala/autocrunchcoder/blob/main/docs/NumIntegrationCL.md Reference to the Python script that serves as a generic demonstration for numerical integration. ```N/A pyCruncher2/scientific/gpu/test_num_integral_cl.py ``` -------------------------------- ### Symengine Symbolic Math Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/AI_Tools.md Demonstrates basic symbolic mathematics operations using the Symengine library in Python. It shows how to define variables, create expressions, and expand them. ```Maxima >>> from symengine import var >>> var("x y z") (x, y, z) >>> e = (x+y+z)**2 >>> e.expand() 2*x*y + 2*x*z + 2*y*z + x**2 + y**2 + z**2 ``` -------------------------------- ### Pymaxima Integration Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/AI_Tools.md Shows how to use the pymaxima library to interact with a Maxima session from Python. It demonstrates sending a command to Maxima to perform symbolic integration and printing the result. ```Python import pymaxima # Start a Maxima session maxima = pymaxima.interact() # Send a command to Maxima result = maxima.eval("integrate(x^2, x)") # Print the result print(result) ``` -------------------------------- ### Doxygen Detailed Descriptions and Examples Commands Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/Doxygen.md Commands used to provide more in-depth explanations and usage examples for code elements. This includes adding detailed descriptions and embedding example code snippets. ```cpp /// @details This class handles the memory management for the simulation. ``` ```cpp /// @example example.cpp ``` -------------------------------- ### Minimal End-to-End OpenCL Example Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/OpenCLBase.md Demonstrates a minimal end-to-end workflow for using the autocrunchcoder library with OpenCL. It includes loading a kernel, setting up buffers, transferring data, launching the kernel, and retrieving results. ```Python ocl = OpenCLBase(nloc=128)ocl.load_program(kernel_path='kernels.cl') n = 1_000_000 x = np.ones(n, np.float32) y = np.zeros(n, np.float32) sz = n*4 ocl.try_make_buffers({'x': sz, 'y': sz}) ocl.toGPU('x_buff', x); ocl.toGPU('y_buff', y) ocl.kernel_params = {'a': 2.0, 'n': n} args = ocl.generate_kernel_args('saxpy') g = (ocl.roundUpGlobalSize(n),) ocl.prg.saxpy(ocl.queue, g, (ocl.nloc,), *args) ocl.fromGPU('y_buff', y) ``` -------------------------------- ### Run GROMACS MCP Server Script Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md Command to execute the Python script that starts the GROMACS MCP server. This makes the GROMACS functionalities available via HTTP. ```Bash python gromacs_mcp_server.py ``` -------------------------------- ### Create and Run GROMACS MCP Server Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/MCP_Perplexity.md This Python script sets up an MCP server using HTTP transport to interact with GROMACS. It defines resources for fetching the GROMACS version and tools for running energy minimization. The server is started when the script is executed directly. ```Python import subprocess import os import tempfile from fast_mcp import FastMCP, HTTPTransport # Create the MCP server with HTTP transport http_transport = HTTPTransport(host="0.0.0.0", port=8081) mcp = FastMCP("GROMACS-MCP", transport=http_transport) @mcp.resource("gromacs://version") def get_gromacs_version() -> str: """Return the GROMACS version""" try: result = subprocess.run( ["gmx", "--version"], capture_output=True, text=True, check=True ) return result.stdout.strip() except Exception as e: return f"Error getting GROMACS version: {str(e)}" @mcp.tool() def run_gromacs_energy_minimization(pdb_file_content: str) -> str: """Run a simple GROMACS energy minimization on a PDB structure""" # Create temporary directory for GROMACS files with tempfile.TemporaryDirectory() as temp_dir: # Write PDB content to file pdb_path = os.path.join(temp_dir, "input.pdb") with open(pdb_path, "w") as f: f.write(pdb_file_content) try: # Convert PDB to GROMACS format subprocess.run( ["gmx", "pdb2gmx", "-f", pdb_path, "-o", os.path.join(temp_dir, "processed.gro"), "-water", "spce", "-ff", "oplsaa", "-ignh"], capture_output=True, check=True, cwd=temp_dir ) # Define box subprocess.run( ["gmx", "editconf", "-f", os.path.join(temp_dir, "processed.gro"), "-o", os.path.join(temp_dir, "box.gro"), "-c", "-d", "1.0", "-bt", "cubic"], capture_output=True, check=True, cwd=temp_dir ) # Create minimization MDP file mdp_content = """ ; minim.mdp - used as input into grompp to generate em.tpr integrator = steep ; Algorithm (steep = steepest descent minimization) emtol = 1000.0 ; Stop minimization when the maximum force < 1000.0 kJ/mol/nm emstep = 0.01 ; Minimization step size nsteps = 50000 ; Maximum number of (minimization) steps to perform ; Parameters describing how to find the neighbors of each atom nstlist = 1 ; Frequency to update the neighbor list cutoff-scheme = Verlet ; Neighbor search method ns_type = grid ; Method to determine neighbor list coulombtype = PME ; Treatment of long range electrostatic interactions rcoulomb = 1.0 ; Short-range electrostatic cut-off rvdw = 1.0 ; Short-range Van der Waals cut-off pbc = xyz ; Periodic Boundary Conditions in all directions """ mdp_path = os.path.join(temp_dir, "minim.mdp") with open(mdp_path, "w") as f: f.write(mdp_content) # Prepare for minimization subprocess.run( ["gmx", "grompp", "-f", mdp_path, "-c", os.path.join(temp_dir, "box.gro"), "-p", os.path.join(temp_dir, "topol.top"), "-o", os.path.join(temp_dir, "em.tpr")], capture_output=True, check=True, cwd=temp_dir ) # Run minimization result = subprocess.run( ["gmx", "mdrun", "-v", "-deffnm", os.path.join(temp_dir, "em")], capture_output=True, text=True, cwd=temp_dir ) # Extract and return results return f"Energy minimization completed:\n{result.stdout}" except subprocess.CalledProcessError as e: return f"Error running GROMACS: {e.stderr}" except Exception as e: return f"Error: {str(e)}" # Start the MCP server if __name__ == "__main__": print(f"Starting GROMACS MCP server on http://0.0.0.0:8081/mcp") mcp.run() ``` -------------------------------- ### Python OpenAI Function Calling for Weather Source: https://github.com/prokophapala/autocrunchcoder/blob/main/doc/Providers/DeepSeek.md This Python code snippet demonstrates how to use OpenAI's Function Calling feature to get weather information. It includes setting up the OpenAI client, defining a 'get_weather' tool with parameters, sending user messages, and processing the model's response which includes a tool call. The example simulates a conversation flow where the model requests weather data and then provides a response based on the tool's output. ```Python from openai import OpenAI def send_messages(messages): response = client.chat.completions.create( model="deepseek-coder", messages=messages, tools=tools ) return response.choices[0].message client = OpenAI( api_key="", base_url="https://api.deepseek.com", ) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get weather of an location, the user shoud supply a location first", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", } }, "required": ["location"] }, } }, ] messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}] message = send_messages(messages) print(f"User>\t {messages[0]['content']}") tool = message.tool_calls[0] messages.append(message) messages.append({"role": "tool", "tool_call_id": tool.id, "content": "24℃"}) message = send_messages(messages) print(f"Model>\t {message.content}") ```