AFM: R to Python Converter

Park AFM with Python

tutorial
AFM
code
Importing AFM images in R and then displaying with Python in Quarto
Author

Thomas Gredig

Published

September 16, 2024

This document shows you how to use Python with Park AFM images. First step is to load the AFM image using the R package. It means that you have to install, the nanoAFMr package.

Code
# install.packages("devtools")
# devtools::install_github("thomasgredig/nanoAFMr")
library(nanoAFMr)
Please cite nanoAFMr 2.3.1 - see https://doi.org/10.5281/zenodo.7464877
Code
f = AFM.getSampleImages(type="tiff")[1]
a = AFM.import(f)
plot(a)
Graphing: Topography

The next step is to select the channel and convert the data into a matrix. The AFM.raster function returns a DataFrame with 3 components, x,y,z, which are in units of nanometers.

Code
d = AFM.raster(a, no=1)
str(d)
'data.frame':   65536 obs. of  3 variables:
 $ x: num  0 9.8 19.6 29.4 39.2 ...
 $ y: num  0 0 0 0 0 0 0 0 0 0 ...
 $ z: num  0.189 0.242 0.309 0.149 -0.179 ...

Now use the reticulate package in R, see R interface to Python, to be able to launch Python from within R.

Next use Python to graph the data with r.d which has the r. prefix. We can now look at the first few elements in z portion of the array:

Code
afmData = r.d
afmData['z'][0:10]
0    0.188732
1    0.242283
2    0.308945
3    0.148716
4   -0.179173
5   -0.714560
6   -1.727324
7   -1.825666
8   -1.850259
9   -0.976103
Name: z, dtype: float64

Reshape the image into a square.

Code
import numpy as np


z = np.array(afmData['z'])
sqrt_z = int(np.sqrt(z.size))
z = z.reshape(sqrt_z, sqrt_z)
x_max = max(afmData['x'])
y_max = max(afmData['y'])
z.shape, x_max, y_max
((256, 256), 2500.0, 2500.0)
Code
import matplotlib.pyplot as plt
plt.imshow(z,
 extent =[0, x_max, 0,y_max],
 origin ='lower') 
plt.show()

source: nanoAFM_R_to_Python.qmd

Citation

BibTeX citation:
@misc{gredig2024,
  author = {Gredig, Thomas and Gredig, Thomas},
  title = {AFM: {R} to {Python} {Converter}},
  date = {2024-09-16},
  url = {https://www.csulb.edu/~tgredig/posts/R-Python-Converter/nanoAFM_R_to_Python.html},
  langid = {en}
}
For attribution, please cite this work as:
Gredig, Thomas, and Thomas Gredig. 2024. “AFM: R to Python Converter.” https://www.csulb.edu/~tgredig/posts/R-Python-Converter/nanoAFM_R_to_Python.html.