======================== CODE SNIPPETS ======================== TITLE: Install ppafm with pip DESCRIPTION: Installs the ppafm package and its dependencies using pip. This is the standard installation method and should work on most platforms. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_0 LANGUAGE: bash CODE: ``` pip install ppafm ``` ---------------------------------------- TITLE: Linux: Install PPAFM DESCRIPTION: Standard installation of PPAFM on Linux after setting up a virtual environment. This involves cloning the repository and installing the package using pip. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_9 LANGUAGE: Shell CODE: ``` git clone https://github.com/Probe-Particle/ppafm.git cd ppafm pip install . ``` ---------------------------------------- TITLE: Build and run ppafm Docker container DESCRIPTION: Steps to clone the ppafm repository, build a Docker image, and run the container for executing ppafm commands. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_5 LANGUAGE: git CODE: ``` git clone https://github.com/Probe-Particle/ppafm.git ``` LANGUAGE: bash CODE: ``` cd ppafm ``` LANGUAGE: bash CODE: ``` docker build -t ppafm:latest . ``` LANGUAGE: powershell CODE: ``` docker run --rm -v ${PWD}:/exec ppafm:latest ``` LANGUAGE: cmd CODE: ``` docker run --rm -v %CD%:/exec ppafm:latest ``` ---------------------------------------- TITLE: Install ppafm with GPU/GUI support (OpenCL) DESCRIPTION: Installs ppafm with OpenCL support for GPU acceleration and GUI applications. Requires additional dependencies like PyQt5 on Linux and OpenCL drivers. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_1 LANGUAGE: bash CODE: ``` pip install ppafm[opencl] ``` LANGUAGE: bash CODE: ``` sudo apt install python3-pyqt5 ``` LANGUAGE: bash CODE: ``` sudo apt install mesa-opencl-icd ``` LANGUAGE: bash CODE: ``` sudo apt install intel-opencl-icd ``` LANGUAGE: bash CODE: ``` sudo apt install pocl-opencl-icd ``` ---------------------------------------- TITLE: Build ppafm from source (Linux/MacOS) DESCRIPTION: Instructions for building ppafm from source on Linux and MacOS, requiring g++ and make, and potentially git. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_6 LANGUAGE: bash CODE: ``` sudo apt install g++ make ``` LANGUAGE: git CODE: ``` git clone https://github.com/Probe-Particle/ppafm.git ``` LANGUAGE: bash CODE: ``` cd ppafm ``` LANGUAGE: bash CODE: ``` pip install . ``` LANGUAGE: bash CODE: ``` conda install git ``` ---------------------------------------- TITLE: Build ppafm from source (Windows) DESCRIPTION: Instructions for building ppafm from source on Windows using Visual Studio Build Tools and the x64 Native Tools Command Prompt. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_7 LANGUAGE: bash CODE: ``` git clone https://github.com/Probe-Particle/ppafm.git ``` LANGUAGE: bash CODE: ``` cd ppafm ``` LANGUAGE: bash CODE: ``` pip install . ``` ---------------------------------------- TITLE: Running Simulation Examples with Bash DESCRIPTION: The project provides example simulations that can be executed using bash scripts. These scripts typically handle data downloading, setup, and execution of the ppafm Python module. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Home.md#_snippet_1 LANGUAGE: Bash CODE: ``` #!/bin/bash # Example script to run a simulation # This is a conceptual example based on the description # Ensure ppafm is installed and accessible in the Python path # pip install ppafm # Download necessary input files if not present # wget https://example.com/path/to/input.xyz # wget https://example.com/path/to/params.ini # Execute the ppafm simulation using Python # python -m ppafm.simulate --geometry input.xyz --params params.ini # Or if there's a specific run script provided in examples: # ./run.sh ``` ---------------------------------------- TITLE: Install ppafm with Anaconda on Windows (Microsoft OpenCL) DESCRIPTION: Specific installation steps for Anaconda on Windows when using the Microsoft OpenCL™ and OpenGL® Compatibility Pack, requiring only PyQt5. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_4 LANGUAGE: bash CODE: ``` conda install pyqt -c conda-forge ``` LANGUAGE: bash CODE: ``` pip install ppafm[opencl] ``` ---------------------------------------- TITLE: Run example simulation DESCRIPTION: Navigates to an example directory and executes a simulation script. This demonstrates how to run a simulation and study its parameters. SOURCE: https://github.com/probe-particle/ppafm/blob/main/README.md#_snippet_2 LANGUAGE: bash CODE: ``` cd examples/PTCDA_single ./run.sh ``` ---------------------------------------- TITLE: Install ppafm with Anaconda and GPU/GUI support DESCRIPTION: Installs ppafm with OpenCL support using Anaconda. It also installs necessary packages like PyQt5 and OpenCL ICDs from conda-forge. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_3 LANGUAGE: bash CODE: ``` conda install pyqt ocl-icd-system -c conda-forge ``` LANGUAGE: bash CODE: ``` pip install ppafm[opencl] ``` ---------------------------------------- TITLE: Install ppafm using pip DESCRIPTION: Installs the ppafm Python package and its dependencies using pip. This is the standard installation method. SOURCE: https://github.com/probe-particle/ppafm/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pip install ppafm ``` ---------------------------------------- TITLE: Build HTML Documentation Locally DESCRIPTION: This command builds the HTML documentation for the ppafm project locally. It requires Sphinx and Furo to be installed. The output is placed in the 'build/html' directory. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_11 LANGUAGE: bash CODE: ``` make html ``` ---------------------------------------- TITLE: Windows: Compile C++ Source Files DESCRIPTION: These commands demonstrate how to compile individual C++ source files into shared libraries (.dll) on Windows using g++, typically after installing MinGW-w64 via Anaconda. This is an alternative to using a Makefile. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_12 LANGUAGE: Shell CODE: ``` g++ -fPIC -std=c++11 -O2 -mtune=native -fopenmp -c ProbeParticle.cpp -o ProbeParticle.o g++ -shared -fopenmp ProbeParticle.o -o ProbeParticle_lib.dll g++ -fPIC -std=c++11 -O2 -mtune=native -fopenmp -c GridUtils.cpp -o GridUtils.o g++ -shared -fopenmp GridUtils.o -o GridUtils_lib.dll g++ -fPIC -std=c++11 -O2 -mtune=native -fopenmp -c fitting.cpp -o fitting.o g++ -shared -fopenmp fitting.o -o fitting_lib.dll g++ -fPIC -std=c++11 -O2 -mtune=native -fopenmp -c fitSpline.cpp -o fitSpline.o g++ -shared -fopenmp fitSpline.o -o fitSpline_lib.dll ``` ---------------------------------------- TITLE: Install ppafm with Development Dependencies DESCRIPTION: Installs the ppafm package in editable mode along with its development dependencies, allowing immediate reflection of file changes in the installed package. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_0 LANGUAGE: bash CODE: ``` pip install -e .[dev] ``` ---------------------------------------- TITLE: Load Simulation Parameters from File DESCRIPTION: Loads simulation parameters from a specified INI file using the `PP.loadParams` function. This is typically done before other simulation setup operations. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_3 LANGUAGE: Python CODE: ``` PP.loadParams( 'params.ini' ) ``` ---------------------------------------- TITLE: Zsh: Install PPAFM with OpenCL support DESCRIPTION: This command shows how to correctly install the PPAFM package with OpenCL support on Zsh, escaping the brackets to prevent pattern matching issues. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_10 LANGUAGE: Shell CODE: ``` pip install ppafm\[opencl\] ``` ---------------------------------------- TITLE: Create and activate Anaconda environment DESCRIPTION: Creates a dedicated Conda environment for ppafm with a specified Python version and activates it. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_2 LANGUAGE: bash CODE: ``` conda create -n ppafm python=3.11 ``` LANGUAGE: bash CODE: ``` conda activate ppafm ``` ---------------------------------------- TITLE: Initialize and Run AFMulator DESCRIPTION: This script initializes the OpenCL environment, prepares the dataset, downloads tip densities, and creates an `AFMulator` instance. It configures simulation parameters such as pixel density, scan dimensions, and Pauli repulsion constants. The code snippet demonstrates the setup for running AFM simulations. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md#_snippet_8 LANGUAGE: Python CODE: ``` if __name__ == "__main__": oclu.init_env(i_platform=0) # Output directory save_dir = Path("./generator_images_fdbm/") save_dir.mkdir(exist_ok=True, parents=True) # Get example data sample_dirs = prepare_dataset(data_dir=Path("./generator_data")) # Load tip densities co_dir = Path("./CO_densities") download_dataset("CO-tip-densities", co_dir) rho_tip, _, _ = TipDensity.from_file(co_dir / "density_CO.xsf") rho_tip_delta, _, _ = TipDensity.from_file(co_dir / "CO_delta_density_aims.xsf") # Create the simulator afmulator = AFMulator( pixPerAngstrome=10, scan_dim=(160, 160, 19), scan_window=((0, 0, 0), (15.9, 15.9, 1.9)), df_steps=10, npbc=(0, 0, 0), A_pauli=12, B_pauli=1.2, ) # Create auxmap objects to generate image descriptors of the samples ``` ---------------------------------------- TITLE: Install Pre-commit Hooks DESCRIPTION: Installs the pre-commit framework, which automatically runs hooks on staged changes during Git commits to ensure code quality. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_1 LANGUAGE: bash CODE: ``` pre-commit install ``` ---------------------------------------- TITLE: Initialize AFMulator with FDBM DESCRIPTION: Initializes the AFMulator with electron densities for the sample and tip, along with Pauli repulsion parameters and DFT-D3 parameters. This setup enables the use of the full-density-based model (FDBM). SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_14 LANGUAGE: Python CODE: ``` from ppafm.ocl.AFMulator import AFMulator, HartreePotential, ElectronDensity, TipDensity pot, xyzs, Zs = HartreePotential.from_file("LOCPOT.xsf", scale=-1) # Sample Hartree potential rho_sample, _, _ = ElectronDensity.from_file("CHGCAR.xsf") # Sample electron density rho_tip, xyzs_tip, Zs_tip = TipDensity.from_file("density_CO.xsf") # Tip electron density rho_tip_delta, _, _ = TipDensity.from_file("CO_delta_density.xsf") # Tip electron delta-density afmulator = AFMulator( ... rho=rho_tip, rho_delta=rho_tip_delta, A_pauli=12.0, B_pauli=1.2, d3_params="PBE", ) af_images = afmulator(xyzs, Zs, qs=pot, rho_sample=rho_sample) ``` ---------------------------------------- TITLE: Manage and Load ProbeParticle Library DESCRIPTION: Demonstrates how to clean previously compiled ProbeParticle C++ library files (.so, .o, .pyc) and then import the ProbeParticle library in Python. Recompilation is triggered if the .so file is missing. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_1 LANGUAGE: Python CODE: ``` def makeclean( ): import os [ os.remove(f) for f in os.listdir(".") if f.endswith(".so") ] [ os.remove(f) for f in os.listdir(".") if f.endswith(".o") ] [ os.remove(f) for f in os.listdir(".") if f.endswith(".pyc") ] makeclean( ) # force to recompile import ProbeParticle as PP ``` ---------------------------------------- TITLE: Windows: Install MinGW-w64 GCC for Anaconda DESCRIPTION: This command installs the necessary MinGW-w64 GCC compiler through Anaconda on Windows, which is required for building C++ code without administrative rights or Visual Studio. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_11 LANGUAGE: Shell CODE: ``` conda install -c rnicolas mingw-w64-posix-msvcrt ``` ---------------------------------------- TITLE: Get help for ppafm CLI tool DESCRIPTION: Displays help information for a specific ppafm command-line tool, such as ppafm-generate-ljff. This is useful for understanding the options and usage of individual tools. SOURCE: https://github.com/probe-particle/ppafm/blob/main/README.md#_snippet_1 LANGUAGE: bash CODE: ``` ppafm-generate-ljff -h ``` ---------------------------------------- TITLE: Prepare and Load AFM Data DESCRIPTION: This code prepares an example dataset by downloading and repackaging it into a format suitable for fast disk reading. It loads Hartree potentials and electron densities from .xsf files, shifts molecules to the center, and saves them as .npz files. It also includes a function to load this prepared data. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md#_snippet_6 LANGUAGE: Python CODE: ``` import os from pathlib import Path import matplotlib.pyplot as plt import numpy as np from ppafm.data import download_dataset from ppafm.io import saveXYZ from ppafm.ml.AuxMap import AtomicDisks, ESMapConstant, HeightMap, vdwSpheres from ppafm.ml.Generator import GeneratorAFMtrainer from ppafm.ocl import oclUtils as oclu from ppafm.ocl.AFMulator import AFMulator, ElectronDensity, HartreePotential, TipDensity class ExampleTrainer(GeneratorAFMtrainer): # Override the on_sample_start method to randomly modify simulation parameters for each sample. def on_sample_start(self): self.randomize_distance(delta=0.2) self.randomize_tip(max_tilt=0.3) def prepare_dataset(data_dir: Path): """ Download an example dataset and repackage it to a format that is better suited for fast reading from the disk. """ if data_dir.exists(): print("Data directory already exists. Skipping data preparation.") sample_dirs = [d for d in data_dir.glob("*") if d.is_dir()] return sample_dirs download_dataset("hartree-density", data_dir) sample_dirs = [d for d in data_dir.glob("*") if d.is_dir()] for sample_dir in sample_dirs: # Load data from .xsf files hartree, xyzs, Zs = HartreePotential.from_file(sample_dir / "LOCPOT.xsf", scale=-1.0) density, _, _ = ElectronDensity.from_file(sample_dir / "CHGCAR.xsf") # In this dataset the molecules are centered in the corner of the box. Let's shift them to the center so # that the distance calculation works correctly in the generator. box_size = np.diag(hartree.lvec[1:]) shift = (np.array(hartree.shape) / 2).astype(np.int32) xyzs = (xyzs + box_size / 2) % box_size hartree_array = np.roll(hartree.array, shift=shift, axis=(0, 1, 2)) density_array = np.roll(density.array, shift=shift, axis=(0, 1, 2)) # Save into .npz files. np.savez(sample_dir / "hartree.npz", data=hartree_array.astype(np.float32), lvec=hartree.lvec, xyzs=xyzs, Zs=Zs) np.savez(sample_dir / "density.npz", data=density_array.astype(np.float32), lvec=density.lvec, xyzs=xyzs, Zs=Zs) return sample_dirs def load_sample(sample_dir: Path): """ Load a sample from a directory. The directory contains the files hartree.npz and density.npz, which contain the sample Hartree potential and electron density in the format that we prepared in prepare_dataset. """ hartree_data = np.load(sample_dir / "hartree.npz") density_data = np.load(sample_dir / "density.npz") xyzs = hartree_data["xyzs"] Zs = hartree_data["Zs"] hartree = HartreePotential(hartree_data["data"], lvec=hartree_data["lvec"]) density = ElectronDensity(density_data["data"], lvec=density_data["lvec"]) return xyzs, Zs, hartree, density ``` ---------------------------------------- TITLE: Import Common Python Libraries DESCRIPTION: This snippet shows the common Python libraries imported for ProbeParticle simulations, including numpy for numerical operations and matplotlib for plotting. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_0 LANGUAGE: Python CODE: ``` import os import numpy as np import matplotlib.pyplot as plt import elements import basUtils ``` ---------------------------------------- TITLE: Launch ppafm-GUI DESCRIPTION: Launches the graphical user interface for the GPU version of the Probe-Particle Model (ppafm). This command requires the GUI support to be installed. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/PPAFM-GUI.md#_snippet_0 LANGUAGE: Shell CODE: ``` ppafm-gui ``` ---------------------------------------- TITLE: Configure Simulation Parameters DESCRIPTION: Sets default simulation parameters using a Python dictionary. This includes grid dimensions, atomic properties, and scanning ranges. These parameters can be modified directly or loaded from an external file. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_2 LANGUAGE: Python CODE: ``` params={ 'PBC': False, 'gridN': np.array( [ 150, 150, 50 ] ).astype(np.int32), 'gridA': np.array( [ 12.798, -7.3889, 0.00000 ] ), 'gridB': np.array( [ 12.798, 7.3889, 0.00000 ] ), 'gridC': np.array( [ 0, 0, 5.0 ] ), 'moleculeShift': np.array( [ 0.0, 0.0, -2.0 ] ), 'probeType': 8, 'charge': 0.00, 'r0Probe' : np.array( [ 0.00, 0.00, 4.00] ), 'stiffness': np.array( [ 0.5, 0.5, 20.00] ), 'scanStep': np.array( [ 0.10, 0.10, 0.10] ), 'scanMin': np.array( [ 0.0, 0.0, 5.0 ] ), 'scanMax': np.array( [ 20.0, 20.0, 8.0 ] ), 'kCantilever' : 1800.0, 'f0Cantilever' : 30300.0, 'Amplitude' : 1.0, 'plotSliceFrom': 16, 'plotSliceTo' : 22, 'plotSliceBy' : 1, 'imageInterpolation': 'nearest', 'colorscale' : 'gray', } ``` ---------------------------------------- TITLE: Define and Allocate Simulation Arrays DESCRIPTION: Defines and allocates arrays for simulation, including tip positions (`rTips`), forces (`fs`), and grid data (`fzs`). It also sets up the scanning grid (`zTips`, `xTips`, `yTips`) and the main force field grid (`FF`). SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_8 LANGUAGE: Python CODE: ``` dz = PP.params['scanStep'][2] zTips = np.arange( PP.params['scanMin'][2], PP.params['scanMax'][2]+0.00001, dz )[::-1]; ntips = len(zTips); print " zTips : ",zTips rTips = np.zeros((ntips,3)) rs = np.zeros((ntips,3)) fs = np.zeros((ntips,3)) rTips[:,0] = 1.0 rTips[:,1] = 1.0 rTips[:,2] = zTips PP.setTip() xTips = np.arange( PP.params['scanMin'][0], PP.params['scanMax'][0]+0.00001, 0.1 ) yTips = np.arange( PP.params['scanMin'][1], PP.params['scanMax'][1]+0.00001, 0.1 ) extent=( xTips[0], xTips[-1], yTips[0], yTips[-1] ) fzs = np.zeros(( len(zTips), len(yTips ), len(xTips ) )); nslice = 10; FFparams = PP.loadSpecies ( 'atomtypes.ini' ) C6,C12 = PP.getAtomsLJ( PP.params['probeType'], iZs, FFparams ) print " # ============ define Grid " cell =np.array([ PP.params['gridA'], PP.params['gridB'], PP.params['gridC'], ]).copy() gridN = PP.params['gridN'] FF = np.zeros( (gridN[2],gridN[1],gridN[0],3) ) ``` ---------------------------------------- TITLE: Google-Style Docstring Example in Python DESCRIPTION: This snippet demonstrates a Google-style docstring for Python functions, as used with the Sphinx Napoleon extension. It includes a plain language description, arguments, and return values, with specific formatting requirements for parsing. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_8 LANGUAGE: Python CODE: ``` def example_function(arg1, arg2): ''' A plain language description of what the function does. This is followed by a list of arguments and (possibly) return values. Arguments: arg1: Description of argument 1. arg2: Description of argument 2. If the description for the argument is very long, it can be split into multiple lines. Returns: ret1: Description of return value 1. ret2: Description of return value 2. ''' ``` ---------------------------------------- TITLE: Handle Periodic Boundary Conditions DESCRIPTION: Applies periodic boundary conditions to the atomic structure by replicating the sample into neighboring unit cells. This is essential for simulations using periodic boundary conditions and is handled by the `PP.PBCAtoms` function. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_6 LANGUAGE: Python CODE: ``` if PP.params['PBC' ]: iZs,Rs,Qs = PP.PBCAtoms( iZs, Rs, Qs, avec=PP.params['gridA'], bvec=PP.params['gridB'] ) ``` ---------------------------------------- TITLE: Remove OpenMP Headers and Calls (C++) DESCRIPTION: Steps to remove OpenMP header files and function calls from C++ source files if OpenMP header files are not installed or causing issues. This involves modifying Grid.h and ProbeParticle.cpp. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_16 LANGUAGE: C++ CODE: ``` #include ``` LANGUAGE: C++ CODE: ``` omp_* function calls ``` ---------------------------------------- TITLE: Load Atomic Structure DESCRIPTION: Loads atomic positions and types from an XYZ file using `basUtils.loadAtoms`. The loaded data is then processed to separate atomic positions (`Rs`) and their corresponding atomic numbers (`iZs`). SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_4 LANGUAGE: Python CODE: ``` atoms = basUtils.loadAtoms('input.xyz', elements.ELEMENT_DICT ) Rs = np.array([atoms[1],atoms[2],atoms[3]]); iZs = np.array( atoms[0]) ``` ---------------------------------------- TITLE: Linux: Resolve Externally Managed Environment Error DESCRIPTION: This snippet addresses the 'externally-managed-environment' error encountered on some Linux distributions when using pip. It demonstrates how to create and activate a virtual environment to bypass system-wide package restrictions. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_8 LANGUAGE: Shell CODE: ``` python3 -m venv /home/prokop/venvs/ppafm source ~/venvs/ppafm/bin/activate ``` ---------------------------------------- TITLE: Run AFM Simulation and Get Image Array DESCRIPTION: Executes the AFM simulation using the configured AFMulator and molecular data. The resulting force-field images are returned as a NumPy array. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_4 LANGUAGE: python CODE: ``` import matplotlib.pyplot as plt afm_images = afmulator(xyzs, Zs, qs) print(afm_images.shape) # (201, 201, 31) for i in range(afm_images.shape[2]): plt.imshow(afm_images[:, :, i].T, origin='lower', cmap='afmhot') plt.savefig(f'afm_{i}.png') plt.close() ``` ---------------------------------------- TITLE: Configure AFM Simulation Parameters (INI) DESCRIPTION: This snippet shows an example configuration file (params.ini) for the Probe Particle Model in AFM simulations. It defines parameters related to the simulation environment, atomic properties, potentials, electrostatics, and scanning behavior. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Complex-Tip-alias-Double-Probe-Particle.md#_snippet_0 LANGUAGE: INI CODE: ``` PBC True nPBC 1 1 1 moleculeShift 0.0 0.0 0.0 useLJ True Catom 6 # Z of the upper PP (C) Oatom 8 # Z of the lower PP (O) rC0 0.0 0.0 1.85 # Total Metal atom-C length 1.85 rO0 0.0 0.0 1.15 # Total C-O length 1.15 Cklat 0.111 # the bending spring constant of the harmonic spring potential of tip-C bond Now it is a bending spring constant. The units should be ev/rad^2, if I am not mistaking Oklat 0.109 # the bending spring constant of the harmonic spring potential of C-O bond # C 0.111 & O 0.109 are giving really close results as stiffness 0.24 in Master Ckrad 20.00 # C radial stiffness (keep 20.0) Okrad 20.00 # O radial stiffness (keep 20.0) ChargeCuUp -0.0669933 # charge of upper Cu atom ChargeCuDown -0.0627402 # charge of lower Cu atom CuUpshift 2.2422001068 # Cu-Cu z distance (important only for electrostatics and if tip = None) Ccharge 0.212718 # charge of upper PP (C) Ocharge -0.11767 # charge of upper PP (O) Omultipole 's' # Multipole of PPs (and Cu atoms iff tip = None) sigma 0.71 # Sigma of PPs charge tip None # Multipole of metal tip-base (If None then, Cu atoms charge is checked) tipZdisp 0.0 # z-shift for the metal tip-base multipole tipsigma 0.71 # Sigma of metal tip-base tipcharge 0.00 # effective charge (or dipole) of the metallic base of the tip (applied if tip != None) scanMin 0.0 0.0 15.5 # start of scanning (x,y,z) scanMax 20.0 20.0 19.0 # end of scanning (x,y,z) Amplitude 1.0 # [Å] oscilation amplitude for conversion Fz->df ``` ---------------------------------------- TITLE: Set OpenMP Threads (Shell) DESCRIPTION: This snippet shows how to set the number of logical CPU cores available for OpenMP parallelization by exporting the OMP_NUM_THREADS environment variable. This is a common way to control thread usage in OpenMP applications. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_13 LANGUAGE: Shell CODE: ``` export OMP_NUM_THREADS=ncores ``` ---------------------------------------- TITLE: Modify Python for OpenMP (Python) DESCRIPTION: This describes a modification needed in the HighLevel.py Python script to switch from an OpenMP-enabled function to a non-OpenMP version. This is part of the troubleshooting process for OpenMP issues. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_15 LANGUAGE: Python CODE: ``` relaxedScan3D() rather than relaxedScan3D_omp() ``` ---------------------------------------- TITLE: Disable OpenMP in Makefile (C++) DESCRIPTION: Instructions for disabling OpenMP in the ppafm C++ project by removing the OpenMP flag from the CPPFLAGS in the Makefile. This is a troubleshooting step for OpenMP-related problems. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Install-ppafm.md#_snippet_14 LANGUAGE: C++ CODE: ``` CPPFLAGS= -fPIC -std=c++11 -O2 -mtune=native -fopenmp ``` ---------------------------------------- TITLE: Load Atomic Species and LJ Parameters DESCRIPTION: Loads Lennard-Jones (LJ) parameters for different atom types from an 'atomtypes.ini' file using `PP.loadSpecies`. It then retrieves the specific LJ parameters (C6, C12) for each atom based on its type and the probe type using `PP.getAtomsLJ`. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_7 LANGUAGE: Python CODE: ``` Qs = np.array( atoms[4] ) FFparams = PP.loadSpecies ( 'atomtypes.ini' ) C6,C12 = PP.getAtomsLJ( PP.params['probeType'], iZs, FFparams ) ``` ---------------------------------------- TITLE: ProbeParticle: Lenard-Jones and Electrostatic Potential Calculation DESCRIPTION: This snippet demonstrates how to set up and utilize force fields in ProbeParticle, specifically calculating Lenard-Jones and electrostatic potentials. It involves setting the force field, retrieving LJ parameters, and conditionally calculating Coulomb interactions based on charge. The results are visualized using matplotlib. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_9 LANGUAGE: Python CODE: ``` PP.setFF( FF, cell ) PP.setFF_Pointer( FF ) PP.getLenardJonesFF( Rs, C6, C12 ) plt.figure(figsize=( 5*nslice,5 )); plt.title( ' FF LJ ' ) for i in range(nslice): plt.subplot( 1, nslice, i+1 ) plt.imshow( FF[i,:,:,2], origin='image', interpolation='nearest' ) withElectrostatics = ( abs( PP.params['charge'] )>0.001 ) if withElectrostatics: print " # =========== Sample Coulomb " FFel = np.zeros( np.shape( FF ) ) CoulombConst = -14.3996448915; # [ e^2 eV/A ] Qs *= CoulombConst #print Qs PP.setFF_Pointer( FFel ) PP.getCoulombFF ( Rs, Qs ) plt.figure(figsize=( 5*nslice,5 )); plt.title( ' FFel ' ) for i in range(nslice): plt.subplot( 1, nslice, i+1 ) plt.imshow( FFel[i,:,:,2], origin='image', interpolation='nearest' ) FF += FFel*PP.params['charge'] PP.setFF_Pointer( FF ) del FFel plt.figure(figsize=( 5*nslice,5 )); plt.title( ' FF total ' ) for i in range(nslice): plt.subplot( 1, nslice, i+1 ) plt.imshow( FF[i,:,:,2], origin='image', interpolation='nearest' ) ``` ---------------------------------------- TITLE: ProbeParticle: 3D-Scan with Tip Relaxation DESCRIPTION: This code snippet illustrates how to perform a 3D scan using ProbeParticle, incorporating tip relaxation. It iterates through defined x and y tip positions, updating the tip's coordinates and calling the `relaxTipStroke` function to find the relaxed position. The resulting forces (fs) are stored for further analysis. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_10 LANGUAGE: Python CODE: ``` for ix,x in enumerate( xTips ): print "relax ix:", ix rTips[:,0] = x for iy,y in enumerate( yTips ): rTips[:,1] = y itrav = PP.relaxTipStroke( rTips, rs, fs ) / float( len(zTips) ) fzs[:,iy,ix] = fs[:,2].copy() ``` ---------------------------------------- TITLE: ProbeParticle: Convert Fz to df DESCRIPTION: This snippet shows the conversion of force data (Fz) to frequency shift (df) using the `Fz2df` function in ProbeParticle. It requires the force data array `fzs`, the z-step `dz`, and cantilever parameters like spring constant `kCantilever`, resonant frequency `f0Cantilever`, and amplitude. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_11 LANGUAGE: Python CODE: ``` dfs = PP.Fz2df( fzs, dz = dz, k0 = PP.params['kCantilever'], f0=PP.params['f0Cantilever'], n=int(PP.params['Amplitude']/dz) ) ``` ---------------------------------------- TITLE: reStructuredText Directives for Sphinx Documentation DESCRIPTION: This example shows how to use reStructuredText (reST) directives within Sphinx to create cross-references to other Python code elements like classes, methods, and functions. The syntax allows linking within the same module or to external ones. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_9 LANGUAGE: reStructuredText CODE: ``` A link to a class in the same module: :class:`myClass` A link to a method in the same module: :meth:`myMethod` A link to a function outside the current module: :func:`.MyFunc`. Notice the dot before the function name that allows for search outside the current module. ``` ---------------------------------------- TITLE: Automatic Geometry Adjustment DESCRIPTION: Automatically adjusts the simulation geometry, including cell fitting and molecule shifting, based on the atomic structure and simulation parameters. This is particularly useful for non-periodic systems like single molecules. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_5 LANGUAGE: Python CODE: ``` if not PP.params['PBC' ]: PP.autoGeom( Rs, shiftXY=True, fitCell=True, border=3.0 ) Rs[0] += PP.params['moleculeShift' ][0] Rs[1] += PP.params['moleculeShift' ][1] Rs[2] += PP.params['moleculeShift' ][2] Rs = np.transpose( Rs, (1,0) ).copy() ``` ---------------------------------------- TITLE: ProbeParticle: Plotting Relaxed 3D Scan Results DESCRIPTION: This code snippet is responsible for visualizing the results of a relaxed 3D scan. It iterates through calculated frequency shifts (`dfs`), displays them as images using matplotlib, adds a colorbar and labels, and saves each slice as a PNG file. The plot title indicates the corresponding tip height (z). SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/scripting.md#_snippet_12 LANGUAGE: Python CODE: ``` print " # ============ Plot Relaxed Scan 3D " #slices = range( PP.params['plotSliceFrom'], PP.params['plotSliceTo'], PP.params['plotSliceBy'] ) #print "plotSliceFrom, plotSliceTo, plotSliceBy : ", PP.params['plotSliceFrom'], PP.params['plotSliceTo'], PP.params['plotSliceBy'] #print slices #nslice = len( slices ) slices = range( 0, len(dfs) ) for ii,i in enumerate(slices): print " plotting ", i plt.figure( figsize=( 10,10 ) ) plt.imshow( dfs[i], origin='image', interpolation=PP.params['imageInterpolation'], cmap=PP.params['colorscale'], extent=extent ) z = zTips[i] - PP.params['moleculeShift' ][2] plt.colorbar(); plt.xlabel(r' Tip_x $AA$') plt.ylabel(r' Tip_y $AA$') plt.title( r"df Tip_z = %2.2f $AA$" %z ) plt.savefig( 'df_%3i.png' %i, bbox_inches='tight' ) ``` ---------------------------------------- TITLE: Python Interface and Utilities in ppafm DESCRIPTION: This snippet covers the Python interface for the ppafm project, including functions for converting force to frequency shift, evaluating Lennard-Jones coefficients, managing periodic boundary conditions, and automatic geometry setup. It also includes utility functions for loading molecular geometries and accessing atomic parameters. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Technical-details.md#_snippet_0 LANGUAGE: Python CODE: ``` from ppafm.ProbeParticle import Fz2df, getAtomsLJ, PBCAtoms, autoGeom, params, loadParams from ppafm.basUtils import loadAtoms from ppafm.Element import Element, elements ``` ---------------------------------------- TITLE: Interpolate 3D Vector Force Field DESCRIPTION: Function to interpolate the precomputed 3D vector force field, considering periodic boundary conditions. This is used to get the force acting on the probe particle at any given position within the simulation grid. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Home.md#_snippet_20 LANGUAGE: Python CODE: ``` interpolate3DvecWrap() ``` ---------------------------------------- TITLE: Initialize AFMulator from Parameters File DESCRIPTION: Constructs an AFMulator instance by loading simulation parameters from a specified INI file, providing a convenient way to reuse configurations. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_3 LANGUAGE: python CODE: ``` from ppafm.opencl import AFMulator afmulator = AFMulator.from_params("./params.ini") ``` ---------------------------------------- TITLE: Configure ExampleTrainer for AFM Simulations DESCRIPTION: Combines AFMulator, auxiliary maps, and a sample generator into an ExampleTrainer object. This configuration includes parameters like batch size, tip-sample distance, tip atomic numbers, and electron densities for various simulation types (e.g., FDBM, LJ). SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md#_snippet_11 LANGUAGE: Python CODE: ``` trainer = ExampleTrainer( afmulator, aux_maps, sample_generator, batch_size=6, # Number of samples per batch distAbove=2.5, # Tip-sample distance, taking into account the effective size of the tip and the sample atoms iZPPs=[8], # Tip atomic numbers rhos=[rho_tip], # Tip electron densities, used for the Pauli overlap integral rho_deltas=[rho_tip_delta], # Tip electron delta densities, used for the electrostatic interaction ) # Example of trainer usage: for afm, desc, mols, scan_windows in trainer: # Do stuff with the data... pass ``` ---------------------------------------- TITLE: Creating a New Release with Bumpver DESCRIPTION: This command-line tool is used to manage project releases. It handles version bumping, creating Git tags, and triggering GitHub Actions workflows for PyPI publication. It supports semantic versioning and various release tags like alpha, beta, and rc. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/For-Developers.md#_snippet_6 LANGUAGE: Bash CODE: ``` pip install -e '.[dev]' bumpver update [--major|--minor|--patch] [--tag-num --tag [alpha|beta|rc]] ``` LANGUAGE: Bash CODE: ``` bumpver update --minor ``` LANGUAGE: Bash CODE: ``` bumpver update --patch ``` LANGUAGE: Bash CODE: ``` bumpver update --tag-num ``` LANGUAGE: Bash CODE: ``` bumpver update --patch --tag alpha ``` LANGUAGE: Bash CODE: ``` bumpver update --tag final ``` ---------------------------------------- TITLE: Initialize AFMulator with Simulation Parameters DESCRIPTION: Creates an AFMulator instance, configuring key simulation parameters such as grid density, scan dimensions, scan window, probe atomic number, oscillation steps, and equilibrium tip position. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_2 LANGUAGE: python CODE: ``` from ppafm.opencl import AFMulator afmulator = AFMulator( pixPerAngstrome=10, scan_dim=(201, 201, 40), scan_window=((0.0, -10.0, 5.0), (20.0, 10.0, 9.0)), iZPP=8, df_steps=10, tipR0=[0.0, 0.0, 3.0] ) ``` ---------------------------------------- TITLE: List Available OpenCL Devices DESCRIPTION: Lists all OpenCL-enabled compute devices usable by ppafm, which is helpful for selecting a specific device if multiple are available. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_5 LANGUAGE: bash CODE: ``` ppafm-gui --list-devices ``` ---------------------------------------- TITLE: View XSF Files GUI DESCRIPTION: A graphical user interface for loading and viewing .xsf files. Users can browse through the slices of the 3D grid data. SOURCE: https://github.com/probe-particle/ppafm/blob/main/__wiki__/Command-line-interface.md#_snippet_27 LANGUAGE: Python CODE: ``` import tkinter as tk from pyqtgraph.Qt import QtGui, QtCore # Example using PyQtGraph class XSFViewerGUI(QtGui.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("XSF Viewer") # Widgets for loading .xsf and displaying slices # if __name__ == '__main__': # app = QtGui.QApplication(sys.argv) # viewer = XSFViewerGUI() # viewer.show() # sys.exit(app.exec_()) ``` ---------------------------------------- TITLE: Run GPU-Accelerated AFM Simulation with AFMulator DESCRIPTION: Demonstrates how to initialize an OpenCL environment, load molecular geometry data, and create an `AFMulator` instance for GPU-accelerated AFM simulations. This involves specifying simulation parameters like scan dimensions, window, force field settings, and tip radius. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_0 LANGUAGE: Python CODE: ``` from ppafm.io import loadXYZ from ppafm.ocl.AFMulator import AFMulator from ppafm.ocl.oclUtils import init_env # Initialize an OpenCL environment. You can change i_platform to select the device to use. init_env(i_platform=0) # Load sample coordinates (xyzs), atomic numbers (Zs), and charges (qs) xyzs, Zs, qs, _ = loadXYZ("./Gr6x6N3hole.xyz") # Create an instance of the simulator afmulator = AFMulator( scan_dim=(201, 201, 40), scan_window=((0.0, -10.0, 5.0), (20.0, 10.0, 9.0)), iZPP=8, df_steps=10, tipR0=[0.0, 0.0, 3.0] ) ``` ---------------------------------------- TITLE: Initialize AFMulator with Lennard-Jones and point-charge electrostatics DESCRIPTION: Initializes the AFMulator with Lennard-Jones force field and point-charge electrostatics. The `rho_sample` argument is optional and defaults to None. Charges for atoms are provided via the `qs` argument, typically loaded from a .xyz file. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md#_snippet_6 LANGUAGE: python CODE: ``` afm_images = afmulator(xyzs, Zs, qs, rho_sample=None) ``` ---------------------------------------- TITLE: Initialize InverseAFMtrainer with XYZ files DESCRIPTION: This snippet shows how to initialize the InverseAFMtrainer for generating AFM data from a directory of XYZ files. It includes setting up the AFMulator, defining auxiliary maps, and specifying molecule paths and batch parameters. SOURCE: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md#_snippet_0 LANGUAGE: Python CODE: ``` from pathlib import Path import numpy as np from ppafm.common import sphereTangentSpace from ppafm.ml.AuxMap import AtomicDisks, AtomRfunc, Bonds, HeightMap, vdwSpheres from ppafm.ml.Generator import InverseAFMtrainer from ppafm.ocl.AFMulator import AFMulator from ppafm.ocl.oclUtils import init_env class ExampleTrainer(InverseAFMtrainer): # We override this callback method in order to augment the samples with randomized tip distance and tilt def on_sample_start(self): self.randomize_distance(delta=0.2) self.randomize_tip(max_tilt=0.3) if __name__ == "__main__": init_env(i_platform=0) # Define simulator with parameters afmulator = AFMulator( pixPerAngstrome=10, scan_dim=(128, 128, 19), scan_window=((2.0, 2.0, 5.0), (18.0, 18.0, 6.9)), df_steps=10, npbc=(0, 0, 0), ) # Define descriptors to generate auxmap_args = {"scan_window": ((2.0, 2.0), (18.0, 18.0)), "scan_dim": (128, 128)} aux_maps = [ vdwSpheres(**auxmap_args), AtomicDisks(**auxmap_args), HeightMap(afmulator.scanner), Bonds(**auxmap_args), AtomRfunc(**auxmap_args), ] # Paths to molecule xyz files xyzs_dir = Path("example_molecules") paths = list(xyzs_dir.glob("*.xyz")) # Combine everything to one trainer = ExampleTrainer( afmulator, aux_maps, paths, batch_size=20, distAbove=4.5, iZPPs=[8], QZs=[[0.1, 0, -0.1, 0]], Qs=[[-10, 20, -10, 0]], ) # Augment molecule list with rotations and shuffle trainer.augment_with_rotations_entropy(sphereTangentSpace(n=100), 30) trainer.shuffle_molecules() # Iterate over batches for ib, (afm, desc, mols) in enumerate(trainer): # Do stuff with the data... pass ```