### Install ppafm with pip Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Installs the ppafm package and its dependencies using pip. This is the standard installation method and should work on most platforms. ```bash pip install ppafm ``` -------------------------------- ### Linux: Install PPAFM Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Standard installation of PPAFM on Linux after setting up a virtual environment. This involves cloning the repository and installing the package using pip. ```Shell git clone https://github.com/Probe-Particle/ppafm.git cd ppafm pip install . ``` -------------------------------- ### Build and run ppafm Docker container Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Steps to clone the ppafm repository, build a Docker image, and run the container for executing ppafm commands. ```git git clone https://github.com/Probe-Particle/ppafm.git ``` ```bash cd ppafm ``` ```bash docker build -t ppafm:latest . ``` ```powershell docker run --rm -v ${PWD}:/exec ppafm:latest ``` ```cmd docker run --rm -v %CD%:/exec ppafm:latest ``` -------------------------------- ### Install ppafm with GPU/GUI support (OpenCL) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Installs ppafm with OpenCL support for GPU acceleration and GUI applications. Requires additional dependencies like PyQt5 on Linux and OpenCL drivers. ```bash pip install ppafm[opencl] ``` ```bash sudo apt install python3-pyqt5 ``` ```bash sudo apt install mesa-opencl-icd ``` ```bash sudo apt install intel-opencl-icd ``` ```bash sudo apt install pocl-opencl-icd ``` -------------------------------- ### Build ppafm from source (Linux/MacOS) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Instructions for building ppafm from source on Linux and MacOS, requiring g++ and make, and potentially git. ```bash sudo apt install g++ make ``` ```git git clone https://github.com/Probe-Particle/ppafm.git ``` ```bash cd ppafm ``` ```bash pip install . ``` ```bash conda install git ``` -------------------------------- ### Build ppafm from source (Windows) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Instructions for building ppafm from source on Windows using Visual Studio Build Tools and the x64 Native Tools Command Prompt. ```bash git clone https://github.com/Probe-Particle/ppafm.git ``` ```bash cd ppafm ``` ```bash pip install . ``` -------------------------------- ### Running Simulation Examples with Bash Source: https://github.com/probe-particle/ppafm/wiki/Home 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. ```Bash #!/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 ``` -------------------------------- ### Install ppafm with Anaconda on Windows (Microsoft OpenCL) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Specific installation steps for Anaconda on Windows when using the Microsoft OpenCL™ and OpenGL® Compatibility Pack, requiring only PyQt5. ```bash conda install pyqt -c conda-forge ``` ```bash pip install ppafm[opencl] ``` -------------------------------- ### Run example simulation Source: https://github.com/probe-particle/ppafm/blob/main/README.md Navigates to an example directory and executes a simulation script. This demonstrates how to run a simulation and study its parameters. ```bash cd examples/PTCDA_single ./run.sh ``` -------------------------------- ### Install ppafm with Anaconda and GPU/GUI support Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Installs ppafm with OpenCL support using Anaconda. It also installs necessary packages like PyQt5 and OpenCL ICDs from conda-forge. ```bash conda install pyqt ocl-icd-system -c conda-forge ``` ```bash pip install ppafm[opencl] ``` -------------------------------- ### Install ppafm using pip Source: https://github.com/probe-particle/ppafm/blob/main/README.md Installs the ppafm Python package and its dependencies using pip. This is the standard installation method. ```bash pip install ppafm ``` -------------------------------- ### Build HTML Documentation Locally Source: https://github.com/probe-particle/ppafm/wiki/For-Developers 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. ```bash make html ``` -------------------------------- ### Windows: Compile C++ Source Files Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```Shell 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 ``` -------------------------------- ### Install ppafm with Development Dependencies Source: https://github.com/probe-particle/ppafm/wiki/For-Developers Installs the ppafm package in editable mode along with its development dependencies, allowing immediate reflection of file changes in the installed package. ```bash pip install -e .[dev] ``` -------------------------------- ### Load Simulation Parameters from File Source: https://github.com/probe-particle/ppafm/wiki/scripting Loads simulation parameters from a specified INI file using the `PP.loadParams` function. This is typically done before other simulation setup operations. ```Python PP.loadParams( 'params.ini' ) ``` -------------------------------- ### Zsh: Install PPAFM with OpenCL support Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm This command shows how to correctly install the PPAFM package with OpenCL support on Zsh, escaping the brackets to prevent pattern matching issues. ```Shell pip install ppafm\[opencl\] ``` -------------------------------- ### Create and activate Anaconda environment Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm Creates a dedicated Conda environment for ppafm with a specified Python version and activates it. ```bash conda create -n ppafm python=3.11 ``` ```bash conda activate ppafm ``` -------------------------------- ### Initialize and Run AFMulator Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md 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. ```Python 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 ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/probe-particle/ppafm/wiki/For-Developers Installs the pre-commit framework, which automatically runs hooks on staged changes during Git commits to ensure code quality. ```bash pre-commit install ``` -------------------------------- ### Initialize AFMulator with FDBM Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md 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). ```Python 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) ``` -------------------------------- ### Manage and Load ProbeParticle Library Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python 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 ``` -------------------------------- ### Windows: Install MinGW-w64 GCC for Anaconda Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```Shell conda install -c rnicolas mingw-w64-posix-msvcrt ``` -------------------------------- ### Get help for ppafm CLI tool Source: https://github.com/probe-particle/ppafm/blob/main/README.md 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. ```bash ppafm-generate-ljff -h ``` -------------------------------- ### Prepare and Load AFM Data Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md 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. ```Python 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 ``` -------------------------------- ### Import Common Python Libraries Source: https://github.com/probe-particle/ppafm/wiki/scripting This snippet shows the common Python libraries imported for ProbeParticle simulations, including numpy for numerical operations and matplotlib for plotting. ```Python import os import numpy as np import matplotlib.pyplot as plt import elements import basUtils ``` -------------------------------- ### Launch ppafm-GUI Source: https://github.com/probe-particle/ppafm/wiki/PPAFM-GUI Launches the graphical user interface for the GPU version of the Probe-Particle Model (ppafm). This command requires the GUI support to be installed. ```Shell ppafm-gui ``` -------------------------------- ### Configure Simulation Parameters Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python 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', } ``` -------------------------------- ### Define and Allocate Simulation Arrays Source: https://github.com/probe-particle/ppafm/wiki/scripting 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`). ```Python 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) ) ``` -------------------------------- ### Google-Style Docstring Example in Python Source: https://github.com/probe-particle/ppafm/wiki/For-Developers 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. ```Python 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. ''' ``` -------------------------------- ### Handle Periodic Boundary Conditions Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python if PP.params['PBC' ]: iZs,Rs,Qs = PP.PBCAtoms( iZs, Rs, Qs, avec=PP.params['gridA'], bvec=PP.params['gridB'] ) ``` -------------------------------- ### Load Atomic Structure Source: https://github.com/probe-particle/ppafm/wiki/scripting 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`). ```Python atoms = basUtils.loadAtoms('input.xyz', elements.ELEMENT_DICT ) Rs = np.array([atoms[1],atoms[2],atoms[3]]); iZs = np.array( atoms[0]) ``` -------------------------------- ### Configure AFM Simulation Parameters (INI) Source: https://github.com/probe-particle/ppafm/wiki/Complex-Tip-alias-Double-Probe-Particle 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. ```INI 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 ``` -------------------------------- ### Load Atomic Species and LJ Parameters Source: https://github.com/probe-particle/ppafm/wiki/scripting 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`. ```Python Qs = np.array( atoms[4] ) FFparams = PP.loadSpecies ( 'atomtypes.ini' ) C6,C12 = PP.getAtomsLJ( PP.params['probeType'], iZs, FFparams ) ``` -------------------------------- ### ProbeParticle: Lenard-Jones and Electrostatic Potential Calculation Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python 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' ) ``` -------------------------------- ### ProbeParticle: 3D-Scan with Tip Relaxation Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python 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() ``` -------------------------------- ### Remove OpenMP Headers and Calls (C++) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```C++ #include ``` ```C++ omp_* function calls ``` -------------------------------- ### Disable OpenMP in Makefile (C++) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```C++ CPPFLAGS= -fPIC -std=c++11 -O2 -mtune=native -fopenmp ``` -------------------------------- ### Initialize AFMulator from Parameters File Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md Constructs an AFMulator instance by loading simulation parameters from a specified INI file, providing a convenient way to reuse configurations. ```python from ppafm.opencl import AFMulator afmulator = AFMulator.from_params("./params.ini") ``` -------------------------------- ### Modify Python for OpenMP (Python) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```Python relaxedScan3D() rather than relaxedScan3D_omp() ``` -------------------------------- ### Configure ExampleTrainer for AFM Simulations Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md 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). ```Python 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 ``` -------------------------------- ### Linux: Resolve Externally Managed Environment Error Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```Shell python3 -m venv /home/prokop/venvs/ppafm source ~/venvs/ppafm/bin/activate ``` -------------------------------- ### Set OpenMP Threads (Shell) Source: https://github.com/probe-particle/ppafm/wiki/Install-ppafm 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. ```Shell export OMP_NUM_THREADS=ncores ``` -------------------------------- ### Creating a New Release with Bumpver Source: https://github.com/probe-particle/ppafm/wiki/For-Developers 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. ```Bash pip install -e '.[dev]' bumpver update [--major|--minor|--patch] [--tag-num --tag [alpha|beta|rc]] ``` ```Bash bumpver update --minor ``` ```Bash bumpver update --patch ``` ```Bash bumpver update --tag-num ``` ```Bash bumpver update --patch --tag alpha ``` ```Bash bumpver update --tag final ``` -------------------------------- ### Initialize AFMulator with Simulation Parameters Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md 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. ```python 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] ) ``` -------------------------------- ### List Available OpenCL Devices Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md Lists all OpenCL-enabled compute devices usable by ppafm, which is helpful for selecting a specific device if multiple are available. ```bash ppafm-gui --list-devices ``` -------------------------------- ### View XSF Files GUI Source: https://github.com/probe-particle/ppafm/wiki/Command-line-interface A graphical user interface for loading and viewing .xsf files. Users can browse through the slices of the 3D grid data. ```Python 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_()) ``` -------------------------------- ### Run GPU-Accelerated AFM Simulation with AFMulator Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md 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. ```Python 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] ) ``` -------------------------------- ### Run AFM Simulation and Get Image Array Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md Executes the AFM simulation using the configured AFMulator and molecular data. The resulting force-field images are returned as a NumPy array. ```python 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() ``` -------------------------------- ### Initialize AFMulator with Lennard-Jones and point-charge electrostatics Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/afmulator-tutorial.md 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. ```python afm_images = afmulator(xyzs, Zs, qs, rho_sample=None) ``` -------------------------------- ### Automatic Geometry Adjustment Source: https://github.com/probe-particle/ppafm/wiki/scripting 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. ```Python 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() ``` -------------------------------- ### Initialize InverseAFMtrainer with XYZ files Source: https://github.com/probe-particle/ppafm/blob/main/doc/sphinx/source/tutorials/generator-tutorial.md 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. ```Python 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 ``` -------------------------------- ### Shift Experimental AFM Images GUI Source: https://github.com/probe-particle/ppafm/wiki/Command-line-interface A GUI application for shifting experimental AFM images. It allows users to align reference data with machine-learned predictions for comparison, as used in research papers. ```Python import tkinter as tk class ExpShifterGUI: def __init__(self, master): self.master = master master.title("Experimental AFM Image Shifter") # GUI elements for loading, shifting, and comparing images # root = tk.Tk() # gui = ExpShifterGUI(root) # root.mainloop() ``` -------------------------------- ### Interpolate 3D Vector Force Field Source: https://github.com/probe-particle/ppafm/wiki/Home 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. ```Python interpolate3DvecWrap() ```