'spatstat' 'envelope'-object cannot be assessed by dclf.test (error: wrong number of rows) - spatstat

I have spatio-temporal data for shrub colonisation, due to a very high number of individuals restricted to three polygonal transects (5m wide, 60-100m long, spaced ~30m apart). I am analysing the data in 'spatstat' version 1.58-2.
I want to assess the clustering between individuals, both total (all mapped individuals) and in subsequent cohorts (recruits vs. established in 7 subsequent periods), by 'pcfinhom' & 'pcfcross.inhom'.
I have created 'envelope'-objects with arguments 'savefuns = T' and 'savepatterns = T' for latter assessment by DCLF-test, for example:
T_all_PCFi_gl<-envelope(T_all_ppp,fun=pcfinhom,nsim=39,verbose=T,
simulate=expression(rpoispp(den_tr[["T_all"]])), #density in all transects
correction="trans",global=T,
savefuns = T, savepatterns = T)
However, if I want to check the results by the DCLF-test,
dclf.test(T_all_PCFi_gl)
I still get this error-message:
Error in data.frame(r = rvals, obs = fX, mmean = m, lo = lo, hi = hi):arguments imply differing number of rows: 55, 56
I have traced the problem to the 'envelope'-object, where "simfun" has one more observation than the dataframe itself, but what do I do wrong? How can I fix this and get the DCLF-test working properly?
The strangest thing is that it doesn't happen in all 7 'pcfcross.inhom' 'envelope'-objects, but apparently only for those with larger number of individuals (>700).
Is it my mistake (if yes, where in the code?), or is it a bug?
Thank you very much in advance for answer!
(I am sorry for not uploading the data, but they are to be published in an article)
EDIT:
Here is output from traceback (,3):
> traceback(,3)
8: stop(gettextf("arguments imply differing number of rows: %s",
paste(unique(nrows), collapse = ", ")), domain = NA)
7: data.frame(r = rvals, obs = fX, mmean = m, lo = lo, hi = hi)
6: (function (Y, ..., rvals = NULL, observed = NULL, theory = NULL,
funX = NULL, nsim = NULL, nsim2 = NULL, jsim = NULL, jsim.mean = NULL,
type = c("pointwise", "global", "variance"), alternative =
c("two.sided",
...
5: do.call(envelope.matrix, resolve.defaults(list(Y = as.matrix(df)),
aargh, list(type = etype, csr = csr, funX = Y, Yname = Yname,
weights = wt), .StripNull = TRUE))
4: envelope.envelope(X, ..., savefuns = TRUE, savepatterns = savepatterns,
Yname = Xname, verbose = verbose)
3: envelope(X, ..., savefuns = TRUE, savepatterns = savepatterns,
Yname = Xname, verbose = verbose)
2: envelopeTest(X, ..., exponent = 2, alternative = alternative,
rinterval = rinterval, leaveout = leaveout, scale = scale,
clamp = clamp, interpolate = interpolate, Xname = Xname)
1: dclf.test(colcl_b1_pcf, alternative = "greater")
Edit 2:
After upgrade to version 1.58-2.042:
> dclf.test(colcl_b5_pcf)
Error in (function (Y, ..., rvals = NULL, observed = NULL, theory = NULL,
:
nrow(funX) == nrow(Y) is not TRUE`
> traceback(,3)
8: stop(simpleError(msg, call = sys.call(-1)))
7: stopifnot(nrow(funX) == nrow(Y))
6: (function (Y, ..., rvals = NULL, observed = NULL, theory = NULL,
funX = NULL, nsim = NULL, nsim2 = NULL, jsim = NULL, jsim.mean = NULL,
type = c("pointwise", "global", "variance"), alternative =
c("two.sided",
...
5: do.call(envelope.matrix, resolve.defaults(list(Y = as.matrix(df)),
aargh, list(type = etype, csr = csr, funX = Y, Yname = Yname,
weights = wt), .StripNull = TRUE))
4: envelope.envelope(X, ..., savefuns = TRUE, savepatterns = savepatterns,
Yname = Xname, verbose = verbose)
3: envelope(X, ..., savefuns = TRUE, savepatterns = savepatterns,
Yname = Xname, verbose = verbose)
2: envelopeTest(X, ..., exponent = 2, alternative = alternative,
rinterval = rinterval, leaveout = leaveout, scale = scale,
clamp = clamp, interpolate = interpolate, Xname = Xname)
1: dclf.test(colcl_b5_pcf)

This is probably a bug in spatstat but I have not been able to reproduce it. Without your data, I may be unable to find the bug.
Please re-run the example and after an error occurs, type traceback(,3) and capture the printed output. This may help me track down the bug.
You could also try including the argument ginterval in the call to envelope. The problem is probably related to the default rule for calculating ginterval.

Related

Error in coxModelFrame.coxph(object) : invalid object set x=TRUE in the call to coxph

The following example is for anyone who is building a Cox Proportional Hazards models and trying to produce prediction error curves, but get an error stating:
Error in coxModelFrame.coxph(object) : invalid object
set x=TRUE in the call to coxph.
Here is the code to reproduce the error:
LIBRARIES
library(survival)
library(survminer)
library(pec)
library(Hmisc)
library(rms)
library(riskRegression)
#install.packages("doMC", repos="http://R-Forge.R-project.org")
library(doMC)
The Data
#Load and store the data
lcOrig <- read.csv("cancer.csv")
#Replace all the 1's with 0's (censored)
lcOrig$status <- gsub(pattern = "1", replacement = "0", x = lcOrig$status, fixed = TRUE)
#Replace all the 2's with 1's (death)
lcOrig$status <- gsub (pattern = "2", replacement = "1", x = lcOrig$status, fixed = TRUE)
#Do the same thing for sex (0 = Males, 1 = Females)
lcOrig$sex <- gsub(pattern = "1", replacement = "0", x = lcOrig$sex, fixed = TRUE)
lcOrig$sex <- gsub(pattern = "2", replacement = "1", x = lcOrig$sex, fixed = TRUE)
#Change the class of these variables to integer.
lcOrig$status <- as.integer(lcOrig$status)
lcOrig$sex <- as.integer(lcOrig$sex)
lcOrig$ph.ecog <- as.integer(lcOrig$ph.ecog)
#Remove missing values and column with over 20% missing data.
apply(lcOrig, 2, function(x) sum(is.na(x))/length(x))
lcOrig <- lcOrig[, c(1:9, 11)]
lc <- lcOrig[complete.cases(lcOrig), ]
Cox Proportional Hazards
fitform1 <- Surv(time, status) ~ inst + age + sex + ph.ecog + ph.karno + pat.karno + wt.loss
cox1 <- coxph(fitform1, data = lc)
PREDICTION ERROR CURVES
extends <- function(...) TRUE
library("doMC")
registerDoMC()
set.seed(0692)
fitpec1 <- pec(list("CPH" = cox1), data = lc, formula = fitform1, splitMethod = "cv10", B = 5, keep.index = TRUE, keep.matrix = TRUE)
The last line of code results in the following error:
Error in coxModelFrame.coxph(object) : invalid object
set x=TRUE in the call to coxph
SOLUTION
Change:
cox1 <- coxph(fitform1, data = lc)
To:
cox1 <- coxph(fitform1, data = lc, x = TRUE)
This did not use to be a requirement 2 years ago, but is now. I hope this helps save you some time!

Mean of one variable when another variable equals 1 in matlab

I would like to get the mean of my reaction time column when my stimnum column is equal to 1
I am not sure if i can do this with one simple line of code or if i need to do a for loop.
stimnum = randi([1 3], [1 100]);
y = 1 + 1.*randn(1, 100);
rt = (y.^2) +.01;
A = rand(1,100);
correct = A>=0.2;
Data= [stimnum; rt; correct ]';
Data = dataset({ Data, 'Stimnum', 'RT', 'Correct'});
rtmean = mean (Data.RT{Data.Stimnum == 1});

Why am I not getting an expected output using logical operators and indexing?

I am having trouble achieving an expected output. I am trying to create a byte adder using logical operators such as AND, XOR and OR. I have taken the minimal code required to reproduce the problem out of code, so assume that finalfirstvalue = "1010" and finalsecondvalue = "0101".
secondvalueindex = (len(finalsecondvalue) - 1)
carry, finalans = False, []
for i in range(-1, -len(finalfirstvalue) - 1, -1):
andone = (bool(finalfirstvalue[i])) & (bool(finalsecondvalue[secondvalueindex]))
xorone = (bool(finalfirstvalue[i])) ^ (bool(finalsecondvalue[secondvalueindex]))
andtwo = (bool(carry)) & (bool(xorone))
xortwo = (bool(carry)) ^ (bool(xorone))
orone = (bool(andone)) | (bool(andtwo))
carry = (bool(orone))
finalans.append(xortwo)
secondvalueindex -= 1
answer = ''.join(str(e) for e in finalans)
print (answer)
Actual Output: FalseTrueTrueTrue
Expected Output: TrueTrueTrueTrue
The code then follows to change back into zeroes and ones.
Because its missing a single boolean I feel like the issue is with my indexing. Although I've played around with it a bit and not had any luck.
I need to carry out these operations on the two variables mentioned at the start, but for the right most elements, and then move to the left by one for the next loop and so on.
First mistake is You are representing your binary numbers as string values.
finalfirstvalue = "1010"
finalsecondvalue = "0101"
secondvalueindex = (len(finalsecondvalue) - 1) == 3
So in second for loop you will get the result as
(finalsecondvalue[secondvalueindex]) == '0'
If you check in your Idle
>>> bool('0')
True
>>>
Because '0' is not actual 0 it is an non-empty string so it return True.
You need to cast your result to int before checking them with bool
Like this
(bool(int(finalsecondvalue[secondvalueindex])))
EDIT 2 Adding with variable lenghts
Full adder with verification using bin() function
a="011101"
b="011110"
if a>b:
b=b.zfill(len(a))
if a<b:
a=a.zfill(len(b))
finalfirstvalue = a
finalsecondvalue = b
carry, finalans = 0, []
secondvalueindex = (len(finalsecondvalue))
for i in reversed(range(0, len(finalfirstvalue))):
xorone = (bool(int(finalfirstvalue[i]))) ^ (bool(int(finalsecondvalue[i])))
andone = (bool(int(finalfirstvalue[i]))) & (bool(int(finalsecondvalue[i])))
xortwo = (carry) ^ (xorone)
andtwo = (carry) & (xorone)
orone = (andone) | (andtwo)
carry = (orone)
finalans.append(xortwo)
finalans.reverse()
answer=(''.join(str(e) for e in finalans))
print(str(carry)+answer)
print(bin(int(a,2) + int(b,2))) #verification
So I found the issue was to do with carry. I changed my code to look like the following. Prior to this code below, is code to convert binary values to boolean. For instance, all ones will equal True and all zeroes will equal False.
carry, finalans = False, []
indexvalue = (len(finalfirstvalue)-1)
while indexvalue >= 0:
andone = (firstvaluelist[indexvalue]) & (secondvaluelist[indexvalue])
xorone = (firstvaluelist[indexvalue]) ^ (secondvaluelist[indexvalue])
andtwo = (carry) & (xorone)
xortwo = (carry) ^ (xorone)
orone = (andone) | (andtwo)
carry = (orone)
if (carry == True) & (indexvalue == 0):
finalans.append(xortwo)
finalans.append(True)
else:
finalans.append(xortwo)
indexvalue -= 1
for n, i in enumerate(finalans):
if i == False:
finalans[n] = "0"
if i == True:
finalans[n] = "1"
finalans.reverse()
answer = ''.join(str(e) for e in finalans)
print (answer)
So if there was a single value missing, it was still stored in carry from the final loop but did not get the opportunity to be appended to the final result. To fix this, I added in an if statement to check if carry is containing anything (True) and if the loop is on its final loop by checking if indexvalue is at 0. This way, if the inputs are 32 and 32, rather than getting [False, False, False, False, False, False] as the output, the newly entered if statement will add the missing value in.

how to convert a swift String to an array of CGGlyph

This snippet can be used for drawing CGGlyphs with a CGContext.
//drawing
let coreGraphicsFont = CTFontCopyGraphicsFont(coreTextFont, nil)
CGContextSetFont(context, coreGraphicsFont);
CGContextSetFontSize(context, CTFontGetSize(coreTextFont))
CGContextSetFillColorWithColor(context, Color.blueColor().CGColor)
CGContextShowGlyphsAtPositions(context, glyphs, positions, length)
But how do I obtain the CGGlyphs from a swift string which contains emoji symbols like flags or accented characters?
let string = "swift: \u{1F496} \u{65}\u{301} \u{E9}\u{20DD} \u{1F1FA}\u{1F1F8}"
Neither of these approaches shows the special characters, even though they are correctly printed to the console. Note that this first approach returns NSGlyph but CGGlyph's are required for drawing.
var progress = CGPointZero
for character in string.characters
{
let glyph = font.glyphWithName(String(character))
glyphs.append(CGGlyph(glyph))
let advancement = font.advancementForGlyph(glyph)
positions.append(progress)
progress.x += advancement.width
}
or this second approach which requires casting to NSString:
var buffer = Array<unichar>(count: length, repeatedValue: 0)
let range = NSRange(location: 0, length: length)
(string as NSString).getCharacters(&buffer, range: range)
glyphs = Array<CGGlyph>(count: length, repeatedValue: 0)
CTFontGetGlyphsForCharacters(coreTextFont, &buffer, &glyphs, length)
//glyph positions
advances = Array<CGSize>(count: length, repeatedValue: CGSize.zero)
CTFontGetAdvancesForGlyphs(ctFont, CTFontOrientation.Default, glyphs, &advances, length)
positions = []
var progress = CGPointZero
for advance in advances
{
positions.append(progress)
progress.x += advance.width
}
Some of the characters are drawn as empty boxes with either approach. Kinda stuck here, hoping you can help.
edit:
Using CTFontDrawGlyphs renders the glyphs correctly, but setting the font, size and text matrix directly before calling CGContextShowGlyphsAtPositions draws nothing. I find that rather odd.
If you generate glyphs yourself, you also need to perform font substitution yourself. When you use Core Text or TextKit to lay out and draw the text, they perform font substitution for you. For example:
let richText = NSAttributedString(string: "HellošŸ˜€ā†’")
let line = CTLineCreateWithAttributedString(richText)
print(line)
Output:
<CTLine: 0x7fa349505f00>{run count = 3, string range = (0, 8), width = 55.3457, A/D/L = 15/4.6875/0, glyph count = 7, runs = (
<CTRun: 0x7fa34969f600>{string range = (0, 5), string = "Hello", attributes = <CFBasicHash 0x7fa3496902d0 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153bb720 [0x10e85a7b0]>{contents = "NSFont"} = <CTFont: 0x7fa3496182f0>{name = Helvetica, size = 12.000000, matrix = 0x0, descriptor = <CTFontDescriptor: 0x7fa34968f860>{attributes = <CFBasicHash 0x7fa34968f8b0 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153c16c0 [0x10e85a7b0]>{contents = "NSFontNameAttribute"} = <CFString 0x1153b4700 [0x10e85a7b0]>{contents = "Helvetica"}
}
>}}
}
}
<CTRun: 0x7fa3496cde40>{string range = (5, 2), string = "\U0001F600", attributes = <CFBasicHash 0x7fa34b11a150 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153bb720 [0x10e85a7b0]>{contents = "NSFont"} = <CTFont: 0x7fa3496c3eb0>{name = AppleColorEmoji, size = 12.000000, matrix = 0x0, descriptor = <CTFontDescriptor: 0x7fa3496a3c30>{attributes = <CFBasicHash 0x7fa3496a3420 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153c16c0 [0x10e85a7b0]>{contents = "NSFontNameAttribute"} = <CFString 0x11cf63bb0 [0x10e85a7b0]>{contents = "AppleColorEmoji"}
}
>}}
}
}
<CTRun: 0x7fa3496cf3e0>{string range = (7, 1), string = "\u2192", attributes = <CFBasicHash 0x7fa34b10ed00 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153bb720 [0x10e85a7b0]>{contents = "NSFont"} = <CTFont: 0x7fa3496cf2c0>{name = PingFangSC-Regular, size = 12.000000, matrix = 0x0, descriptor = <CTFontDescriptor: 0x7fa3496a45a0>{attributes = <CFBasicHash 0x7fa3496a5660 [0x10e85a7b0]>{type = mutable dict, count = 1,
entries =>
2 : <CFString 0x1153c16c0 [0x10e85a7b0]>{contents = "NSFontNameAttribute"} = <CFString 0x11cf63230 [0x10e85a7b0]>{contents = "PingFangSC-Regular"}
}
>}}
}
}
)
}
We can see here that Core Text recognized that the default font (Helvetica) doesn't have glyphs for the emoji or the arrow, so it split the line into three runs, each with the needed font.
The Core Text Programming Guide says this:
Most of the time you should just use a CTLine object to get this information because one font may not encode the entire string. In addition, simple character-to-glyph mapping will not get the correct appearance for complex scripts. This simple glyph mapping may be appropriate if you are trying to display specific Unicode characters for a font.
Your best bet is to use CTLineCreateWithAttributedString to generate glyphs and choose fonts. Then, if you want to adjust the position of the glyphs, use CTLineGetGlyphRuns to get the runs out of the line, and then ask the run for the glyphs, the font, and whatever else you need.
If you want to handle font substitution yourself, I think you're going to want to look into ā€œfont cascadingā€.

Lua splitting a string without separators

Is there an easy way to split a string like this:
M34a79 or M2ab943 or M4c4
into
M,34,a,79 or M,2,ab,943 or M,4,c,4
without any separators?
You can do it with a pair of gsub calls:
x = "M34a79 or M2ab943 or M4c4"
x, _ = x:gsub( "(%d)(%a)", "%1,%2" )
x, _ = x:gsub( "(%a)(%d)", "%1,%2" )
print( x )
M,34,a,79 or M,2,ab,943 or M,4,c,4
Might not work in all cases, but does work on your example.
If you donā€™t mind using the LPEG
library:
local lpeg = require "lpeg"
local C, Ct, P, R = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R
local lpegmatch = lpeg.match
local extract
do
local digit = R"09"
local lower = R"az"
local comma = P","
local space = P" "
local schema = Ct( C(P"M")
* (digit^1 / tonumber)
* C(lower^1)
* (digit^1 / tonumber))
local extractor = Ct((schema + 1)^0)
extract = function (str)
return lpegmatch (extractor, str)
end
end
This will match all sequences of characters of the input
that consist of (in that order)
the letter M,
a sequence of 1 or more decimal digits,
a sequence of 1 or more lowercase characters, and
another sequence of 1 or more decimal digits.
When processing the input each match is put in a subtable,
the digits are converted to Lua numbers on the fly.
Since the question requested it, the leading M is included
in the entries.
Usage example:
local data = extract [[M34a79 or M2ab943 or M4c4]]
for i = 1, #data do
local elm = data[i]
print (string.format ("[%d] = { [1] = %q, [2] = %d, [3] = %q, [4] = %d },",
i, table.unpack (elm)))
end
Output:
[1] = { [1] = "M", [2] = 34, [3] = "a", [4] = 79 },
[2] = { [1] = "M", [2] = 2, [3] = "ab", [4] = 943 },
[3] = { [1] = "M", [2] = 4, [3] = "c", [4] = 4 },
Solution:
http://www.coronalabs.com/blog/2013/04/16/lua-string-magic/
function string:split( inSplitPattern, outResults )
...
end
function val(x)
x = x:gsub( "(%d)(%a)", "%1,%2" )
x = x:gsub( "(%a)(%d)", "%1,%2" )
Table = string.split(x,",")
for i = 1, #Table do
print( Table[i] )
end
end
val("M3a5")
returns M 3 a 5

Resources