Radiometric correction of a landsat image using R - r

I want to do a radiometric correction of a landsat image using:
radiocorr(x, gain, offset, Grescale, Brescale, sunelev, satzenith, edist, Esun,
Lhaze, method = "apparentreflectance")
I performed the correction to each band, as follow:
B1 <- readGDAL("_X20060509_B_1.tif")
B1.ar<-radiocorr(x = B1, Grescale = 0.76583, Brescale = -2.28583, sunelev = 43.99853366,
satzenith = 0, edist = 1.0095786, Esun = 1983, method = "apparentreflectance")
writeGDAL(B1.ar, "C:/Users/Documents/ Reflectance/B1.tif", drivername="GTiff")
How can I make one function to automatically perform the correction to the six bands?
I tried with this function:
atmcor <- function(img, i) {
x<-img[[i]]
Grescale<-gain[i,2]
Brescale<-bias[i,2]
sunelev<-sunelevation[i,2]
satzenith=0
edist<-edistance[i,2]
Esun<-Esun[1,2]
method = "apparentreflectance"
B.ar<-radiocorr(x, Grescale, Brescale, sunelev, satzenith, edist, Esun, method)
return(B.ar)
}
ATMCOR <- atmcor(landsat_stack, 1)
But, I got this error:
(Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), :
length of 'dimnames' [1] not equal to array extent)

If you want to do the radiometric calibration for all bands in only one execution chunk you need to load your metadata file as well.
Therefore you can do it in several forms. But the following code can easily solve your problem.
radCor(img, metaData, method = "apref", bandSet = "full", hazeValues,
hazeBands, atmosphere, darkProp = 0.01, clamp = TRUE, verbose)
When you set the bandSet to "full", all the band in the solar region will be processed.

Related

R:Error in UseMethod(generic = "as.sparse", object = x)

enter image description here
I'm trying to use "Seurat" to analyze B cells for my tutor, but the following error occurs when I try to create the object and I don't know how to correct it.
pbmc <- CreateSeuratObject( counts = BC.data$'B Cells`, Project = " BC.data",min.cells = 3, min.features = 200)
Error in UseMethod(generic = "as.sparse", object = x) :
no applicable method for 'as.sparse' applied to an object of class "Seurat"

error with earth function using MARS algo

I run my ML algo:
EarthAlgo<-earth(cible~., data=train, degree=4, glm=list(family=binomial))
I got:
Error in leaps.setup(x = bx, y = y, force.in = 1, force.out = NULL, intercept = FALSE, :
NA/NaN/Inf in foreign function call (arg 3)
When I try with train<-train[(1:dim(train)[1]-2),], it's ok. I search last two line on my train data set but i do not see error.
Could you help me please?

TensorFlow: restore graph with metrics op (e.g. accuracy), got error 'Tensor' object has no attribute 'initializer'

After training a graph with metrics ops (such as accuracy from tf.python.ops.metrics), I tried to restore the graph and evaluate the accuracy on the test set. However, after restoring the graph with tf.import_meta_graph, when I tried to initialize the local variables (it is necessary) with tf.local_variables_initializer(), I got an error, it said 'Tensor' object has no attribute 'initializer'.
If I print the local variables after restoring, there are two Tensorflow Tensors which may cause the problem.
These two tensorlow Tensors stem from the accuracy metrics:
<tf.Tensor 'accuracy/total:0' shape=() dtype=float32_ref>
<tf.Tensor 'accuracy/count:0' shape=() dtype=float32_ref>
Can someone help me with this? Thank you!
Similar code:
def train():
l_ini = np.array([1, 0, 1, 0, 1, 0], dtype=np.float32)
p_ini = np.array([1, 0, 1, 0, 1, 1], dtype=np.float32)
l = tf.Variable(l_ini, trainable=False)
p = tf.Variable(p_ini, trainable=False)
accuracy = metrics.accuracy(labels=l, predictions=p)
tf.add_to_collection("accuracy", accuracy)
graph = tf.get_default_graph()
sess = tf.Session(graph=graph)
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
acc = sess.run(accuracy)
saver = tf.train.Saver()
saver.save(sess, 'test.ckpt')
def restore():
with tf.Session() as sess:
loader = tf.train.import_meta_graph('./test.ckpt.meta')
loader.restore(sess, './test.ckpt')
accuracy = tf.get_collection("accuracy")
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
acc = sess.run(accuracy)
I have a workaround, instead of retrieving the accuracy collection (the get_collection returned an empty list in my case):
Retrieve the logits and label placeholders.
Then compute the accuracy.
Remember to initialize the local running variables after restoring to session as well:
self.running_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope="your_accuracy_scope_name")

Catching the print of the function

I am using package fda in particular function fRegress. This function includes another function that is called eigchk and checks if coeffients matrix is singular.
Here is the function as the package owners (J. O. Ramsay, Giles Hooker, and Spencer Graves) wrote it.
eigchk <- function(Cmat) {
# check Cmat for singularity
eigval <- eigen(Cmat)$values
ncoef <- length(eigval)
if (eigval[ncoef] < 0) {
neig <- min(length(eigval),10)
cat("\nSmallest eigenvalues:\n")
print(eigval[(ncoef-neig+1):ncoef])
cat("\nLargest eigenvalues:\n")
print(eigval[1:neig])
stop("Negative eigenvalue of coefficient matrix.")
}
if (eigval[ncoef] == 0) stop("Zero eigenvalue of coefficient matrix.")
logcondition <- log10(eigval[1]) - log10(eigval[ncoef])
if (logcondition > 12) {
warning("Near singularity in coefficient matrix.")
cat(paste("\nLog10 Eigenvalues range from\n",
log10(eigval[ncoef])," to ",log10(eigval[1]),"\n"))
}
}
As you can see last if condition checks if logcondition is bigger than 12 and prints then the ranges of eigenvalues.
The following code implements the useage of regularization with roughness pennalty. The code is taken from the book "Functional data analysis with R and Matlab".
annualprec = log10(apply(daily$precav,2,sum))
tempbasis =create.fourier.basis(c(0,365),65)
tempSmooth=smooth.basis(day.5,daily$tempav,tempbasis)
tempfd =tempSmooth$fd
templist = vector("list",2)
templist[[1]] = rep(1,35)
templist[[2]] = tempfd
conbasis = create.constant.basis(c(0,365))
betalist = vector("list",2)
betalist[[1]] = conbasis
SSE = sum((annualprec - mean(annualprec))^2)
Lcoef = c(0,(2*pi/365)^2,0)
harmaccelLfd = vec2Lfd(Lcoef, c(0,365))
betabasis = create.fourier.basis(c(0, 365), 35)
lambda = 10^12.5
betafdPar = fdPar(betabasis, harmaccelLfd, lambda)
betalist[[2]] = betafdPar
annPrecTemp = fRegress(annualprec, templist, betalist)
betaestlist2 = annPrecTemp$betaestlist
annualprechat2 = annPrecTemp$yhatfdobj
SSE1.2 = sum((annualprec-annualprechat2)^2)
RSQ2 = (SSE - SSE1.2)/SSE
Fratio2 = ((SSE-SSE1.2)/3.7)/(SSE1/30.3)
resid = annualprec - annualprechat2
SigmaE. = sum(resid^2)/(35-annPrecTemp$df)
SigmaE = SigmaE.*diag(rep(1,35))
y2cMap = tempSmooth$y2cMap
stderrList = fRegress.stderr(annPrecTemp, y2cMap, SigmaE)
betafdPar = betaestlist2[[2]]
betafd = betafdPar$fd
betastderrList = stderrList$betastderrlist
betastderrfd = betastderrList[[2]]
As penalty factor the authors use certain lambda.
The following code implements the search for the appropriate `lambda.
loglam = seq(5,15,0.5)
nlam = length(loglam)
SSE.CV = matrix(0,nlam,1)
for (ilam in 1:nlam) {
lambda = 10ˆloglam[ilam]
betalisti = betalist
betafdPar2 = betalisti[[2]]
betafdPar2$lambda = lambda
betalisti[[2]] = betafdPar2
fRegi = fRegress.CV(annualprec, templist,
betalisti)
SSE.CV[ilam] = fRegi$SSE.CV
}
By changing the value of the loglam and cross validation I suppose to equaire the best lambda, yet if the length of the loglam is to big or its values lead the coefficient matrix to singulrity. I recieve the following message:
Log10 Eigenvalues range from
-5.44495317739048 to 6.78194912518214
Created by the function eigchk as I already have mentioned above.
Now my question is, are there any way to catch this so called warning? By catch I mean some function or method that warns me when this has happened and I could adjust the values of the loglam. Since there is no actual warning definition in the function beside this print of the message I ran out of ideas.
Thank you all a lot for your suggestions.
By "catch the warning", if you mean, will alert you that there is a potential problem with loglam, then you might want to look at try and tryCatch functions. Then you can define the behavior you want implemented if any warning condition is satisfied.
If you just want to store the output of the warning (which might be assumed from the question title, but may not be what you want), then try looking into capture.output.

Setting a loop in R

I have already discussed a similar type of a question in this following post
How to set a for -loop in R
each file contents as follows:
FILE_1.FASTA
>>TTBK2_Hsap ,(CK1/TTBK)
MSGGGEQLDILSVGILVKERWKVLRKIGGGGFGEIYDALDMLTRENVALKVESAQQPKQVLKMEVAVLKKLQGKDHVCRFIGCGRNDRFNYVVMQLQGRNLADLRRSQSRGTFT
FILE_2.FASTA
>>TTBK2_Hsap ,(CK1/TTBK)
MSGGGEQLDILSVGILVKERWKVLRKIGGGGFGEIYDALDMLTRENVALKVESAQQPKQVLKMEVAVLKKLQGKDHVCRFIGCGRNDRFNYVVMQLQGRNLADLRRSQSRGTFT
However, there is another package in R which works like this:
extractAPAAC(x, props = c("Hydrophobicity", "Hydrophilicity"), lambda = 30,
w = 0.05, customprops = NULL)
I tried creating a function to run it for number of file sequences and the program looks like this
read_and_extract <- function(fasta) {
seq <- readFASTA(fasta)[[1]]
return(extractAPAAC(seq, props = c("Hydrophobicity", "Hydrophilicity"), lambda = 30,
w = 0.05, customprops = NULL))
}
setwd("H:\\CC")
fasta_files <- dir(pattern = "[.]fasta$")
aa_comp <- vapply(fasta_files, read_and_extract, rep(pi, 80))
write.csv(aa_comp, file = "C:\\Users\\PAAC.csv")
This programs shows an error
Error: unexpected ',' in "w = 0.05,"
But I have given w=0.05 as of default value, could anyone tell me where is the actual problem?

Resources