Title: | GUI Tools Made Easy: Interact with Models and Explore Data |
---|---|
Description: | Provides software to facilitate the design, testing, and operation of computer models. It focuses particularly on tools that make it easy to construct and edit a customized graphical user interface ('GUI'). Although our simplified 'GUI' language depends heavily on the R interface to the 'Tcl/Tk' package, a user does not need to know 'Tcl/Tk'. Examples illustrate models built with other R packages, including 'PBSmapping', 'PBSddesolve', and 'BRugs'. A complete user's guide 'PBSmodelling-UG.pdf' shows how to use this package effectively. |
Authors: | Jon T. Schnute [aut], Alex Couture-Beil [aut], Rowan Haigh [aut, cre], Nicholas Boers [ctb], Anisa Egeli [ctb], A. R. Kronlund [ctb], Steve Martell [ctb], Norm Olsen [ctb] |
Maintainer: | Rowan Haigh <[email protected]> |
License: | GPL (>= 2) |
Version: | 2.69.4 |
Built: | 2025-02-02 05:56:32 UTC |
Source: | https://github.com/pbs-software/pbs-modelling |
Call the arrows
function using relative (0:1) coordinates.
addArrows(x1, y1, x2, y2, ...)
addArrows(x1, y1, x2, y2, ...)
x1 |
x-coordinate (0:1) at base of arrow. |
y1 |
y-coordinate (0:1) at base of arrow. |
x2 |
x-coordinate (0:1) at tip of arrow. |
y2 |
y-coordinate (0:1) at tip of arrow. |
... |
additional parameters for the function |
Lines will be drawn from (x1[i],y1[i])
to (x2[i],y2[i])
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada , Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) tt=seq(from=-5,to=5,by=0.01) plot(sin(tt), cos(tt)*(1-sin(tt)), type="l") addArrows(0.2,0.5,0.8,0.5) addArrows(0.8,0.95,0.95,0.55, col="#FF0066") par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) tt=seq(from=-5,to=5,by=0.01) plot(sin(tt), cos(tt)*(1-sin(tt)), type="l") addArrows(0.2,0.5,0.8,0.5) addArrows(0.8,0.95,0.95,0.55, col="#FF0066") par(oldpar) })
Place a label in a plot using relative (0:1) coordinates
addLabel(x, y, txt, ...)
addLabel(x, y, txt, ...)
x |
x-axis coordinate in the range (0:1); can step outside. |
y |
y-axis coordinate in the range (0:1); can step outside. |
txt |
desired label at ( |
... |
additional arguments passed to the function |
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph() addLabel(0.75,seq(from=0.9,to=0.1,by=-0.10),c('a','b','c'), col="#0033AA") par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph() addLabel(0.75,seq(from=0.9,to=0.1,by=-0.10),c('a','b','c'), col="#0033AA") par(oldpar) })
Place a legend in a plot using relative (0:1) coordinates.
addLegend(x, y, ...)
addLegend(x, y, ...)
x |
x-axis coordinate in the range (0:1); can step outside. |
y |
y-axis coordinate in the range (0:1); can step outside. |
... |
arguments used by the function |
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph() n <- sample(1:length(colors()),15); clrs <- colors()[n] addLegend(.2,1,fill=clrs,leg=clrs,cex=1.5) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph() n <- sample(1:length(colors()),15); clrs <- colors()[n] addLegend(.2,1,fill=clrs,leg=clrs,cex=1.5) par(oldpar) })
Compute Fibonacci numbers using four different methods:
1) iteratively using R code,
2) via the closed function in R code,
3) iteratively in C using the .C
function,
and 4) iteratively in C using the .Call
function.
calcFib(n, len=1, method="C")
calcFib(n, len=1, method="C")
n |
nth fibonacci number to calculate |
len |
a vector of length |
method |
select method to use: |
Vector of the last len
Fibonacci numbers
calculated.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Calculate the geometric mean of a numeric vector, possibly excluding zeroes and/or adding an offset to compensate for zero values.
calcGM(x, offset = 0, exzero = TRUE)
calcGM(x, offset = 0, exzero = TRUE)
x |
vector of numbers |
offset |
value to add to all components, including zeroes |
exzero |
if |
Geometric mean of the modified vector x + offset
NA
values are automatically removed from x
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ calcGM(c(0,1,100)) calcGM(c(0,1,100),offset=0.01,exzero=FALSE) })
local(envir=.PBSmodEnv,expr={ calcGM(c(0,1,100)) calcGM(c(0,1,100),offset=0.01,exzero=FALSE) })
Minimization based on the R-stat functions nlm
, nlminb
, and optim
.
Model parameters are scaled and can be active or not in the minimization.
calcMin(pvec, func, method="nlm", trace=0, maxit=1000, reltol=1e-8, steptol=1e-6, temp=10, repN=0, ...)
calcMin(pvec, func, method="nlm", trace=0, maxit=1000, reltol=1e-8, steptol=1e-6, temp=10, repN=0, ...)
pvec |
Initial values of the model parameters to be optimized.
|
func |
The user-defined function to be minimized (or maximized). The function should return a scalar result. |
method |
The minimization method to use: one of |
trace |
Non-negative integer. If positive, tracing information on the
progress of the minimization is produced. Higher values may produce more
tracing information: for method |
maxit |
The maximum number of iterations. Default is |
reltol |
Relative convergence tolerance. The algorithm stops if it is
unable to reduce the value by a factor of |
steptol |
A positive scalar providing the minimum allowable relative step length.
Default is |
temp |
Temperature controlling the |
repN |
Reports the parameter and objective function values on the R-console
every |
... |
Further arguments to be passed to the optimizing function chosen:
|
See optim
for details on the following methods: Nelder-Mead
,
BFGS
, CG
, L-BFGS-B
, and SANN
.
A list with components:
Fout |
The output list from the optimizer function chosen through |
iters |
Number of iterations. |
evals |
Number of evaluations. |
cpuTime |
The user CPU time to execute the minimization. |
elapTime |
The total elapsed time to execute the minimization. |
fminS |
The objective function value calculated at the start of the minimization. |
fminE |
The objective function value calculated at the end of the minimization. |
Pstart |
Starting values for the model parameters. |
Pend |
Final values estimated for the model parameters from the minimization. |
AIC |
Akaike's Information Criterion |
message |
Convergence message from the minimization routine. |
Some arguments to calcMin
have no effect depending on the method
chosen.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
scalePar
, restorePar
, calcMin
, GT0
In the stats
package: nlm
, nlminb
, and optim
.
local(envir=.PBSmodEnv,expr={ Ufun <- function(P) { Linf <- P[1]; K <- P[2]; t0 <- P[3]; obs <- afile$len; pred <- Linf * (1 - exp(-K*(afile$age-t0))); n <- length(obs); ssq <- sum((obs-pred)^2 ); return(n*log(ssq)); }; oldpar = par(no.readonly = TRUE) afile <- data.frame(age=1:16,len=c(7.36,14.3,21.8,27.6,31.5,35.3,39, 41.1,43.8,45.1,47.4,48.9,50.1,51.7,51.7,54.1)); pvec <- data.frame(val=c(70,0.5,0),min=c(40,0.01,-2),max=c(100,2,2), active=c(TRUE,TRUE,TRUE),row.names=c("Linf","K","t0"), stringsAsFactors=FALSE); alist <- calcMin(pvec=pvec,func=Ufun,method="nlm",steptol=1e-4,repN=10); print(alist[-1]); P <- alist$Pend; #resetGraph(); expandGraph(); xnew <- seq(afile$age[1],afile$age[nrow(afile)],len=100); ynew <- P[1] * (1 - exp(-P[2]*(xnew-P[3])) ); plot(afile); lines(xnew,ynew,col="red",lwd=2); addLabel(.05,.88,paste(paste(c("Linf","K","t0"),round(P,c(2,4,4)), sep=" = "),collapse="\n"),adj=0,cex=0.9); par(oldpar) })
local(envir=.PBSmodEnv,expr={ Ufun <- function(P) { Linf <- P[1]; K <- P[2]; t0 <- P[3]; obs <- afile$len; pred <- Linf * (1 - exp(-K*(afile$age-t0))); n <- length(obs); ssq <- sum((obs-pred)^2 ); return(n*log(ssq)); }; oldpar = par(no.readonly = TRUE) afile <- data.frame(age=1:16,len=c(7.36,14.3,21.8,27.6,31.5,35.3,39, 41.1,43.8,45.1,47.4,48.9,50.1,51.7,51.7,54.1)); pvec <- data.frame(val=c(70,0.5,0),min=c(40,0.01,-2),max=c(100,2,2), active=c(TRUE,TRUE,TRUE),row.names=c("Linf","K","t0"), stringsAsFactors=FALSE); alist <- calcMin(pvec=pvec,func=Ufun,method="nlm",steptol=1e-4,repN=10); print(alist[-1]); P <- alist$Pend; #resetGraph(); expandGraph(); xnew <- seq(afile$age[1],afile$age[nrow(afile)],len=100); ynew <- P[1] * (1 - exp(-P[2]*(xnew-P[3])) ); plot(afile); lines(xnew,ynew,col="red",lwd=2); addLabel(.05,.88,paste(paste(c("Linf","K","t0"),round(P,c(2,4,4)), sep=" = "),collapse="\n"),adj=0,cex=0.9); par(oldpar) })
Count of sampled fish-at-age for quillback rockfish (Sebastes maliger) in Johnstone Strait, British Columbia, from 1984 to 2004.
data(CCA.qbr)
data(CCA.qbr)
A matrix with 70 rows (ages) and 14 columns (years). Attributes “syrs” and “cyrs” specify years of survey and commercial data, respectively.
[,c(3:5,9,13,14)] |
Counts-at-age from research survey samples |
[,c(1,2,6:8,10:12)] |
Counts-at-age from commercial fishery samples |
All elements represent sampled counts-at-age in year. Zero-value entries indicate no observations.
Handline surveys for rockfish have been conducted in
Johnstone Strait (British Columbia) and adjacent waterways
(12637'W to 126
53'W,
50
32'N to 50
39'N) since 1986.
Yamanaka and Richards (1993) describe surveys conducted in 1986,
1987, 1988, and 1992. In 2001, the Rockfish Selective Fishery
Study (Berry 2001) targeted quillback rockfish Sebastes
maliger for experiments on improving survival after capture by
hook and line gear. The resulting data subsequently have been
incorporated into the survey data series. The most recent survey
in 2004 essentially repeated the 1992 survey design. Fish samples
from surveys have been supplemented by commercial handline
fishery samples taken from a larger region
(126
35'W to 127
39'W,
50
32'N to 50
59'N) in the years
1984-1985, 1989-1991, 1993, 1996, and 2000 (Schnute and Haigh
2007).
Years 1994, 1997-1999, and 2002-2003 do not have data.
Fisheries and Oceans Canada - GFBio database:
http://www.pac.dfo-mpo.gc.ca/science/species-especes/groundfish-poissonsdesfonds/stats-eng.html
Berry, M.D. (2001) Area 12 (Inside) Rockfish Selective Fishery Study. Science Council of British Columbia, Project Number FS00-05.
Schnute, J.T. and Haigh, R. (2007) Compositional analysis of catch curve data with an application to Sebastes maliger. ICES Journal of Marine Science 64, 218–233.
Yamanaka, K.L. and Richards, L.J. (1993) 1992 Research catch and effort data on nearshore reef-fishes in British Columbia Statistical Area 12. Canadian Manuscript Report of Fisheries and Aquatic Sciences 2184, 77 pp.
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) # Plot age proportions (blue bubbles = survey data, red = commercial) data(CCA.qbr,envir=.PBSmodEnv); clrs=c("cornflowerblue","orangered") z <- CCA.qbr; cyr <- attributes(z)$cyrs; z <- apply(z,2,function(x){x/sum(x)}); z[,cyr] <- -z[,cyr]; x <- as.numeric(dimnames(z)[[2]]); xlim <- range(x) + c(-.5,.5); y <- as.numeric(dimnames(z)[[1]]); ylim <- range(y) + c(-1,1); expandGraph(mgp=c(2,.5,0),las=1) plotBubbles(z,xval=x,yval=y,powr=.5,size=0.15,clrs=clrs, xlim=xlim,ylim=ylim,xlab="Year",ylab="Age",cex.lab=1.5) addLegend(.5,1,bty="n",pch=1,cex=1.2,col=clrs, legend=c("Survey","Commercial"),horiz=TRUE,xjust=.5) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) # Plot age proportions (blue bubbles = survey data, red = commercial) data(CCA.qbr,envir=.PBSmodEnv); clrs=c("cornflowerblue","orangered") z <- CCA.qbr; cyr <- attributes(z)$cyrs; z <- apply(z,2,function(x){x/sum(x)}); z[,cyr] <- -z[,cyr]; x <- as.numeric(dimnames(z)[[2]]); xlim <- range(x) + c(-.5,.5); y <- as.numeric(dimnames(z)[[1]]); ylim <- range(y) + c(-1,1); expandGraph(mgp=c(2,.5,0),las=1) plotBubbles(z,xval=x,yval=y,powr=.5,size=0.15,clrs=clrs, xlim=xlim,ylim=ylim,xlab="Year",ylab="Age",cex.lab=1.5) addLegend(.5,1,bty="n",pch=1,cex=1.2,col=clrs, legend=c("Survey","Commercial"),horiz=TRUE,xjust=.5) par(oldpar) })
Prompts the user to choose one string item from a list of choices displayed in a GUI, then sets a specified variable in a target GUI.
chooseWinVal(choice, varname, winname="window")
chooseWinVal(choice, varname, winname="window")
choice |
vector of strings from which to choose |
varname |
variable name to which |
winname |
window name for the target GUI |
chooseWinVal
activates a setWinVal
command through an
onClose
function created by the getChoice
command and
modified by chooseWinVal
.
No value is returned directly. The choice is written to the PBS options
workspace, accessible through getPBSoptions("getChoice")
. Also set
in PBS options is the window name from which the choice was activated.
Microsoft Windows users may experience difficulties switching focus between the R console and GUI windows. The latter frequently disappear from the screen and need to be reselected (either clicking on the task bar or pressing <Alt><Tab>. This issue can be resolved by switching from MDI to SDI mode. From the R console menu bar, select <Edit> and <GUI preferences>, then change the value of “single or multiple windows” to SDI.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
getChoice
, getWinVal
, setWinVal
## Not run: local(envir=.PBSmodEnv,expr={ dfnam <- c("airquality","attitude","ChickWeight","faithful","freeny", "iris","LifeCycleSavings","longley","morley","Orange", "quakes","randu","rock","stackloss","swiss","trees") wlist <- c( "window name=choisir title=\"Test chooseWinVal\"", "label text=\"Press <ENTER> in the green entry box \nto choose a file, then press <GO>\" sticky=W pady=5", "grid 1 3 sticky=W", "label text=File: sticky=W", "entry name=fnam mode=character width=23 value=\"\" func=chFile entrybg=darkolivegreen1 pady=5", "button text=GO bg=green sticky=W func=test", "") chFile <- function(ch=dfnam,fn="fnam") {chooseWinVal(ch,fn,winname="choisir")}; #-- Example 1 GUI test test <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(winName="choisir",scope="L") if (fnam!="" && any(fnam==dfnam)) { file <- get(fnam); pairs(file,gap=0); } else { resetGraph(); addLabel(.5,.5,"Press <ENTER> in the green entry box \nto choose a file, then press <GO>", col="red",cex=1.5) } } #-- Example 2 Non-GUI test #To try the non-GUI version, type 'test2()' on the command line test2 <- function(fnames=dfnam) { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) frame();resetGraph() again <- TRUE; while (again) { fnam <- sample(fnames,1); file <- get(fnam); flds <- names(file); xfld <- getChoice(paste("Pick x-field from",fnam),flds,gui=FALSE); yfld <- getChoice(paste("Pick y-field from",fnam),flds,gui=FALSE) plot(file[,xfld],file[,yfld],xlab=xfld,ylab=yfld, pch=16,cex=1.2,col="red"); again <- getChoice("Plot another pair?",gui=FALSE) } } require(PBSmodelling) createWin(wlist,astext=TRUE); test(); }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ dfnam <- c("airquality","attitude","ChickWeight","faithful","freeny", "iris","LifeCycleSavings","longley","morley","Orange", "quakes","randu","rock","stackloss","swiss","trees") wlist <- c( "window name=choisir title=\"Test chooseWinVal\"", "label text=\"Press <ENTER> in the green entry box \nto choose a file, then press <GO>\" sticky=W pady=5", "grid 1 3 sticky=W", "label text=File: sticky=W", "entry name=fnam mode=character width=23 value=\"\" func=chFile entrybg=darkolivegreen1 pady=5", "button text=GO bg=green sticky=W func=test", "") chFile <- function(ch=dfnam,fn="fnam") {chooseWinVal(ch,fn,winname="choisir")}; #-- Example 1 GUI test test <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(winName="choisir",scope="L") if (fnam!="" && any(fnam==dfnam)) { file <- get(fnam); pairs(file,gap=0); } else { resetGraph(); addLabel(.5,.5,"Press <ENTER> in the green entry box \nto choose a file, then press <GO>", col="red",cex=1.5) } } #-- Example 2 Non-GUI test #To try the non-GUI version, type 'test2()' on the command line test2 <- function(fnames=dfnam) { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) frame();resetGraph() again <- TRUE; while (again) { fnam <- sample(fnames,1); file <- get(fnam); flds <- names(file); xfld <- getChoice(paste("Pick x-field from",fnam),flds,gui=FALSE); yfld <- getChoice(paste("Pick y-field from",fnam),flds,gui=FALSE) plot(file[,xfld],file[,yfld],xlab=xfld,ylab=yfld, pch=16,cex=1.2,col="red"); again <- getChoice("Plot another pair?",gui=FALSE) } } require(PBSmodelling) createWin(wlist,astext=TRUE); test(); }) ## End(Not run)
Launches a new window which contains an interface for deleting junk files associated with a prefix and a set of suffixes (e.g., PBSadmb project) from the working directory.
cleanProj(prefix, suffix, files)
cleanProj(prefix, suffix, files)
prefix |
default prefix for file names. |
suffix |
character vector of suffixes used for clean options. |
files |
character vector of file names used for clean options. |
All arguments may contain wildcard characters ("*"
to match 0 or
more characters, "?"
to match any single character).
The GUI includes the following:
1 | An entry box for the prefix. |
The default value of this entry box is taken from prefix . |
|
2 | Check boxes for each suffix in the suffix argument and |
for each file name in the files argument. |
|
3 | Buttons marked "Select All" and "Select None" for |
selecting and clearing all the check boxes, respectively. | |
4 | A "Clean" button that deletes files in the working directory |
matching one of the following criteria: | |
(i) file name matches both an expansion of a concatenation of a | |
prefix in the entry box and a suffix chosen with a check box; or | |
(ii) file name matches an expansion of a file chosen with a check box. |
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ cleanProj(prefix="foo",suffix=c(".a*",".b?",".c","-old.d"),files=c("red","blue")) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ cleanProj(prefix="foo",suffix=c(".a*",".b?",".c","-old.d"),files=c("red","blue")) }) ## End(Not run)
Launches a new window which contains an interface for deleting specified files from the working directory.
cleanWD(files)
cleanWD(files)
files |
character vector of file names used for clean options. |
All arguments may contain wildcard characters ("*"
to match 0 or
more characters, "?"
to match any single character).
The GUI includes the following:
1 | Check boxes for each suffix in the suffix argument and |
for each file name in the files argument. |
|
2 | Buttons marked "Select All" and "Select None" for |
selecting and clearing all the check boxes, respectively. | |
3 | A "Clean" button that deletes files in the working directory |
matching file name expansion of files chosen with a check box. |
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ cleanWD(c("*.bak","*.tmp","junk*")) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ cleanWD(c("*.bak","*.tmp","junk*")) }) ## End(Not run)
Generic function to clear all objects from .RData in R
clearAll(hidden=TRUE, verbose=TRUE, PBSsave=TRUE, pos=".PBSmodEnv")
clearAll(hidden=TRUE, verbose=TRUE, PBSsave=TRUE, pos=".PBSmodEnv")
if |
|
verbose |
if |
PBSsave |
if |
pos |
The pos argument can specify the environment in which to look
for the object in any of several ways: as an integer (the position in
the search list); as the character string name of an element in the
search list; or as an environment (including using |
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Disassociate any number of file extensions from commands previously saved
with setPBSext
.
clearPBSext(ext)
clearPBSext(ext)
ext |
optional character vector of file extensions to clear; if unspecified, all associations are removed |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
setPBSext
, getPBSext
, openFile
Clear the R console window or focus on the RGui window using Visual Basic shell scripts.
clearRcon(os=.Platform$OS.type) focusRgui(os=.Platform$OS.type)
clearRcon(os=.Platform$OS.type) focusRgui(os=.Platform$OS.type)
os |
operating system (e.g., |
Creates a VB shell script file called clearRcon.vbs
or focusRgui.vbs
in R's temporary working directory, then executes the script using the shell
command.
While clearRcon
clears the R console, focusRgui
returns the desktop
focus back to the RGui window.
These commands will only work on Windows operating platforms, using the system's executable %SystemRoot%\system32\cscript.exe
.
Norm Olsen, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
cleanWD
, clearPBSext
, clearWinVal
## Not run: local(envir=.PBSmodEnv,expr={ createWin( c("window title=Focus", "button text=\"Go to RGui\" width=20 bg=aliceblue func=focusRgui"), astext=T) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ createWin( c("window title=Focus", "button text=\"Go to RGui\" width=20 bg=aliceblue func=focusRgui"), astext=T) }) ## End(Not run)
Remove all global variables that share a name in common with any widget variable name
defined in names(getWinVal())
. Use this function with caution.
clearWinVal()
clearWinVal()
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Clip a vector at one or both ends using the specified clip pattern to match.
clipVector(vec, clip, end=0)
clipVector(vec, clip, end=0)
vec |
vector object to clip |
clip |
value or string specifying repeated values to clip from ends |
end |
end to clip |
If the vector is named, the names are retained. Otherwise, element positions are assigned as the vector's names.
Clipped vector with names.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ x=c(0,0,0,0,1,1,1,1,0,0) print(clipVector(x,0)) x=c(TRUE,TRUE,FALSE,TRUE) print(clipVector(x,TRUE)) x=c("red","tide","red","red") print(clipVector(x,"red",2)) })
local(envir=.PBSmodEnv,expr={ x=c(0,0,0,0,1,1,1,1,0,0) print(clipVector(x,0)) x=c(TRUE,TRUE,FALSE,TRUE) print(clipVector(x,TRUE)) x=c("red","tide","red","red") print(clipVector(x,"red",2)) })
Close (destroy) one or more windows made with createWin
.
closeWin(name)
closeWin(name)
name |
a vector of window names that indicate which windows to close. These
names appear in the window description file(s) on the line(s) defining WINDOW widgets.
If |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
This function provides an alternative to using R's SHLIB
command to compile C code into a shared library object.
compileC(file, lib="", options="", logWindow=TRUE, logFile=TRUE)
compileC(file, lib="", options="", logWindow=TRUE, logFile=TRUE)
file |
name of the file to compile. |
lib |
name of shared library object (without extension). |
options |
linker options (in one string) to prepend to a compilation command. |
logWindow |
if |
logFile |
if |
If lib=""
, it will take the same name as file
(with a different extension).
If an object with the same name has already been dynamically loaded in R, it will be unloaded automatically for recompilation.
The name of the log file, if created, uses the string value from lib
concatenated with ".log"
.
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd() edir <- system.file("examples", package = "PBSmodelling" ) file.copy(paste(edir,"fib.c",sep="/"), tempdir(), overwrite=TRUE) setwd(tempdir()) compileC("fib.c", lib="myLib", options="myObj.o", logWindow=FALSE) print(list.files()) setwd(cwd) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd() edir <- system.file("examples", package = "PBSmodelling" ) file.copy(paste(edir,"fib.c",sep="/"), tempdir(), overwrite=TRUE) setwd(tempdir()) compileC("fib.c", lib="myLib", options="myObj.o", logWindow=FALSE) print(list.files()) setwd(cwd) }) ## End(Not run)
Convert a window description file (ASCII markup file) to an equivalent window description list. The output list (an ASCII file containing R-source code) is complete, i.e., all default values have been added.
compileDescription(descFile, outFile)
compileDescription(descFile, outFile)
descFile |
name of window description file (markup file). |
outFile |
name of output file containing R source code. |
The window description file descFile
is converted to a list,
which is then converted to R code, and saved to outFile
.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Convert slashes in a string from ‘/’ to ‘\\’ if the operating system is ‘windows’. Do the reverse if the OS is ‘unix’.
convSlashes(expr, os=.Platform$OS.type, addQuotes=FALSE)
convSlashes(expr, os=.Platform$OS.type, addQuotes=FALSE)
expr |
String value (usually a system pathway). |
os |
operating system (either |
addQuotes |
logical: if |
Returns the input string modified to have the appropriate slashes for the specified operating system.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Create a basic window containing a vector and a submit button. This provides a quick way to create a window without the need for a window description file.
createVector(vec, vectorLabels=NULL, func="", windowname="vectorwindow", env=NULL)
createVector(vec, vectorLabels=NULL, func="", windowname="vectorwindow", env=NULL)
vec |
a vector of strings representing widget variables.
The values in |
vectorLabels |
an optional vector of strings to use as labels above each widget. |
func |
string name of function to call when new data are entered in widget boxes or when "GO" is pressed. |
windowname |
unique window name, required if multiple vector windows are created. |
env |
an environment in which to evaluate widget callback functions. |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ #user defined function which is called on new data drawLiss <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(scope="L"); tt <- 2*pi*(0:k)/k; x <- sin(2*pi*m*tt); y <- sin(2*pi*(n*tt+phi)); plot(x,y,type="p"); invisible(NULL); }; #create the vector window createVector(c(m=2, n=3, phi=0, k=1000), func="drawLiss", vectorLabels=c("x cycles","y cycles", "y phase", "points")); }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ #user defined function which is called on new data drawLiss <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(scope="L"); tt <- 2*pi*(0:k)/k; x <- sin(2*pi*m*tt); y <- sin(2*pi*(n*tt+phi)); plot(x,y,type="p"); invisible(NULL); }; #create the vector window createVector(c(m=2, n=3, phi=0, k=1000), func="drawLiss", vectorLabels=c("x cycles","y cycles", "y phase", "points")); }) ## End(Not run)
Create a GUI window with widgets using instructions from a Window Description File (aka mark-up file) .
createWin( fname, astext=FALSE, env=NULL )
createWin( fname, astext=FALSE, env=NULL )
fname |
name of window description file
or list returned from |
astext |
logical: if |
env |
an environment in which to evaluate widget callback functions; see example. |
Generally, the markup file contains a single widget per line. However, widgets can span multiple lines by including a backslash ('\') character at the end of a line, prompting the suppression of the newline character.
For more details on widget types and markup file, see “PBSModelling-UG.pdf”
in the R directory .../library/PBSmodelling/doc
.
It is possible to use a Window Description List produced by
compileDescription
rather than a file name for fname
.
Another alternative is to pass a vector of characters to fname
and set
astext=T
. This vector represents the file contents where each element
is equivalent to a new line in the window description file.
Microsoft Windows users may experience difficulties switching focus between the R console and GUI windows. The latter frequently disappear from the screen and need to be reselected (either clicking on the task bar or pressing <Alt><Tab>. This issue can be resolved by switching from MDI to SDI mode. From the R console menu bar, select <Edit> and <GUI preferences>, then change the value of “single or multiple windows” to SDI.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
parseWinFile
, getWinVal
, setWinVal
closeWin
, compileDescription
, createVector
initHistory
for an example of using astext=TRUE
## Not run: # See file .../library/PBSmodelling/testWidgets/LissWin.txt # Calculate and draw the Lissajous figure local(envir=.PBSmodEnv,expr={ drawLiss <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(scope="L"); ti=2*pi*(0:k)/k; x=sin(2*pi*m*ti); y=sin(2*pi*(n*ti+phi)); plot(x,y,type=ptype); invisible(NULL); }; createWin(system.file("testWidgets/LissWin.txt",package="PBSmodelling")); }) ############################################################ # Environment example: # function in global local(envir=.PBSmodEnv,expr={ hello <- function() { stop( "I shouldn't be called" ) } newNameGreeter <- function( name ) { # method to display window greet <- function() { createWin(c("button \"Say hello\" func=hello"), astext=TRUE, env=parent.env(environment())) } # hello method will refer to the name in this local scope hello <- function() { cat( "Hello", name, "\n" ) } # return functions which the user can call directly return( list( greet=greet, hello=hello ) ) } alex <- newNameGreeter( "Alex" ) jon <- newNameGreeter( "Jon" ) alex$hello() # prints hello Alex jon$hello() # prints hello Jon alex$greet() # creates a GUI with a button, which will print "hello Alex" when pushed }) ## End(Not run)
## Not run: # See file .../library/PBSmodelling/testWidgets/LissWin.txt # Calculate and draw the Lissajous figure local(envir=.PBSmodEnv,expr={ drawLiss <- function() { oldpar = par(no.readonly=TRUE); on.exit(par(oldpar)) getWinVal(scope="L"); ti=2*pi*(0:k)/k; x=sin(2*pi*m*ti); y=sin(2*pi*(n*ti+phi)); plot(x,y,type=ptype); invisible(NULL); }; createWin(system.file("testWidgets/LissWin.txt",package="PBSmodelling")); }) ############################################################ # Environment example: # function in global local(envir=.PBSmodEnv,expr={ hello <- function() { stop( "I shouldn't be called" ) } newNameGreeter <- function( name ) { # method to display window greet <- function() { createWin(c("button \"Say hello\" func=hello"), astext=TRUE, env=parent.env(environment())) } # hello method will refer to the name in this local scope hello <- function() { cat( "Hello", name, "\n" ) } # return functions which the user can call directly return( list( greet=greet, hello=hello ) ) } alex <- newNameGreeter( "Alex" ) jon <- newNameGreeter( "Jon" ) alex$hello() # prints hello Alex jon$hello() # prints hello Jon alex$greet() # creates a GUI with a button, which will print "hello Alex" when pushed }) ## End(Not run)
This function allows a GUI creator to specify widget names that
correspond to names in PBS options. These widgets can then be
used to load and set PBS options using getGUIoptions
and
setGUIoptions
.
declareGUIoptions(newOptions)
declareGUIoptions(newOptions)
newOptions |
a character vector of option names |
declareGUIoptions
is typically called in a GUI initialization function.
The option names are remembered and used for the functions
getGUIoptions
, setGUIoptions
, and promptSave
.
Anisa Egeli, Vancouver Island University, Nanaimo BC
getGUIoptions
, setGUIoptions
,
promptWriteOptions
## Not run: local(envir=.PBSmodEnv,expr={ declareGUIoptions("editor") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ declareGUIoptions("editor") }) ## End(Not run)
Executes the action expression formulated by the user and written as an ‘action’ by a widget.
doAction(act)
doAction(act)
act |
string representing an expression that can be executed |
If act
is missing, doAction
looks for it in the action
directory of the window's widget directory in .PBSmod
. This
action can be accessed through getWinAct()[1]
.
Due to parsing complications, the expression act
translates various symbols.
The function translates:
1. The back tick character ‘`’ to a double quote ‘"’ character. For example,
"openFile(paste(getWinVal()$prefix,`.tpl`,sep=``))"
2. Underscore period ‘_.’ to four back slashes and one period ‘\\\\.’. For example,
"poop=strsplit(`some.thing.else`,split=`_.`)"
Invisibly returns the string expression expr
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
createWin
, evalCall
,
getWinAct
## Not run: local(envir=.PBSmodEnv,expr={ createWin("button text=\"list objects\" func=doAction action=print(ls(all.names=TRUE))", astext=TRUE) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ createWin("button text=\"list objects\" func=doAction action=print(ls(all.names=TRUE))", astext=TRUE) }) ## End(Not run)
Various dot C-support functions used by PBSmodelling code internally.
.libName(lib="") .guiSource() .guiCompileC() .guiDyn() .cleanLoadC() .loadCRunComparison()
.libName(lib="") .guiSource() .guiCompileC() .guiDyn() .cleanLoadC() .loadCRunComparison()
lib |
|
.libName |
given a character vector of shared library object names, returns the file names with the |
appropriate extension for the user's platform (.dll for Windows or .so for Unix) |
|
.guiSource |
sources the .r file in the working directory indicated by the prefix entry widget in the GUI |
.guiCompileC |
gets the prefix and libPrefix arguments from the GUI and uses them to call .compileC
|
.guiDyn |
based on the previous GUI action, either tries to load or unload the library with the lib
|
prefix specified in the GUI (or the project file prefix if this is left blank) | |
.cleanLoadC
|
clean function |
.loadCRunComparison |
runs the provided C and R functions a number of times specified in the GUI and writes |
into text boxes the elapsed time for each |
Varied lists and other objects to facilitate GUI manipulation.
Anisa Egeli, Software Developer, Alumnus of Vancouver Island University, Nanaimo BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-11-04
Various dot-convert functions used by PBSmodelling code internally.
.convertMatrixListToDataFrame(mList, colName="Y", rowNames="X") .convertMatrixListToMatrix(mList) .convertMode(x, mode) .convertOldGridToNewGrid(grid) .convertParamStrToList(x, fname="", line.start=0, line.end=0, sourcefile=list()) .convertParamStrToVector(x, fname="", line=0) .convertVecToArray(x, d, byright=FALSE, byrow=TRUE)
.convertMatrixListToDataFrame(mList, colName="Y", rowNames="X") .convertMatrixListToMatrix(mList) .convertMode(x, mode) .convertOldGridToNewGrid(grid) .convertParamStrToList(x, fname="", line.start=0, line.end=0, sourcefile=list()) .convertParamStrToVector(x, fname="", line=0) .convertVecToArray(x, d, byright=FALSE, byrow=TRUE)
mList |
|
colName |
|
rowNames |
|
x |
|
mode |
|
grid |
|
fname |
|
line.start |
|
line.end |
|
sourcefile |
|
line |
|
d |
|
byright |
|
byrow |
|
Various convert functions used by PBSmodelling code.
.convertMatrixListToMatrix
– Convert a list into an N-dim array
.convertMatrixListToDataFrame
– Convert a list into a data frame
.convertMode
– Convert a variable into a mode without showing any warnings (deprecated?)
.convertOldGridToNewGrid
– Convert old style (where grid has a grid$.widgets[[i]][[j]] data structure)
to new format: list( grid, child, child, ..., child ); this function should never be used by new code
(hopefuly it will be removed one day)
.convertParamStrToList
– Convert a given string of values seperated by spaces into a list
while preserving space and escaped quotes within quotes (kindof – the value must still be
stripped depending if its a single string, or vector of strings)
.convertParamStrToVector
– Convert a string, x, into a vector of elements seperated by whitespace;
whitespace can be interupted as values if it is enclosed by quotes;
special characters (newline, tab, \, ', ") must be escaped with \
.convertVecToArray
– Convert a vector to an array
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-10-30
In PBSmodelling:.createWidget.data
,
.createWidget.history
,
.createWidget.matrix
,
.extractVar
,
.getParamFromStr
,
.readList.P.convertData
,
.superobject.saveValues
Various dot-create functions used by PBSmodelling code internally.
.createTkFont(fontstr) .createWidget(tk, widgetList, winName) .createWidget.button(tk, widgetList, winName) .createWidget.check(tk, widgetList, winName) .createWidget.data(tk, widgetList, winName) .createWidget.droplist(tk, widgetList, winName) .createWidget.entry(tk, widgetList, winName) .createWidget.grid(tk, widgetList, winName) .createWidget.image(tk, widgetList, winName) .createWidget.include(tk, widgetList, winName) .createWidget.label(tk, widgetList, winName) .createWidget.matrix(tk, widgetList, winName) .createWidget.notebook(tk, widgetList, winName) .createWidget.null(tk, widgetList, winName) .createWidget.object(tk, widgetList, winName, userObject=NULL ) .createWidget.object.scrolling(tk, widgetList, winName) .createWidget.progressbar(tk, widgetList, winName) .createWidget.radio(tk, widgetList, winName) .createWidget.slide(tk, widgetList, winName) .createWidget.slideplus(tk, widgetList, winName) .createWidget.spinbox(tk, widgetList, winName) .createWidget.table(tk, widgetList, winName) .createWidget.text(tk, widgetList, winName) .createWidget.vector(tk, widgetList, winName)
.createTkFont(fontstr) .createWidget(tk, widgetList, winName) .createWidget.button(tk, widgetList, winName) .createWidget.check(tk, widgetList, winName) .createWidget.data(tk, widgetList, winName) .createWidget.droplist(tk, widgetList, winName) .createWidget.entry(tk, widgetList, winName) .createWidget.grid(tk, widgetList, winName) .createWidget.image(tk, widgetList, winName) .createWidget.include(tk, widgetList, winName) .createWidget.label(tk, widgetList, winName) .createWidget.matrix(tk, widgetList, winName) .createWidget.notebook(tk, widgetList, winName) .createWidget.null(tk, widgetList, winName) .createWidget.object(tk, widgetList, winName, userObject=NULL ) .createWidget.object.scrolling(tk, widgetList, winName) .createWidget.progressbar(tk, widgetList, winName) .createWidget.radio(tk, widgetList, winName) .createWidget.slide(tk, widgetList, winName) .createWidget.slideplus(tk, widgetList, winName) .createWidget.spinbox(tk, widgetList, winName) .createWidget.table(tk, widgetList, winName) .createWidget.text(tk, widgetList, winName) .createWidget.vector(tk, widgetList, winName)
fontstr |
|
tk |
|
widgetList |
|
winName |
|
userObject |
|
Various create functions used by PBSmodelling code.
.createTkFont
– create a usable TK font from a given string
.createWidget
– Generic function to create most widgets,
which calls appropriate.createWidget.<widgetType>()
function
Alex Couture-Beil, Software Engineer, Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-10-31
In PBSmodelling:testWidgets
,
showArgs
,
.createWidget.history
Various dot functions used by PBSmodelling code internally to support the GUI functions.
.buildgrid(tk, grid, winName, childWidgets) .map.add(winName, key, ...) .map.get(winName, key) .map.getAll(winName) .map.init(winName) .map.set(winName, key, ...) .setMatrixElement(m, a, ind=NULL) .getMatrixListSize(m, d=NULL, big=0) .matrixHelp(matrixList, ind, value) .autoConvertMode(x) .extractData(command, action, winName) .extractFuns(data) .extractVar(winName) .getParamFromStr(inputStr, fname="", line.start=0, line.end=0, sourcefile=list(), paramOrder=.widgetDefs) .table.getvalue(winName, widgetName) .table.setvalue(winName, widgetName, value) .getValueForWidgetSetup(varname, widget, winName) .getSimilarColour(col) .adjustAllColours(tObj) .do.gui.call(what, args, quote=FALSE, envir=parent.frame()) .catError(err, fname, line.start, line.end, sourcefile=list(), errorType="GUI parse error") .catError2(err, fname, line.start) .check.object.exists(tk, widget, winName) .inCollection(haystack, needle) .packWidgetsIntoGrid(widgets, vertical=TRUE) .parsegrid(data, nRow, nCol) .parsemenu(data, nItems) .PBSdimnameHelper(rownames, colnames, dim) .searchCollection(haystack, needle) .setWinValHelper(varname, value, winName) .stopWidget(err, wid.debug, winName) .stripComments(x) .stripSlashes(x, fname="", line.start=0, line.end=0, sourcefile=list()) .stripSlashesVec(x, fname="", line.start=0, line.end=0, sourcefile=list()) .superobject.redraw(winName, widget_name) .superobject.saveValues(winName, widget_name) .trimWhiteSpace(x) .validateWindowDescList(x) .validateWindowDescWidgets(x)
.buildgrid(tk, grid, winName, childWidgets) .map.add(winName, key, ...) .map.get(winName, key) .map.getAll(winName) .map.init(winName) .map.set(winName, key, ...) .setMatrixElement(m, a, ind=NULL) .getMatrixListSize(m, d=NULL, big=0) .matrixHelp(matrixList, ind, value) .autoConvertMode(x) .extractData(command, action, winName) .extractFuns(data) .extractVar(winName) .getParamFromStr(inputStr, fname="", line.start=0, line.end=0, sourcefile=list(), paramOrder=.widgetDefs) .table.getvalue(winName, widgetName) .table.setvalue(winName, widgetName, value) .getValueForWidgetSetup(varname, widget, winName) .getSimilarColour(col) .adjustAllColours(tObj) .do.gui.call(what, args, quote=FALSE, envir=parent.frame()) .catError(err, fname, line.start, line.end, sourcefile=list(), errorType="GUI parse error") .catError2(err, fname, line.start) .check.object.exists(tk, widget, winName) .inCollection(haystack, needle) .packWidgetsIntoGrid(widgets, vertical=TRUE) .parsegrid(data, nRow, nCol) .parsemenu(data, nItems) .PBSdimnameHelper(rownames, colnames, dim) .searchCollection(haystack, needle) .setWinValHelper(varname, value, winName) .stopWidget(err, wid.debug, winName) .stripComments(x) .stripSlashes(x, fname="", line.start=0, line.end=0, sourcefile=list()) .stripSlashesVec(x, fname="", line.start=0, line.end=0, sourcefile=list()) .superobject.redraw(winName, widget_name) .superobject.saveValues(winName, widget_name) .trimWhiteSpace(x) .validateWindowDescList(x) .validateWindowDescWidgets(x)
tk |
|
grid |
|
winName |
|
childWidgets |
|
key |
|
... |
|
m |
|
a |
|
ind |
|
d |
|
big |
|
matrixList |
|
value |
|
x |
|
command |
|
action |
|
data |
|
inputStr |
|
fname |
|
line.start |
|
line.end |
|
sourcefile |
|
paramOrder |
|
widgetName |
|
varname |
|
widget |
|
col |
|
tObj |
|
what |
|
args |
|
quote |
|
envir |
|
err |
|
errorType |
|
haystack |
|
needle |
|
widgets |
|
vertical |
|
nRow |
|
nCol |
|
nItems |
|
rownames |
|
colnames |
|
dim |
|
wid.debug |
|
widget_name |
|
Create—— | |
.buildgrid |
used to create a grid on a window |
Map—— | |
.map.add |
save a new value for a given key; if a previous exists, ignore the new |
value and return previous value | |
.map.get |
returns a value associated with a key |
.map.getAll |
returns all visible items of a map of a certain window |
.map.init |
initialize the data structure that holds the map(s) |
.map.set |
save a new value for a given key, even if it involves overwriting a |
previously stored value | |
Convert—— | |
.setMatrixElement |
helper function used by .convertMatrixListToMatrix
|
to assign values from the matrix list into the array | |
.getMatrixListSize |
helper function used by .convertMatrixListToMatrix
|
to determine the minumum required size of the array needed to create | |
or convert the list into an array | |
.matrixHelp |
used to help .extractVar deal with N-dim matricies; firstly it is |
converted into a ``matrix list'' once the matrix list is completed | |
(and size known), it should be converted into a true array | |
.autoConvertMode
|
converts x into a numeric mode, if it looks like a valid number |
Extract—— | |
.extractData |
called by TK on button presses (or binds, on changes, slides, ...) |
.extractFuns |
get a list of called functions |
.extractVar |
extracts values from the tclvar pointers |
.getParamFromStr
|
returns a list with all parameters extracted from a list |
.table.getvalue |
infer: get a value from a table |
.table.setvalue |
infer: set a value in a table |
.getValueForWidgetSetup |
returns the value(s) to use for initializing a widget from: |
--> widget$value (if set) or |
|
--> global var matching widget$name when value is NULL
|
|
Helper—— | |
.getSimilarColour |
obtains a similar colour (slightly brighter/darker) than the argument |
.adjustAllColours |
for the passed Tk widget, attempts to slightly modify all applicable colours |
.do.gui.call |
extends do.call , which is used to create most Tk widgets, to immediately |
adjust a new widget's colours (to get around how tk_setPalette
|
|
changes the colour of existing widgets) | |
.catError |
used to display parsing errors |
.catError2 |
infer: a variation of .catError
|
.check.object.exists |
call to test for existence of dynamically loaded object for "object" and |
"table" ; returns NULL on no errors; otherwise a tk display |
|
error is created (can be embedded in window) | |
.inCollection |
returns true if needle occurs in haystack |
.packWidgetsIntoGrid |
pack all widgets into a grid with ncol=1 nrow= <number of widgets> |
.parsegrid |
returns two items in a list: |
--> $gridData , which is a list of lists representing columns |
|
--> $unparsedData , which is left over from the grid and still needs parsing |
|
.parsemenu |
very similar to .parsegrid but for menus; |
set up a menu with children menus or menuitems | |
.PBSdimnameHelper |
adds dimnames to stuff (matrix, data.frame) |
.searchCollection |
searches a haystack for a needle, or a similar longer needle |
.setWinValHelper |
infer: help to set GUI Window values |
.stopWidget |
stop due to fatal error during window creation (not parse) |
.stripComments |
removes any trailing comments from a line, but ignores '#' in quoted strings |
.stripComments |
infer: strips out comments from a set of strings |
.stripSlashes |
removes slashes from a string |
.stripSlashesVec
|
given a string, split it into a vector of words, which were seperated by spaces; |
however, if single quotes are used, space is perserved; | |
e.g., x="a b `c d'" converts into "a" "b" "c d"
|
|
.superobject.redraw |
infer: redraw a superobject (whatever that is) |
.superobject.saveValues |
must be outside of .createwidget.superobject since getWinVal
|
must be able to call this | |
.trimWhiteSpace |
remove leading and trailing whitespace |
.validateWindowDescList |
determines if the list represents a valid PBS Modelling description list; |
if any required fields are missing, it will halt via stop() ; |
|
if any fields are omitted which have default values defined in the | |
.widgetDefs list, then those fields and values will be set |
|
.validateWindowDescWidgets
|
used by .validateWindowDescList to validate each widget |
Stuff and such.
Alex Couture-Beil, Software Engineer, Earthly Technologies, Victoria BC
Nicholas M. Boers, Software Engineer, Jobber, Edmonton AB
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-11-01
dot-create.funs
,
dot-convert.funs
Various dot functions used by PBSmodelling code internally for the history widget.
.createWidget.history(tk, widgetList, winName) .sortHelper() .sortHelperActive(hisname) .sortHelperFile(openfile, savefile) .sortWidget(d, hisname) .updateFile() .updateHistory(hisname) .updateHistoryButtons(hisname)
.createWidget.history(tk, widgetList, winName) .sortHelper() .sortHelperActive(hisname) .sortHelperFile(openfile, savefile) .sortWidget(d, hisname) .updateFile() .updateHistory(hisname) .updateHistoryButtons(hisname)
tk |
|
widgetList |
|
winName |
|
hisname |
|
openfile |
|
savefile |
|
d |
|
Various dot functions used by PBSmodelling code to control the history widget.
.createWidget.history
– create a history widget
.sortHelper
– sort entries in an existing history instance
.updateHistory
– update widget values
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-10-31
In PBSmodelling:testWidgets
,
showArgs
Various dot-list functions used by PBSmodelling code internally.
.mergeLists(x, y) .readList.C(fname) .readList.P(fname) .readList.P.convertData(varOptions, varData, fname="", sourcefile=list()) .writeList.P(x, fname="", comments, prefix="")
.mergeLists(x, y) .readList.C(fname) .readList.P(fname) .readList.P.convertData(varOptions, varData, fname="", sourcefile=list()) .writeList.P(x, fname="", comments, prefix="")
x |
|
y |
|
fname |
|
varOptions |
|
varData |
|
sourcefile |
|
comments |
|
prefix |
|
Various dot functions used by PBSmodelling code to control list objects.
.mergeLists
– taken from R Curl : merge x
and y
,
if elements match in both x
and y
, then elements from y
are stored (overwriting x
's elements).
.readList.C
– read ADMB-like input file and create a list;
adapted from 'readAD'
in PBSawatea.
.readList.P
– read list in 'P'
format (PBS format).
.readList.P.convertData
– helper function to convert data into proper mode.
.writeList.P
– saves list x
to disk using 'P'
format (PBS format).
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-10-31
In PBSmodelling:lisp
,
packList
,
readList
,
unpackList
,
writeList
,
.pFormatDefs
An environment set aside for PBSmodelling.
.PBSmodEnv
.PBSmodEnv
A new environment with a .GlobalEnv
parent.
The environment is created in 'zzz.r'
and is used by
PBSmodelling
functions 'lisp'
, 'tget'
,
'tput'
, 'tprint'
, and 'tcall'
.
Generated by a call to the base function new.env()
.
In PBSmodelling:lisp
,
tget
,
packList
,
lisp(.PBSmodEnv)
lisp(.PBSmodEnv)
Various dot functions used by PBSmodelling code internally to support project functions.
.doClean() .doCleanWD() .getHiddenEnv() .getHome() .getPrefix(quiet=FALSE) .makeCleanVec(vecName, items, rowLen) .mergeLists2(list1, list2) .mergeVectors(v1, v2) .optionsNotUpdated() .removeFromList(l, items) .selectCleanBoxes() .setOption(option, type) .showLog(logText, fname, noWindow=FALSE, width=80, height=30) .stripExt(x) .tryOpen(filename, quiet=FALSE)
.doClean() .doCleanWD() .getHiddenEnv() .getHome() .getPrefix(quiet=FALSE) .makeCleanVec(vecName, items, rowLen) .mergeLists2(list1, list2) .mergeVectors(v1, v2) .optionsNotUpdated() .removeFromList(l, items) .selectCleanBoxes() .setOption(option, type) .showLog(logText, fname, noWindow=FALSE, width=80, height=30) .stripExt(x) .tryOpen(filename, quiet=FALSE)
quiet |
|
vecName |
|
items |
|
rowLen |
|
list1 |
|
list2 |
|
v1 |
|
v2 |
|
l |
|
option |
|
type |
|
logText |
|
fname |
|
noWindow |
|
width |
|
height |
|
x |
|
filename |
|
.doClean |
used by cleanProj() ; function called when Clean button is pressed |
.doCleanWD |
Anisa's .doClean function modified for file names only |
.getHiddenEnv |
allow GUIs from outside PBSmodelling to call PBSmodelling's internal hidden functions |
.getHome |
returns platform dependent home drive (Windows) or user home (Unix) |
.getPrefix |
get the project prefix from the focused GUI; used to standardise error message |
.makeCleanVec |
used by cleanProj() to create strings describing checkbox vectors |
.mergeLists2 |
add a second list to a first list; if both lists share any keys, the values from the second list |
overwrite those in the first list; order of components in list is preserved | |
.mergeVectors |
add a second vector to a first vector; if both vectors share any values, the resulting vector will |
only contain this value once | |
.optionsNotUpdated |
check if any of the options given by declareGUIoptions are different in the GUI from their |
stored values; a blank GUI entry is equivalent to the option not being set | |
.removeFromList |
remove components of a list with the given names; "NA" can be used to remove NA names |
.selectCleanBoxes |
used by cleanProj ; selects or deselects all of the checkboxes |
.setOption |
used for setPathOption and setFileOption ; see these functions for a descriptions |
.showLog |
given output for a log, will make pop-up log window containing this output and/or |
write this output to a logfile; "\r" is stripped from the log text for display |
|
.stripExt |
remove file extension from end of filename |
.tryOpen |
tries to open a given file using an editor entered by the GUI; if an editor wasn't set, |
tries to open using openFile ; appropriate alerts are shown if quiet isn't turned on |
|
Varied lists and other objects to facilitate GUI manipulation.
Anisa Egeli, Software Developer, Alumnus of Vancouver Island University, Nanaimo BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-11-01
cleanProj
,
cleanWD
,
findPrefix
,
getGUIoptions
,
setGUIoptions
Various dot support functions used by PBSmodelling code internally.
.fibCall(n, len=1) .fibC(n, len=1) .fibR(n, len=1) .fibClosedForm(n, len=1) .viewPkgDemo() .dClose() .dUpdateDesc() .viewPkgVignette() .addslashes(x, asvector=FALSE ) .findSquare(nc) .forceMode(x, mode) .getArrayPts(d, byright=FALSE, byrow=TRUE) .initPBSoptions() .mapArrayToVec(x, d, byright=FALSE) .tclArrayToVector(str)
.fibCall(n, len=1) .fibC(n, len=1) .fibR(n, len=1) .fibClosedForm(n, len=1) .viewPkgDemo() .dClose() .dUpdateDesc() .viewPkgVignette() .addslashes(x, asvector=FALSE ) .findSquare(nc) .forceMode(x, mode) .getArrayPts(d, byright=FALSE, byrow=TRUE) .initPBSoptions() .mapArrayToVec(x, d, byright=FALSE) .tclArrayToVector(str)
n |
|
len |
|
x |
|
asvector |
|
nc |
|
mode |
|
d |
|
byright |
|
byrow |
|
str |
|
.fibCall |
used by calcFib() to xalculate a vector containing fibonacci numbers |
.viewPkgDemo |
display a GUI to display something equivalent to R's demo()
|
.dClose |
function to execute on closing runDemos()
|
.dUpdateDesc |
update demo window with demo descriptions |
.viewPkgVignettes |
display a GUI to display something equivalent to R's vignette()
|
.addslashes
|
escape special characters from a string, which can then be used in the "P" format; |
if x has more than one element, then it will returned as a nested characterVector
|
|
e.g., c("it's", "O K") becomes "'it\'s' 'O K'"
|
|
.convertVecToArray |
convert a vector to an array |
.findSquare |
calculate number of rows and columns from a single number of panels |
.forceMode |
force a variable into a mode without showing any warnings |
.getArrayPts |
return all possible indices of an array |
.initPBSoptions |
called from zzz.r's .First.lib() intialization function |
.mapArrayToVec |
determine which index to use for a vector, when given an N-dim index of an array |
.tclArrayToVector |
infer: change tcl code to represent array as a vector |
Varied lists and other objects to facilitate GUI manipulation.
Alex Couture-Beil, Software Engineer, Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-11-04
calcFib
,
runDemos
,
showVignettes
,
readPBSoptions
,
runExamples
Various dot-talk functions used by PBSmodelling code internally for 'presentTalk()'
.
.getButton(talk_name, obj) .getButtons(talk) .getIndexForSection(talk, section_id) .getMenus(talk) .getSectionNames(talk) .getTalkIndexes(talk) .nextSlide() .parseTalkFile(talk_fname) .presentTalkOpenFile() .prevSlide() .sectiondrop() .setsection() .slidedrop() .startSlide(talk) .updateSlide(talk)
.getButton(talk_name, obj) .getButtons(talk) .getIndexForSection(talk, section_id) .getMenus(talk) .getSectionNames(talk) .getTalkIndexes(talk) .nextSlide() .parseTalkFile(talk_fname) .presentTalkOpenFile() .prevSlide() .sectiondrop() .setsection() .slidedrop() .startSlide(talk) .updateSlide(talk)
talk_name |
|
obj |
|
talk |
|
section_id |
|
talk_fname |
|
Various dot functions used by PBSmodelling code to control the talk GUI for presentations.
.getButton
– returns win
description for a button for a file or section.
.getButtons
– gets widget descriptions for file and section buttons.
.getIndexForSection
– get the slide index which corresponds to the
first slide in a given section.
.getMenus
– get widget description for menus.
.getSectionNames
– given a talk, return a vector of all section names.
.getTalkIndexes
– retuns a list of 2-element vectors (i,j)
,
where i
is the section index, and j
is the items index;
each element of the list corresponds to a break point.
.parseTalkFile
– returns a talk s4 class, given a filename to an xml
talk
.presentTalkOpenFile
– open files from the win
act
, and supports multiple files.
The function 'presentTalk'
offers a cumbersome system for presenting
talking points using R.
It is likely superceded by more recent appliances like
Shiny.
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-10-31
In PBSmodelling:presentTalk
,
.tagDefs
,
.tagOptionChecks
Primary controller of the various widgets in PBSmodelling
.
.widgetDefs .pFormatDefs .tagDefs .tagOptionChecks .maxActionSize .regex.complex .regex.numeric .regex.logical
.widgetDefs .pFormatDefs .tagDefs .tagOptionChecks .maxActionSize .regex.complex .regex.numeric .regex.logical
List of 25 widgets:
window | list 8 | grid | list 19 | notebook | list 18 | image | list 7 | progressbar | list 15 |
menu | list 6 | menuitem | list 7 | label | list 14 | droplist | list 19 | spinbox | list 21 |
table | list 15 | null | list 4 | include | list 3 | entry | list 22 | button | list 13 |
check | list 15 | radio | list 15 | slide | list 15 | slideplus | list 18 | vector | list 25 |
matrix | list 28 | data | list 28 | object | list 23 | history | list 13 | text | list 16 |
Storage list that specifies characteristics of each widget's arguments.
.widgetDefs |
defines allowed widget parameters names and default values |
.pFormatDefs |
defines allowed P format parameters names and default values |
to be used in 'readList' (when P format is detected) |
|
.tagDefs |
defines formatting for each valid tag used in 'presentTalk' , |
but presumably could be applied to other appliances | |
.tagOptionChecks
|
provides validation check for each tag option |
.maxActionSize |
maximum amount of actions to save in memory (default=50) |
.regex.complex |
catches all valid complex except it also catches "-"
|
.regex.numeric |
catches numeric strings, but also catches "-"
|
.regex.logical |
catches all logical values |
testWidgets
,
showArgs
,
presentTalk
,
readList
str(.widgetDefs,1)
str(.widgetDefs,1)
Wrapper dot functions to run existing or temporary functions from a GUI's function call.
.win.chFile() .win.chTest() .win.closeALL() .win.closeChoice() .win.closeSDE() .win.makeChoice() .win.restoreCWD() .win.runExHelperQuit() .win.tcall() .win.tget() .win.tprint()
.win.chFile() .win.chTest() .win.closeALL() .win.closeChoice() .win.closeSDE() .win.makeChoice() .win.restoreCWD() .win.runExHelperQuit() .win.tcall() .win.tget() .win.tprint()
PBSmodelling Windows (Graphical User Interfaces or GUIs) call wrapper functions that call non-GUI functions in the package.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-25
In PBSmodelling:getWinAct
,
getWinVal
,
runExamples
,
tget
Draw a linear barplot on the current plot. Fill if desired.
drawBars(x, y, width, base=0, fill=NULL, ...)
drawBars(x, y, width, base=0, fill=NULL, ...)
x |
x-coordinates |
y |
y-coordinates |
width |
bar width, computed if missing |
base |
y-value of the base of each bar |
fill |
valid R colour to fill the bars |
... |
further graphical parameters (see |
Jon T. Schnute, Scientist Emeritus,
Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ if (dev.cur()>1) { oldpar=par(no.readonly=TRUE); on.exit(par(oldpar)) } plot(0:10,0:10,type="n") drawBars(x=1:9,y=9:1,col="deepskyblue4",fill="cyan",lwd=3) })
local(envir=.PBSmodEnv,expr={ if (dev.cur()>1) { oldpar=par(no.readonly=TRUE); on.exit(par(oldpar)) } plot(0:10,0:10,type="n") drawBars(x=1:9,y=9:1,col="deepskyblue4",fill="cyan",lwd=3) })
Evaluates a function call after resolving potential argument conflicts.
evalCall(fn, argu, ..., envir = parent.frame(), checkdef=FALSE, checkpar=FALSE)
evalCall(fn, argu, ..., envir = parent.frame(), checkdef=FALSE, checkpar=FALSE)
fn |
R function |
argu |
list of explicitly named arguments and their values to pass to |
... |
additional arguments that a user might wish to pass to |
envir |
environment from which the call originates (currently has no use or effect). |
checkdef |
logical: if |
checkpar |
logical: if |
This function builds a call to the specified function and executes it.
During the build, optional arguments (...) are checked for
(i) duplication with explicit arguments argu
: if any are duplicated,
the user-supplied arguments supersede the explicit ones;
(ii) availability as usable arguments in fn
, fn.default
if
checkdef=TRUE
, and par
if checkpar=TRUE
.
Invisibly returns the string expression of the function call that is
passed to eval(parse(text=expr))
.
Sometimes the user may wish to pass arguments into a function to be used
by other functions within, but may not want all the arguments to be used,
depending on the functions subsequently called. In this case, the user needs
to create a list object called dots
, which is passed to evalCall
.
For instance, if the user passes lwd=4
but only wants this
used in a call to lines
but not in a call to points
,
the function might look like this:
myfunc = function(x=seq(0,360,5), ...) { pdots = ldots = list(...) pdots[["lwd"]] = NULL ldots[["col"]] = "cyan" xrad = x*pi/180 plot(sin(xrad),type="n") evalCall(lines, argu=list(x=sin(xrad)), dots=ldots, checkpar=TRUE) evalCall(points,argu=list(x=sin(xrad)), dots=pdots, checkpar=TRUE) } myfunc(lwd=4,pch=20,col=" blue")
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) # A user may have a function that calls other functions # using specific defaults (e.g., blue triangles) #------------------------------------------------------ pbsfun = function(..., use.evalCall=TRUE) { plotAsp(0,0,type="n",xlim=c(-1.5,1.5),ylim=c(-1.5,1.5), axes=FALSE, frame.plot=TRUE, xlab="",ylab="") if (use.evalCall) evalCall(polygon, ..., argu=list(x=c(-1,1,0),y=c(1,1,-1), col="dodgerblue", border="grey")) else polygon(x=c(-1,1,0),y=c(1,1,-1),col="dodgerblue",border="grey",...) } par(mfrow=c(2,1)) pbsfun(lwd=4,use.evalCall=FALSE) #------------------------------------------------------ # But what if the user wants pink triangles? pbsfun(col="pink",lwd=4,use.evalCall=TRUE,checkpar=TRUE) par(oldpar) }) # Without 'evalCall' an error occurs due to duplicated arguments ## Not run: pbsfun(col="pink",lwd=4,use.evalCall=FALSE)
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) # A user may have a function that calls other functions # using specific defaults (e.g., blue triangles) #------------------------------------------------------ pbsfun = function(..., use.evalCall=TRUE) { plotAsp(0,0,type="n",xlim=c(-1.5,1.5),ylim=c(-1.5,1.5), axes=FALSE, frame.plot=TRUE, xlab="",ylab="") if (use.evalCall) evalCall(polygon, ..., argu=list(x=c(-1,1,0),y=c(1,1,-1), col="dodgerblue", border="grey")) else polygon(x=c(-1,1,0),y=c(1,1,-1),col="dodgerblue",border="grey",...) } par(mfrow=c(2,1)) pbsfun(lwd=4,use.evalCall=FALSE) #------------------------------------------------------ # But what if the user wants pink triangles? pbsfun(col="pink",lwd=4,use.evalCall=TRUE,checkpar=TRUE) par(oldpar) }) # Without 'evalCall' an error occurs due to duplicated arguments ## Not run: pbsfun(col="pink",lwd=4,use.evalCall=FALSE)
Optimize the plotting region(s) by minimizing margins.
expandGraph(mar=c(4,3,1.2,0.5), mgp=c(1.6,.5,0),...)
expandGraph(mar=c(4,3,1.2,0.5), mgp=c(1.6,.5,0),...)
mar |
numerical vector of the form 'c(bottom, left, top, right)' specifying the margins of the plot |
mgp |
numerical vector of the form 'c(axis title, axis labels, axis line)' specifying the margins for axis title, axis labels, and axis line |
... |
additional graphical parameters to be passed to |
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) expandGraph(mfrow=c(2,1)); tt=seq(from=-10, to=10, by=0.05); plot(tt,sin(tt), xlab="this is the x label", ylab="this is the y label", main="main title", sub="sometimes there is a \"sub\" title") plot(cos(tt),sin(tt*2), xlab="cos(t)", ylab="sin(2 t)", main="main title", sub="sometimes there is a \"sub\" title") par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) expandGraph(mfrow=c(2,1)); tt=seq(from=-10, to=10, by=0.05); plot(tt,sin(tt), xlab="this is the x label", ylab="this is the y label", main="main title", sub="sometimes there is a \"sub\" title") plot(cos(tt),sin(tt*2), xlab="cos(t)", ylab="sin(2 t)", main="main title", sub="sometimes there is a \"sub\" title") par(oldpar) })
Export the current history list.
exportHistory(hisname="", fname="")
exportHistory(hisname="", fname="")
hisname |
name of the history list to export. If set to |
fname |
file name where history will be saved. If it is set to |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Use all available patterns in pat
to search in vec
,
and return the matched elements in vec
.
findPat(pat, vec)
findPat(pat, vec)
pat |
character vector of patterns to match in |
vec |
character vector where matches are sought |
A character vector of all matched strings.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ #find all strings with a vowel, or that start with a number print(findPat(c("[aeiou]", "^[0-9]"), c("hello", "WORLD", "1over"))) })
local(envir=.PBSmodEnv,expr={ #find all strings with a vowel, or that start with a number print(findPat(c("[aeiou]", "^[0-9]"), c("hello", "WORLD", "1over"))) })
Find the prefixes or suffixes of files with a given suffix or prefix in a directory.
findPrefix(suffix,path=".") findSuffix(prefix,path=".")
findPrefix(suffix,path=".") findSuffix(prefix,path=".")
suffix |
character vector of suffixes |
prefix |
character vector of prefixes |
path |
directory to look for files in |
The function findPrefix
locates all files in a directory that end with
one of the provided suffixes; where as findSuffix
locates all files
that start with the given prefixes.
A character vector of all the prefixes or sufixes of files in the working directory that matched to one of the given suffixes.
Anisa Egeli, Vancouver Island University, Nanaimo BC
local(envir=.PBSmodEnv,expr={ edir = system.file("examples", package="PBSmodelling") print(findPrefix(suffix=c(".txt", ".r"),path=edir)); cat("\n") #or use R's dir for similar functionality print(dir(pattern="txt$",path=edir)); cat("\n") print(dir(pattern="^[a-h]",path=edir)); cat("\n") })
local(envir=.PBSmodEnv,expr={ edir = system.file("examples", package="PBSmodelling") print(findPrefix(suffix=c(".txt", ".r"),path=edir)); cat("\n") #or use R's dir for similar functionality print(dir(pattern="txt$",path=edir)); cat("\n") print(dir(pattern="^[a-h]",path=edir)); cat("\n") })
Returns the complete filename and path of a program in the PATH environment variable.
This is a wrapper for Sys.which
, and may be deprecated in the future.
findProgram( name, includename=FALSE )
findProgram( name, includename=FALSE )
name |
name of a program to locate |
includename |
boolean: if true, include the filename in the path returned, otherwise just the directory. |
A string containing the location of the program. NULL is returned if the program is not located.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
local(envir=.PBSmodEnv,expr={ print(list( gcc = findProgram( "gcc" ), notepad = findProgram( "notepad" ), R = findProgram( "R", includename=TRUE ) )) })
local(envir=.PBSmodEnv,expr={ print(list( gcc = findProgram( "gcc" ), notepad = findProgram( "notepad" ), R = findProgram( "R", includename=TRUE ) )) })
Bring the specified window into focus, and set it as the active window.
focusWin
will fail to bring the window into focus if it is called from the R
console, since the R console returns focus to itself once a function returns.
However, it will work if focusWin
is called as a result of calling a function
from the GUI window. (i.e., pushing a button or any other widget that has a
function argument).
focusWin(winName, winVal=TRUE)
focusWin(winName, winVal=TRUE)
winName |
name of window to focus |
winVal |
if |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ focus <- function() { winName <- getWinVal()$select; focusWin(winName); mess = paste("Calling focusWin(\"", winName, "\")\n", "getWinVal()$myvar = ", getWinVal()$myvar, "\n\n", sep="",collapse="") cat(mess); invisible() } #create three windows named win1, win2, win3 #each having three radio buttons, which are used to change the focus for(i in 1:3) { winDesc <- c( paste('window onclose=closeWin name=win',i,' title="Win',i,'"', sep=''), paste('entry myvar ', i, sep=''), 'radio name=select value=win1 text="one" function=focus mode=character', 'radio name=select value=win2 text="two" function=focus mode=character', 'radio name=select value=win3 text="three" function=focus mode=character'); createWin(winDesc, astext=TRUE); }; }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ focus <- function() { winName <- getWinVal()$select; focusWin(winName); mess = paste("Calling focusWin(\"", winName, "\")\n", "getWinVal()$myvar = ", getWinVal()$myvar, "\n\n", sep="",collapse="") cat(mess); invisible() } #create three windows named win1, win2, win3 #each having three radio buttons, which are used to change the focus for(i in 1:3) { winDesc <- c( paste('window onclose=closeWin name=win',i,' title="Win',i,'"', sep=''), paste('entry myvar ', i, sep=''), 'radio name=select value=win1 text="one" function=focus mode=character', 'radio name=select value=win2 text="two" function=focus mode=character', 'radio name=select value=win3 text="three" function=focus mode=character'); createWin(winDesc, astext=TRUE); }; }) ## End(Not run)
Generate a test matrix of random numbers (mu
= mean
and signa
= standard deviation), primarily for plotBubbles
.
genMatrix(m,n,mu=0,sigma=1)
genMatrix(m,n,mu=0,sigma=1)
m |
number of rows |
n |
number of columns |
mu |
mean of normal distribution |
sigma |
standard deviation of normal distribution |
An m
by n
matrix with normally distributed random values.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ plotBubbles(genMatrix(20,6)) })
local(envir=.PBSmodEnv,expr={ plotBubbles(genMatrix(20,6)) })
Prompts the user to choose one string item from a list of
choices displayed in a GUI. The simplest case getChoice()
yields TRUE
or FALSE
.
getChoice(choice=c("Yes","No"), question="Make a choice: ", winname="getChoice", horizontal=TRUE, radio=FALSE, qcolor="blue", gui=FALSE, quiet=FALSE)
getChoice(choice=c("Yes","No"), question="Make a choice: ", winname="getChoice", horizontal=TRUE, radio=FALSE, qcolor="blue", gui=FALSE, quiet=FALSE)
choice |
vector of strings from which to choose. |
question |
question or prompting statement. |
winname |
window name for the |
horizontal |
logical: if |
radio |
logical: if |
qcolor |
colour for |
gui |
logical: if |
quiet |
logical: if |
The user's choice is stored in .PBSmod$options$getChoice
(or whatever winname
is supplied).
getChoice
generates an onClose
function that returns focus
to the calling window (if applicable) and prints out the choice.
If called from a GUI (gui=TRUE
), no value is returned directly. Rather,
the choice is written to the PBS options workspace, accessible through
getPBSoptions("getChoice")
(or whatever winname
was supplied).
If called from a command line program (gui=FASLE
), the choice is returned
directly as a string scalar (e.g., answer <- getChoice(gui=F)
).
Microsoft Windows users may experience difficulties switching focus between the R console and GUI windows. The latter frequently disappear from the screen and need to be reselected (either clicking on the task bar or pressing <Alt><Tab>. This issue can be resolved by switching from MDI to SDI mode. From the R console menu bar, select <Edit> and <GUI preferences>, then change the value of “single or multiple windows” to SDI.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
chooseWinVal
, getWinVal
, setWinVal
## Not run: #-- Example 1 local(envir=.PBSmodEnv,expr={ getChoice(c("Fame","Fortune","Health","Beauty","Lunch"), "What do you want?",qcolor="red",gui=FALSE) }) #-- Example 2 local(envir=.PBSmodEnv,expr={ getChoice(c("Homer Simpson","Wilberforce Humphries","Miss Marple","Gary Numan"), "Who`s your idol?",horiz=FALSE,radio=TRUE,gui=FALSE) }) ## End(Not run)
## Not run: #-- Example 1 local(envir=.PBSmodEnv,expr={ getChoice(c("Fame","Fortune","Health","Beauty","Lunch"), "What do you want?",qcolor="red",gui=FALSE) }) #-- Example 2 local(envir=.PBSmodEnv,expr={ getChoice(c("Homer Simpson","Wilberforce Humphries","Miss Marple","Gary Numan"), "Who`s your idol?",horiz=FALSE,radio=TRUE,gui=FALSE) }) ## End(Not run)
Get the PBS options declared for GUI usage and set their corresponding widget values.
getGUIoptions()
getGUIoptions()
The options declared using declareGUIoptions
are
copied from the R environment into widget values. These widgets
should have names that match the names of their corresponding options.
Anisa Egeli, Vancouver Island University, Nanaimo BC
declareGUIoptions
, setGUIoptions
,
promptWriteOptions
, readPBSoptions
## Not run: local(envir=.PBSmodEnv,expr={ getPBSoptions() #loads from default PBSoptions.txt }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ getPBSoptions() #loads from default PBSoptions.txt }) ## End(Not run)
Functions to get and set user options within an option class object.
getOptions(option.object, key) setOptions(option.object, ...) .showOptions(object)
getOptions(option.object, key) setOptions(option.object, ...) .showOptions(object)
option.object |
options class object used for storing package options |
key |
name of option to retrieve; if missing, all options are returned |
... |
any number of user options to set where either |
object |
options class object used for storing package options |
Value of the option specified by key
(if specified) or a list
of all options (if missing).
Alex Couture-Beil, Software Engineer, Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Remote office, Vancouver BC
Last modified Rd: 2024-11-04
See PBSoptions-class
for more details and
an example that uses PBSmodelling's option management functions.
Functions for retrieving and setting the default file name used by loadOptions
and saveOptions
.
getOptionsFileName(option.object) setOptionsFileName(option.object, name)
getOptionsFileName(option.object) setOptionsFileName(option.object, name)
option.object |
options class object used for storing package options |
name |
new name for default file name |
getOptionsFileName
: the default file name
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
loadOptions
, saveOptions
See PBSoptions-class
for more details and
an example using PBSmodelling's option management functions.
The GUI prefix is used for determining which GUI variables are associated with a user option.
getOptionsPrefix(option.object) setOptionsPrefix(option.object, prefix)
getOptionsPrefix(option.object) setOptionsPrefix(option.object, prefix)
option.object |
options class object used for storing package options |
prefix |
new prefix to use |
getOptionsPrefix
: a prefix string used to reference GUI variables
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
See PBSoptions-class
for more details and
an example using PBSmodelling's option management functions.
## Not run: local(envir=.PBSmodEnv,expr={ # For the example, the options object is saved to the temporary environment; # however, a user would normally create the object in his/her workspace. .mypkg <- new( "PBSoptions", filename="my_pkg.txt", initial.options=list(pi=3.14), gui.prefix="opt" ) #prefix the option "pi" with "opt" to get "optpi" createWin( "entry name=optpi", astext = TRUE ) #the GUI variable "optpi" will be loaded with the option "pi" loadOptionsGUI( .mypkg ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ # For the example, the options object is saved to the temporary environment; # however, a user would normally create the object in his/her workspace. .mypkg <- new( "PBSoptions", filename="my_pkg.txt", initial.options=list(pi=3.14), gui.prefix="opt" ) #prefix the option "pi" with "opt" to get "optpi" createWin( "entry name=optpi", astext = TRUE ) #the GUI variable "optpi" will be loaded with the option "pi" loadOptionsGUI( .mypkg ) }) ## End(Not run)
Display all locally defined file extensions and their associated commands,
or search for the command associated with a specific file extension
ext
.
getPBSext(ext)
getPBSext(ext)
ext |
|
Command associated with file extension.
These file associations are not saved from one PBS Modelling session to
the next unless explicitly saved and loaded (see writePBSoptions
and
readPBSoptions
).
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Regional Headquarters (RHQ), Vancouver BC
Last modified Rd: 2023-01-05
In package PBSmodelling:setPBSext
,
openFile
,
clearPBSext
Get a previously defined user option.
getPBSoptions(option)
getPBSoptions(option)
option |
name of option to retrieve. If omitted, a list containing all options is returned. |
Value of the specified option, or NULL
if the specified option is not found.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Get a string vector of actions (latest to earliest).
getWinAct(winName)
getWinAct(winName)
winName |
name of window to retrieve action from |
When a function is called from a GUI, a string descriptor associated with
the action of the function is stored internally (appended to the first position
of the action vector). A user can utilize this action as a type of argument
for programming purposes. The command getWinAct()[1]
yields the latest action.
String vector of recorded actions (latest first).
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Get a vector of all function names referenced by a window.
getWinFun(winName)
getWinFun(winName)
winName |
name of window, to retrieve its function list |
A vector of function names referenced by a window.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Get a list of variables defined and set by the GUI widgets. An optional
argument scope
directs the function to create local or global
variables based on the list that is returned.
getWinVal(v=NULL, scope="", asvector=FALSE, winName="")
getWinVal(v=NULL, scope="", asvector=FALSE, winName="")
v |
vector of variable names to retrieve from the GUI widgets.
If |
scope |
scope of the retrieval. The default sets no variables
in the non-GUI environment; |
asvector |
return a vector instead of a list. WARNING: if a widget variable defines a true vector or matrix, this will not work. |
winName |
window from which to select GUI widget values. The default takes the window that has most recently received new user input. |
TODO: talk about scope=G/P/L and side effects of overwriting existing variables
A list (or vector) with named components, where names and values are defined by GUI widgets.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
parseWinFile
, setWinVal
, clearWinVal
Display a message prompt with "Yes" and "No" buttons.
getYes(message, title="Choice", icon="question")
getYes(message, title="Choice", icon="question")
message |
message to display in prompt window. |
title |
title of prompt window. |
icon |
icon to display in prompt window; options are
|
Returns TRUE
if the "Yes" button is clicked, FALSE
if the "No" button is clicked.
Anisa Egeli, Vancouver Island University, Nanaimo BC
showAlert
, getChoice
, chooseWinVal
## Not run: local(envir=.PBSmodEnv,expr={ if(getYes("Print the number 1?")) print(1) else print("hallucination") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ if(getYes("Print the number 1?")) print(1) else print("hallucination") }) ## End(Not run)
Restrict a numeric value x
to a positive value using a differentiable function.
GT0 stands for “greater than zero”.
GT0(x,eps=1e-4)
GT0(x,eps=1e-4)
x |
vector of values |
eps |
minimum value greater than zero. |
if (x >= eps)..........GT0 = x if (0 < x < eps).......GT0 = (eps/2) * (1 + (x/eps)^2) if (x <= 0)............GT0 = eps/2
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) plotGT0 <- function(eps=1,x1=-2,x2=10,n=1000,col="black") { x <- seq(x1,x2,len=n); y <- GT0(x,eps); lines(x,y,col=col,lwd=2); invisible(list(x=x,y=y)); } testGT0 <- function(eps=c(7,5,3,1,.1),x1=-2,x2=10,n=1000) { x <- seq(x1,x2,len=n); y <- x; plot(x,y,type="l"); mycol <- c("red","blue","green","brown","violet","orange","pink"); for (i in 1:length(eps)) plotGT0(eps=eps[i],x1=x1,x2=x2,n=n,col=mycol[i]); invisible(); }; testGT0() par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) plotGT0 <- function(eps=1,x1=-2,x2=10,n=1000,col="black") { x <- seq(x1,x2,len=n); y <- GT0(x,eps); lines(x,y,col=col,lwd=2); invisible(list(x=x,y=y)); } testGT0 <- function(eps=c(7,5,3,1,.1),x1=-2,x2=10,n=1000) { x <- seq(x1,x2,len=n); y <- x; plot(x,y,type="l"); mycol <- c("red","blue","green","brown","violet","orange","pink"); for (i in 1:length(eps)) plotGT0(eps=eps[i],x1=x1,x2=x2,n=n,col=mycol[i]); invisible(); }; testGT0() par(oldpar) })
Import a history list from file fname
, and place it
into the history list hisname
.
importHistory(hisname="", fname="", updateHis=TRUE)
importHistory(hisname="", fname="", updateHis=TRUE)
hisname |
name of the history list to be populated.
The default ( |
fname |
file name of history file to import.
The default ( |
updateHis |
logical: if |
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
PBS history functions (below) are available to those who would like to use the package's history functionality, without using the pre-defined history widget. These functions allow users to create customized history widgets.
initHistory(hisname, indexname=NULL, sizename=NULL, buttonnames=NULL, modename=NULL, func=NULL, overwrite=TRUE) rmHistory(hisname="", index="") addHistory(hisname="") forwHistory(hisname="") backHistory(hisname="") lastHistory(hisname="") firstHistory(hisname="") jumpHistory(hisname="", index="") clearHistory(hisname="")
initHistory(hisname, indexname=NULL, sizename=NULL, buttonnames=NULL, modename=NULL, func=NULL, overwrite=TRUE) rmHistory(hisname="", index="") addHistory(hisname="") forwHistory(hisname="") backHistory(hisname="") lastHistory(hisname="") firstHistory(hisname="") jumpHistory(hisname="", index="") clearHistory(hisname="")
hisname |
name of the history "list" to manipulate. If it is omitted,
the function uses the value of |
indexname |
name of the index entry widget in the window description file.
If |
sizename |
name of the current size entry widget. If |
buttonnames |
named list of names of the first, prev, next, and last buttons. If |
modename |
name of the radio widgets used to change addHistory\'s mode. If |
index |
index to the history item. The default ( |
func |
name of user supplied function to call when viewing history items. |
overwrite |
if |
PBS Modelling includes a pre-built history widget designed to collect interesting choices of GUI variables so that they can be redisplayed later, rather like a slide show.
Normally, a user would invoke a history widget simply by including a reference to it in the window description file. However, PBS Modelling includes support functions (above) for customized applications.
To create a customized history, each button must be described separately in the window description file rather than making reference to the history widget.
The history "List" must be initialized before any other functions may be called.
The use of a unique history name (hisname
) is used to associate a unique
history session with the supporting functions.
The indexname
and sizename
arguments correspond to the given names
of entry widgets in the window description file, which will be used to display the
current index and total size of the list. The indexname
entry widget can also
be used by jumpHistory
to retrieve a target index.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: # ****** THIS CODE DOES NOT RUN. NEEDS FIXING ***** # Example of creating a custom history widget that saves values # whenever the "Plot" button is pressed. The user can tweak the # inputs "a", "b", and "points" before each "Plot" and see the # "Index" increase. After sufficient archiving, the user can review # scenarios using the "Back" and "Next" buttons. # A custom history is needed to achieve this functionality since # the packages pre-defined history widget does not update plots. # To start, create a Window Description to be used with createWin # using astext=TRUE. P.S. Watch out for special characters which # must be "escaped" twice (first for R, then PBSmodelling). local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) winDesc <- ' window title="Custom History" vector names="a b k" labels="a b points" font="bold" \\ values="1 1 1000" function=myPlot grid 1 3 button function=myHistoryBack text="<- Back" button function=myPlot text="Plot" button function=myHistoryForw text="Next ->" grid 2 2 label "Index" entry name="myHistoryIndex" width=5 label "Size" entry name="myHistorySize" width=5 ' # Convert text to vector with each line represented as a new element winDesc <- strsplit(winDesc, "\n")[[1]] # Custom functions to update plots after restoring history values myHistoryBack <- function() { backHistory("myHistory"); myPlot(saveVal=FALSE); # show the plot with saved values } myHistoryForw <- function() { forwHistory("myHistory"); myPlot(saveVal=FALSE); # show the plot with saved values } myPlot <- function(saveVal=TRUE) { # save all data whenever plot is called (directly) if (saveVal) addHistory("myHistory"); getWinVal(scope="L"); tt <- 2*pi*(0:k)/k; x <- (1+sin(a*tt)); y <- cos(tt)*(1+sin(b*tt)); plot(x, y); } iHistory("myHistory", "myHistoryIndex", "myHistorySize") createWin(winDesc, astext=TRUE) par(oldpar) }) ## End(Not run)
## Not run: # ****** THIS CODE DOES NOT RUN. NEEDS FIXING ***** # Example of creating a custom history widget that saves values # whenever the "Plot" button is pressed. The user can tweak the # inputs "a", "b", and "points" before each "Plot" and see the # "Index" increase. After sufficient archiving, the user can review # scenarios using the "Back" and "Next" buttons. # A custom history is needed to achieve this functionality since # the packages pre-defined history widget does not update plots. # To start, create a Window Description to be used with createWin # using astext=TRUE. P.S. Watch out for special characters which # must be "escaped" twice (first for R, then PBSmodelling). local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) winDesc <- ' window title="Custom History" vector names="a b k" labels="a b points" font="bold" \\ values="1 1 1000" function=myPlot grid 1 3 button function=myHistoryBack text="<- Back" button function=myPlot text="Plot" button function=myHistoryForw text="Next ->" grid 2 2 label "Index" entry name="myHistoryIndex" width=5 label "Size" entry name="myHistorySize" width=5 ' # Convert text to vector with each line represented as a new element winDesc <- strsplit(winDesc, "\n")[[1]] # Custom functions to update plots after restoring history values myHistoryBack <- function() { backHistory("myHistory"); myPlot(saveVal=FALSE); # show the plot with saved values } myHistoryForw <- function() { forwHistory("myHistory"); myPlot(saveVal=FALSE); # show the plot with saved values } myPlot <- function(saveVal=TRUE) { # save all data whenever plot is called (directly) if (saveVal) addHistory("myHistory"); getWinVal(scope="L"); tt <- 2*pi*(0:k)/k; x <- (1+sin(a*tt)); y <- cos(tt)*(1+sin(b*tt)); plot(x, y); } iHistory("myHistory", "myHistoryIndex", "myHistorySize") createWin(winDesc, astext=TRUE) par(oldpar) }) ## End(Not run)
Identify an object by class
, mode
, typeof
,
and attributes
.
isWhat(x)
isWhat(x)
x |
an R object |
No value is returned. The function prints the object's characteristics on the command line.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
The function lisp
returns a vector of character strings
giving the names of the objects in .PBSmodEnv
. It is only
a wrapper for the base function ls
.
lisp(name, pos = .PBSmodEnv, envir = as.environment(pos), all.names = TRUE, pattern)
lisp(name, pos = .PBSmodEnv, envir = as.environment(pos), all.names = TRUE, pattern)
name |
which environment to use in listing the available objects.
See the details section of |
pos |
an alternative argument to |
envir |
an alternative argument to |
all.names |
a logical value. If |
pattern |
an optional regular expression. Only names
matching |
See the base function ls
for details.
Copyright 1995–2012 R Core Development Team; distributed under GPL 2 or later.
ls
, tget
glob2rx
for converting wildcard patterns to regular expressions.
A GUI interface allows users to edit, compile, and embed C functions in the R environment.
loadC()
loadC()
The function loadC()
launches an interactive GUI that can be used
to manage the construction of C functions intended to be called from R. The
GUI provides tools to edit, compile, load, and run C functions in the R
environment.
The loadC
GUI also includes a tool for comparison between the running times
and return values of R and C functions. It is assumed that the R and C
functions are named prefix.r
and prefix.c
, respectively, where
prefix
can be any user-chosen prefix. If an initialization function
prefix.init
exists, it is called before the start of the comparison.
The GUI controls:
File Prefix | Prefix for .c and .r files. |
Lib Prefix | Prefix for shared library object. |
Set WD | Set the working directory. |
Open Log | Open the log file. |
Open.c File | Open the file prefix.c from the working directory. |
Open .r File | Open the file prefix.r from the working directory. |
COMPILE | Compile prefix.c into a shared library object. |
LOAD | Load the shared library object. |
SOURCE R | Source the file prefix.r . |
UNLOAD | Unload the shared library object. |
Options | |
Editor | Text editor to use. |
Update | Commit option changes. |
Browse | Browse for a text editor. |
Clean Options | |
Select All | Select all check boxes specifying file types. |
Select None | Select none of the check boxes. |
Clean Proj | Clean the project of selected file types. |
Clean All | Clean the directory of selected file types. |
Comparison | |
Times to Run | Number of times to run the R and C functions. |
RUN | Run the comparison between R and C functions. |
R Time | Computing time to run the R function multiple times. |
C Time | Computing time to run the C function multiple times. |
Ratio | Ratio of R/C run times. |
Anisa Egeli, Vancouver Island University, Nanaimo BC
Save and load options for use from one R session to another. If no file name is given, then the default file name (specified when the option object was created) is used.
loadOptions(option.object, fname, prompt = FALSE) saveOptions(option.object, fname, prompt = FALSE)
loadOptions(option.object, fname, prompt = FALSE) saveOptions(option.object, fname, prompt = FALSE)
option.object |
options class object used for storing package options |
fname |
file name to use: if missing the default file name is used; if given, file name becomes the default. |
prompt |
logical: if |
If fname
is given (or selected when prompt=TRUE
),
then that file becomes the default file name for subsequent loading and saving.
See PBSoptions-class
for more details and
an example using PBSmodelling's option management functions.
These functions are used to move option values to and from a GUI.
Option values are stored within an R object (as referenced by the option.object
). loadOptionsGUI
copies the values from the R object to the GUI. saveOptionsGUI
copies the GUI values from the tcltk GUI to the R object.
loadOptionsGUI(option.object) saveOptionsGUI(option.object)
loadOptionsGUI(option.object) saveOptionsGUI(option.object)
option.object |
options class object used for storing package options |
See PBSoptions-class
for more details and
an example using PBSmodelling's option management functions.
Convert a vector of solid colours to a vector of translucent ones (or vice versa)
lucent(col.pal=1, a=1)
lucent(col.pal=1, a=1)
col.pal |
vector of colours |
a |
alpha transparency value ( |
The function acts as a small wrapper to the rgb
function.
Vector of transformed colours depending on the alpha transparancy value a
.
Steve Martell, International Pacific Halibut Commission, Seattle WA
pickCol
, testCol
,
col2rgb
, rgb
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) pbsfun = function(clrs=c("moccasin",rainbow(3))){ clrs = c(clrs,lucent(clrs,a=0.25)) testCol(clrs); invisible() } pbsfun() par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) pbsfun = function(clrs=c("moccasin",rainbow(3))){ clrs = c(clrs,lucent(clrs,a=0.25)) testCol(clrs); invisible() } pbsfun() par(oldpar) })
Open examples from the examples subdirectory of a given package.
openExamples(package, prefix, suffix)
openExamples(package, prefix, suffix)
package |
name of the package that contains the examples. |
prefix |
prefix of the example file(s). |
suffix |
character vector of suffixes for the example files. |
Copies of each example file are placed in the working directory and opened. If files with the same name already exist, the user is prompted with a choice to overwrite.
To use this function in a window description file, the
package
, prefix
and suffix
arguments must
be specified as the action of the widget that calls
openExamples
. Furthermore, package
, prefix
,
and each suffix
must be separated by commas. For example,
action=myPackage,example1,.r,.c
will copy example1.r
and example2.c
from the examples
directory of the
package myPackage to the working directory and open these
files. If the function was called by a widget, a widget named
prefix
will be set to the specified prefix.
If all the required arguments are missing, it is assumed that the function is being called by a GUI widget.
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: # Copies fib.c and fib.r from the examples directory in # PBSmodelling to the temporary working directory, and opens these files. local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) openExamples("PBSmodelling", c("fib"), c(".r", ".c")) setwd(cwd) }) ## End(Not run)
## Not run: # Copies fib.c and fib.r from the examples directory in # PBSmodelling to the temporary working directory, and opens these files. local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) openExamples("PBSmodelling", c("fib"), c(".r", ".c")) setwd(cwd) }) ## End(Not run)
Open a file using the program that the operating system (Windows / Mac
OS X / Linux) associates with its type. Users wishing to override the
default application can specify a program association using 'setPBSext'
.
openFile(fname="", package=NULL, select=FALSE)
openFile(fname="", package=NULL, select=FALSE)
fname |
|
package |
|
select |
|
An invisible string vector of the file names and/or commands with file names.
If a command is registered with setPBSext
, then
openFile
will replace all occurrences of "%f"
with the absolute path of the filename before executing the command.
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Regional Headquarters (RHQ), Vancouver BC
Last modified Rd: 2023-01-05
In package PBSmodelling:getPBSext
,
setPBSext
,
clearPBSext
,
writePBSoptions
## Not run: local(envir=.PBSmodEnv,expr={ # use openFile directly: openFile( "doc/PBSmodelling-UG.pdf", package="PBSmodelling" ) }) local(envir=.PBSmodEnv,expr={ # via doAction in a window description file: createWin( "button text=help func=doAction width=20 pady=25 bg=green action=\"openFile(`doc/PBSmodelling-UG.pdf`,package=`PBSmodelling`)\"", astext=TRUE) }) local(envir=.PBSmodEnv,expr={ # Set up 'Firefox' to open '.html' files (only applicable if Firefox is NOT default web browser) setPBSext("html", '"c:/Program Files/Mozilla Firefox/firefox.exe" file://%f') openFile("foo.html") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ # use openFile directly: openFile( "doc/PBSmodelling-UG.pdf", package="PBSmodelling" ) }) local(envir=.PBSmodEnv,expr={ # via doAction in a window description file: createWin( "button text=help func=doAction width=20 pady=25 bg=green action=\"openFile(`doc/PBSmodelling-UG.pdf`,package=`PBSmodelling`)\"", astext=TRUE) }) local(envir=.PBSmodEnv,expr={ # Set up 'Firefox' to open '.html' files (only applicable if Firefox is NOT default web browser) setPBSext("html", '"c:/Program Files/Mozilla Firefox/firefox.exe" file://%f') openFile("foo.html") }) ## End(Not run)
Open package User's Guide ‘<pkg>-UG.pdf’ if it exists.
This function is essentially a wrapper for openFile
.
openUG(pkg = "PBSmodelling")
openUG(pkg = "PBSmodelling")
pkg |
|
The user's guide is assumed to be PDF format with extension pdf
.
The name of the PDF file will be ‘<pkg>-UG.pdf’ (e.g., PBSmodelling-UG.pdf
.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
In package PBSmodelling:openFile
,
showHelp
,
viewCode
Pack a list with existing objects using names only.
packList(stuff, target="PBSlist", value, penv=NULL, tenv=.PBSmodEnv)
packList(stuff, target="PBSlist", value, penv=NULL, tenv=.PBSmodEnv)
stuff |
|
target |
|
value |
|
penv |
|
tenv |
|
A list object called target
will be located in the
tenv
environment. The objects named in stuff
and
located in the penv
environment will appear as named
components within the list object target
.
If an explicit value
is specified, the function uses this value
instead of looking for local objects. Essentially, stuff = value
which is then packed into target
.
No value is returned
The function determines the parent environment from within.
This environment contains the objects from which the function copies to the target environment.
Alternatively, the user can specify the environment where stuff
resides.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Institute of Ocean Sciences (IOS), Sidney BC
Last modified Rd: 2019-03-12
In package PBSmodelling:unpackList
,
readList
,
writeList
Accessor functions:tget
,
tcall
,
tprint
, and
tput
local(envir=.PBSmodEnv,expr={ fn = function() { alpha=rnorm(10) beta=letters gamma=mean delta=longley packList(c("alpha","beta","gamma","delta")) } fn(); tprint(PBSlist) })
local(envir=.PBSmodEnv,expr={ fn = function() { alpha=rnorm(10) beta=letters gamma=mean delta=longley packList(c("alpha","beta","gamma","delta")) } fn(); tprint(PBSlist) })
Pad numbers and/or text with leading and/or trailing zeroes.
pad0(x, n, f = 0)
pad0(x, n, f = 0)
x |
vector of numbers and/or strings |
n |
number of text characters representing a padded integer |
f |
factor of 10 transformation on |
Converts numbers (or text coerced to numeric) to integers and then to text,
and pads them with leading zeroes. If the factor f
is >0, then
trailing zeroes are also added.
If length(f)==1
or length(x)==1
, the function returns
a character vector representing x
with leading zeroes.
If both f
and x
have lengths >1, then a list of
character vectors indexed by f
is returned.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ resetGraph(); x <- pad0(x=123,n=10,f=0:7); addLabel(.5,.5,paste(x,collapse="\n"),cex=1.5); })
local(envir=.PBSmodEnv,expr={ resetGraph(); x <- pad0(x=123,n=10,f=0:7); addLabel(.5,.5,paste(x,collapse="\n"),cex=1.5); })
Parse a window description file (markup file) into
the list format expected by createWin
.
parseWinFile(fname, astext=FALSE)
parseWinFile(fname, astext=FALSE)
fname |
file name of the window description file. |
astext |
if |
A list representing a parsed window description file that can be directly
passed to createWin
.
All widgets are forced into a 1-column by N-row grid.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ x <- parseWinFile(system.file("examples/LissFigWin.txt",package="PBSmodelling")) createWin(x) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ x <- parseWinFile(system.file("examples/LissFigWin.txt",package="PBSmodelling")) createWin(x) }) ## End(Not run)
Pause, typically between graphics displays. Useful for demo purposes.
pause(s = "Press <Enter> to continue")
pause(s = "Press <Enter> to continue")
s |
text issued on the command line when |
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
PBS Modelling provides software to facilitate the design,
testing, and operation of computer models. It focuses particularly on
tools that make it easy to construct and edit a customized graphical
user interface (GUI). Although it depends heavily on the R interface
to the Tcl/Tk
package, a user does not need to know Tcl/Tk.
PBSmodelling
contains examples that illustrate models built using
other R packages, including PBSmapping
, deSolve
,
PBSddesolve
, and BRugs
.
It also serves as a convenient prototype for building new R packages,
along with instructions and batch files to facilitate that process.
The R directory .../library/PBSmodelling/doc
includes a complete
user guide ‘PBSmodelling-UG.pdf’. To use this package effectively,
please consult the guide.
PBS Modelling comes packaged with interesting examples accessed
through the function runExamples()
.
Additionally, users can view PBS Modelling widgets through the
function testWidgets()
.
More generally, a user can run any available demos in his/her locally
installed packages through the function runDemos()
.
Projects commonly involve various settings or options such as paths to C compilers or other third-party tools. PBSmodelling provides a set of option management functions for managing user specific options. Options can be modified through the provided set of functions on the command line, or through a custom GUI. These options can be saved to disk for use in subsequent R sessions.
To use PBSmodelling's suite of option management functions, a PBSoptions
object must be
created for each of your projects. Each PBSoptions
object contains a distinct R environment where
option values are stored; this allows different projects to use overlapping option names without conflicts
(provided each project has its own PBSoptions
class object).
When a PBSoptions
object is created with the new
function, the initial.options
list, if supplied, is stored
as initial user options in the object. The initialization routine then attempts to load user set options from the filename
file. If such a file exists,
these values are stored in the PBSoptions
object overwriting any initial values as specified by initial.options
Option values are not directly stored in the object, but rather in an environment stored in the instance
slot.
Using an environment rather than slots for storing options allows us to pass option object by reference rather than value; that is,
we can save options in the object without the need of returning a new modified class object. It is therefore necessary that users
use the functions listed in the "see also" section to effectively manage user options.
Objects can be created by calls of the form new("PBSoptions",filename,initial.options=list(),gui.prefix="option")
.
filename:
default file name to use when saving and loading options to and from disk
initial.options:
a list with distinctly named initial options to use if no previously saved file exists
gui.prefix:
a prefix used to identify GUI variables which correspond to user options
instance
:The R environment used to store options. Please do not use this directly; use the functions listed under the "see also" section.
signature(x = "PBSoptions")
: prints the list of options
Do not use the slots directly – use the access functions instead.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
getOptions
for retrieving and modifying user options
getOptionsFileName
for retrieving and modifying the default options file name
loadOptions
for loading and saving options from and to disk
getOptionsPrefix
for retrieving and modifying the GUI prefix (for custom GUI interfaces)
loadOptionsGUI
for setting GUI values to reflect user options and vice-versa
## Not run: local(envir=.PBSmodEnv,expr={ #initialize an option manager with a single logical option .mypkg <- new( "PBSoptions", filename="my_pkg.txt", initial.options=list( sillyhatday=FALSE ) ) #retrieving an option silly <- getOptions( .mypkg, "sillyhatday" ) cat( "today is", ifelse( silly, "silly hat day!", "monday" ), "\n" ) #set an option setOptions( .mypkg, sillyhatday = TRUE, photos = "/shares/silly_hat_photos" ) #create a GUI which works with options createWin( c( "check name=optionsillyhatday text=\"silly hat day\"", "entry name=optionphotos width=22 mode=character label=\"photos directory\"", "button func=doAction text=save action=saveOptionsGUI(.mypkg)" ), astext = TRUE ) #update GUI values based on values stored in .mypkg's options loadOptionsGUI( .mypkg ) print(getOptions( .mypkg )) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ #initialize an option manager with a single logical option .mypkg <- new( "PBSoptions", filename="my_pkg.txt", initial.options=list( sillyhatday=FALSE ) ) #retrieving an option silly <- getOptions( .mypkg, "sillyhatday" ) cat( "today is", ifelse( silly, "silly hat day!", "monday" ), "\n" ) #set an option setOptions( .mypkg, sillyhatday = TRUE, photos = "/shares/silly_hat_photos" ) #create a GUI which works with options createWin( c( "check name=optionsillyhatday text=\"silly hat day\"", "entry name=optionphotos width=22 mode=character label=\"photos directory\"", "button func=doAction text=save action=saveOptionsGUI(.mypkg)" ), astext = TRUE ) #update GUI values based on values stored in .mypkg's options loadOptionsGUI( .mypkg ) print(getOptions( .mypkg )) }) ## End(Not run)
Display an interactive colour palette from which the user can choose a colour.
pickCol(returnValue=TRUE)
pickCol(returnValue=TRUE)
returnValue |
If |
A hexidecimal colour value.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ junk<-pickCol(); resetGraph() addLabel(.5,.5,junk,cex=4,col=junk) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ junk<-pickCol(); resetGraph() addLabel(.5,.5,junk,cex=4,col=junk) }) ## End(Not run)
Plot autocorrelation bars (ACF) from a data frame, matrix, or vector.
plotACF(file, lags=20, clrs=c("blue","red","green","magenta","navy"), ...)
plotACF(file, lags=20, clrs=c("blue","red","green","magenta","navy"), ...)
file |
data frame, matrix, or vector of numeric values. |
lags |
maximum number of lags to use in the ACF calculation. |
clrs |
vector of colours. Patterns are repeated if the number
of fields exceed the length of |
... |
additional arguments for |
This function is designed primarily to give greater flexibility when viewing
results from the R-package BRugs
. Use plotACF
in conjunction with
samplesHistory("*",beg=0,plot=FALSE)
rather than samplesAutoC
which calls plotAutoC
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph(); plotACF(trees,lwd=2,lags=30) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) resetGraph(); plotACF(trees,lwd=2,lags=30) par(oldpar) })
Plot x
and y
coordinates using a specified aspect ratio.
plotAsp(x, y, asp=1, ...)
plotAsp(x, y, asp=1, ...)
x |
vector of x-coordinate points in the plot. |
y |
vector of y-coordinate points in the plot. |
asp |
|
... |
additional arguments for |
The function plotAsp
differs from plot(x,y,asp=1)
in the way axis
limits are handled. Rather than expand the range, plotAsp
expands the
margins through padding to keep the aspect ratio accurate.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x <- seq(0,10,0.1) y <- sin(x) par(mfrow=2:1) plotAsp(x,y,asp=1,xlim=c(0,10),ylim=c(-2,2), main="sin(x)") plotAsp(x,y^2,asp=1,xlim=c(0,10),ylim=c(-2,2), main="sin^2(x)") par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x <- seq(0,10,0.1) y <- sin(x) par(mfrow=2:1) plotAsp(x,y,asp=1,xlim=c(0,10),ylim=c(-2,2), main="sin(x)") plotAsp(x,y^2,asp=1,xlim=c(0,10),ylim=c(-2,2), main="sin^2(x)") par(oldpar) })
Construct a bubble plot for a matrix z
.
plotBubbles(z, xval=FALSE, yval=FALSE, dnam=FALSE, rpro=FALSE, cpro=FALSE, rres=FALSE, cres=FALSE, powr=0.5, size=0.2, lwd=1, clrs=c("black","red","blue"), hide0=FALSE, frange=0.05, prettyaxis=FALSE, ...)
plotBubbles(z, xval=FALSE, yval=FALSE, dnam=FALSE, rpro=FALSE, cpro=FALSE, rres=FALSE, cres=FALSE, powr=0.5, size=0.2, lwd=1, clrs=c("black","red","blue"), hide0=FALSE, frange=0.05, prettyaxis=FALSE, ...)
z |
|
xval |
|
yval |
|
dnam |
|
rpro |
|
cpro |
|
rres |
|
cres |
|
powr |
|
size |
|
lwd |
|
clrs |
|
hide0 |
|
frange |
|
prettyaxis |
|
... |
|
The function plotBubbles
essentially flips the z
matrix
visually. The columns of z
become the x-values while the rows of
z
become the y-values, where the first row is displayed as the
bottom y-value and the last row is displayed as the top y-value. The
function's original intention was to display proportions-at-age vs. year.
Jon T. Schnute, Research Scientist Emeritus
Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
In package PBSmodelling:genMatrix
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) plotBubbles(round(genMatrix(40,20),0),clrs=c("green","grey","red")); data(CCA.qbr,envir=.PBSmodEnv) plotBubbles(CCA.qbr,cpro=TRUE,powr=.5,dnam=TRUE,size=.15, ylim=c(0,70),xlab="Year",ylab="Quillback Rockfish Age") par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) plotBubbles(round(genMatrix(40,20),0),clrs=c("green","grey","red")); data(CCA.qbr,envir=.PBSmodEnv) plotBubbles(CCA.qbr,cpro=TRUE,powr=.5,dnam=TRUE,size=.15, ylim=c(0,70),xlab="Year",ylab="Quillback Rockfish Age") par(oldpar) })
Plot the cumulative frequency of a data vector or matrix, showing the median and mean of the distribution.
plotCsum(x, add = FALSE, ylim = c(0, 1), xlab = "Measure", ylab = "Cumulative Proportion", ...)
plotCsum(x, add = FALSE, ylim = c(0, 1), xlab = "Measure", ylab = "Cumulative Proportion", ...)
x |
vector or matrix of numeric values. |
add |
logical: if |
ylim |
limits for the y-axis. |
xlab |
label for the x-axis. |
ylab |
label for the y-axis. |
... |
additional arguments for the |
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x <- rgamma(n=1000,shape=2) plotCsum(x) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x <- rgamma(n=1000,shape=2) plotCsum(x) par(oldpar) })
Plot the density curves from a data frame, matrix, or vector. The mean density curve of the data combined is also shown.
plotDens(file, clrs=c("blue","red","green","magenta","navy"), ...)
plotDens(file, clrs=c("blue","red","green","magenta","navy"), ...)
file |
data frame, matrix, or vector of numeric values. |
clrs |
vector of colours. Patterns are repeated if the number
of fields exceed the length of |
... |
additional arguments for |
This function is designed primarily to give greater flexibility when viewing
results from the R-package BRugs
. Use plotDens
in conjunction with
samplesHistory("*",beg=0,plot=FALSE)
rather than samplesDensity
which calls plotDensity
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) z <- data.frame(y1=rnorm(50,sd=2),y2=rnorm(50,sd=1),y3=rnorm(50,sd=.5)) plotDens(z,lwd=3) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) z <- data.frame(y1=rnorm(50,sd=2),y2=rnorm(50,sd=1),y3=rnorm(50,sd=.5)) plotDens(z,lwd=3) par(oldpar) })
Create a pairs plot where the lower left half comprises either fried egg contours or smoke ring contours, the upper right half comprises glasses of beer filled to the correlation point, and the diagonals show frequency histograms of the input data.
plotFriedEggs(A, eggs=TRUE, rings=TRUE, levs=c(0.01,0.1,0.5,0.75,0.95), pepper=200, replace=FALSE, jitt=c(1,1), bw=25, histclr=NULL)
plotFriedEggs(A, eggs=TRUE, rings=TRUE, levs=c(0.01,0.1,0.5,0.75,0.95), pepper=200, replace=FALSE, jitt=c(1,1), bw=25, histclr=NULL)
A |
data frame or matrix for use in a pairs plot. |
eggs |
logical: if |
rings |
logical: if |
levs |
explicit contour levels expressed as quantiles. |
pepper |
number of samples to draw from |
replace |
logical: if |
jitt |
argument |
bw |
argument |
histclr |
user-specified colour(s) for histogram bars along the diagonal. |
This function comes to us from Dr. Steve Martell of the Fisheries Science Centre at UBC. Obviously many hours of contemplation with his students at the local pub have contributed to this unique rendition of a pairs plot.
If eggs=TRUE
and rings=FALSE
, fried eggs are served.
If eggs=FALSE
and rings=TRUE
, smoke rings are blown.
If eggs=TRUE
and rings=TRUE
, only fried eggs are served.
If eggs=FALSE
and rings=FALSE
, only pepper is sprinkled.
Steve Martell, International Pacific Halibut Commission, Seattle WA
KernSmooth::bkde2D
, grDevices::contourLines
, graphics::contour
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x=rnorm(5000,10,3); y=-x+rnorm(5000,1,4); z=x+rnorm(5000,1,3) A=data.frame(x=x,y=y,z=z) for (i in 1:3) switch(i, {plotFriedEggs(A,eggs=TRUE,rings=FALSE); pause("Here are the eggs...(Press Enter for next)")}, {plotFriedEggs(A,eggs=FALSE,rings=TRUE); pause("Here are the rings...(Press Enter for next)")}, {plotFriedEggs(A,eggs=FALSE,rings=FALSE); cat("Here is the pepper alone.\n")} ) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) x=rnorm(5000,10,3); y=-x+rnorm(5000,1,4); z=x+rnorm(5000,1,3) A=data.frame(x=x,y=y,z=z) for (i in 1:3) switch(i, {plotFriedEggs(A,eggs=TRUE,rings=FALSE); pause("Here are the eggs...(Press Enter for next)")}, {plotFriedEggs(A,eggs=FALSE,rings=TRUE); pause("Here are the rings...(Press Enter for next)")}, {plotFriedEggs(A,eggs=FALSE,rings=FALSE); cat("Here is the pepper alone.\n")} ) par(oldpar) })
Plot (x,y) table (matrix or data frame) as horizontal sidebars.
plotSidebars(z, scale = 1, col = lucent("blue", 0.25), ...)
plotSidebars(z, scale = 1, col = lucent("blue", 0.25), ...)
z |
data frame or matrix of z-values (e.g., age frequencies) where rows form the plot's y-values and columns describe the grouping variable along the x-axis. |
scale |
numeric scale factor controlling the leftward expansion of z-value bars. |
col |
colour to fill bars. |
... |
additional parameters used by |
Plots z-data as horizontal bars arising from an x-coordinate controlled by
the column names of z
. The bars extend left along the y-coordinate
by z*scale
from the central x-coordinate.
Steve Martell, International Pacific Halibut Commission, Seattle WA
plotBubbles
, plotFriedEggs
,
evalCall
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) pbsfun = function () { meanmarg = function(x){x=x[!is.na(x)]; if (length(x)==0 | all(x==0)) NA else sum((x/sum(x))*as.numeric(names(x)))} data(CCA.qbr,envir=.PBSmodEnv) plotSidebars(CCA.qbr,scale=4,las=1,border="navyblue",mar=c(4,4,1,1), lbl=c("Year","Quillback Rockfish Age"),margin=function(x){round(meanmarg(x),0)}) invisible() } pbsfun() par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) pbsfun = function () { meanmarg = function(x){x=x[!is.na(x)]; if (length(x)==0 | all(x==0)) NA else sum((x/sum(x))*as.numeric(names(x)))} data(CCA.qbr,envir=.PBSmodEnv) plotSidebars(CCA.qbr,scale=4,las=1,border="navyblue",mar=c(4,4,1,1), lbl=c("Year","Quillback Rockfish Age"),margin=function(x){round(meanmarg(x),0)}) invisible() } pbsfun() par(oldpar) })
Plot trace lines from a data frame or matrix where the first field contains x-values, and subsequent fields give y-values to be traced over x. If input is a vector, this is traced over the number of observations.
plotTrace(file, clrs=c("blue","red","green","magenta","navy"), ...)
plotTrace(file, clrs=c("blue","red","green","magenta","navy"), ...)
file |
data frame or matrix of x and y-values, or a vector of y-values. |
clrs |
vector of colours. Patterns are repeated if the number
of traces (y-fields) exceed the length of |
... |
additional arguments for |
This function is designed primarily to give greater flexibility when viewing
results from the R-package BRugs
. Use plotTrace
in conjunction with
samplesHistory("*",beg=0,plot=FALSE)
rather than samplesHistory
which calls plotHistory
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) z <- data.frame(x=1:50,y1=rnorm(50,sd=3),y2=rnorm(50,sd=1),y3=rnorm(50,sd=.25)) plotTrace(z,lwd=3) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) z <- data.frame(x=1:50,y1=rnorm(50,sd=3),y2=rnorm(50,sd=1),y3=rnorm(50,sd=.25)) plotTrace(z,lwd=3) par(oldpar) })
Start an R talk from a talk description file that launches a control GUI.
presentTalk(talk)
presentTalk(talk)
talk |
name of file containing XML code (e.g., |
The function presentTalk
is a tool that facilitates lectures
and workshops in R. The function allows the presenter to show code
snippets alongside their execution, making use of R's graphical
capabilities. When presentTalk
is called, a graphical user
interface (GUI) is launched that allows the user to control the
flow of the talk (e.g., switching between talks or skipping to
various sections of a talk.
The automatic control buttons allow the user to move forward or
backward in the talk. The GO
button moves forward one tag
segment, the Back
button moves back to the previous tag
segment. The blue buttons allow movement among sections –
Prev
to the previous section, Restart
to the start of
the current section, and Next
to the next section. Drop down
lists are provided for both indicating the current section and slide
number and as an additional interface for jumping between different
sections or slide numbers.
In addition to the automatic menu items, a user can add buttons to the GUI that accomplish similar purposes.
See the PBSmodelling User's Guide for more information.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
See PBStalk-class
for more details on
PBSmodelling's talk presentation classes.
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd() talk_dir <- system.file("examples", package = "PBSmodelling" ) setwd(talk_dir) presentTalk( "swisstalk.xml" ) # closing the GUI should restore cwd }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd() talk_dir <- system.file("examples", package = "PBSmodelling" ) setwd(talk_dir) presentTalk( "swisstalk.xml" ) # closing the GUI should restore cwd }) ## End(Not run)
If changes have been made to PBS options, this function allows
the user to choose whether to write PBS options to an external
file that can be loaded later by readPBSoptions
.
promptWriteOptions(fname="")
promptWriteOptions(fname="")
fname |
name of file where options will be saved. |
If there are options that have been changed in the GUI but have not been committed to PBSmodelling memory in the global R environment, the user is prompted to choose whether or not to commit these options.
Then, if any PBS options have been changed, the user is prompted to choose
whether to save these options to the file fname
. (When a new R session is
started or when a call to readPBSoptions
or writePBSoptions
is made,
PBS options are considered to be unchanged; when an option is set,
the options are considered to be changed).
If fname=""
, the user is prompted to save under the file name last used
by a call to readPBSoptions
or writePBSoptions
if available.
Otherwise, the default file name "PBSoptions.txt" is used.
Anisa Egeli, Vancouver Island University, Nanaimo BC
writePBSoptions
, readPBSoptions
,
setPBSoptions
## Not run: local(envir=.PBSmodEnv,expr={ promptWriteOptions() #uses default filename PBSoptions.txt }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ promptWriteOptions() #uses default filename PBSoptions.txt }) ## End(Not run)
Read in a list previously saved to an ASCII file by various R functions such
as dput
, dump
, and writeList
. The latter can render
lists in a convenient PBSmodelling format. The function readList
detects the format automatically.
For information about the PBSmodelling format, see writeList
.
readList(fname)
readList(fname)
fname |
file name of the text file containing the list. |
Returns a list object from ASCII files originally formatted in one of the
following ways: "D"
= created by the R functions dput
or dump
;"R"
= R list object that uses ‘structure’ (e.g., Windows History file);"P"
= PBS-formatted file (see writeList
);"C"
= comment-delimited file (e.g., Awatea/Coleraine input files).
When importing a list in the PBSmodelling
("P"
) format,
if two list elements share the same name, the list will import
incorrectly.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
packList
, unpackList
, writeList
Load options that were saved using writePBSoptions
, for use
with openFile
, getPBSoptions
or interfaces such as
loadC
.
readPBSoptions(fname="PBSoptions.txt")
readPBSoptions(fname="PBSoptions.txt")
fname |
file name or full path of file from which the options will be loaded. |
If an option exists in R memory but not in the saved file, the option is not cleared from memory.
Anisa Egeli, Vancouver Island University, Nanaimo BC
writePBSoptions
, getGUIoptions
,
openFile
, getPBSoptions
Reset par()
to default values to ensure that a new plot
utilizes a full figure region. This function helps manage the device
surface, especially after previous plotting has altered it.
resetGraph(reset.mf=TRUE)
resetGraph(reset.mf=TRUE)
reset.mf |
if |
This function resets par()
to its default values.
If reset.mf=TRUE
, it also clears the graphics device with
frame()
. Otherwise, the values of mfrow
, mfcol
,
and mfg
are preserved, and graphics continues as usual in
the current plot. Use resetGraph
only before a high level
command that would routinely advance to a new frame.
invisible return of the reset value par()
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Restore scaled parameters to their original units. Used in minimization by calcMin
.
restorePar(S,pvec)
restorePar(S,pvec)
S |
scaled parameter vector. |
pvec |
a data frame comprising four columns -
|
Restoration algorithm:
Parameter vector converted from scaled units to original units specified by pvec
.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ pvec <- data.frame(val=c(1,100,10000),min=c(0,0,0),max=c(5,500,50000), active=c(TRUE,TRUE,TRUE)) S <- c(.5,.5,.5) P <- restorePar(S,pvec) print(cbind(pvec,S,P)) })
local(envir=.PBSmodEnv,expr={ pvec <- data.frame(val=c(1,100,10000),min=c(0,0,0),max=c(5,500,50000), active=c(TRUE,TRUE,TRUE)) S <- c(.5,.5,.5) P <- restorePar(S,pvec) print(cbind(pvec,S,P)) })
An interactive GUI for accessing demos from any R package installed on the
user's system. runDemos
is a convenient alternative to R's demo
function.
runDemos(package)
runDemos(package)
package |
display demos from a particular package (optional). |
If the argument package
is not specified, the function will look for
demos in all packages installed on the user's system.
The runDemos
GUI attempts to retain the user's objects and restore
the working directory. However, pre-existing objects will be overwritten
if their names coincide with names used by the various demos. Also,
depending on conditions, the user may lose working directory focus.
We suggest that cautious users run this demo from a project where data objects are
not critical.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
runExamples
for examples specific to PBSmodelling.
Display a GUI to demonstrate one PBS Modelling example.
The example source files can be found in the R directory
.../library/PBSmodelling/examples
.
runExample(ex, pkg="PBSmodelling")
runExample(ex, pkg="PBSmodelling")
ex |
string specifying an example in the |
pkg |
package with an |
If no example is specified or if the example does not exist, a GUI pops up informing you of potential choices. Note that the string choice is case-sensitive.
Some examples use external packages which must be installed to work correctly:
BRugs
- LinReg
, MarkRec
, and CCA
;
deSolve/PBSddesolve
- FishRes
;
PBSmapping
- FishTows
.
The examples are copied from .../library/PBSmodelling/examples
to R's current
temporary working directory and run from there.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Display an interactive GUI to demonstrate PBS Modelling examples.
The example source files can be found in the R directory
.../library/PBSmodelling/examples
.
runExamples()
runExamples()
Some examples use external packages which must be installed to work correctly:
BRugs
- LinReg
, MarkRec
, and CCA
;
deSolve/PBSddesolve
- FishRes
;
PBSmapping
- FishTows
.
The examples are copied from .../library/PBSmodelling/examples
to R's current
temporary working directory and run from there.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Scale parameters for function minimization by calcMin
.
scalePar(pvec)
scalePar(pvec)
pvec |
a data frame comprising four columns -
|
Scaling algorithm:
Parameter vector scaled between 0 and 1.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ pvec <- data.frame(val=c(1,100,10000),min=c(0,0,0),max=c(5,500,50000), active=c(TRUE,TRUE,TRUE)) S <- scalePar(pvec) print(cbind(pvec,S)) })
local(envir=.PBSmodEnv,expr={ pvec <- data.frame(val=c(1,100,10000),min=c(0,0,0),max=c(5,500,50000), active=c(TRUE,TRUE,TRUE)) S <- scalePar(pvec) print(cbind(pvec,S)) })
Display the default directory chooser prompt provided by the Operating System.
selectDir(initialdir=getwd(), mustexist=TRUE, title="", usewidget=NULL)
selectDir(initialdir=getwd(), mustexist=TRUE, title="", usewidget=NULL)
initialdir |
initially selected directory |
mustexist |
if logical value is |
title |
title for the prompt window |
usewidget |
store the selected directory in the named entry widget |
The directory path selected by the user
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ dir(selectDir(title="select a directory to list contents of")) #integration with widget via doAction createWin( c( "entry foo mode=character", "button text=\"select dir\" func=doAction action=\"selectDir(usewidget=`foo`)\"" ), astext=TRUE ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ dir(selectDir(title="select a directory to list contents of")) #integration with widget via doAction createWin( c( "entry foo mode=character", "button text=\"select dir\" func=doAction action=\"selectDir(usewidget=`foo`)\"" ), astext=TRUE ) }) ## End(Not run)
Display the default Open or Save prompt provided by the Operating System.
selectFile(initialfile="", initialdir=getwd(), filetype=list(c("*","All Files")), mode="open", multiple=FALSE, title="", defaultextension="", usewidget=NULL)
selectFile(initialfile="", initialdir=getwd(), filetype=list(c("*","All Files")), mode="open", multiple=FALSE, title="", defaultextension="", usewidget=NULL)
initialfile |
initially selected file |
initialdir |
initially directory the dialog opens |
filetype |
a list of character vectors indicating file types made available
to users of the GUI. Each vector is of length one or two. The first element
specifies either the file extension or |
mode |
string: if |
multiple |
if |
title |
title for the prompt window |
defaultextension |
default file extension if none is provided by the user |
usewidget |
store the selected file in the named entry widget |
The file name and path of the file(s) selected by the user.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ #integration with widget via doAction createWin( c( "entry foo mode=character width=60", "button text=\"select file\" func=doAction action=\"selectFile(usewidget=`foo`)\"" ), astext=TRUE ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ #integration with widget via doAction createWin( c( "entry foo mode=character width=60", "button text=\"select file\" func=doAction action=\"selectFile(usewidget=`foo`)\"" ), astext=TRUE ) }) ## End(Not run)
Set a PBS option by browsing for a file. This function provides
an alternative to using setPBSoptions
when setting an
option that has a path to a file as its value.
setFileOption(option)
setFileOption(option)
option |
name PBS option to change |
If all the required arguments are missing, it is assumed that the function is being called by a GUI widget.
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ setPathOption("editor") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ setPathOption("editor") }) ## End(Not run)
Set PBS options from corresponding values of widgets in a GUI.
setGUIoptions(option)
setGUIoptions(option)
option |
the name of a single option or the string |
A GUI may have PBS options that it uses, which have corresponding widgets that
are used for entering values for these options. These are declared by
declareGUIoptions
.
If the option
argument is the name of an option,
setGUIoptions
transfers the value of this option from a
same-named widget into PBS options global R environment database.
If the option
argument is "*"
, then all the
options that have been declared by declareGUIoptions
will be transferred in this fashion.
To use this function in a window description file, the
option
argument must be specified as the action of the
widget that calls setGUIoptions
– action=editor
or action=*
for example.
If all the required arguments are missing, it is assumed that the function is being called by a GUI widget.
Anisa Egeli, Vancouver Island University, Nanaimo BC
declareGUIoptions
, getGUIoptions
,
setPBSoptions
,
## Not run: local(envir=.PBSmodEnv,expr={ setGUIoptions("editor") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ setGUIoptions("editor") }) ## End(Not run)
Set a PBS option by browsing for a directory. This function provides
an alternative to using setPBSoptions
when setting an option
that has a path as its value.
setPathOption(option)
setPathOption(option)
option |
name PBS option to change |
If all the required arguments are missing, it is assumed that the function is being called by a GUI widget.
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ setPathOption("myPath") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ setPathOption("myPath") }) ## End(Not run)
Set a command with an associated extension, for use in
openFile
. The command must specify where the target file
name is inserted by indicating a '%f'
.
setPBSext(ext, cmd)
setPBSext(ext, cmd)
ext |
|
cmd |
|
These values are not saved from one PBS Modelling session to the next.
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Regional Headquarters (RHQ), Vancouver BC
Last modified Rd: 2023-01-05
In package PBSmodelling:getPBSext
,
openFile
,
clearPBSext
## Not run: local(envir=.PBSmodEnv,expr={ ## Set 'Firefox' to open '.html' files (only applicable if Firefox is NOT default web browser) setPBSext("html", '"c:/Program Files/Mozilla Firefox/firefox.exe" file://%f') openFile("foo.html") ## Set 'notepad' to open '.txt' files (only applicable if notepad is NOT default editor) ## Note that commands to editors (at least in Windows) do not use 'file://'. setPBSext('txt', '"C:/Windows/notepad.exe" %f') openFile("foo.txt") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ ## Set 'Firefox' to open '.html' files (only applicable if Firefox is NOT default web browser) setPBSext("html", '"c:/Program Files/Mozilla Firefox/firefox.exe" file://%f') openFile("foo.html") ## Set 'notepad' to open '.txt' files (only applicable if notepad is NOT default editor) ## Note that commands to editors (at least in Windows) do not use 'file://'. setPBSext('txt', '"C:/Windows/notepad.exe" %f') openFile("foo.txt") }) ## End(Not run)
Options set by the user for use by other functions.
setPBSoptions(option, value, sublist=FALSE)
setPBSoptions(option, value, sublist=FALSE)
option |
name of the option to set. |
value |
new value to assign this option. |
sublist |
if |
Objects can be placed into the PBS options manager (see PBSoptions-class
).
If the user wishes to change the object associated with an option, issue the command:
setPBSoptions("someOldOption",someNewOption)
If an option comprises a list object, a user can alter specific components of the list
by activating the sublist
argument:
setPBSoptions(option="myList", value=list(gamma=130), sublist=TRUE)
See example below.
A value .PBSmod$.options$.optionsChanged
is set to TRUE
when an option is changed,
so that the user doesn't always have to be prompted to save the options file.
By default, .PBSmod$.options$.optionsChanged
is not set or NULL
.
Also, if an option is set to ""
or NULL
then it is removed. .initPBSoptions()
is now called first (options starting with a dot "."
do not set .optionsChanged
).
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
getPBSoptions
, writePBSoptions
,
readPBSoptions
local(envir=.PBSmodEnv,expr={ myList=list(alpha=1,beta=2,gamma=3,delta=4) setPBSoptions(option="myList", myList) cat("Original myList:\n---------------\n") print(getPBSoptions("myList")) setPBSoptions(option="myList", value=list(gamma=130), sublist=TRUE) cat("Revised myList:\n--------------\n") print(getPBSoptions("myList")) })
local(envir=.PBSmodEnv,expr={ myList=list(alpha=1,beta=2,gamma=3,delta=4) setPBSoptions(option="myList", myList) cat("Original myList:\n---------------\n") print(getPBSoptions("myList")) setPBSoptions(option="myList", value=list(gamma=130), sublist=TRUE) cat("Revised myList:\n--------------\n") print(getPBSoptions("myList")) })
Allows the user to browse a directory tree to set the working directory. Optionally, files with given suffixes can be located in the new directory.
setwdGUI()
setwdGUI()
## Not run: local(envir=.PBSmodEnv,expr={ createWin( "button text=\"Change working directory\" func=setwdGUI", astext=TRUE ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ createWin( "button text=\"Change working directory\" func=setwdGUI", astext=TRUE ) }) ## End(Not run)
Update the foreground and background colors of a widget
setWidgetColor(name, radioValue, winName = .PBSmodEnv$.PBSmod$.activeWin, ...)
setWidgetColor(name, radioValue, winName = .PBSmodEnv$.PBSmod$.activeWin, ...)
name |
the name of the widget |
radioValue |
if specified, modify a particular radio option, as identified by the value, rather than the complete set (identified by the common name) |
winName |
window from which to select the GUI widget. The window that most recently receive user input is used by default if winname is not supplied |
... |
any combination of "fg", "bg", "disablefg", "disablebg", "entryfg", "entrybg", "noeditfg", "noeditbg" arguments, depending on type of widget - see details |
The setWidgetColor function allows dynamic updating of widget colors during program execution. However, two factors determine whether dynamic color updating is possible for a particular widget: (i) the type of widget, and (ii) the nature of the Tk implementation in the underlying widget library. Thus, a given widget may not support all combinations of colour variables. The following widgets support the corresponding options:
fg, bg, disablefg
fg, bg, disablefg, entryfg, entrybg
entryfg, entrybg, noeditfg, noeditbg
fg, bg
entryfg, entrybg, noeditfg, noeditbg
fg, bg
entryfg, entrybg, noeditfg, noeditbg
entryfg, entrybg, noeditfg, noeditbg
fg, bg
fg, bg
fg, bg
entryfg, entrybg
fg, bg
entryfg, entrybg, noeditfg, noeditbg
These options are described in the PBSmodelling User Guide under Appendix A.
Be aware that Tk uses gray for the highlight color during a selection operation. This means that when the background colour is also gray, there is no visual clue that the value has been selected for a copy operation.
Alex Couture-Beil (VIU, Nanaimo BC) and Allen R. Kronlund (PBS, Nanaimo BC)
## Not run: local(envir=.PBSmodEnv,expr={ createWin("label \"hello world\" name=hello", astext=TRUE) setWidgetColor( "hello", bg="lightgreen", fg="purple" ) }) local(envir=.PBSmodEnv,expr={ createWin("vector names=v length=3 values=\"1 2 3\"", astext=TRUE) setWidgetColor( "v[1]", entrybg="lightgreen", entryfg="purple" ) setWidgetColor( "v[2]", entrybg="green", entryfg="purple" ) setWidgetColor( "v[3]", entrybg="forestgreen", entryfg="purple" ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ createWin("label \"hello world\" name=hello", astext=TRUE) setWidgetColor( "hello", bg="lightgreen", fg="purple" ) }) local(envir=.PBSmodEnv,expr={ createWin("vector names=v length=3 values=\"1 2 3\"", astext=TRUE) setWidgetColor( "v[1]", entrybg="lightgreen", entryfg="purple" ) setWidgetColor( "v[2]", entrybg="green", entryfg="purple" ) setWidgetColor( "v[3]", entrybg="forestgreen", entryfg="purple" ) }) ## End(Not run)
Update the read-only state of a widget.
setWidgetState( varname, state, radiovalue, winname, warn=TRUE )
setWidgetState( varname, state, radiovalue, winname, warn=TRUE )
varname |
the name of the widget |
state |
"normal" or "disabled" and for some widgets "readonly" as described under Details below. |
radiovalue |
if specified, disable a particular radio option, as identified by the value, rather than the complete set (identified by the common name) |
winname |
window from which to select the GUI widget. The window that most recently receive user input is used by default if winname is not supplied. |
warn |
if TRUE, display a warning if readonly is converted to disabled (only applies for widgets that don't accept readonly) |
The setWidgetState function allows dynamic control of widget functioning during program execution. The function serves as a wrapper for the tkconfigure function available in the underlying Tk libraries used by PBS Modelling. Thus, setWidgetState is only available for those widgets that use Tk library widgets.
The state of the following PBS Modelling widgets can be set to "normal" or "disabled": button, check, data, droplist, entry, matrix, object, radio, slide, spinbox, table, text, and vector. When the state variable is set to "disabled", values displayed in the widget cannot be changed or copied except in the case of the object and table widgets which permit the values to be copied.
The data, entry, matrix, and vector widgets support a "readonly" state that allows values displayed in the widget to be copied but not changed. The displayed value can be selected using the keyboard or mouse. However, the copy and paste operations can only be accomplished via Ctrl-C and Ctrl-V, respectively, not the mouse.
Be aware that Tk uses gray for the highlight color during a selection operation. This means that when the background colour is also gray, there is no visual clue that the value has been selected for a copy operation.
Exceptions to the behaviour determined by state include the object, table and text widgets. There is no "readonly" state applicable to these widgets. Nevertheless, the values displayed can be copied even when the state is "disabled".
Individual radio widgets grouped by the name variable of a radio declaration can be updated by specifying radiovalue in the call to setWidgetState.
The state of individual elements in the data, matrix, and vector widgets can be updated by indexing. For the vector and matrix widgets any element can be addressed by appending the desired index to the widget name using square brackets (e.g., "myVec[2]" or "myMatrix[2,3]"). The data widget is indexed differently than the matrix widget by adding "d" after the brackets (e.g., "myData[1,1]d"). This change in syntax is required for internal coding of PBS Modelling.
Alex Couture-Beil (VIU, Nanaimo BC) and Allen R. Kronlund (PBS, Nanaimo BC)
## Not run: local(envir=.PBSmodEnv,expr={ winDesc <- c('vector length=3 name=vec labels="normal disabled readonly" values="1 2 3"', "matrix nrow=2 ncol=2 name=mat", "button name=but_name" ); createWin(winDesc, astext=TRUE) setWidgetState( "vec[1]", "normal" ) setWidgetState( "vec[2]", "disabled" ) setWidgetState( "vec[3]", "readonly" ) setWidgetState( "mat", "readonly" ) setWinVal( list( mat = matrix( 1:4, 2, 2 ) ) ) #works for buttons too setWidgetState( "but_name", "disabled" ) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ winDesc <- c('vector length=3 name=vec labels="normal disabled readonly" values="1 2 3"', "matrix nrow=2 ncol=2 name=mat", "button name=but_name" ); createWin(winDesc, astext=TRUE) setWidgetState( "vec[1]", "normal" ) setWidgetState( "vec[2]", "disabled" ) setWidgetState( "vec[3]", "readonly" ) setWidgetState( "mat", "readonly" ) setWinVal( list( mat = matrix( 1:4, 2, 2 ) ) ) #works for buttons too setWidgetState( "but_name", "disabled" ) }) ## End(Not run)
Append a string value specifying an action to the first position of an action vector.
setWinAct(winName, action)
setWinAct(winName, action)
winName |
window name where action is taking place. |
action |
string value describing an action. |
When a function is called from a GUI, a string descriptor associated with
the action of the function is stored internally (appended to the first position
of the action vector). A user can utilize this action as a type of argument
for programming purposes. The command getWinAct()[1]
yields the latest action.
Sometimes it is useful to “fake” an action. Calling setWinAct
allows
the recording of an action, even if a button has not been pressed.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Update a widget with a new value.
setWinVal(vars, winName)
setWinVal(vars, winName)
vars |
a list or vector with named components. |
winName |
window from which to select GUI widget values. The default takes the window that has most recently received new user input. |
The vars
argument expects a list or vector with named elements.
Every element name corresponds to the widget name which will be updated
with the supplied element value.
The vector
, matrix
, and data
widgets can be updated in
several ways. If more than one name is specified for the names
argument
of these widgets, each element is treated like an entry
widget.
If however, a single name
describes any of these three widgets, the entire
widget can be updated by passing an appropriately sized object.
Alternatively, any element can be updated by appending its index in square brackets
to the end of the name
. The data
widget is indexed differently
than the matrix
widget by adding "d" after the brackets. This tweak is necessary
for the internal coding (bookkeeping) of PBS Modelling. Example: "foo[1,1]d"
.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ winDesc <- c("vector length=3 name=vec", "matrix nrow=2 ncol=2 name=mat", "slideplus name=foo"); createWin(winDesc, astext=TRUE) setWinVal(list(vec=1:3, "mat[1,1]"=123, foo.max=1.5, foo.min=0.25, foo=0.7)) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ winDesc <- c("vector length=3 name=vec", "matrix nrow=2 ncol=2 name=mat", "slideplus name=foo"); createWin(winDesc, astext=TRUE) setWinVal(list(vec=1:3, "mat[1,1]"=123, foo.max=1.5, foo.min=0.25, foo=0.7)) }) ## End(Not run)
Return a character representation of a number with added zeroes out to a specified number of decimal places.
show0(x, n, add2int=FALSE, round2n=FALSE)
show0(x, n, add2int=FALSE, round2n=FALSE)
x |
numeric data (scalar, vector, or matrix). |
n |
number of decimal places to show, including zeroes. |
add2int |
if |
round2n |
if |
A scalar/vector of strings representing numbers. Useful for labelling purposes.
By default, this function does not round or truncate numbers. It simply adds zeroes if
n
is greater than the available digits in the decimal part of a number. The user can
choose to round the numbers first by setting argument round2n = TRUE
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) frame() #do not show decimals on integers addLabel(0.25,0.75,show0(15.2,4)) addLabel(0.25,0.7,show0(15.1,4)) addLabel(0.25,0.65,show0(15,4)) #show decimals on integers addLabel(0.25,0.55,show0(15.2,4,TRUE)) addLabel(0.25,0.5,show0(15.1,4,TRUE)) addLabel(0.25,0.45,show0(15,4,TRUE)) par(oldpar) })
local(envir=.PBSmodEnv,expr={ oldpar = par(no.readonly=TRUE) frame() #do not show decimals on integers addLabel(0.25,0.75,show0(15.2,4)) addLabel(0.25,0.7,show0(15.1,4)) addLabel(0.25,0.65,show0(15,4)) #show decimals on integers addLabel(0.25,0.55,show0(15.2,4,TRUE)) addLabel(0.25,0.5,show0(15.1,4,TRUE)) addLabel(0.25,0.45,show0(15,4,TRUE)) par(oldpar) })
Display an alert window that contains a specified message and an OK button for dismissing the window.
showAlert(message, title="Alert", icon="warning")
showAlert(message, title="Alert", icon="warning")
message |
message to display in alert window |
title |
title of alert window |
icon |
icon to display in alert window; options are
|
Anisa Egeli, Vancouver Island University, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ showAlert("Hello World!") }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ showAlert("Hello World!") }) ## End(Not run)
For each widget specified, display its arguments in order with their default values. The display list can be expanded to report each argument on a single line.
showArgs(widget, width=70, showargs=FALSE)
showArgs(widget, width=70, showargs=FALSE)
widget |
vector string of widget names; if not specified (default), the function displays information about all widgets in alphabetical order. |
width |
numeric width used by |
showargs |
logical:, if |
A text stream to the R console. Invisibly returns the widget usage lines.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Display the help pages for installed packages that match the supplied pattern in an HTML browser window.
showHelp(pattern="methods", ...)
showHelp(pattern="methods", ...)
pattern |
string pattern to match to package names |
... |
allows user to specify two additional arguments: |
The specified pattern is matched to R-packages installed on
the user's system. The code uses the utils
function browseURL
to display the HTML Help Pages using
a browser that the system associates with html
extensions. (See help for browseURL
for other operating systems.
A list is invisibly returned, comprising:
Apacks |
all packages installed on user's system |
Spacks |
selected packages based on specified pattern |
URLs |
path and file name of HTML Help Page |
Help pages are displayed in a separate browser window.
The connection time for browsers (at least in Windows OS)
is slow. If the HTML browser program is not already running,
multiple matching pages will most likely not be displayed. However,
subsequent calls to showHelp
should show all matches.
This function will now only work in R (>=3.2.0) or from SVN revision >= 67548.
The CRAN gurus now disallow direct calls to tools:::httpdPort
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Show the packages specified by the user and compare these to the installed packages on the user's system. Display packages not installed.
showPacks(packs=c("PBSmodelling","PBSmapping","PBSddesolve", "rgl","deSolve","akima","deldir","sp","maptools","KernSmooth"))
showPacks(packs=c("PBSmodelling","PBSmapping","PBSddesolve", "rgl","deSolve","akima","deldir","sp","maptools","KernSmooth"))
packs |
string vector of package names that are compared to installed packages. |
Invisibly returns a list of Apacks
(all packages installed on user's system),
Ipacks
(packages in packs
that are installed), and
Mpacks
(packages that are missing).
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Evaluate the supplied expression, reflect it on the command line, and show the results of the evaluation.
showRes(x, cr=TRUE, pau=TRUE)
showRes(x, cr=TRUE, pau=TRUE)
x |
an R expression to evaluate |
cr |
logical: if |
pau |
logical: if |
The results of the expression are return invisibly.
Jon T. Schnute, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ showRes("x=rnorm(100)",pau=FALSE) })
local(envir=.PBSmodEnv,expr={ showRes("x=rnorm(100)",pau=FALSE) })
Create a GUI that displays all vignettes for installed packages.
The user can choose to view the source file for building the vignette
or the final .pdf
file.
showVignettes(package)
showVignettes(package)
package |
character string specifying package name that exists in the user's R library |
If the argument package
is not specified, the function
will look for vignettes in all packages installed on the user's
system. The user can choose to view the source file
for building the vignette (usually *.Rnw
or *.Snw
files)
or the final build from the source code (*.pdf
).
showVignettes
uses the PBSmodelling function
openFile
to display the .Rnw
and .pdf
files
using programs that the system associates with these extensions.
On systems that do not support file extension associations, the
function setPBSext
can temporarily set a command to associate
with an extension.
Anisa Egeli, Vancouver Island University, Nanaimo BC
showHelp
, openFile
, setPBSext
, getPBSext
Utility to sort history. When called without any arguments, an interactive GUI
is used to pick which history to sort. When called with hisname
, sort
this active history widget. When called with file
and outfile
,
sort the history located in file
and save to outfile
.
sortHistory(file="", outfile=file, hisname="")
sortHistory(file="", outfile=file, hisname="")
file |
file name of saved history to sort. |
outfile |
file to save sorted history to. |
hisname |
name of active history widget and window it is located in, given
in the form |
After selecting a history to sort (either from given arguments, or interactive GUI) the R data editor window will be displayed. The editor will have one column named \"new\" which will have numbers 1,2,3,...,n. This represents the current ordering of the history. You may change the numbers around to define a new order. The list is sorted by reassigning the index in row i as index i.
For example, if the history had three items 1,2,3. Reordering this to 3,2,1 will reverse the order; changing the list to 1,2,1,1 will remove entry 3 and create two duplicates of entry 1.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
The function presentTalk
is a tool that facilitates lectures and workshops in R.
It allows the presenter to show code snippets alongside their
execution, making use of R's graphical capabilities.
For presentTalk
to work, six S4 class objects are created:
talk |
root element that constitutes a talk; |
section |
branch element that defines a section within a talk; |
text |
leaf element that specifies text to be printed on the R console; |
file |
leaf element that specifies files to be opened by the OS; |
code |
leaf element that specifies R code to be executed; |
break |
leaf element that specifies where to allow a break in the talk. |
The leaf elements, also termed primitive elements, occur in isolation and cannot
contain other elements. Therefore, only two levels of nesting are supported: sections
within a talk and primitives within a section.
See Appendix B in the PBSmodelling User's Guide for more information.
This function uses a convenience function called xmlGetAttr
(from the package XML) that retrieves the value of a named attribute in an XML node.
The function presentTalk
translates the XML code into a list structure
called .presentTalk
below the global object .PBSmod
. The GUI is
represented as a list structure called presentwin
under .PBSmod
,
as for all GUI objects in PBSmodelling.
talk | ||
name |
character |
string giving the name of the talk (required) |
sections |
list |
list of sections within the talk |
files |
list |
list of files within the talk |
section | ||
name |
character |
string giving the name of the section (required) |
items |
list |
list of the four primitive (leaf-element) S4 classes |
button |
logical |
should GUI have a button that selects section? |
col |
integer |
column in lower section of GUI to place button |
section_id |
integer |
specify if section does not immediately follow a talk |
text | ||
text |
character |
text to display on the R console |
"break" |
logical |
break the presentation after displaying the text specified? |
file | ||
name |
character |
string giving the name in the GUI for a group of files to open (required) |
filename |
character |
individual file names associated with the group name in the GUI |
"break" |
logical |
break the presentation after opening the group of files? |
button |
logical |
should GUI add a button that opens this group of files? |
col |
integer |
column in lower section of GUI to place button |
code | ||
show |
logical |
show the code snippet in the R console? |
print |
logical |
print the results of running the R code? |
code |
character |
the actual chunk of R code |
"break" |
character |
string describing where to introduce breaks in the code segment |
eval |
logical |
evaluate the R code? |
break | ||
.xData |
NULL |
allows a break in the talk for user interaction on the R console. |
Objects can be created by calls of the form:
new("talk", name=name) new("section", name = node$attributes["name"], button = as.logical(xmlGetAttr(node,"button",FALSE)), col = as.integer(xmlGetAttr(node,"col",2))) new("text", text = xmlValue(node), "break" = as.logical(xmlGetAttr(node,"break",TRUE))) new("file", name = xmlGetAttr(node,"name",""), "break" = as.logical(xmlGetAttr(node,"break",TRUE)), filename = xmlValue(node), button = as.logical(xmlGetAttr(node,"button",FALSE)), col = as.integer(xmlGetAttr(node,"col",3))) new("code", show = as.logical(xmlGetAttr(node,"show",TRUE)), print = as.logical(xmlGetAttr(node,"print",TRUE)), code = xmlValue(node), "break" = tolower(xmlGetAttr(node,"break","print"))) new("break")
Alex Couture-Beil, Software Engineer
Earthly Technologies, Victoria BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
presentTalk
for presenting a talk in R.
xmlGetAttr
for retrieving the value of a named attribute in an XML node.
setClass
for creating a class definition.
PBSoptions-class
for a complicated S4 class implementation.
Display how the alpha transparency for rgb()
varies.
testAlpha(alpha=seq(0,1,len=25), fg="blue", bg="yellow", border="black", grid=FALSE, ...)
testAlpha(alpha=seq(0,1,len=25), fg="blue", bg="yellow", border="black", grid=FALSE, ...)
alpha |
|
fg |
|
bg |
|
border |
|
grid |
|
... |
|
Invisibly returns the compound RGB matrix for fg
, alpha
,
bg
, and border
.
Jon T. Schnute, Research Scientist Emeritus
Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Maintainer: Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
In package PBSmodelling:testCol
,
testLty
,
testLwd
In package PBStools:testPch
Display colours as round patches in a plot. Useful for programming purposes.
Colours can be specified in any of 3 different ways:
(i) by colour name,
(ii) by hexadecimal colour code created by rgb()
, or
(iii) by calling one of the colour palettes.
testCol(cnam=colors()[sample(length(colors()),15)])
testCol(cnam=colors()[sample(length(colors()),15)])
cnam |
|
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
In package PBSmodelling:pickCol
,
testAlpha
In package PBStools:testPch
In package grDevices:palettes
local(envir=.PBSmodEnv,expr={ # mix and match patterns testCol(c("sky","fire","sea","wood")) }) local(envir=.PBSmodEnv,expr={ # display transparencies of blue testCol(rgb(0,0,1,seq(0.05,1,0.05))) }) local(envir=.PBSmodEnv,expr={ # display colours of the rainbow testCol(rainbow(64,end=0.75)) }) local(envir=.PBSmodEnv,expr={ # display basic palette colours testCol(1:length(palette())) }) local(envir=.PBSmodEnv,expr={ # mix colour types testCol(c("#9e7ad3", "purple", 6)) })
local(envir=.PBSmodEnv,expr={ # mix and match patterns testCol(c("sky","fire","sea","wood")) }) local(envir=.PBSmodEnv,expr={ # display transparencies of blue testCol(rgb(0,0,1,seq(0.05,1,0.05))) }) local(envir=.PBSmodEnv,expr={ # display colours of the rainbow testCol(rainbow(64,end=0.75)) }) local(envir=.PBSmodEnv,expr={ # display basic palette colours testCol(1:length(palette())) }) local(envir=.PBSmodEnv,expr={ # mix colour types testCol(c("#9e7ad3", "purple", 6)) })
Display line types available.
testLty(newframe=TRUE, n=1:18, ...)
testLty(newframe=TRUE, n=1:18, ...)
newframe |
|
n |
|
... |
|
Quick representation of line types for reference purposes.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-18
In package PBSmodelling:testLwd
,
testCol
In package PBStools:testPch
Display line widths. User can specify particular ranges for lwd
.
Colours can also be specified and are internally repeated as necessary.
testLwd(lwd=1:20, col=c("black","blue"), newframe=TRUE)
testLwd(lwd=1:20, col=c("black","blue"), newframe=TRUE)
lwd |
line widths to display. Ranges can be specified. |
col |
colours to use for lines. Patterns are repeated if
|
.
newframe |
if |
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
local(envir=.PBSmodEnv,expr={ testLwd(3:15,col=c("salmon","aquamarine","gold")) })
local(envir=.PBSmodEnv,expr={ testLwd(3:15,col=c("salmon","aquamarine","gold")) })
Display an interactive GUI to demonstrate the available widgets in PBS Modelling.
A text
window displays the window description file source code. The user
can modify this sample code and recreate the test GUI by pressing the button below.
The Window Description Files can be found in the R directory .../library/PBSmodelling/testWidgets
.
testWidgets()
testWidgets()
Following are the widgets and default values supported by PBS Modelling.
For detailed descriptions, see Appendix A in ‘PBSModelling-UG.pdf’
located in the R directory .../library/PBSmodelling/doc
.
button text="Calculate" font="" fg="black" bg="" disablefg=NULL width=0 name=NULL function="" action="button" sticky="" padx=0 pady=0 check name mode="logical" checked=FALSE text="" font="" fg="black" bg="" disablefg=NULL function="" action="check" edit=TRUE sticky="" padx=0 pady=0 data nrow ncol names modes="numeric" rowlabels="" collabels="" rownames="X" colnames="Y" font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" noeditfg="black" noeditbg="gray" values="" byrow=TRUE function="" enter=TRUE action="data" edit=TRUE width=6 borderwidth=0 sticky="" padx=0 pady=0 droplist name values=NULL choices=NULL labels=NULL selected=1 add=FALSE font="" fg="black" bg="white" function="" enter=TRUE action="droplist" edit=TRUE mode="character" width=20 sticky="" padx=0 pady=0 entry name value="" width=20 label=NULL font="" fg="" bg="" entryfont="" entryfg="black" entrybg="white" noeditfg="black" noeditbg="gray" edit=TRUE password=FALSE function="" enter=TRUE action="entry" mode="numeric" sticky="" padx=0 pady=0 grid nrow=1 ncol=1 toptitle="" sidetitle="" topfont="" sidefont="" topfg=NULL sidefg=NULL fg="black" topbg=NULL sidebg=NULL bg="" byrow=TRUE borderwidth=1 relief="flat" sticky="" padx=0 pady=0 history name="default" function="" import="" fg="black" bg="" entryfg="black" entrybg="white" text=NULL textsize=0 sticky="" padx=0 pady=0 image file=NULL varname=NULL subsample=NULL sticky="" padx=0 pady=0 include file=NULL name=NULL label text="" name="" mode="character" font="" fg="black" bg="" sticky="" justify="left" anchor="center" wraplength=0 width=0 padx=0 pady=0 matrix nrow ncol names rowlabels="" collabels="" rownames="" colnames="" font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" noeditfg="black" noeditbg="gray" values="" byrow=TRUE function="" enter=TRUE action="matrix" edit=TRUE mode="numeric" width=6 borderwidth=0 sticky="" padx=0 pady=0 menu nitems=1 label font="" fg="" bg="" menuitem label font="" fg="" bg="" function action="menuitem" notebook tabs name=NULL selected=1 tabpos="top" font="" fg=NULL bg=NULL width=0 height=0 homogeneous=FALSE arcradius=2 tabbevelsize=0 function=NULL action="notebook" sticky="we" padx=0 pady=0 null bg="" padx=0 pady=0 object name rowshow=0 font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" noeditfg="black" noeditbg="gray" vertical=FALSE collabels=TRUE rowlabels=TRUE function="" enter=TRUE action="data" edit=TRUE width=6 borderwidth=0 sticky="" padx=0 pady=0 progressbar name value=0 maximum=100 style="normal" width=NULL height=NULL vertical=FALSE fg=NULL bg=NULL relief="sunken" borderwidth=2 sticky="" padx=0 pady=0 radio name value text="" font="" fg="black" bg="" function="" action="radio" edit=TRUE mode="numeric" selected=FALSE sticky="" padx=0 pady=0 slide name from=0 to=100 value=NA showvalue=FALSE orientation="horizontal" font="" fg="black" bg="" function="" action="slide" sticky="" padx=0 pady=0 slideplus name from=0 to=1 by=0.01 value=NA font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" function="" enter=FALSE action="slideplus" sticky="" padx=0 pady=0 spinbox name from to by=1 value=NA label="" font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" function="" enter=TRUE edit=TRUE action="droplist" width=20 sticky="" padx=0 pady=0 table name rowshow=0 font="" fg="black" bg="white" rowlabels="" collabels="" function="" action="table" edit=TRUE width=10 sticky="" padx=0 pady=0 text name height=8 width=30 edit=FALSE scrollbar=TRUE fg="black" bg="white" mode="character" font="" value="" borderwidth=1 relief="sunken" sticky="" padx=0 pady=0 vector names length=0 labels="" values="" vecnames="" font="" fg="black" bg="" entryfont="" entryfg="black" entrybg="white" noeditfg="black" noeditbg="gray" vertical=FALSE function="" enter=TRUE action="vector" edit=TRUE mode="numeric" width=6 borderwidth=0 sticky="" padx=0 pady=0 window name="window" title="" vertical=TRUE bg="#D4D0C8" fg="#000000" onclose="" remove=FALSE
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
Get/print objects from or put objects into a temporary work environment
called .PBSmodEnv
. These objects include .PBSmod
,
which controls the GUI system.
tget(x, penv=NULL, tenv=.PBSmodEnv) tcall(x, penv=NULL, tenv=.PBSmodEnv) tprint(x, penv=NULL, tenv=.PBSmodEnv) tput(x, penv=NULL, tenv=.PBSmodEnv)
tget(x, penv=NULL, tenv=.PBSmodEnv) tcall(x, penv=NULL, tenv=.PBSmodEnv) tprint(x, penv=NULL, tenv=.PBSmodEnv) tput(x, penv=NULL, tenv=.PBSmodEnv)
x |
|
penv |
|
tenv |
|
These accessor functions were developed as a response to the CRAN repository policy statement: “Packages should not modify the global environment (user's workspace).”
There are also wrapper functions called .win.tget
,
.win.tcall
, and .win.tprint
that can be used in
window description files to launch functions or print objects
from the .PBSmodEnv
workspace.
The wrapper uses getWinAct
to get the function (or object)
name that a user specifies in the action
argument of a
widget command.
Objects are retrieved from or sent to the temporary working
environment to/from the place where the function(s) are called.
Additionally, tcall
invisibly returns the object without
transferring, which is useful when the object is a function that the
user may wish to call, for example, tcall(myfunc)()
.
Additional wrapper functions to access functions in .PBSmodEnv
are named with the prefix .win
.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Offsite, Vancouver BC
Last modified Rd: 2023-10-25
## Not run: local(envir=.PBSmodEnv,expr={ str(tcall(.PBSmod),2) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ str(tcall(.PBSmod),2) }) ## End(Not run)
Make local or global variables (depending on the scope specified) from the named components of a list.
unpackList(x, scope="L")
unpackList(x, scope="L")
x |
named list to unpack. |
scope |
If |
A character vector of unpacked variable names.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
local(envir=.PBSmodEnv,expr={ x <- list(a=21,b=23); unpackList(x); print(a); })
local(envir=.PBSmodEnv,expr={ x <- list(a=21,b=23); unpackList(x); print(a); })
Update the currently active GUI with values from R's memory at the specified location.
updateGUI(scope = "L")
updateGUI(scope = "L")
scope |
either |
If the characteristics of the local R objects do not match those of the GUI objects, the update will fail.
Invisibly returns a Boolean vector that specifies whether the objects in the local R environment match items in the active GUI.
Rob Kronlund, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
## Not run: local(envir=.PBSmodEnv,expr={ #law of free food: http://www.phdcomics.com/comics.php?f=1223 createWin( c( "vector names=\"foodquality hunger cost\" values=\"0.6 0.8 0.1\" width=10", "entry name=taste edit=F label=taste:" ), astext=TRUE ) getWinVal( scope="P" ) taste <- foodquality * hunger / cost updateGUI() }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ #law of free food: http://www.phdcomics.com/comics.php?f=1223 createWin( c( "vector names=\"foodquality hunger cost\" values=\"0.6 0.8 0.1\" width=10", "entry name=taste edit=F label=taste:" ), astext=TRUE ) getWinVal( scope="P" ) taste <- foodquality * hunger / cost updateGUI() }) ## End(Not run)
Lengths-at-age for freshwater mussels (Anodonta kennerlyi).
data(vbdata)
data(vbdata)
A data frame with 16 rows and 2 columns c("age","len")
.
Data for demonstration of the von Bertalanffy model used in the
calcMin
example.
Fisheries and Oceans Canada - Mittertreiner and Schnute (1985)
Mittertreiner, A. and Schnute, J. (1985) Simplex: a manual and software package for easy nonlinear parameter estimation and interpretation in fishery research. Canadian Technical Report of Fisheries and Aquatic Sciences 1384, xi + 90 pp.
Starting parameter values for Linf
, K
, and t0
for
von Bertalanffy minimization using length-at-age data (vbdata
)
for freshwater mussels (Anodonta kennerlyi).
data(vbpars)
data(vbpars)
A matrix with 3 rows and 3 columns c("Linf","K","t0")
. Each row contains
the starting values, minima, and maxima, respectively, for the three parameters.
Data for demonstration of the von Bertalanffy model used in
the calcMin
example.
Mittertreiner, A. and Schnute, J. (1985) Simplex: a manual and software package for easy nonlinear parameter estimation and interpretation in fishery research. Canadian Technical Report of Fisheries and Aquatic Sciences 1384, xi + 90 pp.
View the first or last or random n
elements or rows of an object.
Components of lists will be subset using iterative calls to view
.
view(obj, n=5, last=FALSE, random=FALSE, print.console=TRUE, ...)
view(obj, n=5, last=FALSE, random=FALSE, print.console=TRUE, ...)
obj |
|
n |
|
last |
|
random |
|
print.console |
|
... |
|
Invisibly returns the results of the call to view
.
If random=TRUE
, random sampling will take place before the last
operator is applied.
Rowan Haigh, Program Head – Offshore Rockfish
Pacific Biological Station (PBS), Fisheries & Oceans Canada (DFO), Nanaimo BC
locus opus: Institute of Ocean Sciences (IOS), Sidney BC
Last modified Rd: 2019-03-12
In package PBSmodelling:lisp
,
showArgs
,
testCol
,
viewCode
In package utils:head
, tail
View the R code of all functions in a specified package installed on the user's system.
viewCode(pkg="PBSmodelling", funs, output=4, ...)
viewCode(pkg="PBSmodelling", funs, output=4, ...)
pkg |
string name of a package installed on the user's computer. |
funs |
string vector of explicit function names from |
output |
numeric value: 1 = function names only, 2 = function names with brief description, 3 = functions and their arguments, and 4 = function R-code (default). |
... |
allows user to specify two additional arguments for |
If funs
is not specified, then all functions, including
hidden (dot) functions are displayed.
If the package has a namespace, functions there are also displayed.
Invisibly returns source code of all functions in the specified package.
The function invokes openFile
to display the results.
Output type 2 (function name with brief description) will now only work in
R (>=3.2.0) or from SVN revision >= 67548.
The CRAN gurus now disallow direct calls to tools:::httpdPort
.
Rowan Haigh, Pacific Biological Station, Fisheries and Oceans Canada, Nanaimo BC
Write an ASCII text representation in either "D"
format or "P"
format.
The "D"
format makes use of dput
and dget
and produces an R
representation of the list. The "P"
format represents a simple list in an
easy-to-read, ad hoc PBSmodelling
format.
writeList(x, fname, format="D", comments="")
writeList(x, fname, format="D", comments="")
x |
R list object to write to an ASCII text file. |
fname |
file name of the text file to create. |
format |
format of the file to create: |
comments |
vector of character strings to use as initial-line comments in the file. |
The "D"
format is equivalent to using R's base
functions
dput
and dget
, which support all R objects.
The "P"
format only supports a list that may contain lists,
vectors, matrices, arrays, and data frames. Scalars are treated
like vectors. It writes each list element using the following
conventions:
$
denotes the start of a list element, and the element's
name follows this character; for nested lists, $
separates
each nesting level;
$$
, on the next line, denotes a line used to describe
the element's structure, which includes object type, mode(s), names
(if vector), rownames (if matrix or data), and colnames (if matrix
or data); and
subsequent lines contain data (one line for a vector and multiple lines for a matrix or other data).
If a list's elements are unnamed, have the name NA, or have the
empty string as a name, this function generates names ("P"
format only). If two list elements share the same name, the list
will export correctly, but it will import incorrectly.
Arrays with three or more dimensions have dim
and
dimnames
arguments. dim
describes the dimension of the
data (a vector as returned by dim(some_array)
) and
dimnames
is a vector of length sum(dim(some_array)+1)
and is constructed as follows:
foreach dimension d,
first append the name of the dimension d and
then append all labels within that dimension
Multiple rows of data for matrices or data frames must have equal numbers of entries (separated by whitespace).
Note that array data are written the same format as they are
displayed in the R console: nrow=dim()[1]
, ncol=dim()[2]
repeated by scrolling through successively higher dimensions, increasing the
index from left to right within each dimension. The flattened table will have
dim()[2]
columns.
For complete details, see “PBSmodelling-UG.pdf” at the location described when loading this package.
String containing the file name.
Alex Couture-Beil, Vancouver Island University, Nanaimo BC
packList
, readList
, unpackList
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) test <- list(a=10,b=euro,c=view(WorldPhones),d=view(USArrests)) writeList(test,"test.txt",format="P", comments=" Scalar, Vector, Matrix, Data Frame") openFile("test.txt") setwd(cwd) }) local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) ##Example of dimnames for Arrays dimnames(Titanic) writeList( list( Titanic ), format="P") setwd(cwd) }) ## End(Not run)
## Not run: local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) test <- list(a=10,b=euro,c=view(WorldPhones),d=view(USArrests)) writeList(test,"test.txt",format="P", comments=" Scalar, Vector, Matrix, Data Frame") openFile("test.txt") setwd(cwd) }) local(envir=.PBSmodEnv,expr={ cwd = getwd(); setwd(tempdir()) ##Example of dimnames for Arrays dimnames(Titanic) writeList( list( Titanic ), format="P") setwd(cwd) }) ## End(Not run)
Save options that were set using setPBSoptions
,
setPBSext
, or interfaces such as loadC
.
These options can be reloaded using readPBSoptions
.
writePBSoptions(fname="PBSoptions.txt")
writePBSoptions(fname="PBSoptions.txt")
fname |
file name or full path of file to which the options will be saved. |
Options with names starting with "."
will not be saved.
Anisa Egeli, Vancouver Island University, Nanaimo BC
readPBSoptions
, setPBSoptions
,
setPBSext
, promptWriteOptions