How to calculate the distance of adsorbent atoms from the surface

simple way of determining a distance to a surface

when an interaction is established between and adsorbate and a surface, the surface is deformed; this script calculated the average of the z coordinate of all surface atoms and takes that as reference to which the distance of adsorbent atoms can be calculated.

This script creates lists and hashes and
sorts the values of a hash;

ATTENTION!!
this script needs the standard orientation
the slab document must have the vaccum in C direction (i.e. C along Z, B in YZ plane
if not --> right click in .xsd document and go /Lattice Parameters/Advanced to change
Displaystyle lattice original

The script:

#!perl

use strict;
use MaterialsScript qw(:all);

#ATTENTION!!
#this script needs the standard orientation
#the slab document must have the vaccum in C direction
#C along Z, B in YZ plane
# if not --> right click in .xsd document and go /Lattice Parameters/Advanced to change
# Displaystyle lattice original

#############################################################
#####################CHANGE TO YOUR NEEDS##################################

#Enter the name of your file
my \$doc = \$Documents {"Pt (1 0 0).xsd"};

my \$atoms = \$doc-> DisplayRange->Atoms;

#how many atoms are in the surface?
my \$Nosurf = 9;

#the total number of atoms adsorbed?
my \$ads = 4;

##############################################################

#I create an array of all the z-coordinates of my system

my @data;

foreach my \$atom (@\$atoms) {
my \$z = \$atom->Z;
push(@data, \$z);

}

#get the surface data

my @sorted_data = sort { \$b <=> \$a} @data;

my @surface = @sorted_data[\$ads..\$Nosurf+\$ads-1];

#now I add all the z-coordinates up and calculate the average

my \$sum;

foreach my \$n (@surface) {

\$sum += \$n;}


my \$average = \$sum/\$Nosurf;

print "The average z-coordinate of the surface atoms is \$average\n\n";

##here we create a hash
## the keys are the atomsymbols_a number
## the values are the z-coordinates

my %adsorbate;
for (my \$i=0; \$i< \$atoms -> Count; ++\$i){
my \$z= \$atoms->Item(\$i)->Z;
my \$name = join ("_",\$atoms->Item(\$i) -> ElementSymbol, "\$i");
\$adsorbate{\$name} = \$z;

}

#now lets sort the hash by values
my \$count=0;
print "Distances for each atom from the surface:\n\n";
my @sorted_keys = sort hashValue keys (%adsorbate);

foreach my \$key (@sorted_keys) {
print "\$key:",(\$adsorbate{\$key}-\$average),"\n";

}

###########A subroutine#######################

sub hashValue {
(\$adsorbate{\$b} <=> \$adsorbate{\$a});
}
###########################################