marginparsep has been altered.
topmargin has been altered.
marginparpush has been altered.
The page layout violates the ICML style. Please do not change the page layout,
or include packages like geometry, savetrees, or fullpage, which change it for
you. We’re not able to reliably undo arbitrary changes to the style. Please
remove the offending package(s), or layout-changing commands and try again.

Unsupervised Out-of-Distribution Detection with Diffusion Inpainting

Zhenzhen Liu * 1  Jin Peng Zhou * 1  Yufan Wang 1  Kilian Q. Weinberger 1

††footnotetext: *Equal contribution 1Cornell University. Correspondence to:
Zhenzhen Liu<EMAIL_ADDRESS>Jin Peng Zhou<EMAIL_ADDRESS>

###### Abstract

Unsupervised out-of-distribution detection (OOD) seeks to identify out-of-
domain data by learning only from unlabeled in-domain data. We present a novel
approach for this task – Lift, Map, Detect (LMD) – that leverages recent
advancement in diffusion models. Diffusion models are one type of generative
models. At their core, they learn an iterative denoising process that
gradually maps a noisy image closer to their training manifolds. LMD leverages
this intuition for OOD detection. Specifically, LMD lifts an image off its
original manifold by corrupting it, and maps it towards the in-domain manifold
with a diffusion model. For an out-of-domain image, the mapped image would
have a large distance away from its original manifold, and LMD would identify
it as OOD accordingly. We show through extensive experiments that LMD achieves
competitive performance across a broad variety of datasets.

##  1 Introduction

Figure 1: The pictorial intuition behind LMD for OOD detection. A diffusion
model learns a mapping to the in-domain manifold. LMD lifts an image off its
manifold by masking, and uses the diffusion model to move it towards the in-
domain manifold. An in-domain image would have a much smaller distance between
the original and mapped locations than its out-of-domain counterparts.

Out-of-distribution (OOD) detection seeks to classify whether a data point
belongs to a particular domain. It is especially important, because machine
learning models typically assume that test-time samples are drawn from the
same distribution as the training data. If the test data do not follow the
training distribution, they can inadvertently produce non-sensical results.
The increased use of machine learning models in high-stake areas, such as
medicine Hamet & Tremblay (2017) and criminal justice Rigano (2019), amplifies
the importance of OOD detection. For example, if a doctor mistakenly inputs a
chest X-ray into a brain tumor detector, the model would likely still return a
prediction – which would be meaningless and possibly misleading.

Previous researches have studied OOD detection under different settings:
supervised and unsupervised. Within the supervised setup, the supervision can
originate from different sources. In the most informed setting, one assumes
access to representative out-of-domain samples. These allow one to train an
OOD detector as a classifier distinguishing in-domain from out-of-domain data,
and achieves high performance Hendrycks et al. (2018); Ruff et al. (2019) – as
long as the out-of-domain data do not deviate from the assumed out-of-domain
distribution. In many practical applications, however, such knowledge is
unattainable. In fact, out-of-domain data can be highly diverse and
unpredictable. A significantly more relaxed assumption is to only require
access to an in-domain classifier or class labels. Under this setting, methods
such as Hendrycks & Gimpel (2016); Liang et al. (2017); Lee et al. (2018);
Huang et al. (2021); Wang et al. (2022) have achieved competitive performance.
Although less informed, this setting relies on two implicit assumptions: the
in-domain data have well-defined classes, and there are sufficiently plenty
data with class annotations. In practice, these assumptions often cannot be
met. Unlabeled data do not require the expensive human annotation, and thus
are often readily available in large quantity. Ideally, one would like to
build an OOD detector that only requires unlabeled in-domain data during
training.

Recently, a class of generative models – the diffusion models (DM) Ho et al.
(2020); Song et al. (2020) – have gained increasing popularity. DMs formulate
two processes: The forward process converts an image to a sample drawn from a
noise distribution by iteratively adding noise to its pixels; the backward
process maps a noise image towards a specific image manifold by iteratively
removing noise from the image. A dedicated neural network is trained to
perform the denoising steps in the backward process.

In this paper, we argue that we can leverage the property that the diffusion
model learns a mapping to a manifold, and turn it into a strong unsupervised
OOD detector. Intuitively, if we lift an image from its manifold, then the
lifted image can be mapped back to its original vicinity with a diffusion
model trained over the same manifold. If instead the diffusion model is
trained over a different manifold, it would attempt to map the lifted image
towards its own training manifold, causing a large distance between the
original and mapped images. Thus, we can detect out-of-domain images based on
such distance.

To this end, we propose a novel unsupervised OOD detection approach called
Lift, Map, Detect (LMD) that captures the above intuition. We can lift an
image from its original manifold by corrupting it. For example, a face image
masked in the center clearly does not belong to the face manifold anymore. As
shown by Song et al. (2020); Lugmayr et al. (2022), the diffusion model can
impute the missing regions of an image with visually plausible content, a
process commonly referred as inpainting, without retraining. Thus, we can map
the lifted image by inpainting with a diffusion model trained over the in-
domain data. We can then use a standard image similarity metric to measure the
distance between the original and mapped images, and detect an out-of-domain
image when we observe a large distance. Figure 1 illustrates an example: A
diffusion model trained on face images maps a lifted in-domain face image
closer to the original image than an out-of-domain fire hydrant counterpart.

To summarize our contributions:

  1. 1.

We propose a novel approach LMD for unsupervised OOD detection, which directly
leverages the diffusion model’s manifold mapping ability without retraining.
We introduce design choices that improve the separability between in-domain
and out-of-domain data.

  2. 2.

We show that LMD is versatile through experiments on datasets with different
coloring, variability and resolution.

  3. 3.

We provide qualitative visualization and quantitative ablation results that
verify the basis of our approach and our design choices.

##  2 Background

Unsupervised OOD Detection. We formalize the unsupervised OOD detection task
as follows: Given a distribution of interest $\mathcal{D}$, one would like to
build a detector that decides whether a data point $\mathbf{x}$ is drawn from
$\mathcal{D}$. The detector is only built upon unlabeled in-distribution
samples $\mathbf{x_{1}},\cdots,\mathbf{x_{n}}\sim\mathcal{D}$. Given a test
data point $\mathbf{x}$, the detector outputs an OOD score $s(\mathbf{x})$,
where a higher $s(\mathbf{x})$ signifies that $\mathbf{x}$ is more likely
_not_ to be sampled from $\mathcal{D}$.

Existing works can be roughly divided into three categories: likelihood-based,
reconstruction-based, and feature-based. Likelihood-based approaches date back
to Bishop (1994). At a high level, one fits the in-domain distribution with a
model, and evaluates the likelihood of the test data under the model. Recent
approaches often employ a deep generative model that supports likelihood
computation, such as PixelCNN++ Salimans et al. (2017) or Glow Kingma &
Dhariwal (2018). However, several works Choi et al. (2018); Nalisnick et al.
(2018); Kirichenko et al. (2020) have found that generative models sometimes
assign higher likelihood to out-of-domain data.

This issue can be alleviated in various ways. One line of work adopts a
likelihood ratio approach: Ren et al. (2019) trains a semantic model and a
background model, and takes the ratio of the likelihoods from the two models.
Serrà et al. (2019) observes a negative correlation between an image’s
complexity and its likelihood, and adjusts the likelihood by the compression
size. Xiao et al. (2020) optimizes the model configuration to maximize a test
image’s likelihood, and measures the amount of likelihood improvement. Another
line of work adopts a typicality test approach Nalisnick et al. (2019);
Morningstar et al. (2021); Bergamin et al. (2022). They examine the
distribution of in-domain likelihood or other model statistics, and evaluate
the typicality of the test data model statistics through hypothesis testing or
density estimation. Lastly, several works Maaløe et al. (2019); Kirichenko et
al. (2020) seek to improve the design choices of generative models.

Reconstruction-based approaches evaluate how well a data point can be
reconstructed by a model learned over the in-domain data. Our approach LMD
falls into this category. Within this line of work, Sakurada & Yairi (2014);
Xia et al. (2015); Zhou & Paffenroth (2017); Zong et al. (2018) encode and
decode data with autoencoders. Schlegl et al. (2017); Li et al. (2018) perform
GAN Goodfellow et al. (2014) inversion for a data point, and evaluate its
reconstruction error and discriminator confidence under the inverted latent
variable. Additionally, concurrent to our work, Graham et al. (2022) leverages
diffusion models to reconstruct images at varied diffusion steps, while we
mask and inpaint an image repeatedly with fixed steps. The two approaches are
complementary to each other.

Feature-based approaches featurize data in an unsupervised manner, and fit a
simple OOD detector like a Gaussian Mixture Model over the in-domain features.
Denouden et al. (2018) leverages the latent variables of an autoencoder, and
evaluates the Mahalanobis distance in the latent space along with the data
reconstruction error. Ahmadian & Lindsten (2021) extracts low-level features
from the encoder of an invertible generative model. Hendrycks et al. (2019);
Bergman & Hoshen (2020); Tack et al. (2020); Sehwag et al. (2021) learn a
representation over the in-domain data through self-supervised training; Xiao
et al. (2021) further shows that one can instead use a strong pretrained
feature extractor while maintaining comparable performance.

Diffusion Models. In this section, we provide a brief overview of the
diffusion models (DM). It is a type of generative model that learns the
distribution of its training data. DM formulates a forward process of
corrupting data by adding noise to them, commonly referred as diffusion. It
learns the reverse process of gradually producing a less noisy sample,
commonly referred as denoising. One classic formulation of DM is called
Denoising Diffusion Probabilistic Models (DDPMs) Sohl-Dickstein et al. (2015);
Ho et al. (2020). Specifically, starting from a data sample $x_{0}$, each step
$t=1,2,\cdots,T$ of the diffusion process injects Gaussian noise given by

$q(x_{t}|x_{t-1})=\mathcal{N}(x_{t};\sqrt{1-\beta_{t}}x_{t},\beta_{t}\mathbf{I})$
(1)

where $\beta_{t}$ follows a fixed variance schedule. The DDPM with a prior
distribution $x_{T}\sim\mathcal{N}(0,1)$ learn the denoising process given by

$p_{\theta}(x_{t-1}|x_{t})=\mathcal{N}(x_{t-1};\mu_{\theta}(x_{t},t),\Sigma_{\theta}(x_{t},t))$
(2)

where both $\mu_{\theta}(x_{t},t)$ and $\Sigma_{\theta}(x_{t},t)$ are learned
by a neural network parametrized by $\theta$. Note that other formulations of
DMs, such as score-based generative models Song & Ermon (2019) and stochastic
differential equations Song et al. (2020), also support diffusion and
denoising processes. Since LMD is agnostic to different formulations of DMs,
we refer the reader to Yang et al. (2022) for a more detailed mathematical
description of the other formulations.

##  3 Lift, Map, Detect

Figure 2: High-level workflow of LMD. LMD employs a diffusion model learned
over the in-domain manifold. It first repeatedly lifts an image from its
manifold by masking it, and maps it towards the diffusion model’s training
manifold by inpainting. Then, it inspects the median distance between the
original image and each mapped image to detect out-of-domain images. As out-
of-domain images cannot be mapped back to their own manifolds, they have
larger distances.

The intuition behind our algorithm, Lift, Map, Detect (LMD), is illustrated in
Figure 1. In a nutshell, we employ a diffusion model learned over the in-
domain data, which provides a mapping towards the underlying in-domain image
manifold. To test whether an image is in-domain or out-of-domain, we lift the
image off its original manifold through corruption, and map the lifted image
to the in-domain manifold with the trained DM. If the original image is in-
domain, it is mapped back to its manifold, near its original location. If it
is out-of-domain, the image is mapped to a different manifold, likely leaving
a large distance between the original image and the mapped image. Figure 2
shows the high-level workflow of LMD. Algorithm 2 summarizes the key steps of
LMD in pseudocode.

Lifting Images. To lift an image off its manifold, we need to corrupt the
image so that it no longer appears to be from its original manifold.
Concretely, we apply a mask to the image so that part of it is completely
removed. Since various mask patterns and sizes can be used, masking provides a
direct and flexible way to lift the image from the manifold. For example, it
is intuitive to see that the larger the mask is, the further away the image is
lifted from the manifold.

Mapping the Lifted Images. Since diffusion models (DM) can perform inpainting
without retraining Song et al. (2020); Lugmayr et al. (2022) (see Algorithm
1), we naturally employ a DM and use inpainting to map the lifted images.
Specifically, we employ a DM parametrized by $\theta_{in}$ that is trained on
the in-domain data. This DM can model the in-domain distribution well enough
to map a lifted in-domain image back to its original vicinity. Meanwhile, the
DM should have almost no knowledge about the out-of-domain manifold. Thus, it
naturally maps a lifted out-of-domain image towards the DM’s training
manifold, which is the in-domain manifold. This phenomenon leads to a larger
distance between the original and mapped images for out-of-domain images than
the in-domain ones. For ease of reference, we also refer these mapped images
as reconstructed images or simply reconstructions.

Algorithm 1 Inpaint

Input: original image $x_{orig}$, binary mask $M$ where 0 indicates region to
be inpainted, diffusion model $\theta$

Output: inpainted image $x_{inp}$

for $i=T$ to $1$ do

if $i==T$ then

$x_{inp}$ $\leftarrow$ sample from noise distribution

end if

$x_{orig}^{\prime}$ $\leftarrow$ diffuse($x_{orig};\>\theta$) to step $i-1$

$x_{inp}$ $\leftarrow$ denoise($x_{inp};\>\theta$) to step $i-1$

$x_{inp}$ $\leftarrow$ $x_{orig}^{\prime}\cdot M+x_{inp}\cdot(1-M)$

end for

return $x_{inp}$

Reconstruction Distance Metric. We adopt the Learned Perceptual Image Patch
Similarity (LPIPS) Zhang et al. (2018) metric, a standard and strong metric
that captures the perceptual difference between images. Since LPIPS assigns
higher values to more dissimilar images, we compute the LPIPS between original
and reconstructed images, and use it directly as the OOD score. We perform
detailed ablation on different reconstruction distance metrics in Section 4.4.

It is worth noting that mapping lifted images is the most crucial component.
The hypothesis – in-domain reconstructions are closer to their original images
than the out-of-domain ones – ensures the effectiveness of LMD. With this in
mind, we now discuss two simple and yet effective ways that can further
improve detection performance consistently: multiple reconstructions and novel
masking strategy.

Multiple Reconstructions. The DM inpainting process inherently involves
multiple sampling steps. Occasionally, due to randomness, DM could provide
dissimilar reconstructions for in-domain data, or similar reconstructions for
out-of-domain data. This could make the reconstruction distance of the in-
domain and out-of-domain images less separable, and hence leads to suboptimal
OOD detection performance. To reduce the randomness, we perform multiple
lifting and mapping attempts for each image. We calculate the OOD score from
each attempt, and take the median111In our preliminary experiments, we find
that median works the best than other simple aggregation methods such as mean.
OOD score as the final OOD score for an image. As shown in 4.3, the simple
median aggregation already provides strong performance. For further
improvement, one may use a parameterized model to learn the distribution of
the reconstruction distance across multiple attempts. We leave this to future
work.

Algorithm 2 Lift, Map, Detect (LMD)

Input: test image $x$, in-domain diffusion model $\theta_{in}$

Output: OOD score of test image $x$

for $i=1$ to $r$ do

$M_{r}$ $\leftarrow$ Get_Mask($i$)

$x_{r}^{\prime}$ $\leftarrow$ Inpaint($x,M_{r},\theta_{in}$)

$d_{r}$ $\leftarrow$ Distance($x,x_{r}^{\prime}$)

end for

return Aggregate($d_{1},\ldots,d_{r}$)

Novel Masking Strategy. The extent to which we mask an image is crucial to the
detection performance. If the size of the mask is too large (or too small),
the reconstruction distance for both in-domain and out-of-domain images would
be very large (or very small). Indeed, if the mask covers the entire image,
the reconstruction will be independent of the original image. In this case, if
the in-domain manifold contains diverse images, an in-domain reconstruction
can be far from its original image despite still being on the same manifold.
Therefore, a suitable masking strategy should leave enough context to allow
in-domain reconstructions to be similar to the original ones. To this end, we
propose to use a checkerboard mask pattern. It divides an image into an
$N\times N$ grid of image patches independent of the image size, and masks out
half of the patches similar to a checkerboard. When multiple reconstruction
attempts are performed, we also invert the masked and unmasked regions at each
attempt. We call this masking strategy alternating checkerboard $N\times N$
(see Figure 3). Alternating checkerboard ensures all regions of the image to
be masked with just two attempts. This avoids situations in which the
distinguishing features of an out-of-domain image is never masked. LMD by
default sets $N=8$; ablation study on different mask choices can be found in
Table 2.

Figure 3: The alternating checkerboard mask pattern. We invert regions that
are masked and unmasked at each reconstruction attempt. The example in the
figure is $8\times 8$.

##  4 Experiments

###  4.1 Experiment Settings

Evaluation Metric. LMD outputs an OOD score for each input, so in practice we
need to apply a threshold to binarize the decision. In the experiments, we
follow Hendrycks & Gimpel (2016); Ren et al. (2019); Xiao et al. (2021), and
use the area under Receiver Operating Characteristic curve (ROC-AUC) as our
quantitative evaluation metric.

Baselines. We compare our methods with four existing baselines: Likelihood
Bishop (1994), Input Complexity Serrà et al. (2019), Likelihood Regret Xiao et
al. (2020), and Pretrained Feature Extractor + Mahalanobis Distance Xiao et
al. (2021). Likelihood is obtained from the DM using the implementation from
Song et al. (2020) 222https://github.com/yang-song/score_sde_pytorch. For both
Input Complexity and Likelihood Regret, we adapt the official GitHub
repository of Likelihood Regret333https://github.com/XavierXiao/Likelihood-
Regret. Specifically, to compute the Input Complexity, we use the likelihood
calculated from the DM for a fair comparison, and convert the compression size
to bits per dimension; we use the PNG compressor, because it yields the best
performance among all available compressors in the GitHub repository.
Pretrained Feature Extractor + Mahalanobis Distance is implemented by
ourselves, as there is no existing publicly available implementations to our
best knowledge.

Datasets. We perform OOD detection pairwise among CIFAR10 Krizhevsky (2009),
CIFAR100 Krizhevsky (2009) and SVHN Netzer et al. (2011), and pairwise among
MNIST LeCun et al. (2010), KMNIST Clanuwat et al. (2018) and FashionMNIST Xiao
et al. (2017). For LMD and all the baselines, we use the training set of the
in-domain dataset to train the model if needed, and evaluate the performance
on the full test set of in-domain and out-of-domain datasets. Additionally, to
demonstrate our performance on higher resolution images, we show qualitative
results on CelebA-HQ Karras et al. (2017) as in-domain and ImageNet
Russakovsky et al. (2015) as out-of-domain.

Table 1: ROC-AUC performance of LMD against various baselines on 12 pairs of
datasets. Higher is better.
ID | OOD | Likelihood | IC | LR | Pretrained | LMD
---|---|---|---|---|---|---
CIFAR-10 | CIFAR-100 | 0.520 | 0.568 | 0.546 | 0.806 | 0.607
| SVHN | 0.180 | 0.870 | 0.904 | 0.888 | 0.992
CIFAR100 | CIFAR-10 | 0.495 | 0.468 | 0.484 | 0.543 | 0.568
| SVHN | 0.193 | 0.792 | 0.896 | 0.776 | 0.985
SVHN | CIFAR-10 | 0.974 | 0.973 | 0.805 | 0.999 | 0.914
| CIFAR-100 | 0.970 | 0.976 | 0.821 | 0.999 | 0.876
MNIST | KMNIST | 0.948 | 0.903 | 0.999 | 0.887 | 0.984
| FashionMNIST | 0.997 | 1.000 | 0.999 | 0.999 | 0.999
KMNIST | MNIST | 0.152 | 0.951 | 0.431 | 0.582 | 0.978
| FashionMNIST | 0.833 | 0.999 | 0.557 | 0.993 | 0.993
FashionMNIST | MNIST | 0.172 | 0.912 | 0.971 | 0.647 | 0.992
| KMNIST | 0.542 | 0.584 | 0.994 | 0.730 | 0.990
Average |  | 0.581 | 0.833 | 0.783 | 0.821 | 0.907

###  4.2 Implementation Details of LMD

We adapt the diffusion model implementation from Song et al. (2020). For
experiments in Table 1, we use Song et al. (2020)’s pretrained checkpoint for
CIFAR10, and we train DMs on the training set of the in-domain dataset for all
the other datasets. We evaluate the OOD scores of the full in-domain and out-
of-domain test sets. The inpainting reconstruction is repeated 10 times with
alternating checkerboard $8\times 8$ masks (Figure 3). For CelebA-HQ vs.
ImageNet, we observe that CelebA-HQ does not have a train/test set split, and
its pretrained checkpoint is trained over the full dataset. Thus, to avoid
potential memorization issue, we use the pretrained FFHQ Karras et al. (2019)
checkpoint instead. We randomly sample a subset of size 100 from each dataset,
and standardize all images to $256\times 256$. We explore three mask choices:
checkerboard $4\times 4$, checkerboard $8\times 8$, and a square centered
mask. We reconstruct each image only once. We use LPIPS as the reconstruction
distance metric to calculate the OOD score for all the experiments.

###  4.3 Experimental Results

Table 1 shows the performance of LMD and the baselines on various pairs of
datasets. LMD achieves the highest performance on five pairs, with a maximum
improvement of 10% (CIFAR100 vs. SVHN). LMD also achieves the second highest
performance on five other pairs, and has the highest average ROC-AUC. This
shows that LMD is consistent and versatile. We observe that the performance of
the baselines are competitive on some pairs but limited on the others.

Figure 5 shows examples of the original, masked and inpainted images for three
pairs. We show four reconstruction examples for each image, two with
checkerboard mask and two with inverted checkerboard mask. The diffusion
models reconstruct the in-domain images relatively accurately, while
introducing a lot of artifacts in the out-of-domain inpaintings. For example,
when SVHN is out-of-domain, the noise almost overwhelms the signals in the
inpaintings.

Figure 6 shows the qualitative results and the ROC-AUC for CelebA-HQ vs.
ImageNet. Checkerboard $8\times 8$ performs competitively, achieving an ROC-
AUC of 0.991 without any repeated reconstructions. Visually, the in-domain
inpaintings look almost identical to the original images, while the out-of-
domain inpaintings are locally incoherent. In this specific setting,
checkerboard $4\times 4$ and center masks yield slightly better performance.
This is probably because faces are highly structured and provide strong
inductive bias. Thus, with larger contiguous masked regions, the DM can still
produce reasonably authentic reconstructions for the in-domain images, while
being able to introduce more obvious artifacts for the out-of-domain images.
Consequently, the reconstruction qualities of the two domains are more
distinguishable. More discussion on mask choices can be found in Section 4.4.

Figure 4: Visualization of the masks used in the mask ablation. For the random
patch mask, this figure only shows one example; we sample a different pattern
at each reconstruction attempt. Figure 5: Reconstruction examples from three
dataset pairs. “Orig.” stands for the original image; “Inp.” stands for the
inpainted image. In general, the in-domain reconstructions are close to their
original images, while the out-of-domain reconstructions are noisy and
different from the original ones. Figure 6: Reconstruction examples from
CelebA-HQ (in-domain) and ImageNet (out-of-domain) using different masks. For
out-of-domain inpaintings, the checkerboard masks introduce locally incoherent
artifacts, while the center mask introduces face-like artifacts. This makes
the out-of-domain images highly distinguishable. Table 2: ROC-AUC on three
dataset pairs with different mask types. Alternating checkerboard $8\times 8$
shows strong and consistent performance.

Mask Type | CIFAR10 vs. CIFAR100 | CIFAR10 vs. SVHN | MNIST vs. KMNIST
---|---|---|---
Alternating Checkerboard $4\times 4$ | 0.594 | 0.987 | 0.923
Alternating Checkerboard $8\times 8$ | 0.607 | 0.992 | 0.984
Alternating Checkerboard $16\times 16$ | 0.597 | 0.981 | 0.997
Fixed Checkerboard $8\times 8$ | 0.601 | 0.990 | 0.974
Center | 0.570 | 0.978 | 0.479
Random Patch | 0.591 | 0.990 | 0.912

###  4.4 Ablation

Effects of Mask Choices. Table 2 shows ablation results on different types of
mask patterns (see Figure 4). Specifically, we examine the following patterns:
alternating checkerboard $4\times 4$ and $16\times 16$, a fixed non-
alternating $8\times 8$ checkerboard, a square centered mask covering one-
fourth of an image (center), and a random patch mask covering 50% of an
$8\times 8$ patch grid (random patch) introduced in Xie et al.
(2022)444https://github.com/microsoft/SimMIM.

Alternating checkerboard $8\times 8$ performs consistently across the three
datasets, while other patterns have fluctuation in their performance. In
particular, alternating checkerboard $4\times 4$ performs poorly on MNIST vs.
KMNIST. This suggests that if the masked patches are too large, both in-domain
and out-of-domain reconstructions may be dissimilar from the original images.
Fixed checkerboard $8\times 8$ performs only slightly worse than its
alternating counterpart, usually with a performance drop of less than 0.01.
This may be because for these datasets, the distinguishing features of the in-
domain and out-of-domain images exist in many patches. Thus, they can already
be captured well enough by the fixed $8\times 8$ mask. Nevertheless, the
alternating checkerboard pattern should still be preferred, since it can mask
the entire image across multiple reconstruction attempts. Not surprisingly,
the center mask exhibits very poor performance (0.444) on MNIST vs. KMNIST, as
it removes too much information from the images. Lastly, we find that the
random patch mask also performs competitively.

Effects of Reconstruction Distance Metrics. LMD needs to assess the
reconstruction distance of the inpaintings from the DM, so we explore three
off-the-shelf reconstruction distance metrics: Mean Squared Error (MSE),
Structural Similarity Index Measure (SSIM) Wang et al. (2003), and Learned
Perceptual Image Patch Similarity (LPIPS) Zhang et al. (2018). Additionally,
Xiao et al. (2021) demonstrates strong performance using SimCLRv2 Chen et al.
(2020) representations, so we experiment with a SimCLRv2-based error metric
too. Specifically, we calculate the cosine distance between the SimCLRv2
representations of the original and reconstructed images, which we simply
refer as SimCLRv2. These four reconstruction distance metrics range from
shallow reference based to deep feature based metrics.

Table 3: ROC-AUC on three dataset pairs with different reconstruction distance
metrics. LPIPS shows strong and consistent performance.

Recon. Metric | CIFAR10 | MNIST | KMNIST
---|---|---|---
| vs. CIFAR100 | vs. KMNIST | vs. MNIST
MSE | 0.548 | 0.998 | 0.835
SSIM | 0.624 | 0.997 | 0.922
LPIPS | 0.607 | 0.984 | 0.978
SimCLRv2 | 0.713 | 0.983 | 0.920

We summarize the results of three dataset pairs in Table 3. LPIPS is
competitive on all three dataset pairs, while MSE, SSIM and SimCLRv2 fluctuate
in their performance. Interestingly, on CIFAR10 vs. CIFAR100, SimCLRv2
outperforms other metrics significantly, with an improvement of 0.09. In Table
1, Xiao et al. (2021) also outperforms all other methods on CIFAR10 vs.
CIFAR100 using SimCLRv2 representations. This indicates that some
reconstruction distance metrics can be particularly suitable for specific
domains.

Number of Reconstruction Attempts per Image. We also study the effect of the
number of reconstruction attempts on the performance. Figure 7 shows the ROC-
AUC from one attempt to ten attempts per image for two pairs of datasets. In
both dataset pairs, increasing the number of attempts almost always improves
the ROC-AUC. The improvement is especially significant initially, and
saturates at around ten attempts. The improvement is consistent across all
four error metrics, further supporting the effectiveness of LMD’s multiple
reconstructions approach.

(a) MNIST vs. KMNIST

(b) KMNIST vs. MNIST

Figure 7: ROC-AUC against number of reconstruction attempts on two pairs of
datasets. As the number of reconstruction attempts increases, the OOD
detection performance improves regardless of the choice of the reconstruction
distance metric.  Table 4: ROC-AUC performance of our OOD detection framework
with an alternative lifting and mapping instantiation – diffusion and
denoising. It shows strong performance, although it is slightly outperformed
by our default choice of masking and inpainting.

Mapping | CIFAR10 | CIFAR10 | FashionMNIST
---|---|---|---
Method | vs. CIFAR100 | vs. SVHN | vs. MNIST
Denoising | 0.600 | 0.976 | 0.941
Inpainting | 0.607 | 0.992 | 0.992

Alternative Way of Lifting and Mapping. Alternatively, we can lift an image by
diffusion, and map it by denoising. Table 4 shows the performance of our OOD
detection framework under this instantiation on three dataset pairs. In our
experiments, we add noise to step $t=500$ in each attempt, where $T=1000$, as
it generally yields good results. Similar to our inpainting setting, we
perform 10 attempts per image, and use the median reconstruction error under
LPIPS as the OOD score. We observe that diffusion/denoising is also
competitive, although it is slightly outperformed by masking/inpainting in
some cases. This indicates that our framework is generally applicable in OOD
detection, and supports various promising alternative instantiations.

##  5 Discussion and Conclusion

One limitation of the vanilla diffusion model is that the denoising process
involves many iterations and is thus slow. Consequently, like many DM-based
algorithms in other applications Meng et al. (2021); Lugmayr et al. (2022),
LMD is hard to be applied to real-time OOD detection at the current stage.
Recently, there has been a popular line of work on speeding up diffusion
models without retraining. For example, Nichol & Dhariwal (2021) re-scales the
noise schedule to skip sampling steps, Liu et al. (2022) proposes pseudo
numerical methods for diffusion models, and Watson et al. (2022) optimizes
fast samplers that enable sampling with only 10-20 steps. This opens up a
promising direction for future work to integrate these methods into LMD.

In conclusion, we leverage the diffusion model’s manifold mapping ability, and
propose a method – Lift, Map, Detect (LMD) – for unsupervised OOD detection.
We show that it is competitive and versatile through our experiments.

##  6 Acknowledgement

This research is supported by grants from DARPA AIE program, Geometries of
Learning (HR00112290078), the Natural Sciences and Engineering Research
Council of Canada (NSERC) (567916), the National Science Foundation NSF
(IIS-2107161, III1526012, IIS-1149882, and IIS-1724282), and the Cornell
Center for Materials Research with funding from the NSF MRSEC program
(DMR-1719875).

## References

  * Ahmadian & Lindsten (2021) Ahmadian, A. and Lindsten, F.  Likelihood-free out-of-distribution detection with invertible generative models.  In _IJCAI_ , pp. 2119–2125, 2021.
  * Bergamin et al. (2022) Bergamin, F., Mattei, P.-A., Havtorn, J. D., Senetaire, H., Schmutz, H., Maaløe, L., Hauberg, S., and Frellsen, J.  Model-agnostic out-of-distribution detection using combined statistical tests.  In _International Conference on Artificial Intelligence and Statistics_ , pp. 10753–10776. PMLR, 2022.
  * Bergman & Hoshen (2020) Bergman, L. and Hoshen, Y.  Classification-based anomaly detection for general data.  _arXiv preprint arXiv:2005.02359_ , 2020.
  * Bishop (1994) Bishop, C. M.  Novelty detection and neural network validation.  _IEE Proceedings-Vision, Image and Signal processing_ , 141(4):217–222, 1994.
  * Chen et al. (2020) Chen, T., Kornblith, S., Swersky, K., Norouzi, M., and Hinton, G. E.  Big self-supervised models are strong semi-supervised learners.  _Advances in neural information processing systems_ , 33:22243–22255, 2020.
  * Choi et al. (2018) Choi, H., Jang, E., and Alemi, A. A.  Waic, but why? generative ensembles for robust anomaly detection.  _arXiv preprint arXiv:1810.01392_ , 2018.
  * Clanuwat et al. (2018) Clanuwat, T., Bober-Irizar, M., Kitamoto, A., Lamb, A., Yamamoto, K., and Ha, D.  Deep learning for classical japanese literature.  2018\.
  * Denouden et al. (2018) Denouden, T., Salay, R., Czarnecki, K., Abdelzad, V., Phan, B., and Vernekar, S.  Improving reconstruction autoencoder out-of-distribution detection with mahalanobis distance.  _arXiv preprint arXiv:1812.02765_ , 2018.
  * Goodfellow et al. (2014) Goodfellow, I. J., Pouget-Abadie, J., Mirza, M., Xu, B., Warde-Farley, D., Ozair, S., Courville, A., and Bengio, Y.  Generative adversarial networks, 2014.  URL https://arxiv.org/abs/1406.2661.
  * Graham et al. (2022) Graham, M. S., Pinaya, W. H., Tudosiu, P.-D., Nachev, P., Ourselin, S., and Cardoso, M. J.  Denoising diffusion models for out-of-distribution detection.  _arXiv preprint arXiv:2211.07740_ , 2022.
  * Hamet & Tremblay (2017) Hamet, P. and Tremblay, J.  Artificial intelligence in medicine.  _Metabolism_ , 69:S36–S40, 2017.
  * Hendrycks & Gimpel (2016) Hendrycks, D. and Gimpel, K.  A baseline for detecting misclassified and out-of-distribution examples in neural networks.  _arXiv preprint arXiv:1610.02136_ , 2016.
  * Hendrycks et al. (2018) Hendrycks, D., Mazeika, M., and Dietterich, T.  Deep anomaly detection with outlier exposure.  _arXiv preprint arXiv:1812.04606_ , 2018.
  * Hendrycks et al. (2019) Hendrycks, D., Mazeika, M., Kadavath, S., and Song, D.  Using self-supervised learning can improve model robustness and uncertainty.  _Advances in neural information processing systems_ , 32, 2019.
  * Ho et al. (2020) Ho, J., Jain, A., and Abbeel, P.  Denoising diffusion probabilistic models.  _Advances in Neural Information Processing Systems_ , 33:6840–6851, 2020.
  * Huang et al. (2021) Huang, R., Geng, A., and Li, Y.  On the importance of gradients for detecting distributional shifts in the wild.  _Advances in Neural Information Processing Systems_ , 34:677–689, 2021.
  * Karras et al. (2017) Karras, T., Aila, T., Laine, S., and Lehtinen, J.  Progressive growing of gans for improved quality, stability, and variation.  _CoRR_ , abs/1710.10196, 2017.  URL http://arxiv.org/abs/1710.10196.
  * Karras et al. (2019) Karras, T., Laine, S., and Aila, T.  A style-based generator architecture for generative adversarial networks.  In _Proceedings of the IEEE/CVF conference on computer vision and pattern recognition_ , pp. 4401–4410, 2019.
  * Kingma & Dhariwal (2018) Kingma, D. P. and Dhariwal, P.  Glow: Generative flow with invertible 1x1 convolutions.  _Advances in neural information processing systems_ , 31, 2018.
  * Kirichenko et al. (2020) Kirichenko, P., Izmailov, P., and Wilson, A. G.  Why normalizing flows fail to detect out-of-distribution data.  _Advances in neural information processing systems_ , 33:20578–20589, 2020.
  * Krizhevsky (2009) Krizhevsky, A.  Learning multiple layers of features from tiny images.  Technical report, 2009.
  * LeCun et al. (2010) LeCun, Y., Cortes, C., and Burges, C.  Mnist handwritten digit database.  _ATT Labs [Online]. Available: http://yann.lecun.com/exdb/mnist_ , 2, 2010.
  * Lee et al. (2018) Lee, K., Lee, K., Lee, H., and Shin, J.  A simple unified framework for detecting out-of-distribution samples and adversarial attacks.  _Advances in neural information processing systems_ , 31, 2018.
  * Li et al. (2018) Li, D., Chen, D., Goh, J., and Ng, S.-k.  Anomaly detection with generative adversarial networks for multivariate time series.  _arXiv preprint arXiv:1809.04758_ , 2018.
  * Liang et al. (2017) Liang, S., Li, Y., and Srikant, R.  Enhancing the reliability of out-of-distribution image detection in neural networks.  _arXiv preprint arXiv:1706.02690_ , 2017.
  * Liu et al. (2022) Liu, L., Ren, Y., Lin, Z., and Zhao, Z.  Pseudo numerical methods for diffusion models on manifolds.  _arXiv preprint arXiv:2202.09778_ , 2022.
  * Lugmayr et al. (2022) Lugmayr, A., Danelljan, M., Romero, A., Yu, F., Timofte, R., and Van Gool, L.  Repaint: Inpainting using denoising diffusion probabilistic models.  In _Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition_ , pp. 11461–11471, 2022.
  * Maaløe et al. (2019) Maaløe, L., Fraccaro, M., Liévin, V., and Winther, O.  Biva: A very deep hierarchy of latent variables for generative modeling.  _Advances in neural information processing systems_ , 32, 2019.
  * Meng et al. (2021) Meng, C., He, Y., Song, Y., Song, J., Wu, J., Zhu, J.-Y., and Ermon, S.  Sdedit: Guided image synthesis and editing with stochastic differential equations.  In _International Conference on Learning Representations_ , 2021.
  * Morningstar et al. (2021) Morningstar, W., Ham, C., Gallagher, A., Lakshminarayanan, B., Alemi, A., and Dillon, J.  Density of states estimation for out of distribution detection.  In _International Conference on Artificial Intelligence and Statistics_ , pp. 3232–3240. PMLR, 2021.
  * Nalisnick et al. (2018) Nalisnick, E., Matsukawa, A., Teh, Y. W., Gorur, D., and Lakshminarayanan, B.  Do deep generative models know what they don’t know?  _arXiv preprint arXiv:1810.09136_ , 2018.
  * Nalisnick et al. (2019) Nalisnick, E. T., Matsukawa, A., Teh, Y. W., and Lakshminarayanan, B.  Detecting out-of-distribution inputs to deep generative models using a test for typicality.  2019\.
  * Netzer et al. (2011) Netzer, Y., Wang, T., Coates, A., Bissacco, A., Wu, B., and Ng, A. Y.  Reading digits in natural images with unsupervised feature learning.  2011\.
  * Nichol & Dhariwal (2021) Nichol, A. Q. and Dhariwal, P.  Improved denoising diffusion probabilistic models.  In _International Conference on Machine Learning_ , pp. 8162–8171. PMLR, 2021.
  * Ren et al. (2019) Ren, J., Liu, P. J., Fertig, E., Snoek, J., Poplin, R., Depristo, M., Dillon, J., and Lakshminarayanan, B.  Likelihood ratios for out-of-distribution detection.  _Advances in neural information processing systems_ , 32, 2019.
  * Rigano (2019) Rigano, C.  Using artificial intelligence to address criminal justice needs.  _National Institute of Justice Journal_ , 280:1–10, 2019\.
  * Ruff et al. (2019) Ruff, L., Vandermeulen, R. A., Görnitz, N., Binder, A., Müller, E., Müller, K.-R., and Kloft, M.  Deep semi-supervised anomaly detection.  _arXiv preprint arXiv:1906.02694_ , 2019.
  * Russakovsky et al. (2015) Russakovsky, O., Deng, J., Su, H., Krause, J., Satheesh, S., Ma, S., Huang, Z., Karpathy, A., Khosla, A., Bernstein, M., Berg, A. C., and Fei-Fei, L.  ImageNet Large Scale Visual Recognition Challenge.  _International Journal of Computer Vision (IJCV)_ , 115(3):211–252, 2015.  doi: 10.1007/s11263-015-0816-y.
  * Sakurada & Yairi (2014) Sakurada, M. and Yairi, T.  Anomaly detection using autoencoders with nonlinear dimensionality reduction.  In _Proceedings of the MLSDA 2014 2nd workshop on machine learning for sensory data analysis_ , pp. 4–11, 2014.
  * Salimans et al. (2017) Salimans, T., Karpathy, A., Chen, X., and Kingma, D. P.  Pixelcnn++: Improving the pixelcnn with discretized logistic mixture likelihood and other modifications.  _arXiv preprint arXiv:1701.05517_ , 2017.
  * Schlegl et al. (2017) Schlegl, T., Seeböck, P., Waldstein, S. M., Schmidt-Erfurth, U., and Langs, G.  Unsupervised anomaly detection with generative adversarial networks to guide marker discovery.  In _International conference on information processing in medical imaging_ , pp. 146–157. Springer, 2017.
  * Sehwag et al. (2021) Sehwag, V., Chiang, M., and Mittal, P.  Ssd: A unified framework for self-supervised outlier detection.  _arXiv preprint arXiv:2103.12051_ , 2021.
  * Serrà et al. (2019) Serrà, J., Álvarez, D., Gómez, V., Slizovskaia, O., Núñez, J. F., and Luque, J.  Input complexity and out-of-distribution detection with likelihood-based generative models.  _arXiv preprint arXiv:1909.11480_ , 2019.
  * Sohl-Dickstein et al. (2015) Sohl-Dickstein, J., Weiss, E., Maheswaranathan, N., and Ganguli, S.  Deep unsupervised learning using nonequilibrium thermodynamics.  In _International Conference on Machine Learning_ , pp. 2256–2265. PMLR, 2015.
  * Song & Ermon (2019) Song, Y. and Ermon, S.  Generative modeling by estimating gradients of the data distribution.  _Advances in neural information processing systems_ , 32, 2019.
  * Song et al. (2020) Song, Y., Sohl-Dickstein, J., Kingma, D. P., Kumar, A., Ermon, S., and Poole, B.  Score-based generative modeling through stochastic differential equations.  _arXiv preprint arXiv:2011.13456_ , 2020.
  * Tack et al. (2020) Tack, J., Mo, S., Jeong, J., and Shin, J.  Csi: Novelty detection via contrastive learning on distributionally shifted instances.  _Advances in neural information processing systems_ , 33:11839–11852, 2020.
  * Wang et al. (2022) Wang, H., Li, Z., Feng, L., and Zhang, W.  Vim: Out-of-distribution with virtual-logit matching.  In _Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition_ , pp. 4921–4930, 2022.
  * Wang et al. (2003) Wang, Z., Simoncelli, E. P., and Bovik, A. C.  Multiscale structural similarity for image quality assessment.  In _The Thrity-Seventh Asilomar Conference on Signals, Systems & Computers, 2003_, volume 2, pp. 1398–1402. Ieee, 2003.
  * Watson et al. (2022) Watson, D., Chan, W., Ho, J., and Norouzi, M.  Learning fast samplers for diffusion models by differentiating through sample quality.  In _International Conference on Learning Representations_ , 2022.
  * Xia et al. (2015) Xia, Y., Cao, X., Wen, F., Hua, G., and Sun, J.  Learning discriminative reconstructions for unsupervised outlier removal.  In _Proceedings of the IEEE International Conference on Computer Vision_ , pp. 1511–1519, 2015.
  * Xiao et al. (2017) Xiao, H., Rasul, K., and Vollgraf, R.  Fashion-mnist: a novel image dataset for benchmarking machine learning algorithms.  _CoRR_ , abs/1708.07747, 2017.  URL http://arxiv.org/abs/1708.07747.
  * Xiao et al. (2020) Xiao, Z., Yan, Q., and Amit, Y.  Likelihood regret: An out-of-distribution detection score for variational auto-encoder.  _Advances in neural information processing systems_ , 33:20685–20696, 2020.
  * Xiao et al. (2021) Xiao, Z., Yan, Q., and Amit, Y.  Do we really need to learn representations from in-domain data for outlier detection?  _arXiv preprint arXiv:2105.09270_ , 2021.
  * Xie et al. (2022) Xie, Z., Zhang, Z., Cao, Y., Lin, Y., Bao, J., Yao, Z., Dai, Q., and Hu, H.  Simmim: A simple framework for masked image modeling.  In _Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition_ , pp. 9653–9663, 2022.
  * Yang et al. (2022) Yang, L., Zhang, Z., Song, Y., Hong, S., Xu, R., Zhao, Y., Shao, Y., Zhang, W., Cui, B., and Yang, M.-H.  Diffusion models: A comprehensive survey of methods and applications.  _arXiv preprint arXiv:2209.00796_ , 2022.
  * Zhang et al. (2018) Zhang, R., Isola, P., Efros, A. A., Shechtman, E., and Wang, O.  The unreasonable effectiveness of deep features as a perceptual metric.  In _Proceedings of the IEEE conference on computer vision and pattern recognition_ , pp. 586–595, 2018.
  * Zhou & Paffenroth (2017) Zhou, C. and Paffenroth, R. C.  Anomaly detection with robust deep autoencoders.  In _Proceedings of the 23rd ACM SIGKDD international conference on knowledge discovery and data mining_ , pp. 665–674, 2017.
  * Zong et al. (2018) Zong, B., Song, Q., Min, M. R., Cheng, W., Lumezanu, C., Cho, D., and Chen, H.  Deep autoencoding gaussian mixture model for unsupervised anomaly detection.  In _International conference on learning representations_ , 2018.


# Gas molecules (CO, NH3, CO2) sensing with Polyaniline Emardline salt (PANI
ES) : a turbo TDDFT study

N. Hadian Jazia I. Abdolhosseini Sarsarib,c N. Zare Dehnavia a)Department of
Physics, Central Tehran Branch, Islamic Azad University, Tehran, Iran
b)Department of Physics, Isfahan University of Technology, Isfahan,
84156-83111, Iran
c)Computational Physical Sciences Research Laboratory, School of Nano-Science,
Institute for Research in Fundamental Sciences (IPM), P.O. Box 19395-5531,
Tehran, Iran

###### Abstract

The adsorption of gas molecules (CO, NH3, CO2 ) on Polyaniline Emeraldine salt
has been performed to study gas sensing. Density functional theory (DFT) and
time dependent density functional theory (TD-DFT) calculations have been
carried out to compute the response mechanism of polyaniline emeraldine salt
(PANI ES) oligoanalinines (with two to six rings) to gas molecules. The
optimized geometry and electronic structure corresponding to molecule and
complexes are computed with the pseudo-potential and full-potential methods.
The absorption spectra corresponding to polyaniline emeraldine salt molecule
and its complexes are calculated using TD-DFT. We found it out that the
electronic and optical features corresponding to complexes show more sensitive
to the NH3 adsorption. The optical absorption spectrum analysis was used for
all ( nPANI ES-X ) and isolated nPANI ES. Then, the related spectrum indicates
that the $\lambda_{max}$ is shifted red or blue, is affected by the kind of
complex.

Polyaniline emeraldine salt,Pseudopotential, Optical absorption spectrum

##  I INTRODUCTION

Some gas molecules such as CO, NH3, CO2 can make serious problems, therefore
their detection at ppm and/or ppb concentration is so important for the human
safety and health Mahajan (1985); Timmer  _et al._ (2005); Kruse and Tekiela
(1996); Paul  _et al._ (2009); Sepaniak  _et al._ (2006). Many articles
recently gave emphasis to property of gas sensors. In the last few years, a
new generation of gas sensors has been prepared, using conductive polymers
(CP)Bai and Shi (2007); Yagüe and Borrós (2012); Penza  _et al._ (2004). It is
found that the conductive polymers could be utilized for detecting small
concentration of CO, NH3, CO2 with high sensitivity at ambient temperature
Nicolas-Debarnot and Poncin-Epaillard (2003).

Conductive polymers (CPs) (Polyaniline (PANI), polypyrrole (PPY),
poly(o-phenylenediamine) (POPD) and poly(3,4-ethylenedioxythiophene) (PEDOT))
have received a lot of attention since the first discovery of polyacetylen
(CH)x in 1977Liu  _et al._ (2004); Chen  _et al._ (2012). The many single
subject studies demonstrate their biosensing and gas sensing capabilitiesBai
and Shi (2007).

Among CPs, PANI was studied as gas sensors, experimentally and theoretically.
People hope they will profit greatly from its low cost, high sensitivity,
environmental stability and short response time toward guest molecule at
ambient temperature in sensing devicesGonçalves and Balogh (2012); Hoa  _et
al._ (1992). The response mechanisms of PANI to gas molecules were studied
theoretically to give some explanations for empirical observations in
detailVirji  _et al._ (2006); Potyrailo  _et al._ (2009); Pinto  _et al._
(2008). Recently, more and more theoretical papers have been published
concerning PANI by the mean of Ab-initio or density functional theory (DFT)
methodsChoi  _et al._ (1999); Sein  _et al._ (2000); Ullah  _et al._ (2013);
Ćirić-Marjanović (2013). Geometric and electronic structures of various
neutral aniline oligomers were studied by Lim etalLim  _et al._ (2000).

In this paper, we studied a variety of complexes to model the interaction
between individual oligoanilines and different gas molecules with (DFT) and
Time-Dependent Density Functional Theory (TD-DFT) approaches. Based on the
synthesis procedure, PANI has three different oxidation states: PANI
Lecuemeraldin base (LB), Pernigraniline base (PNB), Emeradin base (EB). Acid
doping, nitrogen in PANI-EB chain is able to be protonated to afford
conducting Emeraldine salt (ES) which indicates excellent conductivity as the
result of extensive $\pi$ conjugating in the polymer chainMacDiarmid (2001).
In this work, we mainly investigated electronic, optical and structural PANI
ES, and the effect of interacted gas molecules on it. Radical cation ES
oligoanilines with two, four and six benzene rings ended by nitrogen atoms are
represented in Fig. 1.

Figure 1:  Optimized structure of PANI ES molecule. The C, N and H atoms
indicate with brown, blue and pink spheres respectively.

The general reaction mechanism through which PANI ES gives response to samples
X (X=NH3, CO2, CO) are given based on the subsequent reactions:

$\rm PANIES+x^{0}\longrightarrow PANIEB+X^{+}$ (1) $\rm
PANIEB+X^{+}\longrightarrow PANIES+x^{0}$ (2)

##  II Computational Details

Our electronic structure computation and geometry optimizations have been
carried out in the frame-work of (DFT) by using PAW pseudpopotential as well
as numerical orbital atoms (NAO) full potential methods applied in the Quantum
Espresso (QE)Giannozzi  _et al._ (2009) and FHI-aimsBlum  _et al._ (2009)
computational packages, respectively. GGA-PBE exchange-correlation functionals
Perdew  _et al._ (1996) and supercell approach were applied for simulating
isolated PANI ES molecule in QE. A vacuum thickness of around 24 Bohr was used
for avoiding interaction of neighboring molecules. Cut-off energy of 40 Ry and
500 Ry, is applied for plane wave development of wave functions and electron
density, However full potential computations were carried out with $tier3$
base set and atomic ZORA scalar relativistic impacts.

Electronic properties the energy of the highest occupied molecular orbital (
EHOMO ), the energy of the lowest unoccupied molecular orbital ( ELUMO ) and
HL gap ( EHL ) are calculated at the previously mentioned level of the theory.
The chemical potential ($\mu$) was defined viaRocha  _et al._ (2015).

$\rm\mu=\frac{-(E_{HOMO}+E_{LUMO})}{2}$ (3)

In addition, the hardness $\eta$ can be calculated by the use of Koopmans’
theorem as:

$\rm\eta=\frac{(E_{LUMO}-E_{HOMO})}{2}$ (4)

Softness (S) was described using the following equationsParr  _et al._ (1999):

$\rm S=\frac{1}{2\eta}$ (5)

To compute the gas molecules adsorption energy on nPANI ES, Equation (5) has
been used.

$\rm E_{ads}=E_{nPANIES-x}-(E_{nPANIES}+E_{X}).$ (6)

where EnPANIES-x is the whole energy of the optimized nPANI ES interacted with
diverse molecules of gas, EnPANIES is the throughout energy of an isolated
nPANI ES, EX is the full energy of any gas molecules in the relaxed form.

The optical absorption spectrum of the molecules is calculated in the
framework of Liouville-Lanczos approach to time-dependent DFT, implemented in
Turbo-TDDFT code, that is part of QE distributionMalcıoğlu  _et al._ (2011);
Ullrich and Yang (2014). The Liouville-Lanczos approach iterations optimized
2000 for our calculations.

##  III RESULTS AND DISCUSIONS

The interaction of NH3, CO2, CO gas molecules with PANI ES on different
positions have been optimized using the above mentioned method. For NH3 and
CO2, just one configuration on PANI ES can be optimized, However two
configurations can be optimized for CO (O end and C end) nPANI ES-OC (CO(1))
and nPANI ES-CO (CO(2)). Following complete optimization of all configurations
on PANI ES, the most stable one was applied for further the study. We find
that the divers gas molecules prefer different geometries in the adsorption.
Our data of the optimized geometric parameters and the data of the absorption
energy are listed in table1. The geometries of the optimized complexes deliver
important data about the response mechanism of conduction toward different gas
molecules.

Table 1:  Optimized geometric of parameters using DFT level of theory (Bond lengths in Å, bond angles in deg.  Species |  $d_{H5..X}$(vdw) | $d_{N2..H5}$ |  $\angle$C1N2C3 |  $\angle$N2H5..X |  $\angle$C1N2C3C4
---|---|---|---|---|---
Isolated 2PANI ES | - | 1.01 | 129.04 | - | 22.27
2PANI ES-CO(2) | 2.19 | 1.01 | 129.01 | 179.75 | 22.29
2PANI ES-CO(1) | 2.12 | 1.02 | 128.58 | 179.91 | 23.07
2PANI ES-CO2 | 2.07 | 1.01 | 129.16 | 179.98 | 21.86
2PANI ES-NH3 | 1.87 | 1.04 | 127.71 | 179.29 | 24.49
Isolated 4PANI ES | - | 1.01 | 130.36 | - | 22.58
4PANI ES-CO(2) | 2.12 | 1.02 | 129.02 | 179.25 | 22.67
4PANI ES-CO(1) | 2.12 | 1.01 | 129.04 | 179.15 | 22.35
4PANI ES-CO2 | 2.00 | 1.01 | 129.57 | 179.78 | 20.97
4PANI ES-NH3 | 1.84 | 1.04 | 128.29 | 178.66 | 23.04
Isolated 6PANI ES | - | 1.01 | 129.53 | - | 21.65
6PANI ES-CO(2) | 2.08 | 1.01 | 129.50 | 179.82 | 20.78
6PANI ES-CO(1) | 2.13 | 1.02 | 128.95 | 179.78 | 22.13
6PANI ES-CO2 | 1.99 | 1.01 | 129.53 | 179.68 | 21.44
6PANI ES-NH3 | 1.84 | 1.04 | 128.43 | 177.83 | 23.28

The distance between H5 and X gas ($d_{H5..X}$) shows notable changes in
different gas molecules adsorption. The nearest distance between nPANI ES and
gas molecules is confirmed for NH3 by the distance of 1.87Å, 1.84Å, 1.84 Å for
n=2,4,6, respectively, which points to strong interaction between them but
CO(1) and CO(2) have the largest distance which points to less interaction
between them. This result is completely in agreement with the obtained
adsorption energies. For nPANI ES-NH3 complexes, $d_{H5..X}$ distance
decreases about 0.03Å from 2 to 6. The reduction of $d_{H5..X}$ distance with
chain length elongation illustrates the reduction in interaction with chain
elongation. The distance $d_{N2..H5}$ increases when nPANI ES interacts with
ammonia (table 1). This bond enhance/reduce as the result of generating/losing
of ion dipole electrostatic interaction between nPANI ES and the above-
mentioned molecules.

Another important geometric factor in nPANI ES and nPANI ES-X is the bridging
angle ($\angle$C1N2C3) which decrease when nPANI ES interacts with NH3
molecule. The maximum and minimum decrease in angle is about 2.07 Å and 1.1 Å
in 4PANI ES-NH3 and 6PANI ES-CO(1) complexes regarding their equivalent non-
complexed nPANI ES. The larger decrease in angle means the stronger
electrostatic attraction between nPANI ES and NH3. considering the analysis of
the decrease in bond angles, it can be concluded that the interaction between
nPANI ES and NH3 increase and alongside the increase in chain length
elongation, consistent with the inference from the bond length analysis (vide
supra).

Another important parameter is the $\angle$N2H5..X angle which only shows the
situation of gas molecules on nPANI ES. it increases from about 129 degree (in
nPANI ES) to about 180 degree in all nPANI ES-X complexes. As the result of
existing different gas molecules which is presented in table 1 the dihedral
angle $\angle$C1N2C3C4 is altered based on the kind of X as guests which are
posiibly beacuse of the ion dipole interaction. This factor will influence the
electronic structure of complexes.

###  III.1 Electronic properties

The electronic structure corresponding to the best nPANI ES molecule and its
complexes were computed with both pseudo-potential and full potential methods
and result showed an excellent was observed. The electronic properties of
nPANI ES are completely modified by gas molecules. The prime focus of the
present work is on ionization electron, electron affinity, HOMO-LUMO(HL) gap
and adsorption characteristic of gas molecules on nPANI ES. Table 2 represents
the HOMO energy, LUMO energy, Dipole moment, Mulliken charge transfer, HL gap
and adsorption energy of isolated nPANI ES and nPANI ES complexes. The HL gap
of isolated nPANI ES is 2.71, 2.31 and 2.36 eV for n=2, 4, 6.

The incorporation of gas molecules decreases the EHL except for 4PANI ES-NH3.
So we conclude that for n =2-6 the highest conductivity between nPANI ES and
different gas molecules are confirmed for CO(1), CO(2). Analyzing the HL gap
variation upon gas molecules adsorption on nPANI ES isolated clearly suggests
that nPANI ES can be used as a sensor. As can be observed in table 2, the HL
gap of each gas molecules is much higher than the HL gap of nPANI ES.

However, upon complexation, the HL gap of the resultant complex is quite
different from that one for of the nPANI ES, depending on the nature of the
gas molecules. It can be said (but it is not true for all cases) that the
smaller difference in the HL gap of gas molecules and nPANI ES molecule, the
greater change in HL gap of their complex (further hybridization), and as it
can be observed for CO(2), CO(1). For other samples like CO2 the large
difference in the EHL of the gas molecule and nPANI ES results in an
inconsiderable variation in the HL gap of the resultant complex, which makes
it difficult to transfer electronsChattaraj and Giri (2009).

When gas molecules get adsorbed on nPANI ES, the alteration in adsorption
energy would be observed. The positive and negative values of $E_{ad}$ show
the endothermic and exothermic reaction respectively, based on the adsorption
of gas molecules on nPANI ES. The adsorption energy magnitude is different and
a negative value of adsorption energy infers that the energy transfers from
isolated nPANI ES to gas molecules. The adsorption energy magnitude for nPANI
ES-NH3 is higher than others.

The electronic features can also be discussed in terms of Mulliken charge
transfer (Q) between gas molecules and isolated nPANI ES. The positive value
corresponding to Mulliken charge transfer indicates the charge tansfer from
gas molecules to nPANI ES, while the negative value corresponding to Mulliken
charge transfer indicates the charge transfer from nPANI ES isolated to gas
molecules. In the present work, for all positions, the positive value of
Mulliken charge transfer is taken in to consideration and indicates the
electrons transfer from gas molecules to nPANI ES. The magnitude of Mulliken
charge transfer is found to be higher when NH3 molecule get adsorbed on nPANI
ES comparing to the adsorption of other molecules and it is due to more value
of adsorption energy for nPANI ES-NH3 that can be observed in table 2.

A weak interaction is observed in nPANI ES-CO2 complexes, comparing those of
nPANI ES-NH3 (see table 2). The HOMO of 2PANI ES gets electric charge clouds
from CO2 of nearby 0.13 eV which is 0.2 eV smaller comparing to that of the
2PANI ES-NH3 complex. The transfer of this electron clouds happen from the
HOMO of CO2 to LUMO of nPANI ES, instead of ion-dipole electrostatic
interaction with ammonia, give a rise to a weak type of attractive force. The
small electron cloud transfer from analyte to polymer in 2PANI ES-CO2
comparing to 2PANI ES-NH3 complex manifests itself in weak sensing of CO2
using the polymer. The 4PANI ES-CO2 and 6PANI ES-CO2 complexes have 0.17 eV
and 0.03 eV smaller electron cloud attraction, respectively, as comparing to
its nPANI ES-NH3.

Table 2:  The calculated electronic properties of of nPANI ES and nPANI ES-X complexes, where n = 2-6 and X = NH3, CO(1), CO(2) and CO2, $E_{g}$ = $\lvert E_{HOMO}-E_{LUMO}\rvert$, $E_{d}$: adsorption energy, $Q(e)$: Mulliken charge transfer, $\mu_{D}$: dipole moment.  Species |  $E_{HOMO}$(eV) |  $E_{LUMO}$(eV) | $E_{HL}(eV)$ | $E_{ad}(eV)$ | $Q(e)$ | $\mu_{D}(Debye)$
---|---|---|---|---|---|---
Isolated 2PANI ES | -3.69 | -0.97 | 2.72 | - | - | -0.22
2PANI ES-CO(2) | -3.63 | -2.50 | 1.12 | -0.08 | 0.02 | -0.39
2PANI ES-CO(1) | -3.60 | -2.59 | 1.00 | -0.16 | 0.03 | -0.60
2PANI ES-CO2 | -3.56 | -1.15 | 2.41 | -0.12 | 0.01 | -0.90
2PANI ES-NH3 | -3.36 | -0.95 | 2.41 | -0.41 | 0.06 | -3.00
Isolated 4PANI ES | -3.39 | -1.07 | 2.31 | - | - | 24.76
4PANI ES-CO(2) | -3.41 | -2.47 | 0.93 | -0.17 | 0.03 | 27.22
4PANI ES-CO(1) | -3.42 | -2.39 | 1.03 | -0.08 | 0.02 | 27.82
4PANI ES-CO2 | -3.37 | -1.06 | 2.31 | -0.13 | 0.01 | 31.80
4PANI ES-NH3 | -3.23 | -0.89 | 2.34 | -0.43 | 0.06 | 32.67
Isolated 6PANI ES | -3.35 | -0.98 | 2.36 | - | - | -1.11
6PANI ES-CO(2) | -3.37 | -2.41 | 0.95 | -0.08 | 0.02 | 23.59
6PANI ES-CO(1) | -3.36 | -2.49 | 0.87 | -0.17 | 0.03 | 22.04
6PANI ES-CO2 | -3.33 | -1.07 | 2.25 | -0.13 | 0.02 | 22.59
6PANI ES-NH3 | -3.22 | -0.97 | 2.25 | -0.50 | 0.06 | 25.29
CO(2) | -9.11 | -2.32 | 6.78 | - | - | 0.16
CO(1) | -9.10 | -2.31 | 6.79 | - | - | -0.17
CO2 | -9.34 | -1.01 | 8.32 | - | - | -0.01
NH3 | -6.12 | -0.74 | 5.38 | - | - | -1.37

The computed amounts of dipole moment $\mu_{D}$ of interacted CO(1), CO(2),
CO2 and NH3 with nPANI ES are presented in table 2Rad (2016). The dipole
moment considers the electronic and geometrical features and gives an insight
into the distribution of charges in alone Polyaniline emardline salt. Our
findings indicated that upon interaction of analytes with nPANI ES the
dimension and directions of $\mu_{D}$ will be changed based on the
configuration of adsorption. As presented in table 2, for each system of
interaction with nPANI ES, the dipole moment increased compare to isolated
nPANI ES.

Orbital density of nPANI ES molecule and several of its derivatives are
computed and showed in table 3. The main activity of electrons is in the state
of HOMO. Therefor we are pretty zealous to study the HOMO-LUMO orbitals of all
structures. As it is presented in table 3. The distribution of HOMO and LUMO
(See table 3) for nPANI ES and complexed forms of species are: nPANI ES-CO(2),
nPANI ES-CO(1), nPANI ES-CO2 and nPANI ES-NH3 for (n=2,4,6). As can be seen in
table 3 for all systems, HOMO is localized on nPANI ES molecule except for
4PANI ES-CO(2) and 6PANI ES-CO(1), the HOMO are located on both CO(2), CO(1)
and 4PANI ES, 6PANI ES-CO(1). This relocation of HOMO corresponds to the
highest change in the EHL and causes the highest interaction energy.
Similarly, for 2PANI ES, 4PANI ES and 6PANI ES, 4 PANI ES-CO2 the LUMO is
located on nPANI ES molecule due to weak interaction between nPANI ES with gas
molecules. The LUMO for 2PANI ES-CO(2), 2PANI ES-CO(1), 4PANI ES-CO(2), 4PANI
ES-CO(1),6PANI ES-CO(2) and 6PANI ES-CO(1) are throughly located on the CO(2),
CO(1) with an exception for 2PANI ES-CO2, 2PANI ES-NH3, 6PANI ES-CO2, 4PANI
ES-NH3, the LUMO which are localized both on CO2, NH3 and polymer rings. This
relocation of LUMO corresponds to the highest change in the EHL, that results
in the highest interaction energy.

Table 3:  Orbital density of nPANI ES molecule and its derivatives.  Phase | Isolated 2PANI ES | 2PANI ES-CO(2) | 2PANI ES-CO(1) | 2PANI ES-CO2 | 2PANI ES-NH33
---|---|---|---|---|---
LUMO |  |  |  |  |
HUMO |  |  |  |  |
Phase | Isolated 4PANI ES | 4PANI ES-CO(2) | 4PANI ES-CO(1) | 4PANI ES-CO2 | 4PANI ES-NH33
LUMO |  |  |  |  |
HUMO |  |  |  |  |
Phase | Isolated 6PANI ES | 6PANI ES-CO(2) | 6PANI ES-CO(1) | 6PANI ES-CO2 | 6PANI ES-NH33
LUMO |  |  |  |  |
HUMO |  |  |  |  |

Table 4 represents the global reactivity indices which are computed by DFT for
the highest stable configuration of gas molecules adsorbed onto nPANI ES
molecule; The electronic features of nPANI ES can also be discussed in terms
of Ionization Potential (IP) and Electron Affinity (EA). IP denotes the amount
of energy required to remove the electron from nPANI ES. For n=2, high value
of IP is observed for isolated nPANI ES, and IP decrease after incorporation
of gas molecules but high value of IP for n=4,6 relates to 4PANI ES-CO(1)and
6PANI ES-CO(2). High value of IP infers that the electrons in nPANI ES
complexes are bound to the isolated nPANI ES . EA represents the alteration in
the energy beacuse of the adding electron in nPANI ES. The high value of EA is
one of the favorable conditions for chemical sensors. Since the global
hardness of a species is defined as its resistance against deformation in the
existance of an electric field, increasing the global hardness increases the
stability and reduces the reactivity of the species Rocha  _et al._ (2015).
The global electrophilicity includes data on the chemical potential (which is
related to electron transfer) and the hardness, (which is related to
stability). Note that, for nPANI ES-CO(1) and nPANI ES-CO(2) the HL gap is
relatively small, leading to low hardness value for this complex comparing the
softness , electrophilicity and electronic chemical potential values which are
high. It can be concluded that the enhanced hardness of complexes indicates
that they are more stable in good according to the high HL gap recorded for
these complexes.

Table 4:  The global reactivity indices were calculated via DFT for the most stable configuration of NH3, CO(1), CO(2) and CO2 adsorbed onto nPANI ES. IP: Ionizaton potential (-$E_{HOMO}$), EA: electron affinity (-$E_{LUMO}$), $\eta$ : hardness, $\mu$: chemical potential, S: softness.  Species | IP(eV) | EA(eV) |  $\eta$(eV) |  $\mu$(eV) | S(eV)
---|---|---|---|---|---
2PANI ES | 3.69 | 0.97 | 1.36 | -2.33 | 0.36
2PANI ES-CO(2) | 3.63 | 2.50 | 0.56 | -3.06 | 0.88
2PANI ES-CO(1) | 3.60 | 2.59 | 0.50 | -3.09 | 0.99
2PANI ES-CO2 | 3.56 | 1.15 | 1.20 | -2.35 | 0.41
2PANI ES-NH3 | 3.56 | 0.95 | 1.30 | -2.25 | 0.38
4PANI ES | 3.39 | 1.07 | 1.15 | -2.23 | 0.43
4PANI ES-CO(2) | 3.41 | 2.47 | 0.46 | -2.94 | 1.07
4PANI ES-CO(1) | 3.42 | 2.39 | 0.51 | -2.91 | 0.96
4PANI ES-CO2 | 3.37 | 1.06 | 1.15 | -2.22 | 0.43
4PANI ES-NH3 | 3.23 | 0.89 | 1.17 | -2.06 | 0.43
6PANI ES | 3.35 | 0.98 | 1.18 | -2.17 | 0.42
6PANI ES-CO(2) | 3.37 | 2.41 | 0.47 | -2.89 | 1.04
6PANI ES-CO(1) | 3.36 | 2.49 | 0.43 | -2.92 | 1.14
6PANI ES-CO2 | 3.33 | 1.79 | 1.13 | -2.20 | 0.45
6PANI ES-NH3 | 3.22 | 0.97 | 1.12 | -2.09 | 0.44

###  III.2 Electronic and Vibrational Properties

The electronic structures corresponding to the optimized nPANI ES and nPANI
ES-X molecules are calculated by using both pseudo-potential and full
potential methodes with a good agreement with each other. The HL gap of 2PANI
ES was obtained 2.72 eV within pseudo-potential method, which is significantly
bigger than the experimental gap of about 3.48 eV Al-Daghman  _et al._ (2016).
This difference shows the major deficiency of LDA/GGA functional for
predicting the excited states features. Thus,TD-DFT calculations will be
utilized to attain some reliable outcomes for HL gap. The vibrational spectra
corresponding to the molecule is computed to study dynamical stability and IR
spectrum for the systems. The resulted IR spectrum of the nPANI ES and nPANI
ES-X molecules are listed in Fig. 2, Fig. 3 and Fig. 4. Dynamical stability of
the molecule proved by the absence of any imaginary style in the spectrum. As
an evident, 2PANI ES, 4PANI ES and 6PANI ES have 3 greater IR intensity that
relate to the stronger bonds. Vibrations around 598 $(cm^{-1})$, 1508
$(cm^{-1})$, 1264 $(cm^{-1})$, 296 $(cm^{-1})$, 1506 $(cm^{-1})$, 1509
$(cm^{-1})$, 288 $(cm^{-1})$, 1312 $(cm^{-1})$ and 1482 $(cm^{-1})$ frequency
show greater IR intensity respectively for 2PANI ES, 4PANI ES and 6PANI ES. We
can conclude when rings of PANI ES increased from n=2 to n= 6, the value and
position of IR intensity, and vibration frequencies are changed.

In addition, when gas molecules get absorbed on nPANI ES, the value of IR
intensity and vibrational frequencies are changed. Interaction 2PANI ES-X with
gas molecules where X=CO(1), CO(2), CO2 causes new bonds C=O and O=H around
2120 to 2355 $(cm^{-1})$ and around 3539 to 3564 $(cm^{-1})$, respectively.
There is also change in the vibrational frequencies position with higher IR
intensity in 2PANI ES-X complexes compare to isolated 2PANI ES. The highest
amount of C=O bonds IR intensity occurs in nPANI ES-CO2, while interacting NH3
with 2PANI ES results in the biggest change in the vibrational frequencies.
Similarly, the interaction of 4PANI ES-X and 6PANI ES-X (X=CO(1), CO(2), CO2)
with gas molecules causes new bonds C=O and O=H around 2120 to 2355
$(cm^{-1})$ and around 3539 to 3564 $(cm^{-1})$ respectively. We can observe
for 2PANI ES-NH3, 4PANI ES-NH3 and 6PANI ES-NH3 the amount of a higher and
increased IR intensity. Analyzing the IR spectrum corresponding to the systems
with adsorption of gas molecules on an isolated nPANI ES clearly suggests that
nPANI ES can be used as sensor.

Figure 2:  calculated IR spectrum of 2PANI ES with gas molecules that adsorbed
on it.

Figure 3:  calculated IR spectrum of 4PANI ES with gas molecules that adsorbed
on it.

Figure 4:  calculated IR spectrum of 6PANI ES with gas molecules that adsorbed
on it.

###  III.3 Optical properties

The Liovile-lanczos approach with TD-DFT is used for determining the optical
spectrum. In this method, the optimization of iterations number should be
performed. The absorption spectrum corresponding to 2PANI ES have been
calculated using various iterations number (Fig. 5). It is observed that a
flat optical spectrum is resulted with 1000 iteration, while sharp peaks is
observed by enhancing iterations. The obtained absorption spectra with 2000
and 2500 iterations are fully overlapped. Therefore, 2000 iterations is the
optimal factor for our following computations.

Figure 5:  Optimizing the number of iterations to determine the optical
spectrum of the 2PANI ES molecule.

The first peak of the absorption spectrum shows the first excited state and
the energy that is equal to the energy needed for transfer of one electron
from the (HOMO) to (LUMO). The following peaks in the absorption spectrum
represent the subsequent electrons excitation from other states. By enhancing
the energy between different states, excitation happens in larger energy. Fig.
6 presents the optical spectrum complexes and the transition states
corresponding to nPANI ES molecule. The first peak is just associated with
(first excitation), but the following peaks are associated with several
excitations which broadening for each peak affecting by the amount of electron
excitations in the corresponding energy. The data that are calculated here
showed in table 5. We used Equation (6) to compute the adsorption energy of
gas molecules on nPANI ES.

Figure 6:  Achieved absorption optical spectrum complexes and transition states corresponding to nPANIES molecule. The insets present the initial part of the spectra in a slim window.  Table 5:  The optical absorption spectrum factor for nPANI ES and its complexes using the Liovile-lanczos appraoch with TD-DFT. $E_{F}$ :First excited energy. $\lambda_{max}$ : maximum wave lenght, $\Delta$E : diffrence between first excited energy of nPANI ES with first excited energy of nPANI ES-X, where X=CO(1), CO(2), CO2 and NH3.  structure |  $E_{F}$(eV) |  $\lambda_{max}$(nm) |  $\Delta$E(eV) | Result
---|---|---|---|---
Isolated 2PANI ES | 3.60 | 344 | - | -
2PANI ES-CO(2) | 3.57 | 348 | -0.02 | blue
2PANI ES-CO(1) | 3.56 | 348 | -0.04 | blue
2PANI ES-CO2 | 3.59 | 345 | -0.01 | blue
2PANI ES-NH3 | 3.50 | 353 | -0.09 | blue
Isolated 4PANI ES | 2.67 | 462 | - | -
4PANI ES-CO(2) | 2.81 | 440 | 0.13 | red
4PANI ES-CO(1) | 2.81 | 440 | 0.13 | red
4PANI ES-CO2 | 2.81 | 440 | 0.13 | red
4PANI ES-NH3 | 2.77 | 446 | 0.09 | red
Isolated 6PANI ES | 2.54 | 487 | - | -
6PANI ES-CO(2) | 2.57 | 482 | 0.02 | red
6PANI ES-CO(1) | 2.58 | 479 | 0.04 | red
6PANI ES-CO2 | 2.55 | 484 | 0.01 | red
6PANI ES-NH3 | 2.50 | 475 | -0.04 | blue

The experimental $\lambda_{max}$ value of PANI ES is 356 nm (3.48 eV),VERA A
_et al._ (2003) which is 0.12 eV lower than our calculated $\lambda_{max}$
value of 344 nm for free 2PANI ES (3.6 eV). This difference is due to the
infinite number of nPANI ES lengths considered in emprical study while our
computation simulated is on the basis of the limited length for a polymer
having only two, four and six rings.

Obviously, from the data listed in table 5, when gas molecules interacts with
nPANI ES, the values for complexes are blue-shifted for 2PANI ES and its
complexes, and red shifted for 4PANI ES and 6PANI ES except 6PANI ES-NH${3}$
which are due to the $\pi$ $\longrightarrow$ $\pi^{*}$ transition. These value
of blue and red shifts show the nPANI ES sensing ability toward CO(2), CO(1),
CO2 and NH3. It can be said that more shifted value (but it is not true for
all cases), 2PANI ES-NH3 and 6PANI ES-NH3 compared to other species which is
totally in accordance with their difference in the value of adsorption energy.

##  IV CONCLUSION

Density functional computations were carried out to study the structural,
electronic, and optical properties of nPANI ES molecule and its complexes,
with both QE and FHI-aims computational packages. The nearest distance between
nPANI ES and gas molecules is confirmed for NH3 by the distance around of 1.8Å
which points to strong interaction between them but CO(1) and CO(2) have the
largest distance which points to less interaction between them. This result is
completely in accordance with the obtained adsorption energies. The maximum
and minimum decrease in angle $\angle$C1N2C3 is about 2.07Å and 1.1Å in 4PANI
ES-NH3 and 6PANI ES-CO(1) complexes regarding their corresponding non-
complexed nPANI ES. The larger decrease in angle means the stronger
electrostatic attraction between nPANI ES and NH3. The kind of interaction
between the tested species (CO, NH3, CO2) with nPANI ES is studied with an
understanding of the HOMO and LUMO energies. simulating electronic features
such as HL gap from the energies of HOMO and LUMO supports the sensing ability
of nPANI ES towards the above-mentioned species. The magnitude of Mulliken
charge transfer is observed to be more when the adsorption of NH3 molecule get
adsorbed on nPANI ES comparing to the adsorption of other molecules. The IR
spectrum of the systems with adsorption of gas molecules on an isolated nPANI
ES introduce nPANI ES as a sensor. We can observe the amount of a higher and
increased IR intensity in 2PANI ES-NH3, 4PANI ES-NH3 and 6PANI ES-NH3
complexes. We computed optical properties of nPANI ES molecule and its
complexes using optical spectrum, next compared them with experimental. The
similarity of $\lambda_{max}$ and experimental $\lambda_{max}$ prove the
effectiveness of Liouville-Lanczos method in computing the $\lambda_{max}$ and
determining $\lambda_{max}$ . optical absorption spectrum analysis is also
applied to all species and the resulted spectra indicates that the
$\lambda_{max}$ were red or blue- shifted depending on the type of complex
(blue-shifted for 2PANI ES and its complexes, and red shifted for 4PANI ES and
6PANI-NH3) because of $\pi$ $\longrightarrow$ $\pi^{*}$ transition which is
can be considered as a testimony for the success of interaction between nPANI
ES and the species tested. All analyses reveal a physisorption procedure for
all species over interaction with nPANI ES.

##  V ACKNOWLEDGMENTS

The authors thankfully appreciate the Sheikh Bahaei National High Performance
Computing Center (SBNHPCC) for providing time and calculation facilities.
SBNHPCC is supported with scientific and technological department of
presidential office and Isfahan University of Technology (IUT). We want to
appreciate Mr. Habib Ullah for the fine work he did on preparing structures.

## References

  * Mahajan (1985) S. Mahajan,  _Pollution control in process industries_ (Tata McGraw-Hill Education, 1985).
  * Timmer  _et al._ (2005) B. Timmer, W. Olthuis, and A. Van den Berg, Sensors and Actuators B: Chemical 107, 666 (2005).
  * Kruse and Tekiela (1996) H. Kruse and M. Tekiela, Energy Conversion and Management 37, 1013 (1996).
  * Paul  _et al._ (2009) S. Paul, F. Amalraj, and S. Radhakrishnan, Synthetic Metals 159, 1019 (2009).
  * Sepaniak  _et al._ (2006) S. Sepaniak, T. Forges, H. Gerard, B. Foliguet, M.-C. Bene, and P. Monnier-Barbarino, Toxicology 223, 54 (2006).
  * Bai and Shi (2007) H. Bai and G. Shi, Sensors 7, 267 (2007).
  * Yagüe and Borrós (2012) J. L. Yagüe and S. Borrós, Plasma Processes and Polymers 9 (2012).
  * Penza  _et al._ (2004) M. Penza, G. Cassano, P. Aversa, F. Antolini, A. Cusano, A. Cutolo, M. Giordano, and L. Nicolais, Applied Physics Letters 85, 2379 (2004).
  * Nicolas-Debarnot and Poncin-Epaillard (2003) D. Nicolas-Debarnot and F. Poncin-Epaillard, Analytica Chimica Acta 475, 1 (2003).
  * Liu  _et al._ (2004) H. Liu, J. Kameoka, D. A. Czaplewski, and H. Craighead, Nano Letters 4, 671 (2004).
  * Chen  _et al._ (2012) X. Chen, C. A. Yuan, C. K. Wong, H. Ye, S. Y. Leung, and G. Zhang, Sensors and Actuators B: Chemical 174, 210 (2012).
  * Gonçalves and Balogh (2012) V. Gonçalves and D. T. Balogh, Sensors and Actuators B: Chemical 162, 307 (2012).
  * Hoa  _et al._ (1992) D. Hoa, T. S. Kumar, N. Punekar, R. Srinivasa, R. Lal, and A. Contractor, Analytical chemistry 64, 2645 (1992).
  * Virji  _et al._ (2006) S. Virji, R. B. Kaner, and B. H. Weiller, Inorganic chemistry 45, 10467 (2006).
  * Potyrailo  _et al._ (2009) R. A. Potyrailo, C. Surman, S. Go, Y. Lee, T. Sivavec, and W. G. Morris, Journal of Applied Physics 106, 124902 (2009).
  * Pinto  _et al._ (2008) N. J. Pinto, I. Ramos, R. Rojas, P.-C. Wang, and A. T. Johnson, Sensors and Actuators B: Chemical 129, 621 (2008).
  * Choi  _et al._ (1999) C. H. Choi, M. Kertesz, M.-I. Boyer, M. Cochet, S. Quillard, G. Louarn, and S. Lefrant, Chemistry of materials 11, 855 (1999).
  * Sein  _et al._ (2000) L. T. Sein, T. Duong, Y. Wei, and S. A. Jansen, Synthetic Metals 113, 145 (2000).
  * Ullah  _et al._ (2013) H. Ullah, A.-u.-H. A. Shah, S. Bilal, and K. Ayub, The Journal of Physical Chemistry C 117, 23701 (2013).
  * Ćirić-Marjanović (2013) G. Ćirić-Marjanović, Synthetic Metals 177, 1 (2013).
  * Lim  _et al._ (2000) S. Lim, K. Tan, E. Kang, and W. Chin, The Journal of Chemical Physics 112, 10648 (2000).
  * MacDiarmid (2001) A. G. MacDiarmid, Synthetic metals 125, 11 (2001).
  * Giannozzi  _et al._ (2009) P. Giannozzi, S. Baroni, N. Bonini, M. Calandra, R. Car, C. Cavazzoni, D. Ceresoli, G. L. Chiarotti, M. Cococcioni, I. Dabo, A. Dal Corso, S. de Gironcoli, S. Fabris, G. Fratesi, R. Gebauer, U. Gerstmann, C. Gougoussis, A. Kokalj, M. Lazzeri, L. Martin-Samos, N. Marzari, F. Mauri, R. Mazzarello, S. Paolini, A. Pasquarello, L. Paulatto, C. Sbraccia, S. Scandolo, G. Sclauzero, A. P. Seitsonen, A. Smogunov, P. Umari, and R. M. Wentzcovitch, Journal of physics. Condensed matter 21, 395502 (2009).
  * Blum  _et al._ (2009) V. Blum, R. Gehrke, F. Hanke, and P. Havu, Computer Physics … , 1 (2009).
  * Perdew  _et al._ (1996) J. P. Perdew, K. Burke, and M. Ernzerhof, Physical review letters 77, 3865 (1996).
  * Rocha  _et al._ (2015) M. Rocha, A. Di Santo, J. M. Arias, D. M. Gil, and A. B. Altabef, Spectrochimica Acta Part A: Molecular and Biomolecular Spectroscopy 136, 635 (2015).
  * Parr  _et al._ (1999) R. G. Parr, L. v. Szentpaly, and S. Liu, Journal of the American Chemical Society 121, 1922 (1999).
  * Malcıoğlu  _et al._ (2011) O. B. Malcıoğlu, R. Gebauer, D. Rocca, and S. Baroni, Computer Physics Communications 182, 1744 (2011).
  * Ullrich and Yang (2014) C. A. Ullrich and Z.-h. Yang, Brazilian Journal of Physics 44, 154 (2014).
  * Chattaraj and Giri (2009) P. K. Chattaraj and S. Giri, Annual Reports Section” C”(Physical Chemistry) 105, 13 (2009).
  * Rad (2016) A. S. Rad, Molecular Physics 114, 584 (2016).
  * Al-Daghman  _et al._ (2016) A. Al-Daghman, K. Ibrahim, N. Ahmed, and M. A. Al-Messiere, Journal of Optoelectronics and Biomedical Materials Vol 8, 175 (2016).
  * VERA A  _et al._ (2003) R. VERA A, H. ROMERO B, and E. Ahumada, Journal of the Chilean Chemical Society 48, 35 (2003).