How to seperately label edge.label.position for parameter estimates and covariances - semplot

I am trying to seperately position the edge labels for the parameter estimates and the covariances. For the parameter estimates I would like them at .1 and for the covariances and disturbances I would like them at .5, but I only know how to change them through the edge.label.position argument.
semPaths(fit,"std", layout = "tree3",
whatLabels = "std", edge.label.cex=.9, curvePivot = TRUE,
residuals = TRUE, rotation = 2, sizeMan = 16, sizeMan2 = 6,
sizeInt = 8, exoVar = FALSE, exoCov = FALSE,
nodeLabels = c("Social","Intrapersonal", "Distress
Tolerance","Intrusion","Avoidance","NACM","Arousal",
"BPD Symptoms"), edge.label.position = .5,
label.cex = .8, label.scale = FALSE)
I expect the parameter estimates to be on the left side of the structural paths near the manifest variables and the parameter estimates to be in the middle of the paths for the covariance and disturbance.

Related

How to create my own layers on MONAI U-Net?

I'm using MONAI on Spyder Anaconda to build a U-Net network. I want to add/modify layers starting from this baseline.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nets.UNet(
spatial_dims = 2,
in_channels = 3,
out_channels = 1,
channels = (4, 8, 16, 32, 64),
strides = (2, 2, 2, 2),
num_res_units = 3,
norm = layers.Norm.BATCH,
kernel_size=3,).to(device)
loss_function = losses.DiceLoss()
torch.backends.cudnn.benchmark = True
optimizer = torch.optim.Adam(model.parameters(), lr = 1e-4, weight_decay = 0)
post_pred = Compose([EnsureType(), Activations(sigmoid = True), AsDiscrete(threshold=0.5)])
post_label = Compose([EnsureType()])
inferer = SimpleInferer()
utils.set_determinism(seed=46)
My final aim is to create a MultiResUNet that has different layers such as:
class Conv2d_batchnorm(torch.nn.Module):
'''
2D Convolutional layers
Arguments:
num_in_filters {int} -- number of input filters
num_out_filters {int} -- number of output filters
kernel_size {tuple} -- size of the convolving kernel
stride {tuple} -- stride of the convolution (default: {(1, 1)})
activation {str} -- activation function (default: {'relu'})
'''
def __init__(self, num_in_filters, num_out_filters, kernel_size, stride = (1,1), activation = 'relu'):
super().__init__()
self.activation = activation
self.conv1 = torch.nn.Conv2d(in_channels=num_in_filters, out_channels=num_out_filters, kernel_size=kernel_size, stride=stride, padding = 'same')
self.batchnorm = torch.nn.BatchNorm2d(num_out_filters)
def forward(self,x):
x = self.conv1(x)
x = self.batchnorm(x)
if self.activation == 'relu':
return torch.nn.functional.relu(x)
else:
return x
This is just an example of a different Conv2d layer that I would use instead of the native one of the baseline.
Hope some of you can figure out how to proceed.
Thanks, Fede

Map Layer Issues in ggplot2

I'm having a few issues with finalizing my map for a report. I think I'm warm on the solutions, but haven't quite figured them out. I would really appreciate any help on solutions so that I can finally move on!
1) The scale bar will NOT populate in the MainMap code and the subsequent Figure1 plot. This is "remedied" in the MainMap code if I comment out the "BCWA_land" map layer. However, when I retain the "BCWA_land" map layer it will eliminate the scale bar and produces this error:
Warning message: Removed 3 rows containing missing values (geom_text).
And this is the code:
MainMap <- ggplot(QOI) +
geom_sf(aes(fill = quadID)) +
scale_fill_manual(values = c("#6b8c42",
"#70b2ae",
"#d65a31")) +
labs(fill = "Quadrants of Interest",
caption = "Figure 1: Map depicting the quadrants in the WSDOT project area as well as other quadrants of interest in the Puget Sound area.")+
ggtitle("WSDOT Project Area and Quadrants of Interest") +
scalebar(x.min = -123, x.max = -122.8, y.min = 47, y.max = 47.1, location = "bottomleft",
transform = TRUE, dist = 10, dist_unit = "km", st.size = 3, st.bottom = TRUE, st.dist = 0.1) +
north(data = QOI, location = "topleft", scale = 0.1, symbol = 12, x.min = -123, y.min = 48.3, x.max = -122.7, y.max = 48.4) +
theme_bw()+
theme(panel.grid= element_line(color = "gray50"),
panel.background = element_blank(),
panel.ontop = TRUE,
legend.text = element_text(size = 11, margin = margin(l = 3), hjust = 0),
legend.position = c(0.95, 0.1),
legend.justification = c(0.85, 0.1),
legend.background = element_rect(colour = "#3c4245", fill = "#f4f4f3"),
axis.title = element_blank(),
plot.title = element_text(face = "bold", colour = "#3c4245", hjust = 0.5, margin = margin(b=10, unit = "pt")),
plot.caption = element_text(face = "italic", colour = "#3c4245", margin = margin(t = 7), hjust = 0, vjust = 0.5)) +
geom_sf(data = BCWA_land) + #this is what I've tried to comment out to determine the scale bar problem
xlim (-123.1, -121.4) +
ylim (47.0, 48.45)
MainMap
InsetRect <- data.frame(xmin=-123.2, xmax=-122.1, ymin=47.02, ymax=48.45)
InsetMap <- ggplotGrob( ggplot( quads) +
geom_sf(aes(fill = "")) +
scale_fill_manual(values = c("#eefbfb"))+
geom_sf(data = BCWA_land) +
scale_x_continuous(expand = c(0,0), limits = c(-124.5, -122.0)) +
scale_y_continuous(expand = c(0,0), limits = c(47.0, 49.5)) +
geom_rect(data = InsetRect,aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
color="#3c4245",
size=1.25,
fill=NA,
inherit.aes = FALSE) +
theme_bw()+
theme(legend.position = "none",
panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.margin = margin(0,0,0,0)))
InsetMap
Figure1 <- MainMap +
annotation_custom(grob = InsetMap, xmin = -122.2, xmax = -121.3,
ymin = 47.75, ymax = 48.5)
Figure1
As you can see I'm not getting this issue or error for my north arrow so I'm not really sure what is happening with the scale bar!
This problem is probably a little too OCD, however I REALLY don't want the gridlines to show up on the InsetMap, and was hoping that the InsetMap would overlay on top of the MainMap, without gridlines as I had those parameters set to element_blank() in the InsetMap code.
Here is an image of my plot. If you would like the data for this, please let me know. Because these are shapefiles, the data is unwieldy and not super conducive to SO's character limit for a post...
If anyone has any insight into a solution(s) I would so so appreciate that!! Thanks for your time!
The issue was the
xlim (-123.1, -121.4) +
ylim (47.0, 48.45)
call that I made. Instead, I used coord_sf(xlim = c(min, max), ylim = c(min, max)). I thought that this would be helpful to someone who might be in my position later on!
Essentially the difference between setting the limits of to the graph using just the x/y lim calls is that that truncates the data that is available in your dataset, whereas the coord_sf call simply "focuses" your graph on that extent if you will without altering the data you have available in your dataset.

Wind roses overlayed on map

I have wind data from multiple weather stations and I have the coordinates of the each weather station. I want to overlay wind roses from each station over a map using the stations' lat and long. Is there a straight forward way of doing this in R?
This is how I did it so far in R. I saved the windroses as png and then overlayed it on map.
#######################################
########produce map of GTA##############
#######################################
ggmap=get_map(location=c(left=-80.7 , bottom=43 , right=-77.7 , top=44.9))
gta=ggmap(ggmap)+ scale_y_continuous(limits=c(43.2, 44.5))
####################################################
###########for loop to make wind roses##############
###################################################
data_list<- list.files(path= "/home/npak/Documents/weather_data/meso_west_data/", pattern = "\\.csv$", recursive = FALSE, full.names = TRUE)
l<-length(data_list)
for (i in 1:l){
header<-readLines(data_list[i], 8)
variables = strsplit(header, ',')
vars=variables[[7]]
info= strsplit(header, ':')
lat= as.numeric(info[[3]][2])
long= as.numeric(info[[4]][2])
elev= as.numeric(info[[5]][2])
name=info[[2]][2]
data <- read.table(data_list[i], header= FALSE, sep=",", col.names = paste0("V",seq_len(30)), fill=TRUE, skip=8)
missing= length(data)-length(vars)
colnames(data)= c(vars, rep("Empty", missing) )
print(unique(data$Station_ID))
data$ws<-data$wind_speed_set_1
data$wd<-data$wind_direction_set_1
data$date<- as.POSIXct(data$Date_Time, format = "%Y-%m-%d %H:%M")
ID<-unique(data$Station_ID)
png(filename=(file<- paste('/home/npak/Documents/weather_data/meso_west_data/map_1year/', ID ,'all_year_map.png')),
width = 2400, height = 2400,bg = "transparent")
windRose(data,
breaks = c(1.5,3.3,5.5,8),
max.freq = 25
,paddle = FALSE,
, annotate = FALSE, key= FALSE,
auto.text = FALSE, ,grid.line = list(lty =0, value= 10),
cols=c("red", "red2", "red3", "red4"))
#,annotate = FALSE, key= FALSE)
#dev.off()
dev.off.crop(file=file)
mypng <- readPNG(file<- paste('/home/npak/Documents/weather_data/meso_west_data/map_1year/', ID ,'all_year_map.png'))
gta=gta+inset_raster(mypng, ymin = lat-0.2,ymax= lat+0.2,xmin = long-0.2,xmax = long+0.2)
}
######################################################
###############save map into png#######################################
##########################################################
png('/home/npak/Documents/weather_data/meso_west_data/map_1year/gta_annual.png',
width = 2400, height = 2400)
print(gta)
dev.off()
But it doesn't look as good. Right now I am saving the png image with a transparent background but the axis and frames are still there which makes the map look a bit messy. This is how it looks like:
Windroses overlayed on map
So I am looking for something simillar but to directly plot it over the map and not using the png pictures.

R: how to properly create rx_forest_model object?

I'm trying to do a churn analysis with R and SQL Server 2016.
I have uploaded my dataset on my database in a local SQL Server and I did all the preliminary work on this dataset.
Well, now I have this function trainModel() which I would use to estimate my random model forest:
trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString
trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
table = trainTable,
colInfo = cdrColInfo)
## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)
## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
data = trainDataSQL,
nTree = 8,
maxDepth = 16,
mTry = 2,
minBucket = 1,
replace = TRUE,
importance = TRUE,
seed = 8,
parms = list(loss = c(0, 4, 1, 0)))
return(rx_forest_model)
}
But when I run the function I get this wrong output:
> system.time({
+ trainModel(sqlSettings, trainTable)
+ })
user system elapsed
0.29 0.07 58.18
Warning message:
In tempGetNumObs(numObs) :
Number of observations not available for this data source. 'numObs' set to 1e6.
And for this warning message, the function trainModel() does not create the object rx_forest_model
Does anyone have any suggestions on how to solve this problem?
After several attempts, I found the reason why the function trainModel() did not function properly.
Is not a connection string problem and is not even a data source type issue.
The problem is in the syntax of function trainModel().
It is enough to eliminate from the body of the function the statement:
return(rx_forest_model)
In this way, the function returns the same warning message, but creates the object rx_forest_model in the correct way.
So, the correct function is:
trainModel = function(sqlSettings, trainTable) {
sqlConnString = sqlSettings$connString
trainDataSQL <- RxSqlServerData(connectionString = sqlConnString,
table = trainTable,
colInfo = cdrColInfo)
## Create training formula
labelVar = "churn"
trainVars <- rxGetVarNames(trainDataSQL)
trainVars <- trainVars[!trainVars %in% c(labelVar)]
temp <- paste(c(labelVar, paste(trainVars, collapse = "+")), collapse = "~")
formula <- as.formula(temp)
## Train gradient tree boosting with mxFastTree on SQL data source
library(RevoScaleR)
rx_forest_model <- rxDForest(formula = formula,
data = trainDataSQL,
nTree = 8,
maxDepth = 16,
mTry = 2,
minBucket = 1,
replace = TRUE,
importance = TRUE,
seed = 8,
parms = list(loss = c(0, 4, 1, 0)))
}

Error adding scale bar with map.scale

I manage to create a map and even include a north arrow, but can't get the map.scale to work and getting this kind of error:
Error in map.scale(x = -83, y = 12, ratio = FALSE, relwidth = 0.2, cex
= 0.6) : unused arguments (ratio = FALSE, relwidth = 0.2, cex = 0.6)
Here is the code:
library(maps)
library(mapdata)
library(ggmap)
library(mapproj)
library(maptools) #for shapefiles
library(scales) #for transparency
library(GISTools)
range <- readShapePoly("isthmanianpacificmoistforestecoregion") #layer of data for species range
map("worldHires", c('Cost', 'pan', 'Nic', 'Colombia'), xlim=c(-89,-75),ylim=c(5,13), col="lightgray", fill=TRUE) #plot the region I want
map.scale(-81,8,relwidth = 0.15, metric = TRUE, ratio = TRUE)
plot(range, add=TRUE, xlim=c(-89,-75),ylim=c(5,13), col=alpha("green", 0.6), border=TRUE)
map.scale(x=-80, y=10) #, relwidth=0.3, cex=0.5, ratio=FALSE)
north.arrow(xb=-77, yb=12, len=0.2, lab="N", col="black", fill=TRUE) #
The problem is that map.scale() is a function for both maps and GISTools packages. You are trying to use the function from the maps package. Since you are loading first maps and then GISTools, the map.scale() from maps is being masked (probably R throws a warning when loading the last package).
The solution is to specify the package in the function call:
maps::map.scale(-81,8,relwidth = 0.15, metric = TRUE, ratio = TRUE)
Also why two calls to map.scale? You should probably exclude one of them.

Resources