├── .github ├── .gitignore └── workflows │ └── R-CMD-check.yaml ├── _config.yml ├── data └── Trancura9414001.RData ├── .Rbuildignore ├── inst ├── doc │ └── hydroPSO_SWAT2005_MF2005.pdf ├── hydroPSO2pest.pst ├── CITATION └── Rscripts │ └── hydroPSO-Rscript.R ├── man ├── hydroPSO-internal.Rd ├── Trancura9414001.Rd ├── read_best.Rd ├── hydromodInR.Rd ├── wquantile.Rd ├── hydroPSO2pest.Rd ├── pest2hydroPSO.Rd ├── plot_2parOF.Rd ├── verification.Rd ├── hydroPSO-package.Rd ├── plot_ParamsPerIter.Rd ├── quant2ecdf.Rd ├── plot_NparOF.Rd ├── ReadPlot_GofPerParticle.Rd ├── ReadPlot_convergence.Rd ├── hydromod.Rd ├── params2ecdf.Rd └── test_functions.Rd ├── .travis.yml ├── R ├── zl.R ├── read_velocities.R ├── hydromodInR.R ├── read_best.R ├── read.paramfile.R ├── read.ParameterRanges.R ├── plot_convergence.R ├── ParameterValues2InputFiles.R ├── read_GofPerParticle.R ├── wquantile.R ├── plot_GofPerParticle.R ├── ModifyInputFile.R ├── plot_2parOF.R ├── read_convergence.R ├── read_results.R ├── plot_ParamsPerIter.R ├── read_particles.R ├── plot_NparOF.R └── plot_out.R ├── .gitignore ├── vignettes ├── hydroPSO_SWAT2005_MF2005.tex ├── hydroPSO_TUWmodel-vignette-link.Rmd └── hydroPSO_GR4J-vignette-link.Rmd ├── DESCRIPTION └── NAMESPACE /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /data/Trancura9414001.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzambran/hydroPSO/HEAD/data/Trancura9414001.RData -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | README.md 2 | .git 3 | .travis.yml 4 | _config.yml 5 | ^\.github$ 6 | ^docs$ 7 | ^pkgdown$ 8 | ^_pkgdown\.yml$ 9 | -------------------------------------------------------------------------------- /inst/doc/hydroPSO_SWAT2005_MF2005.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hzambran/hydroPSO/HEAD/inst/doc/hydroPSO_SWAT2005_MF2005.pdf -------------------------------------------------------------------------------- /man/hydroPSO-internal.Rd: -------------------------------------------------------------------------------- 1 | \name{hydroPSO-internal} 2 | \title{Internal hydroPSO objects} 3 | \alias{ParameterValues2InputFiles} 4 | \alias{read.ParameterRanges} 5 | \alias{rLHS} 6 | \alias{hydromod.eval.SA} 7 | \alias{hydromodInR.eval} 8 | \description{Internal hydroPSO objects.} 9 | \details{These are not to be called by the user.} 10 | \keyword{internal} 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: r 2 | sudo: false 3 | cache: packages 4 | 5 | r: 6 | - oldrel 7 | - release 8 | - devel 9 | 10 | before_install: 11 | - tlmgr install index 12 | 13 | branches: 14 | except: 15 | - example-data 16 | - gh-pages 17 | 18 | apt_packages: 19 | - build-essential 20 | - tcl8.6 21 | - tk8.6 22 | - tcl8.6-dev 23 | - tk8.6-dev 24 | 25 | before_install: 26 | - export DISPLAY=:99.0 27 | 28 | r_packages: 29 | - sm 30 | - vioplot 31 | 32 | notifications: 33 | email: 34 | on_success: change 35 | on_failure: change 36 | 37 | -------------------------------------------------------------------------------- /R/zl.R: -------------------------------------------------------------------------------- 1 | # File zFirst.R 2 | # Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # http://www.rforge.net/hydroPSO/ 5 | # Copyright 2011-2020 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | # Distributed under GPL 2 or later 7 | 8 | .onAttach <- function(libname, pkgname) { 9 | 10 | packageStartupMessage("(C) 2011-2020 M. Zambrano-Bigiarini and R. Rojas (GPL >=2 license)\n", 11 | "Type 'citation('hydroPSO')' to see how to cite this package") 12 | invisible() 13 | 14 | } # '.onAttach' END 15 | 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | .Rapp.history 4 | 5 | # Session Data files 6 | .RData 7 | 8 | # User-specific files 9 | .Ruserdata 10 | 11 | # Example code in package build process 12 | *-Ex.R 13 | 14 | # Output files from R CMD build 15 | /*.tar.gz 16 | 17 | # Output files from R CMD check 18 | /*.Rcheck/ 19 | 20 | # RStudio files 21 | .Rproj.user/ 22 | 23 | # produced vignettes 24 | vignettes/*.html 25 | vignettes/*.pdf 26 | 27 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 28 | .httr-oauth 29 | 30 | # knitr and R markdown default cache directories 31 | *_cache/ 32 | /cache/ 33 | 34 | # Temporary files created by R markdown 35 | *.utf8.md 36 | *.knit.md 37 | 38 | # R Environment Variables 39 | .Renviron 40 | -------------------------------------------------------------------------------- /vignettes/hydroPSO_SWAT2005_MF2005.tex: -------------------------------------------------------------------------------- 1 | \documentclass{article} 2 | \usepackage{pdfpages} 3 | \usepackage[utf8]{inputenc} 4 | \usepackage[english]{babel} 5 | \usepackage{hyperref} 6 | \hypersetup{ 7 | colorlinks=true, 8 | linkcolor=blue, 9 | filecolor=blue, 10 | urlcolor=blue, 11 | } 12 | %\VignetteIndexEntry{A tutorial for interfacing `hydroPSO` with `SWAT-2005` and `MODFLOW-2005`} 13 | %\VignetteEngine{knitr::rmarkdown} 14 | %\VignetteEncoding{UTF-8} 15 | 16 | \begin{document} 17 | %\includepdf[pages=-, fitpaper=true]{mypaper.pdf} 18 | A tutorial for interfacing hydroPSO with SWAT-2005 and MODFLOW-2005 can be found on \href{https://www.rforge.net/hydroPSO/files/hydroPSO\_vignette.pdf}{https://www.rforge.net/hydroPSO/files/hydroPSO\_vignette.pdf} 19 | \end{document} 20 | -------------------------------------------------------------------------------- /vignettes/hydroPSO_TUWmodel-vignette-link.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tutorial for using `hydroPSO` to calibrate `TUWmodel`" 3 | author: 4 | - "Mauricio Zambrano-Bigiarini" 5 | date: "v0.9.3, April 27th, 2020" 6 | output: 7 | pdf_document: 8 | number_sections: true 9 | fig_caption: yes 10 | html_document: 11 | number_sections: true 12 | urlcolor: blue 13 | subtitle: 'Study area: Trancura River Basin, Chile' 14 | vignette: > 15 | %\VignetteIndexEntry{Tutorial for using `hydroPSO` to calibrate `TUWmodel`} 16 | %\VignetteEngine{knitr::rmarkdown} 17 | \usepackage[utf8]{inputenc} 18 | %\VignetteEncoding{UTF-8} 19 | --- 20 | 21 | A tutorial for using `hydroPSO` to calibrate `TUWmodel` can be found [**https://doi.org/10.5281/zenodo.3772176**](https://doi.org/10.5281/zenodo.3772176) 22 | 23 | 24 | -------------------------------------------------------------------------------- /inst/hydroPSO2pest.pst: -------------------------------------------------------------------------------- 1 | pcf 2 | * control data 3 | restart estimation 4 | npar nobs npar 0 1 5 | ntpl nins single point 1 0 0 6 | 5.0 2.0 0.3 0.03 10 999 7 | 3.0 3.0 0.001 0 8 | 0.1 9 | 30 0.01 3 3 0.01 3 10 | 1 1 1 11 | * parameter groups 12 | param.name relative 0.01 0.0 switch 2.0 parabolic 13 | * parameter data 14 | param.name none relative param.ini param.min param.max param.name 1.0000 0.0000 1 15 | * observation groups 16 | obsgroup 17 | * observation data 18 | obs00001 obs.value 1.0 obsgroup 19 | * model command line 20 | exe.fname 21 | * model input/output 22 | file001.tpl input001.txt 23 | ModelOut.ins output.txt 24 | * prior information 25 | -------------------------------------------------------------------------------- /vignettes/hydroPSO_GR4J-vignette-link.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tutorial for using `hydroPSO` to calibrate the `GR4J` hydrological model" 3 | author: 4 | - "Mauricio Zambrano-Bigiarini" 5 | date: "v0.3, April 28th, 2020" 6 | output: 7 | pdf_document: 8 | number_sections: true 9 | fig_caption: yes 10 | html_document: 11 | number_sections: true 12 | urlcolor: blue 13 | subtitle: 'Study area: Trancura River Basin, Chile' 14 | vignette: > 15 | %\VignetteIndexEntry{Tutorial for using `hydroPSO` to calibrate the `GR4J` hydrological model`} 16 | %\VignetteEngine{knitr::rmarkdown} 17 | \usepackage[utf8]{inputenc} 18 | %\VignetteEncoding{UTF-8} 19 | --- 20 | 21 | A tutorial for using `hydroPSO` to calibrate the `GR4J` hydrological model can be found at [**https://doi.org/10.5281/zenodo.3774533**](https://doi.org/10.5281/zenodo.3774533). 22 | 23 | 24 | -------------------------------------------------------------------------------- /R/read_velocities.R: -------------------------------------------------------------------------------- 1 | # File read.velocities.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2011-2012 Mauricio Zambrano-Bigairini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'read_velocities' # 9 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 10 | # Started: 08-Nov-2011, # 11 | # Updates: # 12 | ################################################################################ 13 | 14 | 15 | read_velocities <- function(file="Velocities.txt", ... ) { 16 | 17 | out <- read_particles(file=file,...) 18 | names(out) <- c("velocities", "gofs", "best.velocity", "best.gof") 19 | return(out) 20 | 21 | } # 'read_velocities' END 22 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | 9 | name: R-CMD-check 10 | 11 | jobs: 12 | R-CMD-check: 13 | runs-on: ${{ matrix.config.os }} 14 | 15 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | config: 21 | - {os: macos-latest, r: 'release'} 22 | - {os: macos-latest, r: 'devel', http-user-agent: 'release'} 23 | - {os: windows-latest, r: 'release'} 24 | - {os: windows-latest, r: 'devel', http-user-agent: 'release'} 25 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 26 | - {os: ubuntu-latest, r: 'release'} 27 | - {os: ubuntu-latest, r: 'oldrel-1'} 28 | 29 | env: 30 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 31 | R_KEEP_PKG_SOURCE: yes 32 | 33 | steps: 34 | - uses: actions/checkout@v3 35 | 36 | - uses: r-lib/actions/setup-pandoc@v2 37 | 38 | - uses: r-lib/actions/setup-tinytex@v2 39 | 40 | - uses: r-lib/actions/setup-r@v2 41 | with: 42 | r-version: ${{ matrix.config.r }} 43 | http-user-agent: ${{ matrix.config.http-user-agent }} 44 | use-public-rspm: true 45 | 46 | - uses: r-lib/actions/setup-r-dependencies@v2 47 | with: 48 | extra-packages: any::rcmdcheck 49 | needs: check 50 | 51 | - uses: r-lib/actions/check-r-package@v2 52 | with: 53 | upload-snapshots: true 54 | build_args: c('--compact-vignettes=gs+qpdf') 55 | -------------------------------------------------------------------------------- /R/hydromodInR.R: -------------------------------------------------------------------------------- 1 | # File hydromodInR.R 2 | # Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # http://www.rforge.net/hydroPSO/ 5 | # Copyright 2024-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | # Distributed under GPL 2 or later 7 | 8 | ################################################################################ 9 | # hydromod # 10 | ################################################################################ 11 | # Purpose : This is a wrapper function for the internal 'hydromodInR.eval' # 12 | # function. # 13 | # To run an R-based hydrological/environmental model for a single # 14 | # particle, and get a goodness-of-fit value by comparing the # 15 | # simulated values against observations # 16 | ################################################################################ 17 | # Output : A list of two elements: # 18 | # 1) sim: simulated values obtained by running the hydrological # 19 | # model # 20 | # 2) GoF: goodness-of fit of the simualted values against observed# 21 | # ones, by using THE USER-DEFINED 'gof' measure # 22 | ################################################################################ 23 | # Author : Mauricio Zambrano-Bigiarini # 24 | # Started: 19-Nov-2020 # 25 | # Updates: 10-Jul-2024 # 26 | ################################################################################ 27 | hydromodInR <- function( 28 | part, 29 | Particles, 30 | model.FUN, 31 | model.FUN.args 32 | ) { 33 | 34 | hydromodInR.eval(part, Particles, model.FUN, model.FUN.args) 35 | 36 | } # 'hydromodInR' END 37 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: hydroPSO 2 | Type: Package 3 | Title: Particle Swarm Optimisation, with Focus on Environmental Models 4 | Version: 0.5-24 5 | Author: Mauricio Zambrano-Bigiarini [aut, cre] (), Rodrigo Rojas [ctb] 6 | Authors@R: c(person("Mauricio", "Zambrano-Bigiarini", email="mzb.devel@gmail.com", role=c("aut","cre"), comment=c(ORCID = "0000-0002-9536-643X")), person("Rodrigo", "Rojas", email="Rodrigo.RojasMujica@gmail.com", role=c("ctb")) ) 7 | Maintainer: Mauricio Zambrano-Bigiarini 8 | Description: State-of-the-art version of the Particle Swarm Optimisation (PSO) algorithm (SPSO-2011 and SPSO-2007 capable). 'hydroPSO' can be used as a replacement of the 'optim' R function for (global) optimization of non-smooth and non-linear functions. However, the main focus of 'hydroPSO' is the calibration of environmental and other real-world models that need to be executed from the system console. 'hydroPSO' is model-independent, allowing the user to easily interface any computer simulation model with the calibration engine (PSO). 'hydroPSO' communicates with the model through the model's own input and output files, without requiring access to the model's source code. Several PSO variants and controlling options are included to fine-tune the performance of the calibration engine to different calibration problems. An advanced sensitivity analysis function together with user-friendly plotting summaries facilitate the interpretation and assessment of the calibration results. 'hydroPSO' is parallel-capable, to alleviate the computational burden of complex models with "long" execution time. Bugs reports/comments/questions are very welcomed (in English, Spanish or Italian). See Zambrano-Bigiarini and Rojas (2013) for more details. 9 | License: GPL (>=2) 10 | Depends: R (>= 3.6.0) 11 | Imports: methods, grDevices, graphics, stats, utils, Hmisc, sp, lattice, zoo(>= 1.7-2), grid, lhs, hydroTSM(>= 0.3-6), hydroGOF(>= 0.3-5), parallel, vioplot, scatterplot3d, data.table, pbapply 12 | Suggests: knitr, rmarkdown 13 | VignetteBuilder: knitr 14 | URL: https://github.com/hzambran/hydroPSO 15 | BugReports: https://github.com/hzambran/hydroPSO/issues 16 | LazyLoad: yes 17 | ByteCompile: TRUE 18 | NeedsCompilation: no 19 | Repository: CRAN 20 | Packaged: Sun 2 Nov 20:43:09 -03 2025 ; hzambran 21 | -------------------------------------------------------------------------------- /R/read_best.R: -------------------------------------------------------------------------------- 1 | # File read_best.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'read_best' # 9 | ################################################################################ 10 | # Purpose: # 11 | # To read the 'BestParameterSet.txt' ouput file, wich stores the best parameter# 12 | # set and its corresponding best fitness value # 13 | ################################################################################ 14 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 15 | # Started: 08-Nov-2011, # 16 | # Updates: # 17 | ################################################################################ 18 | 19 | read_best <- function(file="BestParameterSet.txt", 20 | verbose=TRUE 21 | ) { 22 | 23 | 24 | # Checking that 'file' exists 25 | if ( !file.exists(file) ) 26 | stop( paste("Invalid argument value: The file '", basename(file), "' doesn't exist", sep="" ) ) 27 | 28 | # Reading the file 29 | if (verbose) message( " ") 30 | if (verbose) message( "[ Reading the file '", basename(file), "' ... ]" ) 31 | best <- read.table(file=file, header=TRUE, skip=0) 32 | 33 | # computing the number of columns 34 | ncols <- ncol(best) 35 | 36 | # Getting the number of the 'best particle' 37 | best.part.number <- best[, 1] 38 | 39 | # Getting the GoF of the 'best particle' 40 | best.param.gof <- best[, 2] 41 | 42 | # Getting the Parameter Values of the 'best particle' 43 | best.param.values <- best[, 3:ncols] 44 | 45 | out <- list(best.part.number=best.part.number, 46 | best.param.values=best.param.values, 47 | best.param.gof=best.param.gof) 48 | 49 | return(out) 50 | 51 | } # 'read_best' END 52 | -------------------------------------------------------------------------------- /R/read.paramfile.R: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # read.paramfile # 3 | ################################################################################ 4 | # Purpose : Reading 'ParamFiles.txt' and 'ParamRanges.txt' files # 5 | ################################################################################ 6 | # Output : A data.frame with the following columns # 7 | # For 'ParamRanges.txt' file: # 8 | # 1) ParameterNmbr: numeric, from 1 to the number of parameters # 9 | # 2) ParameterName: character, with a meaningful name of each parameter 10 | # 3) MinValue : numeirc, with the minum value that each parameter can take 11 | # 3) MaxValue : numeric, with the maximum value that each parameter can take 12 | # 13 | # For 'ParamFiles.txt' file: # 14 | # 1) ParameterNmbr: numeric, from 1 to the number of parameters # 15 | # 2) ParameterName: character, with a meaningful name of each parameter 16 | # 3) Filename : character, with the name of each file that has to be modified 17 | # 4) Row.Number : numeric, with the number of the row in 'ParamFiles.txt' that has to be modified 18 | # 5) Col.Start : numeric, with the number of the colum in 'ParamFiles.txt' where the modification starts 19 | # 6) Col.End : numeric, with the number of the colum in 'ParamFiles.txt' where the modification ends 20 | # 7) Decimals : numeric, with the number of decimal places to be used for writing the new values in 'ParamFiles.txt' 21 | ################################################################################ 22 | # Author : Mauricio Zambrano-Bigiarini # 23 | # Started : 13-Dec-2010 at JRC Ispra # 24 | # Last Update: 13-Dec-2010 # 25 | ################################################################################ 26 | # Function for 27 | read.paramfile <- function(file="ParamFiles.txt") { 28 | 29 | x <- read.table(file=file, header=TRUE, skip=0, stringsAsFactors=FALSE) 30 | 31 | return(x) 32 | 33 | } #'read.paramfile' END 34 | -------------------------------------------------------------------------------- /man/Trancura9414001.Rd: -------------------------------------------------------------------------------- 1 | %%File Trancura9414001.Rd 2 | %% Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% http://www.rforge.net/hydroPSO/ 5 | %% Copyright 2020-2020 Mauricio Zambrano-Bigiarini 6 | %% Distributed under GPL 2 or later 7 | 8 | \name{Trancura9414001} 9 | \docType{data} 10 | \alias{Trancura9414001} 11 | \title{ 12 | Hydrometeorological time series for Trancura antes de Llafenco basin 13 | } 14 | \description{ 15 | Daily time series of precipitation, mean air temperature, potential evapotranspiration and streamflows for the catchment draining into the 'Trancura antes de Llafenco' streamflow station (Cod.BNA: 9414001, drainage area= 1415 km2), Araucania Region, Chile (Lat:-39.3333, Lon:-71.6667), with data from 01/Jan/1979 to 31/Dec/2016 (including some gaps). 16 | } 17 | \usage{ 18 | data(Trancura9414001) 19 | } 20 | 21 | %%\details{ 22 | %% 23 | %%} 24 | \format{ 25 | data.frame with 5 columns: \cr 26 | -) \var{Date}: character with the date (YYYY-MM-DD) for each daily observation. \cr 27 | -) \var{P_mm}: Spatially-averaged mean daily values of precipitation computed based on the CR2met dataset, [mm/day]. \cr 28 | -) \var{Tmean_degC}: Spatially-averaged mean daily values of air temperature computed based on the CR2met dataset, [degree Celsius]. \cr 29 | -) \var{PET_mm}: Spatially-averaged mean daily values of precipitation computed based on the Hargreaves-Samani equation and daily maximum and minimum air temperatures obtained from the CR2met dataset, [mm/day]. \cr 30 | -) \var{Qobs_m3s}: Daily sreamflows measured at the Trancura antes de Llafenco (9414001) station. \cr 31 | } 32 | \source{ 33 | Provided by Center for Climate and Resilience Research, Universidad de Chile, Santiago, Chile (\url{https://www.cr2.cl} at \url{https://camels.cr2.cl/}, last accessed [Feb 2020]). \cr 34 | These data are intended to be used for research purposes only, being distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. 35 | } 36 | 37 | \references{ 38 | \cite{Alvarez-Garreton, C., Mendoza, P. A., Boisier, J. P., Addor, N., Galleguillos, M., Zambrano-Bigiarini, M., Lara, A., Puelma, C., Cortes, G., Garreaud, R., McPhee, J., and Ayala, A (2018). The CAMELS-CL dataset: catchment attributes and meteorology for large sample studies-Chile dataset. Hydrology and Earth System Sciences, 22(11), 5817-5846. doi:10.5194/hess-22-5817-2018.} 39 | } 40 | \keyword{datasets} 41 | -------------------------------------------------------------------------------- /man/read_best.Rd: -------------------------------------------------------------------------------- 1 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 2 | %% http://cran.r-project.org/web/packages/hydroPSO 3 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 4 | %% Distributed under GPL 2 or later 5 | 6 | \name{read_best} 7 | \Rdversion{1.1} 8 | \alias{read_best} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | Reading the 'BestParameterSet.txt' output file 12 | } 13 | \description{ 14 | This function reads the contents of the the \sQuote{BestParameterSet.txt} output file, which stores the best parameter set and its corresponding goodness-of-fit value found during the optimisation 15 | } 16 | \usage{ 17 | read_best(file="BestParameterSet.txt", verbose=TRUE) 18 | } 19 | %- maybe also 'usage' for other objects documented here. 20 | \arguments{ 21 | \item{file}{ 22 | character, name (including path) of the output file with the best parameter set and its corresponding best fitness value found during the optimisation 23 | } 24 | \item{verbose}{ 25 | logical, if TRUE, progress messages are printed 26 | } 27 | } 28 | %%\details{ 29 | %% ~~ If necessary, more details than the description above ~~ 30 | %%} 31 | \value{ 32 | a list with the following three elements: 33 | 34 | \item{best.part.number}{numeric of length 1, with the number of PSO particle that achieved the best optimisation value.} 35 | \item{best.param.values}{numeric with the parameter values of PSO particle that achieved the best optimisation value.} 36 | \item{bbest.param.gof}{numeric of length one with the GoF of the PSO particle that achieved the best optimisation value.} 37 | } 38 | %%\references{ 39 | %% 40 | %%} 41 | \author{ 42 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 43 | } 44 | %%\note{ 45 | %% ~~further notes~~ 46 | %%} 47 | 48 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 49 | 50 | \seealso{ 51 | \code{\link{read_results}}, \code{\link{plot_results}} 52 | } 53 | \examples{ 54 | \dontrun{ 55 | # Setting the user home directory as working directory 56 | setwd("~") 57 | 58 | # Number of dimensions to be optimised 59 | D <- 4 60 | 61 | # Boundaries of the search space (Sphere test function) 62 | lower <- rep(-100, D) 63 | upper <- rep(100, D) 64 | 65 | # Setting the seed 66 | set.seed(100) 67 | 68 | # Runing PSO with the 'Sphere' test function, writting the results to text files 69 | hydroPSO(fn=sphere, lower=lower, upper=upper, 70 | control=list(maxit=100, write2disk=TRUE, plot=TRUE) ) 71 | 72 | # Reading the best parameter set and its corresponsing gof found by hydroPSO 73 | setwd("PSO.out") 74 | read_best() 75 | } 76 | } 77 | % Add one or more standard keywords, see file 'KEYWORDS' in the 78 | % R documentation directory. 79 | %\keyword{graph} 80 | \keyword{manip}% __ONLY ONE__ keyword per line 81 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | ## -*- R -*- 2 | citHeader("To cite 'hydroPSO' in publications use:") 3 | 4 | year <- sub(".*(2[[:digit:]]{3})-.*", "\\1", meta$Date, perl = TRUE) 5 | vers <- paste("R package version", meta$Version) 6 | 7 | bibentry( 8 | bibtype="Article", 9 | title= "A model-independent Particle Swarm Optimisation software for model calibration", 10 | journal="Environmental Modelling & Software", 11 | author="Zambrano-Bigiarini, M. and Rojas, R.", 12 | volume= "43", 13 | number="", 14 | pages="5-25", 15 | year="2013", 16 | note="", 17 | doi="10.1016/j.envsoft.2013.01.004", 18 | url="http://dx.doi.org/10.1016/j.envsoft.2013.01.004", 19 | textVersion="Zambrano-Bigiarini, M.; R. Rojas (2013), A model-independent Particle Swarm Optimisation software for model calibration, Environmental Modelling & Software, 43, 5-25, doi:10.1016/j.envsoft.2013.01.004", 20 | key = "Zambrano-BigiariniRojas2013-hydroPSO_article" 21 | ) 22 | 23 | #citEntry( 24 | # entry="Article", 25 | # title= "Standard Particle Swarm Optimisation 2011 at CEC-2013: A baseline for future PSO improvements", 26 | # journal="Proceedings of 2013 IEEE Congress on Evolutionary Computation (CEC'2013)", 27 | # author="Zambrano-Bigiarini, M. and M. Clerc and R. Rojas", 28 | # volume= "", 29 | # number="", 30 | # pages="", 31 | # year="2013", 32 | # note="(accepted)", 33 | # textVersion="Zambrano-Bigiarini, M., M. Clerc, R. Rojas (2013), Standard Particle Swarm Optimisation 2011 at CEC-2013: A baseline for future PSO improvements, In Proceedings of 2013 IEEE Congress on Evolutionary Computation (CEC'2013) (accepted)", 34 | # key = "Zambrano-Bigiarini+al2013-hydroPSO_article2" 35 | # ) 36 | 37 | bibentry(bibtype= "Manual", 38 | title = "hydroPSO: Particle Swarm Optimisation, with Focus on Environmental Models", 39 | author = c( 40 | person("Mauricio", "Zambrano-Bigiarini", email="mzb.devel@gmail.com", role=c("aut","cre")), 41 | person("Rodrigo", "Rojas", email="Rodrigo.RojasMujica@gmail.com", role=c("ctb")) 42 | ), 43 | year = year, 44 | note = paste(vers, ". doi:10.5281/zenodo.1287350"), 45 | url = "https://CRAN.R-project.org/package=hydroPSO", 46 | textVersion = paste( 47 | "Zambrano-Bigiarini, M. and Rojas, R.(", year, "). ", 48 | "hydroPSO: Particle Swarm Optimisation, with Focus on Environmental Models. ", 49 | vers, 50 | ". URL:https://cran.r-project.org/package=hydroPSO", 51 | ". doi:10.5281/zenodo.1287350", 52 | ".", sep=""), 53 | key = "Zambrano-BigiariniRojas-hydroPSO_pkg" 54 | ) 55 | 56 | #citFooter("We have invested a lot of time and effort in creating hydroPSO, please cite it if you use it !") 57 | 58 | -------------------------------------------------------------------------------- /R/read.ParameterRanges.R: -------------------------------------------------------------------------------- 1 | # Part of the hydroPSO package, http://www.rforge.net/hydroPSO/ 2 | # Copyright 2010-2012 Mauricio Zambrano-Bigiarini 3 | # Distributed under GPL 2 or later 4 | 5 | ################################################################################ 6 | # read.ParameterRanges # 7 | ################################################################################ 8 | # Purpose: To read a file containing the minimum and maximum values within # 9 | # one or more parameter can be varied within an optimisation # 10 | # algorithm # 11 | ################################################################################ 12 | # Output : A data.frame with the following columns # 13 | # 1) ParameterNmbr: numeric, from 1 to the number of prameters # 14 | # 2) ParameterName: character, with a meaningful name of each parameter 15 | # 3) MinValue : numeric, with the minum value that each parameter can take 16 | # 4) MaxValue : numeric, with the maximum value that each parameter can take 17 | ################################################################################ 18 | # Author : Mauricio Zambrano-Bigiarini # 19 | # Started : 13-Dec-2010 at JRC Ispra # 20 | # Last Update: 13-Dec-2010 ; 11-Jan-2012 # 21 | # 14-Nov-2024 ; 30-Nov-2024 # 22 | ################################################################################ 23 | read.ParameterRanges <- function(ParamRanges.fname="ParamRanges.txt", # It has to have a row with the header 24 | flag.full=FALSE, 25 | verbose=TRUE) { 26 | 27 | # Reading the file with the Range of the paramters 28 | ParamRanges <- read.paramfile(file=ParamRanges.fname) 29 | 30 | n1 <- length(levels(as.factor(ParamRanges[,1]))) # Number of Param IDs 31 | n2 <- length(levels(as.factor(ParamRanges[,2]))) # Number of Param Names 32 | if ( n1 != n2) 33 | stop( paste("In '", basename(ParamRanges.fname), "' : Number of 'ParameterNmbr' != Number of 'ParameterName' (", n1, " != ", n2, ")", sep="" ) ) 34 | 35 | # Number of parameters that have to be optimised 36 | nparam <- nrow(ParamRanges) 37 | 38 | if (verbose) message( paste("[ Number of parameters:", nparam, " ]", sep=" ") ) 39 | if (verbose) message( paste("[ Parameters' names : ", paste(ParamRanges[,2], collapse = ", "), " ]", sep="" ) ) 40 | 41 | # Giving a meaningful name to each parameter in 'X.MinMax' 42 | rownames(ParamRanges) <- ParamRanges[,2] 43 | 44 | # If 'flag.full' is FALSE (original hydroPSO version) it returns only the 3rd and 4th column, with the minim and maximum possible values, respectively 45 | if (flag.full) { 46 | out <- ParamRanges 47 | } else out <- ParamRanges[,3:4] 48 | 49 | return(out) 50 | 51 | } # 'read.ParameterRanges' END 52 | 53 | #read.ParameterRanges("./PSO/ParamRanges.txt") 54 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | importFrom("grDevices", colorRampPalette, dev.new, dev.off, png, rainbow) 2 | importFrom("graphics", Axis, abline, axis, boxplot, grid, hist, legend, lines, mtext, par, plot) 3 | importFrom("methods", "is") 4 | importFrom("stats", approxfun, cor, fivenum, lm, median, quantile, rnorm, runif, time, window) 5 | importFrom("utils", read.table, write.table, installed.packages, ls.str, modifyList, sessionInfo, setTxtProgressBar, txtProgressBar) 6 | 7 | importFrom("Hmisc", wtd.quantile, wtd.Ecdf) 8 | importFrom("sp", coordinates, spplot) 9 | importFrom("lattice", xyplot, axis.default) 10 | importFrom("zoo", is.zoo, zoo, coredata, read.zoo, write.zoo, as.zoo, 'time<-') 11 | importFrom("lhs", randomLHS) 12 | importFrom("parallel", detectCores, makeForkCluster, makeCluster, clusterCall, clusterExport, mclapply, parRapply, clusterApply, stopCluster) 13 | import(grid) 14 | importFrom("hydroTSM", hydroplot, hydropairs, dip, mip, yip, vector2zoo) 15 | importFrom("vioplot", vioplot) 16 | importFrom("hydroGOF", ggof) 17 | importFrom("scatterplot3d", scatterplot3d) 18 | importFrom("data.table", fread) 19 | importFrom("pbapply", pblapply, pboptions) 20 | #exportPattern("^[^\\.]") 21 | export(hydroPSO, 22 | lhoat, 23 | params2ecdf, 24 | params2ecdf.default, 25 | params2ecdf.matrix, 26 | params2ecdf.data.frame, 27 | quant2ecdf, 28 | quant2ecdf.default, 29 | quant2ecdf.matrix, 30 | quant2ecdf.data.frame, 31 | plot_ParamsPerIter, 32 | plot_ParamsPerIter.matrix, 33 | plot_ParamsPerIter.data.frame, 34 | hydromod, 35 | plot_2parOF, 36 | plot_NparOF, 37 | plot_out, 38 | plot_params, 39 | plot_params.default, 40 | plot_params.matrix, 41 | plot_params.data.frame, 42 | plot_particles, 43 | plot_GofPerParticle, 44 | plot_convergence, 45 | plot_results, 46 | read_params, 47 | read_params.default, 48 | read_best, 49 | read_particles, 50 | read_GofPerParticle, 51 | read_velocities, 52 | read_out, 53 | read_convergence, 54 | read_results, 55 | verification, 56 | wquantile, 57 | ackley, 58 | griewank, 59 | rastrigrin, # wrong name, only used for backward compatibility 60 | rastrigin, 61 | rosenbrock, 62 | schafferF6, 63 | schwefel, 64 | sphere, 65 | sackley, 66 | sgriewank, 67 | srastrigin, 68 | srosenbrock, 69 | sschwefel1_2, 70 | ssphere, 71 | hydroPSO2pest, 72 | pest2hydroPSO, 73 | read.ParameterRanges, 74 | rLHS, 75 | hydromodInR.eval, 76 | hydromodInR 77 | ) 78 | 79 | S3method(read_params, default) 80 | 81 | S3method(params2ecdf, default) 82 | S3method(params2ecdf, matrix) 83 | S3method(params2ecdf, data.frame) 84 | 85 | S3method(plot_params, default) 86 | S3method(plot_params, matrix) 87 | S3method(plot_params, data.frame) 88 | 89 | S3method(quant2ecdf, default) 90 | S3method(quant2ecdf, matrix) 91 | S3method(quant2ecdf, data.frame) 92 | 93 | S3method(plot_ParamsPerIter, default) 94 | S3method(plot_ParamsPerIter, matrix) 95 | S3method(plot_ParamsPerIter, data.frame) 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /man/hydromodInR.Rd: -------------------------------------------------------------------------------- 1 | %% File hydromodInR.Rd 2 | %% Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | %% https://cran.r-project.org/package=hydroPSO 4 | %% http://www.rforge.net/hydroPSO/ 5 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | %% Distributed under GPL 2 or later 7 | 8 | \name{hydromodInR} 9 | \alias{hydromodInR} 10 | %- Also NEED an '\alias' for EACH other topic documented here. 11 | \title{ 12 | hydromodInR 13 | } 14 | \description{ 15 | This function runs an R-based model using a single parameter set taken from a matrix/data.frame with many parameter sets. 16 | 17 | This function is for internal use within the package, and it is only documented in case it be useful to other packages. See Details section for more information. 18 | } 19 | \usage{ 20 | hydromodInR(part, Particles, model.FUN, model.FUN.args ) 21 | } 22 | %- maybe also 'usage' for other objects documented here. 23 | \arguments{ 24 | \item{part}{ 25 | numeric, a single integer value indicating the row number in \code{Particles} which is used to select the parameter set used to run the model specified in \code{model.FUN}. 26 | } 27 | \item{Particles}{ 28 | matrix/data.frame with all the parameter sets that can be used to run the model defined in \code{model.FUN}. 29 | 30 | It has as many columns as parameters used by the model, and as many rows as parameter sets provided by the user in \code{Particles}. 31 | } 32 | \item{model.FUN}{ 33 | character, valid R function representing the model code to be calibrated/optimised. 34 | } 35 | \item{model.FUN.args}{ 36 | list with the arguments to be passed to \code{model.FUN}. 37 | } 38 | 39 | %% \item{\dots}{ 40 | %% ~~Describe \code{\dots} here~~ 41 | %%} 42 | } 43 | \details{ 44 | This function takes an R-based user-defined model, a matrix/data.frame with many parameter sets (e.g., randomly generated or the output of a previous optimisation/calibration), and index indicating which specific parameter set must be used from the matrix/data.frame, and then runs the model and returns a goodness-of-fit value as measure of model performance, by comparing observations against simulated equivalents. 45 | 46 | This function it was designed to run a model implemented as an R function, not an executable file that runs in the system console. 47 | } 48 | \value{ 49 | This function MUST return a list with two elements: 50 | \item{sim}{numeric, with the simulated values obtained by running the model} 51 | \item{GoF}{numeric, goodness-of-fit value representing how close each one of the simulated values in \code{sim} are to their observed counterparts, by using the USER-DEFINED \code{gof.FUN} function} 52 | } 53 | %%\references{ 54 | %% ~put references to the literature/web site here ~ 55 | %%} 56 | \author{ 57 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 58 | } 59 | %%\note{ 60 | %% ~~further notes~~ 61 | %%} 62 | 63 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 64 | 65 | \seealso{ 66 | \code{\link{hydroPSO}}, \code{\link{hydromod}} 67 | } 68 | %%\examples{ 69 | %%} 70 | % Add one or more standard keywords, see file 'KEYWORDS' in the 71 | % R documentation directory. 72 | \keyword{files} 73 | \keyword{optimisation}% __ONLY ONE__ keyword per line 74 | -------------------------------------------------------------------------------- /man/wquantile.Rd: -------------------------------------------------------------------------------- 1 | %% File wquantile.R 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{wquantile} 8 | \Rdversion{1.1} 9 | \alias{wquantile} 10 | %- Also NEED an '\alias' for EACH other topic documented here. 11 | \title{ 12 | Weighted Quantiles 13 | } 14 | \description{ 15 | This function computes weighted quantiles of each column (by default, or for each row if specified by the user) of a matrix/data.frame. 16 | 17 | It is a wrapper to the \code{\link[Hmisc]{wtd.quantile}} function of the \bold{Hmisc} package, specially designed for a matrix containing daily/monthly/seasonal/annual streamflows simulated by different (behavioural) parameter sets. 18 | } 19 | \usage{ 20 | wquantile(x, weights=NULL, byrow=FALSE, probs=c(.025, .5, .975), 21 | normwt=TRUE, verbose=TRUE) 22 | } 23 | %- maybe also 'usage' for other objects documented here. 24 | \arguments{ 25 | \item{x}{ 26 | numeric or matrix for the computation of the weighted quantiles 27 | } 28 | \item{weights}{ 29 | numeric vector, values of the weights to be used for computing the quantiles. See \code{\link[Hmisc]{wtd.quantile}}. \cr 30 | Omitting the \code{weights} argument or specifying \code{NULL} or a zero-length vector will result in the usual unweighted estimates 31 | } 32 | \item{byrow}{ 33 | logical, indicates if the computations have to be made for each column or for each row of \code{x} \cr 34 | When the simulated values obtained with different behavioural parameter sets are stored in columns, \code{byrow} must be \kbd{TRUE} \cr 35 | When the simulated values obtained with different behavioural parameter sets are stored in rows, \code{byrow} must be \kbd{FALSE} 36 | } 37 | \item{probs}{ 38 | numeric vector, quantiles to be computed. \code{\link[Hmisc]{wtd.quantile}} \cr 39 | Default value is \kbd{c(.025, .5, .975)} ( => 2.5\%, 50\%, 97.5\% ) 40 | } 41 | \item{normwt}{ 42 | See \code{\link[Hmisc]{wtd.quantile}}. Specify \code{normwt=TRUE} to make \code{weights} sum to \code{length(x)} after deletion of NAs 43 | } 44 | \item{verbose}{ 45 | logical; if TRUE, progress messages are printed 46 | } 47 | } 48 | %%\details{ 49 | %% ~~ If necessary, more details than the description above ~~ 50 | %%} 51 | \value{ 52 | A data.frame with the weighted quantiles of each column (by default, or for each row if specified by the user using the \code{byrow} argument) of a matrix/data.frame given as input in \code{x}. 53 | %% If it is a LIST, use 54 | %% \item{comp1 }{Description of 'comp1'} 55 | %% \item{comp2 }{Description of 'comp2'} 56 | %% ... 57 | } 58 | %\references{ 59 | 60 | %} 61 | \author{ 62 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 63 | } 64 | %\note{ 65 | %% ~~further notes~~ 66 | %} 67 | 68 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 69 | 70 | \seealso{ 71 | \code{\link[Hmisc]{wtd.quantile}} 72 | } 73 | \examples{ 74 | # random matrix with 100 parameter sets (in rows) corresponding to 10 75 | # different parameters 76 | params <- matrix(rnorm(1000), ncol=10, nrow=100) 77 | colnames(params) <- paste("Param", 1:10, sep="") 78 | 79 | # empirical CDFs for each one of the 10 parameters of x, with equal weight for 80 | # each one of the 100 parameter sets 81 | wquantile(params, weights=rep(1,100), byrow=FALSE) 82 | } 83 | % Add one or more standard keywords, see file 'KEYWORDS' in the 84 | % R documentation directory. 85 | \keyword{math} 86 | %%\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line 87 | -------------------------------------------------------------------------------- /man/hydroPSO2pest.Rd: -------------------------------------------------------------------------------- 1 | %% File hydroPSO2pest.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2012-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{hydroPSO2pest} 8 | \alias{hydroPSO2pest} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | Export hydroPSO input files to PEST 12 | } 13 | \description{ 14 | This function exports the content of the hydroPSO input files \sQuote{ParamRanges.txt} and \sQuote{ParamFiles.txt} to PEST, into a single \sQuote{.pst} files with corresponding \sQuote{.tpl} and \sQuote{.ins} files 15 | } 16 | \usage{ 17 | hydroPSO2pest(param.files="ParamFiles.txt", param.ranges="ParamRanges.txt", 18 | observations.fname="Observations.txt", exe.fname, 19 | drty.model=getwd(), pst.fname="hydroPSO2PEST.pst", verbose=TRUE) 20 | } 21 | %- maybe also 'usage' for other objects documented here. 22 | \arguments{ 23 | \item{param.files}{ 24 | character, name (full path) of the hydroPSO input file storing the location and names of the model files that have to be modified for each parameter subject to calibration. \cr 25 | By default this file is called \sQuote{ParamFiles.txt} and -if the full path it is not specified- it is searched for within the \sQuote{PSO.in} subdirectory of \code{drty.model} 26 | } 27 | \item{param.ranges}{ 28 | character, name (full path) of the hydroPSO input file defining the minimum and maximum boundary values for each one of the parameters to be calibrated \cr 29 | By default this file is called \sQuote{ParamRanges.txt} and -if the full path it is not specified- it is searched for within the \sQuote{PSO.in} subdirectory of \code{drty.model} 30 | } 31 | \item{observations.fname}{ 32 | character name (full path) of the hydroPSO output file storing the observed values used during the optimisation. \cr 33 | By default this file is called \sQuote{Observations.txt} and -if the full path it is not specified- it is searched for within the \sQuote{PSO.out} subdirectory of \code{drty.model} 34 | } 35 | \item{exe.fname}{ 36 | character, model command line arguments to be entered through a prompted string to execute the user-defined model 37 | } 38 | \item{drty.model}{ 39 | character, path to the executable file of the model specified in \code{exe.fname}. ALL the files required to run the model have to be located within this directory (however, input files may be located elsewhere) 40 | } 41 | \item{pst.fname}{ 42 | character, with the name of the output \sQuote{.pst} file 43 | } 44 | \item{verbose}{ 45 | logical, indicates if progress messages are to be printed. By default \code{verbose=TRUE} 46 | } 47 | } 48 | %%\details{ 49 | %% ~~ If necessary, more details than the description above ~~ 50 | %%} 51 | \value{ 52 | A single text textfilet mo be used as input file by PEST. The name of the output text file is \code{pst.fname} and it is located within the\code{drty.model} directory. 53 | } 54 | %%\references{ 55 | %% ~put references to the literature/web site here ~ 56 | %%} 57 | \author{ 58 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 59 | } 60 | %%\note{ 61 | %% ~~further notes~~ 62 | %%} 63 | 64 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 65 | 66 | \seealso{ 67 | \code{\link{pest2hydroPSO}}, \code{\link{hydroPSO}} 68 | } 69 | %%\examples{ 70 | %%} 71 | % Add one or more standard keywords, see file 'KEYWORDS' in the 72 | % R documentation directory. 73 | \keyword{files} 74 | \keyword{optimisation}% __ONLY ONE__ keyword per line 75 | -------------------------------------------------------------------------------- /R/plot_convergence.R: -------------------------------------------------------------------------------- 1 | # File plot_convergence.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2008-2011 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'plot_convergence' # 9 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 10 | # Started: 08-Nov-2011, # 11 | # Updates: 13-Ene-2012 ; 14-Nov-2012 ; 20-Nov-2012 # 12 | ################################################################################ 13 | 14 | 15 | plot_convergence <- function(x, 16 | verbose=TRUE, 17 | col=c("black", "darkolivegreen"), 18 | lty=c(1,3), 19 | lwd=c(2,2), 20 | main="Global Optimum & Normalized Swarm Radius vs Iteration Number", 21 | xlab="Iteration Number", 22 | ylab=c("Global Optimum", expression(delta[norm]) ), 23 | pch=c(15, 18), 24 | cex=1, 25 | cex.main=1.4, cex.axis=1.2, cex.lab=1.2, 26 | legend.pos="topright", 27 | ..., 28 | #### PNG options ### 29 | do.png=FALSE, 30 | png.width=1500, 31 | png.height=900, 32 | png.res=90, 33 | png.fname="ConvergenceMeasures.png" 34 | 35 | ) { 36 | 37 | 38 | # Checking that 'x' exists 39 | if ( missing(x) ) stop( "Missing argument: 'x'" ) 40 | 41 | if (ncol(x)!=6) stop( paste("Invalid argument: 'ncol(x) != 6 (", ncol(x), "!=6)", sep="") ) 42 | 43 | ############################ Getting the values ############################## 44 | # Iteration number 45 | iter <- x[,1] 46 | # Global best 47 | gbest <- x[,2] 48 | # Normalized swarm radius 49 | nradius <- x[,5] 50 | 51 | ############################ Plotting ############################## 52 | msg <- "[ Plotting convergence measures" 53 | if (do.png) msg <- paste(msg, " into '", basename(png.fname), sep="") 54 | msg <- paste(msg, "' ... ]", sep="") 55 | if (verbose) message(msg) 56 | 57 | if (do.png) png(filename=png.fname, width=png.width, height=png.height, res=png.res) 58 | 59 | # Saving default plotting parameters 60 | old.par <- par(no.readonly=TRUE) 61 | if (!do.png) on.exit(par(old.par)) 62 | 63 | oma <- c(2, 1, 2, 1) 64 | mar <- c(5, 4.5, 4, 4.5)+.1 65 | par(oma=oma, mar=mar) 66 | 67 | # Plotting the Gbest 68 | plot(iter, gbest, col=col[1], lty=lty[1], lwd=lwd[1], pch=pch[1], ylab=ylab[1], 69 | xlab=xlab, cex=cex, cex.lab=cex.lab, cex.axis=cex.axis, cex.main=cex.main, 70 | main=main, type="o", ylim=range(pretty(gbest)), panel.first=grid(), ...) 71 | ynticks <- par("yaxp")[3] + 1 72 | 73 | # Plotting the Normalized swarm radius as secondary Y-axis. 74 | # Based on code from: http://rgraphics.limnology.wisc.edu/line.php 75 | par(new=TRUE, oma=oma) 76 | ylim <- range(nradius, na.rm=TRUE) 77 | plot(iter, nradius, ,xaxt="n", yaxt="n", ylim=ylim, 78 | xlab="", ylab="", col=col[2], lty=lty[2], lwd=lwd[2], pch=pch[2], 79 | cex=cex, type="o", ...) 80 | 81 | yat <- seq(ylim[1], ylim[2], length=ynticks) 82 | axis(4, col=col[2], col.axis=col[2], at= yat, labels=format(yat, scientific=TRUE, digits=4)) 83 | mtext(ylab[2], side=4, line=3, cex=1.4*cex.lab, col=col[2]) 84 | 85 | # Showing a legend 86 | legend(legend.pos, legend=ylab, lty=lty, col=col, pch=pch, lwd=lwd, bty="n", cex=1.4*cex.lab) 87 | 88 | if (do.png) dev.off() 89 | 90 | } # 'plot_convergence' END 91 | -------------------------------------------------------------------------------- /man/pest2hydroPSO.Rd: -------------------------------------------------------------------------------- 1 | %% File pest2hydroPSO.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2012-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{pest2hydroPSO} 8 | \alias{pest2hydroPSO} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | Import PEST input files to hydroPSO 12 | } 13 | \description{ 14 | This function imports the PEST input files (a master \sQuote{.pst} and its corresponding \sQuote{.tpl} and \sQuote{.ins}) into \code{\link{hydroPSO}} (\sQuote{ParamRanges.txt} and \sQuote{ParamFiles.txt}) 15 | } 16 | \usage{ 17 | pest2hydroPSO(pst.fname, drty.pest=NULL, drty.model=NULL, drty.out="PSO.in", 18 | param.files="ParamFiles.txt", param.ranges="ParamRanges.txt", 19 | decimals=5, verbose=TRUE) 20 | } 21 | %- maybe also 'usage' for other objects documented here. 22 | \arguments{ 23 | \item{pst.fname}{ 24 | character, with name of the PEST input file (\sQuote{.pst}), which contains all the information regarding parameters, observations and template files (\sQuote{.tpl} and \sQuote{.ins}) used by PEST 25 | } 26 | \item{drty.pest}{ 27 | character, path to the executable file of PEST. ALL the files required to run PEST with the model have to be located within this directory (\sQuote{.tpl} and \sQuote{.ins}) \cr 28 | Default value is \code{NULL}, which assigns to \code{drty.pest} the parent directory of \code{pst.fname} 29 | } 30 | \item{drty.model}{ 31 | character, path to the executable file of the model specified in \code{exe.fname}. ALL the files required to run the model have to be located within this directory \cr 32 | Default value is \code{NULL}, which assigns to \code{drty.pest} the parent directory of \code{pst.fname} 33 | } 34 | \item{drty.out}{ 35 | character, name of the directory that will store all the output files produced by this function \cr 36 | Default value is \sQuote{PSO.in}, which creteas a directory called \sQuote{PSO.in} within the parent directory of \code{pst.fname} 37 | } 38 | \item{param.files}{ 39 | character, name of the output file that will store the location and names of the model files that have to be modified for each parameter subject to calibration with hydroPSO. \cr 40 | By default this file is called \sQuote{ParamFiles.txt} and -if the full path it is not specified- it is searched for within the \sQuote{PSO.in} subdirectory of \code{drty.model} 41 | } 42 | \item{param.ranges}{ 43 | character, name of the output file defining the minimum and maximum boundary values for each one of the parameters to be calibrated with hydroPSO. \cr 44 | By default this file is called \sQuote{ParamRanges.txt} and -if the full path it is not specified- it is searched for within the \sQuote{PSO.in} subdirectory of \code{drty.model} 45 | } 46 | \item{decimals}{ 47 | character, model command line arguments to be entered through a prompted string to execute the user-defined model 48 | } 49 | \item{verbose}{ 50 | logical, indicates if progress messages are to be printed. By default \code{verbose=TRUE} 51 | } 52 | 53 | 54 | %% \item{\dots}{ 55 | %% ~~Describe \code{\dots} here~~ 56 | %%} 57 | } 58 | %%\details{ 59 | %% ~~ If necessary, more details than the description above ~~ 60 | %%} 61 | \value{ 62 | Two input files for \code{\link{hydroPSO}}: 63 | \item{param.files}{plain text file with the location and names of the model files that have to be modified for each parameter subject to calibration with hydroPSO} 64 | \item{param.ranges}{plain text file defining the minimum and maximum boundary values for each one of the parameters to be calibrated with hydroPSO} 65 | 66 | } 67 | %%\references{ 68 | %% ~put references to the literature/web site here ~ 69 | %%} 70 | \author{ 71 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 72 | } 73 | %%\note{ 74 | %% ~~further notes~~ 75 | %%} 76 | 77 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 78 | 79 | \seealso{ 80 | \code{\link{hydroPSO2pest}}, \code{\link{hydroPSO}} 81 | } 82 | %%\examples{ 83 | %%} 84 | % Add one or more standard keywords, see file 'KEYWORDS' in the 85 | % R documentation directory. 86 | \keyword{files} 87 | \keyword{optimisation}% __ONLY ONE__ keyword per line 88 | -------------------------------------------------------------------------------- /R/ParameterValues2InputFiles.R: -------------------------------------------------------------------------------- 1 | # Part of the hydroPSO package, http://www.rforge.net/hydroPSO/ 2 | # Copyright 2010-2024 Mauricio Zambrano-Bigiarini 3 | # Distributed under GPL 2 or later 4 | 5 | ################################################################################ 6 | # ParameterValues2InputFiles # 7 | ################################################################################ 8 | # Purpose : To write several values into several plain text files, by using # 9 | # the filenames, row and column positions defined in the # 10 | # 'ParamFiles.fname' file # 11 | ################################################################################ 12 | # Output : A mofified text file ('filename') # 13 | ################################################################################ 14 | # Author : Mauricio Zambrano-Bigiarini # 15 | # Started : 15-Dec-2010 at JRC Ispra # 16 | # Updates : 12-May-2011 # 17 | # 27-Jan-2021 # 18 | # 14-Nov-2024 ; 30-Nov-2024 # 19 | ################################################################################ 20 | ParameterValues2InputFiles <- function(NewValues, 21 | ParamFiles.fname="ParamFiles.txt", 22 | ParamRanges.fname="ParamRanges.txt", 23 | verbose=TRUE 24 | ) { 25 | 26 | # Checking 'NewValues' 27 | if ( is.na( match(class(NewValues), c("numeric", "integer") ) ) ) 28 | stop("Invalid argument: class(NewValues) has to be in c('numeric', 'integer')") 29 | 30 | # Number of values provided by the user 31 | nval <- length(NewValues) 32 | 33 | # Reading the file with the location of the paramters 34 | ParamFiles <- read.paramfile(file=ParamFiles.fname) 35 | ParamRangesFull <- read.ParameterRanges(ParamRanges.fname=ParamRanges.fname, 36 | flag.full=TRUE, verbose=verbose) 37 | 38 | n1 <- length(levels(as.factor(ParamFiles[,1]))) # Number of Param IDs 39 | n2 <- length(levels(as.factor(ParamFiles[,2]))) # Number of Param Names 40 | if ( n1 != n2) 41 | stop( paste("In '", ParamFiles.fname, "' : Number of 'ParameterNmbr' != Number of 'ParameterName' (", n1, " != ", n2, ")", sep="" ) ) 42 | if ( n1 != nval) 43 | stop( paste("Number of Parameters != Number of Values' (", n1, " != ", nval, ")", sep="" ) ) 44 | 45 | # Number of files that have to be changed 46 | nfiles <- nrow(ParamFiles) 47 | 48 | # Loop in all the files that have to be changed 49 | for (i in 1:nfiles) { 50 | 51 | ParamID <- ParamFiles[i,1] 52 | ParamName <- ParamFiles[i,2] 53 | filename <- ParamFiles[i,3] 54 | lrow <- ParamFiles[i,4] 55 | col.ini <- ParamFiles[i,5] 56 | col.fin <- ParamFiles[i,6] 57 | decimals <- ParamFiles[i,7] 58 | 59 | if(ncol(ParamFiles) >= 8){ 60 | refValue <- ParamFiles[i,8] # numeric, only used when change.type == "mult" | change.type == "addi", reference value for making de parameter modification 61 | change.type <- ParamRangesFull[ParamName,5] # character, specification of the type of parameter modification ("repl", "mult", "addi") 62 | minValue <- ParamRangesFull[ParamName,6] 63 | maxValue <- ParamRangesFull[ParamName,7] 64 | }else{ 65 | change.type <- "repl" 66 | refValue <- 0 67 | minValue <- 0 68 | maxValue <- 0 69 | } 70 | 71 | ModifyInputFile(ParamID=ParamName, newvalue=NewValues[ParamID], 72 | filename=filename, row=lrow, col.ini=col.ini, col.fin=col.fin, 73 | decimals=decimals, change.type=change.type, 74 | refValue=refValue, minValue=minValue, maxValue=maxValue, 75 | verbose=verbose) 76 | 77 | } # FOR end 78 | 79 | 80 | } # 'ParameterValues2InputFiles' end 81 | 82 | 83 | #ParameterValues2InputFiles( NewValues=c(100.111, 200.122, 300.133), ParamFiles.fname="./PSO/ParamFiles.txt" ) 84 | -------------------------------------------------------------------------------- /inst/Rscripts/hydroPSO-Rscript.R: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | ## File hydroPSO-Rscript.R # 3 | ## Part of the hydroPSO R package: # 4 | ## http://www.rforge.net/hydroPSO/ ; # 5 | ## http://cran.r-project.org/web/packages/hydroPSO # 6 | ## Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 7 | ## Distributed under GPL 2 or later # 8 | ## # 9 | ## R script created with he PEST2hydroPSO function # 10 | ## # 11 | ## Created by Mauricio Zambrano-Bigiarini and Rodrigo Rojas. 08-Nov-2012 # 12 | ## Last Update: 08-Nov-2012 # 13 | ## 04-Jun-2013 # 14 | ################################################################################ 15 | 16 | ###Loading required libraries 17 | library(hydroPSO) 18 | library(hydroGOF) 19 | # library(hydroTSM) # OPTIONAL package 20 | 21 | ################################################################################ 22 | ################## User-defined variables - START ########################### 23 | ################################################################################ 24 | 25 | ###Definition of working directory: input, output and model files paths 26 | model.drty <- "user.model.drty" 27 | setwd(model.drty) 28 | 29 | ###Period of analysis. 30 | ###Only required for out.FUN 31 | ###To define subperiod of analysis to compute the goodness-of-fit (GoF) measures 32 | Sim.Ini <- "YYYY-MM-DD" 33 | Sim.Fin <- "YYYY-MM-DD" 34 | gof.Ini <- "YYYY-MM-DD" 35 | gof.Fin <- "YYYY-MM-DD" 36 | 37 | 38 | ###Function for reading the simulated equivalents 39 | out.FUN="read_output" # name of user-defined function for reading model outputs 40 | out.FUN.args=list( ###START out.FUN.args 41 | file="filename.out" # name of the output file 42 | #,,, # additional arguments for 'out.FUN' 43 | ) ###END out.FUN.args 44 | 45 | 46 | ###Goodness-of-fit function, either pre-defined from hydroGOF (e.g., ssq) or 47 | ###customized 48 | gof.FUN <- "ssq" # sum of squared residuals. PEST default. 49 | # any other model performance measure could be used 50 | gof.FUN.args <- list() 51 | 52 | ################################################################################ 53 | ################### User-defined variables - END ############################ 54 | ################################################################################ 55 | 56 | ###Getting the OBSERVATIONS 57 | obs.fname <- "PEST2hydroPSO_OBS.txt" 58 | obs.fname <- paste(model.drty, "/PSO.in/", obs.fname, sep="") 59 | obs <- read.table(obs.fname) 60 | 61 | ###MAIN model function 62 | model.FUN.args=list( 63 | model.drty=model.drty, 64 | param.files=paste(model.drty,"/PSO.in/ParamFiles.txt",sep=""), 65 | exe.fname="ModelCommandLine", #TODO 66 | #stdout="", 67 | out.FUN=out.FUN, 68 | out.FUN.args=out.FUN.args, 69 | gof.FUN=gof.FUN, 70 | gof.FUN.args=gof.FUN.args, 71 | #gof.Ini=gof.Ini, # un-comment if 'gof.Ini' is defined 72 | #gof.Fin=gof.Fin, # un-comment if 'gof.Fin' is defined 73 | obs=obs 74 | ) ###END model.FUN.args 75 | 76 | ### MAIN PSO ALGORITHM 77 | ### For hydroPSO fine-tuning parameters, see Zambrano-Bigiarini and Rojas, 2012 78 | hydroPSO( 79 | fn="hydromod", 80 | model.FUN="hydromod", 81 | model.FUN.args=model.FUN.args, 82 | control=list( ###START control options 83 | param.ranges="ParamRanges.txt", 84 | MinMax="min", # minimisation of ssq 85 | #maxit=1000, # case dependent 86 | #npart=40, # case dependent 87 | #,,, # additional arguments for hydroPSO 88 | REPORT=5 # frequency of screen messages 89 | ) ###END control options 90 | ) ###END MAIN hydroPSO ALGORITHM 91 | 92 | # Plotting the results 93 | plot_results(MinMax="min", do.png=TRUE) 94 | -------------------------------------------------------------------------------- /R/read_GofPerParticle.R: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 'read_GofPerParticle' # 3 | ################################################################################ 4 | # Purpose: This function reads the output file 'Particles_GofPerIter.txt' and # 5 | # plots the value of each parameter and the objective function against# 6 | # the iteration number. # 7 | ################################################################################ 8 | # Author : Mauricio Zambrano Bigarini # 9 | # Started : 20-Dec-2010 at JRC, Ispra # 10 | # Modified: 11-Nov-2011 ; 21-Feb-2012 # 11 | ################################################################################ 12 | 13 | read_GofPerParticle <- function(file="Particles_GofPerIter.txt", 14 | na.strings="NA", 15 | plot=TRUE, 16 | ### Plotting arguments ### 17 | ptype="one", # Valid values are: in c("one", "many") 18 | nrows="auto", 19 | main=NULL, 20 | xlab="Number of Iterations", 21 | cex=0.4, 22 | cex.main=1.5, 23 | cex.axis=1.7, 24 | cex.lab=1.5, 25 | col, 26 | lty=3, 27 | ylim=NULL, 28 | verbose=TRUE, 29 | #### PNG options ### 30 | do.png=FALSE, 31 | png.width=1500, 32 | png.height=900, 33 | png.res=90, 34 | png.fname="Particles_GofPerIter.png" 35 | ) { 36 | 37 | # Checking that 'file' exists 38 | if ( !file.exists(file) ) 39 | stop( "Invalid argument value: The file '", basename(file), "' doesn't exist") 40 | 41 | # Reading ALL the PARAMETER SETS 42 | if (verbose) message( " ") 43 | if (verbose) message( "[ Reading the file '", basename(file), "' ... ]" ) 44 | Particles.GofPerIter <- read.table(file=file, header=TRUE, skip=0, na.strings=na.strings) 45 | 46 | # Removing the column with the iteration number 47 | Particles.GofPerIter <- Particles.GofPerIter[, 2:ncol(Particles.GofPerIter)] 48 | 49 | # Number of iterations that will be analysed 50 | niter <- nrow(Particles.GofPerIter) 51 | 52 | # Number of particles 53 | npart <- ncol(Particles.GofPerIter) 54 | 55 | # Printing the number of particles read 56 | if (verbose) message( "[ Number of particles : ", npart, " ]" ) 57 | 58 | # Printing the number of iterations read 59 | if (verbose) message( "[ Number of iterations: ", niter, " ]" ) 60 | 61 | # Setting the colours 62 | if (missing(col)) col <- rainbow(ncol(Particles.GofPerIter)) 63 | 64 | # Plotting 65 | if (plot) { 66 | plot_GofPerParticle(x=Particles.GofPerIter, 67 | ptype=ptype, 68 | nrows=nrows, 69 | main=main, 70 | xlab=xlab, 71 | cex=cex, 72 | cex.main=cex.main, 73 | cex.axis=cex.axis, 74 | cex.lab=cex.lab, 75 | col=col, 76 | lty=lty, 77 | ylim=ylim, 78 | verbose=verbose, 79 | do.png=do.png, 80 | png.width=png.width, 81 | png.height=png.height, 82 | png.res=png.res, 83 | png.fname=png.fname 84 | ) 85 | } # IF end 86 | 87 | return(Particles.GofPerIter) 88 | 89 | } # 'read_GofPerParticle' END 90 | 91 | #plotParticlesGof(ptype="many", nrows=3 ) 92 | -------------------------------------------------------------------------------- /man/plot_2parOF.Rd: -------------------------------------------------------------------------------- 1 | %% File plot_2parOF.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{plot_2parOF} 8 | \alias{plot_2parOF} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | plot_2parOF 12 | } 13 | \description{ 14 | This function plots the values of the objective function in a two dimensional box, where the boundaries of each parameter are used as axis limits 15 | } 16 | \usage{ 17 | plot_2parOF(params, gofs, p1.name, p2.name, type="sp", MinMax=c("min","max"), 18 | gof.name="GoF", main=paste(gof.name, "Surface"), GOFcuts, 19 | colorRamp= colorRampPalette(c("darkred", "red", "orange", "yellow", 20 | "green", "darkgreen", "cyan")), points.cex=0.7, alpha=0.65, 21 | axis.rot=c(0, 0), auto.key=TRUE, key.space= "right") 22 | } 23 | %- maybe also 'usage' for other objects documented here. 24 | \arguments{ 25 | \item{params}{ 26 | matrix or data.frame with the parameter values 27 | } 28 | \item{gofs}{ 29 | numeric with the values of goodness-of-fit values for each one of the parameters in \code{params} (in the same order!) 30 | } 31 | \item{p1.name}{ 32 | character, name of the 1st parameter to be plotted 33 | } 34 | \item{p2.name}{ 35 | character, name of the 2nd parameter to be plotted 36 | } 37 | \item{type}{ 38 | character, type of plot. Valid values are: \cr 39 | -) \kbd{sp}: spatial plot \cr 40 | -) \kbd{scatter3d}: 3d scatterogram 41 | } 42 | \item{MinMax}{ 43 | character, indicates whether the optimum value in \code{gofs} corresponds to the minimum or maximum of the objective function. Valid values are in: \code{c('min', 'max')}. \cr 44 | By default, \code{MinMax='min'} which plot particles with lower goodness-of-fit values on top of those with larger values, in each one of the output figures 45 | } 46 | \item{gof.name}{ 47 | character, name of the objective function to be plotted. It has to correspond to the name of one column of \code{params} 48 | } 49 | \item{main}{ 50 | character with the title for the plot 51 | } 52 | \item{GOFcuts}{ 53 | numeric, specifies at which values of the objective function given in \code{gofs} the colours of the plot have to change \cr 54 | If \code{GOFcuts} is missing, the interval for colours change are defined by the (unique values of the) five quantiles of \code{gofs}, computed by \code{\link[stats]{fivenum}} 55 | } 56 | \item{colorRamp}{ 57 | R function defining the colour ramp to be used for colouring the pseudo-3D dotty plots of Parameter Values, OR character representing those colours 58 | } 59 | \item{points.cex}{ 60 | size of the points to be plotted 61 | } 62 | \item{alpha}{ 63 | numeric between 0 and 1 representing the transparency level to apply to \code{colorRamp}, \sQuote{0} means fully transparent and \sQuote{1} means opaque 64 | } 65 | \item{axis.rot}{ 66 | numeric vector of length 2 representing the angle (in degrees) by which the axis labels are to be rotated, left/bottom and right/top, respectively. 67 | } 68 | \item{auto.key}{ 69 | logical, indicates whether the legend has to be drawn or not 70 | } 71 | \item{key.space}{ 72 | character, position of the legend with respect to the plot 73 | } 74 | } 75 | %%\details{ 76 | %% ~~ If necessary, more details than the description above ~~ 77 | %%} 78 | \value{ 79 | A lattice-based figure with the values of the objective function in a two dimensional box, where the boundaries of each parameter are used as axis. 80 | %% If it is a LIST, use 81 | %% \item{comp1 }{Description of 'comp1'} 82 | %% \item{comp2 }{Description of 'comp2'} 83 | %% ... 84 | } 85 | %%\references{ 86 | %% ~put references to the literature/web site here ~ 87 | %%} 88 | \author{ 89 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 90 | } 91 | %%\note{ 92 | %% ~~further notes~~ 93 | %%} 94 | 95 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 96 | 97 | \seealso{ 98 | \code{\link{read_results}}, \code{\link{plot_results}}, \code{\link{plot_GofPerParticle}}, \code{\link{plot_ParamsPerIter}} 99 | } 100 | %%\examples{ 101 | 102 | %%} 103 | % Add one or more standard keywords, see file 'KEYWORDS' in the 104 | % R documentation directory. 105 | \keyword{math} 106 | \keyword{graph}% __ONLY ONE__ keyword per line 107 | -------------------------------------------------------------------------------- /R/wquantile.R: -------------------------------------------------------------------------------- 1 | # File wquantile.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2010-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'wquantile' # 9 | ################################################################################ 10 | # Purpose: This function computes weighted quantiles of each column (by default# 11 | # or for each row if specified by the user) of a matrix/data.frame # 12 | # It is a wrapper to the 'wtd.quantiles' function of the 'Hmisc' # 13 | # package, specially thought for a matrix containing streamflows # 14 | # simulated by different (behavioural) parameter sets # 15 | ################################################################################ 16 | # Author : Mauricio Zambrano-Bigiarini # 17 | # Started: June 09th, 2010 # 18 | # Updates: 27-Sep-2013 # 19 | ################################################################################ 20 | # 21 | 22 | # Result\Value: It returns a matrix with an amount of rows equal to the 23 | # amount of columns in 'x', and as many columns (by default, or for each 24 | # row if specified by the user) as 'length(probs)' 25 | 26 | # Original idea taken from: http://rwiki.sciviews.org/doku.php?id=guides:tutorials:hydrological_data_analysis:glue 27 | 28 | # x : a numeric matrix, which columns (by default) contains the values to be 29 | # used for the computation of the weighted quantiles 30 | # weights : a numeric vector of weights. \cr 31 | # Omitting the 'weights' argument or specifying 'NULL' or a 32 | # zero-length vector will result in the usual unweighted estimates. 33 | # byrow : logical, indicating if the computations have to be made for each column or for each row of \code{x}. 34 | # When the values to be used for the computation of the quantiles are stored in rows, \code{byrow} must be \kbd{TRUE}. \cr 35 | # When the values to be used for the computation of the quantiles are stored in columns, \code{byrow} must be \kbd{FALSE}. 36 | # probs : a vector of quantiles to compute. 37 | # Default is c(.025, .5, .975) (2.5\%, 50\%, 97.5\%) 38 | # normwt : specify 'normwt=TRUE' to make 'weights' sum to 'length(x)' after deletion of NAs 39 | # verbose : logical; if TRUE, progress messages are printed 40 | 41 | wquantile <- function(x, weights=NULL, byrow=FALSE, probs=c(.025, .5, .975), 42 | normwt=TRUE, verbose=TRUE ) { 43 | 44 | # computation of the 95PPU of the Parameters 45 | #require(Hmisc) # 'wtd.quantile' 46 | 47 | if (byrow==TRUE) { 48 | 49 | nobs <- ncol(x) 50 | n <- nrow(x) 51 | 52 | } else { 53 | 54 | nobs <- nrow(x) 55 | n <- ncol(x) 56 | 57 | } # ELSE end 58 | 59 | # If the user provided the weights 60 | if ( !missing(weights) ) { 61 | if ( length(weights) != nobs ) { 62 | if (byrow==TRUE) { 63 | stop( paste("Invalid argument: 'length(weights) != ncol(x)' (", length(weights), "!=", nobs, ")", sep="" ) ) 64 | } else stop( paste("Invalid argument: 'length(weights) != nrow(x)' (", length(weights), "!=", nobs, ")", sep="" ) ) 65 | } # IF end 66 | } # IF end 67 | 68 | if (verbose) pbar <- txtProgressBar(min = 0, max = n, style = 3) 69 | 70 | tmp <- sapply(1:n, function(i, p) { 71 | 72 | #if (verbose) print( paste(i, "/", n, format(round(100*i/n, 2), width=6, justify="left"), 73 | # "%", sep=""), quote=FALSE ) 74 | if (verbose) setTxtProgressBar(pbar, i) 75 | 76 | if (byrow==TRUE) { 77 | 78 | as.numeric(Hmisc::wtd.quantile(p[i, ], weights = weights, probs = probs, normwt=normwt)) 79 | 80 | } else as.numeric(Hmisc::wtd.quantile(p[, i], weights = weights, probs = probs, normwt=normwt)) 81 | 82 | }, p = x) 83 | 84 | # clossing the progress bar 85 | if (verbose) close(pbar) 86 | 87 | p95 <- t(tmp) 88 | colnames(p95) <- paste(probs*100, "%", sep="") 89 | 90 | if (byrow==TRUE) { 91 | if ( !is.null(rownames(x)) ) rownames(p95) <- rownames(x) 92 | } else { 93 | if ( !is.null(colnames(x)) ) rownames(p95) <- colnames(x) 94 | } # ELSE end 95 | 96 | return(p95) 97 | 98 | } #'wquantile' END 99 | -------------------------------------------------------------------------------- /man/verification.Rd: -------------------------------------------------------------------------------- 1 | %% File verification.Rd 2 | %% Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% http://www.rforge.net/hydroPSO/ 5 | %% Copyright 2011-2020 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | %% Distributed under GPL 2 or later 7 | 8 | \name{verification} 9 | \alias{verification} 10 | %- Also NEED an '\alias' for EACH other topic documented here. 11 | \title{ 12 | verification 13 | } 14 | \description{ 15 | Run the model and get a goodness-of-fit value by comparing the simulated values against observations for the optimum parameter set found by optimisation 16 | } 17 | \usage{ 18 | verification(fn="hydromod", par, ..., control=list(), 19 | model.FUN=NULL, model.FUN.args=list() ) 20 | } 21 | %- maybe also 'usage' for other objects documented here. 22 | \arguments{ 23 | \item{fn}{ 24 | character, name of a valid R function to be optimised or character value \kbd{'hydromod'}. When \code{fn='hydromod'} the algorithm uses \code{model.FUN} and \code{model.FUN.args} to extract the values simulated by the model and to compute its corresponding goodness-of-fit function. When \code{fn!='hydromod'} the algorithm uses the value(s) returned by \code{fn} as both model output and its corresponding goodness-of-fit \cr 25 | When \code{fn='hydromod'} the algorithm will optimise the model defined by \code{model.FUN} and \code{model.args} 26 | } 27 | \item{\dots}{ 28 | OPTIONAL. Only used when \code{fn!='hydromod' & fn!='hydromodInR'}. \cr 29 | further arguments to be passed to \code{fn}. 30 | } 31 | \item{par}{ 32 | numeric, or matrix/data.frame with the parameter sets that will be used for verification \cr 33 | Parameter sets in \code{par} must be stored by row, i.e., each different row represents a different parameter set 34 | } 35 | \item{control}{ 36 | a list of control parameters. See \sQuote{Details} 37 | } 38 | \item{model.FUN}{ 39 | OPTIONAL. Only used when \code{fn='hydromod'} \cr 40 | character, valid R function representing the model code to be calibrated/optimised 41 | } 42 | \item{model.FUN.args}{ 43 | OPTIONAL. Only used when \code{fn='hydromod'} \cr 44 | list with the arguments to be passed to \code{model.FUN} 45 | } 46 | 47 | } 48 | \details{ 49 | The \code{control} argument is a list that can supply any of the following components: 50 | \describe{ 51 | 52 | \item{drty.in}{ 53 | character, path to the directory storing the input files required for PSO, i.e. \sQuote{ParamRanges.txt} and \sQuote{ParamFiles.txt} 54 | } 55 | \item{drty.out}{ 56 | character, path to the directory storing the output files generated by \kbd{hydroPSO} 57 | } 58 | \item{digits}{ 59 | OPTIONAL. Only used when \code{write2disk=TRUE} \cr 60 | numeric, number of significant digits used for writing the outputs in scientific notation 61 | } 62 | \item{gof.name}{ 63 | character, ONLY used for identifying the goodness-of-fit of each model run and writing it to the \kbd{LH_OAT-gof.txt} output file 64 | } 65 | \item{MinMax}{ 66 | character, indicates whether the optimum value for the analysed problem corresponds to the minimum or maximum of the the objective function. It is used to select the \sQuote{best} parameter set. 67 | Valid values are in: \code{c('min', 'max')} 68 | } 69 | \item{do.plots}{ 70 | logical, if TRUE a PNG plot with the comparison between observed and simulated values is produced for each parameter set used in the LH-OAT 71 | } 72 | \item{write2disk}{ 73 | logical, indicates if the output files will be written to the disk 74 | } 75 | \item{verbose}{ 76 | logical, if TRUE progress messages are printed 77 | } 78 | } 79 | } 80 | %%\details{ 81 | %% ~~ If necessary, more details than the description above ~~ 82 | %%} 83 | \value{ 84 | A list of two elements: \cr 85 | \item{gofs}{numeric with the goodness-of-fit values corresponding to each one of the parameter sets provided in \code{par}} 86 | \item{model.values}{data.frame with the model outputs corresponding to each one of the parameter sets provided in \code{par}} 87 | \item{best.param}{numeric with the parameter values of the "best" paraemter set found during the verification period} 88 | \item{best.gof}{numeric with the goodness-of-fit of the "best" parameter set found during the verification period} 89 | 90 | } 91 | %%\references{ 92 | %% ~put references to the literature/web site here ~ 93 | %%} 94 | \author{ 95 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 96 | } 97 | %%\note{ 98 | %% ~~further notes~~ 99 | %%} 100 | 101 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 102 | 103 | \seealso{ 104 | \code{\link{hydromod}} 105 | } 106 | %%\examples{ 107 | %% 108 | %%} 109 | % Add one or more standard keywords, see file 'KEYWORDS' in the 110 | % R documentation directory. 111 | \keyword{optimize} 112 | \keyword{files}% __ONLY ONE__ keyword per line 113 | -------------------------------------------------------------------------------- /man/hydroPSO-package.Rd: -------------------------------------------------------------------------------- 1 | %% File hydroPSO-package.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2021 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{hydroPSO-package} 8 | \alias{hydroPSO-package} 9 | %%\alias{hydroPSO} 10 | \docType{package} 11 | \title{ 12 | A flexible and model-independent Particle Swarm Optimisation (PSO) package for calibration/optimisation of environmental models 13 | } 14 | \description{ 15 | hydroPSO implements a state-of-the-art version of the Particle Swarm Optimisation (PSO) algorithm developed by Kennedy and Eberhart (1995) and Eberhart and Kennedy (1995). PSO is a population-based stochastic optimisation technique inspired by social behaviour of bird flocking, which shares some similarities with other evolutionary optimisation techniques such as Genetic Algorithms (GA). In PSO, however, the multi-dimensional solution space is explored on the basis of individual and global best-known ``particle positions'' with no presence of evolution operators. 16 | 17 | hydroPSO can be used as a replacement of the 'optim' R function for (global) optimization of non-smooth and non-linear functions. However, the main focus of hydroPSO is the calibration of environmental and other real-world models that need to be executed from the system console. hydroPSO is model-independent, allowing the user to easily interface any computer simulation model with the calibration engine (PSO). hydroPSO communicates with the model through the model's own input and output files, without requiring access to the model's source code. In principle, hydroPSO only needs to know ``which'' model parameters need to be calibrated and ``where'' they need to be written. Then, it will take control over the model(s) to be calibrated until either a maximum number of iterations or an error tolerance is reached: both being problem-specific and user-defined. hydroPSO is able to take advantage of multi-core machines or network clusters to alleviate the computational burden of complex models with "long" execution time. 18 | 19 | hydroPSO includes sensitivity analysis, by using the Latin Hypercube One-At-a-Time (LH-OAT) method (van Griensven et al., 2006). In addition, advanced plotting summaries and detailed information about the evolution of hydroPSO's performance facilitate the interpretation and assessment of the calibration results. At the same time, hydroPSO features a suite of controlling options and PSO variants to fine-tune the performance of the calibration engine to the model for which parameters are sought, thus, allowing the user to customise it to different modelling problems. 20 | 21 | At the same time, hydroPSO includes 4 different topologies (random, von Neumann, lbest, gbest), (non-)linear / random / adaptive / best-ratio inertia weight definitions (IW.type), time-variant acceleration coefficients (use.TVc1 and use.TVc2), time-varying maximum velocity (use.TVlambda), regrouping strategy when premature convergence is detected (use.RG), options for clamping the maximal velocity (lambda), random or LHS initialization of positions and velocities (Xini.type and Vini.type), synchronous or asynchronous update, 5 types of boundary conditions (absorbing2011, absorbing2007, reflecting, damping, invisible) among others. The default control arguments in hydroPSO implements the Standard PSO 2011 - SPSO2011 (see Clerc 2012; Clerc et al., 2010), although (better) settings recommeneded by the authors are described in Zambrano-Bigiarini & Rojas 2012. 22 | 23 | } 24 | \details{ 25 | \tabular{ll}{ 26 | Package: \tab hydroPSO\cr 27 | Type: \tab Package\cr 28 | Version: \tab 0.6-0\cr 29 | Date: \tab 2024-07-15\cr 30 | License: \tab GPL (>=2)\cr 31 | LazyLoad: \tab yes\cr 32 | Packaged: \tab Tue Jul 15 19:26:53 -04 2024; MZB \cr 33 | BuiltUnder: \tab R version 4.4.0 (2024-04-24) -- "Puppy Cup"; aarch64-apple-darwin20 34 | } 35 | %%~~ An overview of how to use the package, including the most important functions ~~ 36 | } 37 | \author{ 38 | Mauricio Zambrano-Bigiarini and Rodrigo Rojas 39 | 40 | Maintainer: Mauricio Zambrano-Bigiarini 41 | } 42 | \references{ 43 | \cite{Zambrano-Bigiarini, M.; R. Rojas (2013), A model-independent Particle Swarm Optimisation software for model calibration, Environmental Modelling & Software, 43, 5-25, doi:10.1016/j.envsoft.2013.01.004} 44 | 45 | \cite{Zambrano-Bigiarini, M., M. Clerc, R. Rojas (2013), Standard Particle Swarm Optimisation 2011 at CEC-2013: A baseline for future PSO improvements, In Proceedings of 2013 IEEE Congress on Evolutionary Computation (CEC'2013). doi:10.1109/CEC.2013.6557848} 46 | 47 | \cite{Abdelaziz, Ramadan, and Mauricio Zambrano-Bigiarini (2014), Particle Swarm Optimization for inverse modeling of solute transport in fractured gneiss aquifer. Journal of Contaminant Hydrology, 164, 285-298. doi:10.1016/j.jconhyd.2014.06.003} 48 | 49 | \cite{Abdelaziz, R.; Merkel, B. J.; Zambrano-Bigiarini, M.; Nair, S. (2019). Particle Swarm Optimization for Surface complexation with the PHREEQC geochemical model, Geoscientific Model Development, 12, 167-177. doi:10.5194/gmd-12-167-2019} 50 | } 51 | %%~~ Optionally other standard keywords, one per line, from file KEYWORDS in ~~ 52 | %%~~ the R documentation directory ~~ 53 | \keyword{ package } 54 | \seealso{ 55 | %%~~ Optional links to other man pages, e.g. ~~ 56 | %%\code{\link[hydroGOF:hydroGOF]{}} 57 | \url{https://github.com/hzambran/hydroGOF} \cr 58 | \url{https://github.com/hzambran/hydroTSM} 59 | } 60 | %%\examples{ 61 | %%~~ simple examples of the most important functions ~~ 62 | %%} 63 | -------------------------------------------------------------------------------- /R/plot_GofPerParticle.R: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # 'plot_GofPerParticle' # 3 | ################################################################################ 4 | # Purpose: It plots the value of each parameter and the objective # 5 | # function against the iteration number. # 6 | ################################################################################ 7 | # Author : Mauricio Zambrano-Bigarini # 8 | # Started : 20-Dec-2010 at JRC, Ispra # 9 | # Modified: 11-Nov-2011 ; 21-Feb-2012 # 10 | ################################################################################ 11 | 12 | plot_GofPerParticle <- function(x, # data.frame with the GoF for each particle per iteration. ncol=number of particles ; nrow = number of iterations 13 | ptype="one", # character, representing the type of plot. Valid values are: in c("one", "many"), for plotting all the particles in the smae figure or in one windows per particle, respectively 14 | nrows="auto", 15 | main=NULL, 16 | xlab="Number of Iterations", 17 | cex=0.4, 18 | cex.main=1.5, 19 | cex.axis=1.7, 20 | cex.lab=1.5, 21 | col=rainbow(ncol(x)), 22 | lty=3, 23 | ylim=NULL, 24 | verbose=TRUE, 25 | ..., 26 | #### PNG options ### 27 | do.png=FALSE, 28 | png.width=1500, 29 | png.height=900, 30 | png.res=90, 31 | png.fname="Particles_GofPerIter.png" 32 | ) { 33 | 34 | # Checking the user provide a valid value for 'ptype' 35 | if (is.na(match(ptype, c("one", "many")))) 36 | stop("Invalid argument: 'ptype' must be in c('one', 'many')") 37 | 38 | # Number of iterations that will be analysed 39 | niter <- nrow(x) 40 | iters <- 1:niter 41 | 42 | # Number of particles 43 | npart <- ncol(x) 44 | 45 | # Computing the number of rows for the plot 46 | if (nrows == "auto") { 47 | if ( npart <= 5 ) lnr <- 1 48 | if ( (npart > 5) & (npart <= 14) ) lnr <- 2 49 | if ( npart > 14 ) lnr <- ceiling(npart/7) 50 | } else lnr <- nrows 51 | 52 | # Defining the plotting window 53 | nr <- lnr 54 | nc <- ceiling(npart/lnr) 55 | 56 | # Range of the objective function, considering ALL the particles 57 | if (is.null(ylim)) ylim <- range( x, na.rm=TRUE ) 58 | 59 | ############################################################################## 60 | # 2) Plotting # 61 | ############################################################################## 62 | msg <- "[ Plotting GoF for each particle vs Number of Model Evaluations" 63 | if (do.png) msg <- paste(msg, " into '", basename(png.fname), sep="") 64 | msg <- paste(msg, "' ... ]", sep="") 65 | message(msg) 66 | 67 | if (do.png) png(filename=png.fname, width=png.width, height=png.height, res=png.res) 68 | 69 | # Saving default plotting parameters 70 | old.par <- par(no.readonly=TRUE) 71 | if (!do.png) on.exit(par(old.par)) 72 | 73 | # Doing the plots 74 | if (ptype=="many") { 75 | 76 | par(mfrow=c(nr,nc)) 77 | if (!is.null(main)) par(oma=c(1,1,3,0)) 78 | for ( i in 1:npart ) { 79 | plot(iters, 80 | x[,i], 81 | type="o", lty=lty, col=col[i], 82 | cex=cex, cex.lab=cex.lab, cex.axis=1.5, 83 | main=paste("Particle", i, sep=" "), 84 | xlim=c(1,niter), ylim=ylim, 85 | xlab=xlab, 86 | ylab=paste("Particle", i, sep=" ") 87 | ) 88 | } # FOR end 89 | 90 | # Adding a main title for the plot 91 | if (!is.null(main)) mtext(main, side=3, line=1, cex=cex.main, outer=TRUE) 92 | 93 | } else if (ptype=="one") { 94 | 95 | if (is.null(main)) main <- "GoF per Particle" 96 | # Plotting the first particle 97 | plot(iters, 98 | x[,2], 99 | type="o", lty=lty, col=col[1], 100 | cex=cex, cex.lab=cex.lab, cex.axis=1.5, 101 | main=main, 102 | xlim=c(1,niter), ylim=ylim, 103 | xlab=xlab, 104 | ylab="GoF" 105 | ) 106 | 107 | if (npart > 1) { 108 | for ( i in 2:npart ) { 109 | lines(iters, 110 | x[,i], 111 | type="o", lty=lty, col=col[i], 112 | cex=cex, cex.lab=cex.lab, cex.axis=1.5, 113 | xlim=c(1,niter), ylim=ylim, 114 | xlab=xlab, 115 | ylab="GoF" 116 | ) 117 | } # FOR end 118 | } # IF end 119 | } # ELSE end 120 | 121 | if (do.png) dev.off() 122 | 123 | } # 'plot_GofPerParticle' END 124 | 125 | #plot_GofPerParticle(ptype="many", nrows=3 ) 126 | -------------------------------------------------------------------------------- /R/ModifyInputFile.R: -------------------------------------------------------------------------------- 1 | # Part of the hydroPSO package, http://www.rforge.net/hydroPSO/ 2 | # Copyright 2010-2024 Mauricio Zambrano-Bigiarini 3 | # Distributed under GPL 2 or later 4 | 5 | ################################################################################ 6 | # ModifyInputfile # 7 | ################################################################################ 8 | # Purpose : To write a numeric value into a specified position of a plain # 9 | # text file # 10 | ################################################################################ 11 | # Output : A mofified text file ('filename') # 12 | ################################################################################ 13 | # Author : Mauricio Zambrano-Bigiarini # 14 | # Started: 17-Dec-2010 at JRC Ispra # 15 | # Updates: 20-Jan-2011 # 16 | # 06-Sep-2013 # 17 | # 09-Abr-2014 # 18 | # 27-Jan-2021 # 19 | # 10-Jul-2024 # 20 | ################################################################################ 21 | 22 | ModifyInputFile <- function( 23 | ParamID, # character, with the ID of the parameter to be modified (only used for visualization purposes) 24 | newvalue, # numeric value to be written into the text file 25 | filename, # character, with the name of the text file that will be modified 26 | row, # numeric, with the row number in \code{filename} where \code{newvalue} will be written 27 | col.ini, # numeric, with the starting column number in \code{filename} where \code{newvalue} is going to be written. 28 | col.fin, # numeric, with the ending column number in \code{filename} where \code{newvalue} is going to be written. 29 | decimals, # numeric, with the number of decimal places used to write \code{newvalue} into \code{filename} 30 | change.type=c("repl", "addi", "mult"), # character, specification of the type of parameter modification ("repl", "mult", "addi") 31 | refValue, # numeric, only used when TypeChange == "mult" | TypeChange == "addi", reference value for making de parameter modification 32 | minValue, # numeric, absolute minimum value that a parameter can take when making a change. When a multiplicative (change.type='mult') or additive (change.type='addi') change tries to make a change where the actual parameter value be lower than 'minValue' then the changed value is set to 'minValue' 33 | maxValue, # numeric, absolute maximum value that a parameter can take when making a change. When a multiplicative (change.type='mult') or additive (change.type='addi') change tries to make a change where the actual parameter value be higher than 'maxValue' then the changed value is set to 'maxValue' 34 | verbose=TRUE) { 35 | 36 | change.type <- match.arg(change.type) 37 | if (!file.exists(filename)) 38 | stop( paste("Invalid argument: the file '", filename, "' doesn't exist!", sep="") ) 39 | oldoptions <- options() 40 | on.exit(options(oldoptions)) 41 | 42 | options(scipen=999) 43 | 44 | if(change.type == "repl"){ # actual value is replaced by new value 45 | 46 | newvalue <- newvalue 47 | 48 | }else if(change.type == "addi"){ # additive change 49 | 50 | newvalue <- newvalue + refValue 51 | newvalue <- max(c(min(c(newvalue, maxValue)), minValue)) 52 | 53 | } else if(change.type == "mult"){ # multiplicative change 54 | 55 | newvalue <- newvalue * refValue 56 | newvalue <- max(c(min(c(newvalue, maxValue)), minValue)) 57 | } # ELSE end 58 | 59 | 60 | 61 | lines <- readLines(filename) 62 | 63 | myline <- lines[row] 64 | 65 | L.trg <- col.fin - col.ini + 1 66 | 67 | newvalue.stg <- as.character(round(newvalue, decimals)) 68 | 69 | L <- nchar(newvalue.stg) 70 | 71 | # message("ParamID : ", ParamID) 72 | # message("filename : ", basename(filename)) 73 | # message("row : ", row) 74 | # message("new value: ", newvalue.stg) 75 | # message("L.trg : ", L.trg) 76 | 77 | if (L < L.trg) newvalue.stg <- format(newvalue, justify="right", width=L.trg, nsmall=decimals) 78 | 79 | if (L > L.trg) { 80 | #newvalue.stg <- format(newvalue, justify="right", width=L.trg, scientific=TRUE) 81 | #e.pos <- which(strsplit(newvalue.stg, split=character(0))[[1]] == "e") 82 | #newvalue.stg <- format(newvalue, justify="right", width=L.trg, scientific=TRUE, digits=e.pos-1) 83 | nexp <- 2 84 | if (abs(newvalue) >= 1E100) nexp <- 3 85 | dig <- max(decimals-(L - L.trg)-3-nexp, 0) 86 | suppressWarnings( 87 | newvalue.stg <- formatC(newvalue, width=L.trg, format="E", digits=dig) 88 | ) 89 | } # IF end 90 | 91 | substr(myline, col.ini, col.fin) <- newvalue.stg 92 | 93 | lines[row] <- myline 94 | 95 | writeLines(lines, filename) 96 | 97 | if (verbose) 98 | message( paste("[", ParamID, ": '", round(newvalue,5), "' was successfully put into '", basename(filename), "']", sep="") ) 99 | 100 | options(oldoptions) # reset (all) initial options 101 | } # 'ModifyInputFile' END 102 | -------------------------------------------------------------------------------- /man/plot_ParamsPerIter.Rd: -------------------------------------------------------------------------------- 1 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 2 | %% http://cran.r-project.org/web/packages/hydroPSO 3 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 4 | %% Distributed under GPL 2 or later 5 | 6 | \name{plot_ParamsPerIter} 7 | \alias{plot_ParamsPerIter} 8 | \alias{plot_ParamsPerIter.default} 9 | \alias{plot_ParamsPerIter.matrix} 10 | \alias{plot_ParamsPerIter.data.frame} 11 | %- Also NEED an '\alias' for EACH other topic documented here. 12 | \title{ 13 | Plot parameter values against the iteration number 14 | } 15 | \description{ 16 | Function to plot the value of each parameter against the iteration number 17 | } 18 | \usage{ 19 | plot_ParamsPerIter(params,...) 20 | 21 | \method{plot_ParamsPerIter}{default}(params, param.names=colnames(params), 22 | main=NULL, xlab="Number of evaluations", nrows="auto", cex=0.5, 23 | cex.main=1.2,cex.axis=1.7,cex.lab=1.5, col=rainbow(ncol(params)), 24 | lty=3, verbose=TRUE, ..., do.png=FALSE, png.width=1500, 25 | png.height=900, png.res=90, png.fname="Params_ValuePerRun.png" ) 26 | 27 | \method{plot_ParamsPerIter}{matrix}(params, param.names=colnames(params), 28 | main=NULL, xlab="Number of evaluations", nrows="auto", cex=0.5, 29 | cex.main=1.2,cex.axis=1.7,cex.lab=1.5, col=rainbow(ncol(params)), 30 | lty=3, verbose=TRUE, ..., do.png=FALSE, png.width=1500, 31 | png.height=900, png.res=90, png.fname="Params_ValuePerRun.png" ) 32 | 33 | \method{plot_ParamsPerIter}{data.frame}(params, param.names=colnames(params), 34 | main=NULL, xlab="Number of evaluations", nrows="auto", cex=0.5, 35 | cex.main=1.2,cex.axis=1.7,cex.lab=1.5, col=rainbow(ncol(params)), 36 | lty=3, verbose=TRUE, ..., do.png=FALSE, png.width=1500, 37 | png.height=900, png.res=90, png.fname="Params_ValuePerRun.png" ) 38 | } 39 | %- maybe also 'usage' for other objects documented here. 40 | \arguments{ 41 | \item{params}{ 42 | matrix or data.frame with the parameter values, where each row represent a different parameter set, and each column represent the value of a different model's parameter 43 | } 44 | \item{param.names}{ 45 | character vector, names to be used for each model's parameter in \code{params} (by default its column names) 46 | } 47 | \item{main}{ 48 | character, title for the plot 49 | } 50 | \item{xlab}{ 51 | character, title for the x axis. See \code{\link[graphics]{plot}} 52 | } 53 | \item{nrows}{ 54 | numeric, number of rows to be used in the plotting window. If \code{nrows} is set to \kbd{auto}, the number of rows is automatically computed depending on the number of columns of \code{params} 55 | } 56 | \item{cex}{ 57 | numeric, magnification for text and symbols relative to the default. See \code{\link[graphics]{par}} 58 | } 59 | \item{cex.main}{ 60 | numeric, magnification to be used for main titles relative to the current setting of \code{cex}. See \code{\link[graphics]{par}} 61 | } 62 | \item{cex.axis}{ 63 | numeric, magnification to be used for axis annotation relative to the current setting of \code{cex}. See \code{\link[graphics]{par}} 64 | } 65 | \item{cex.lab}{ 66 | numeric, magnification to be used for x and y labels relative to the current setting of \code{cex}. See \code{\link[graphics]{par}} 67 | } 68 | \item{col}{ 69 | specification for the default plotting colour. See \code{\link[graphics]{par}} 70 | } 71 | \item{lty}{ 72 | line type. See \code{\link[graphics]{par}} 73 | } 74 | \item{verbose}{ 75 | logical, if TRUE, progress messages are printed 76 | } 77 | \item{\dots}{ 78 | further arguments passed to the \code{plot} function or from other methods. 79 | } 80 | \item{do.png}{ 81 | logical, indicates if all the figures have to be saved into PNG files instead of the screen device 82 | } 83 | \item{png.width}{ 84 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 85 | numeric with the width of the device. See \code{\link[grDevices]{png}} 86 | } 87 | \item{png.height}{ 88 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 89 | numeric with the height of the device. See \code{\link[grDevices]{png}} 90 | } 91 | \item{png.res}{ 92 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 93 | numeric with the nominal resolution in ppi which will be recorded in the PNG file, if a positive integer of the device. See \code{\link[grDevices]{png}} 94 | } 95 | \item{png.fname}{ 96 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 97 | character, with the filename used to store the PNG file 98 | } 99 | } 100 | %%\details{ 101 | %% ~~ If necessary, more details than the description above ~~ 102 | %%} 103 | \value{ 104 | A single figure with \code{nparam} number of panels (\code{nparam=ncol(params)}), where each panel has a plot the value of each parameter against the iteration number. 105 | %% If it is a LIST, use 106 | %% \item{comp1 }{Description of 'comp1'} 107 | %% \item{comp2 }{Description of 'comp2'} 108 | %% ... 109 | } 110 | %%\references{ 111 | %% ~put references to the literature/web site here ~ 112 | %%} 113 | \author{ 114 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 115 | } 116 | %%\note{ 117 | %% ~~further notes~~ 118 | %%} 119 | 120 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 121 | 122 | \seealso{ 123 | \code{\link{plot_results}}, \code{\link{plot_2parOF}}, \code{\link{plot_NparOF}}, \code{\link{plot_GofPerParticle}} 124 | } 125 | \examples{ 126 | # Number of dimensions to be optimised 127 | D <- 5 128 | 129 | # Boundaries of the search space (Griewank test function) 130 | lower <- rep(-600, D) 131 | upper <- rep(600, D) 132 | 133 | \dontrun{ 134 | # Setting the user's home directory as working directory 135 | setwd("~") 136 | 137 | # Setting the seed 138 | set.seed(100) 139 | 140 | # Running PSO with the 'griewank' test function, writing the results to text files 141 | hydroPSO(fn=griewank, lower=lower, upper=upper, 142 | control=list(use.IW = TRUE, IW.type= "linear", IW.w= c(1.0, 0.4), 143 | write2disk=TRUE) ) 144 | 145 | # reading the 'Particles.txt' output file of PSO 146 | setwd("PSO.out") 147 | particles <- read_particles(plot=FALSE) 148 | 149 | # plotting the value of each parameter and the objective function against the 150 | # iteration number 151 | plot_ParamsPerIter(particles[["part.params"]]) 152 | } 153 | } 154 | % Add one or more standard keywords, see file 'KEYWORDS' in the 155 | % R documentation directory. 156 | \keyword{manip} 157 | \keyword{graph}% __ONLY ONE__ keyword per line 158 | -------------------------------------------------------------------------------- /man/quant2ecdf.Rd: -------------------------------------------------------------------------------- 1 | %% File quant2ecdf.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{quant2ecdf} 8 | \Rdversion{1.1} 9 | \alias{quant2ecdf} 10 | \alias{quant2ecdf.default} 11 | \alias{quant2ecdf.matrix} 12 | \alias{quant2ecdf.data.frame} 13 | %- Also NEED an '\alias' for EACH other topic documented here. 14 | \title{ 15 | Simulated Values -> Empirical CDFs 16 | } 17 | \description{ 18 | This function computes ECDFs for user-defined quantiles of the simulated equivalents, with optional plot 19 | } 20 | \usage{ 21 | quant2ecdf(sim, ...) 22 | 23 | \method{quant2ecdf}{default}(sim, weights=NULL, byrow=TRUE, 24 | quantiles.desired= c(0.05, 0.5, 0.95), plot=TRUE, obs=NULL, 25 | quantiles.labels= c("Q5", "Q50", "Q95"), main=NULL, 26 | ylab="Probability", col="blue", leg.cex=1.2, leg.pos="bottomright", 27 | cex.axis=1.2, cex.main=1.2, cex.lab=1.2, verbose=TRUE, ...) 28 | 29 | \method{quant2ecdf}{matrix}(sim, weights=NULL, byrow=TRUE, 30 | quantiles.desired= c(0.05, 0.5, 0.95), plot=TRUE, obs=NULL, 31 | quantiles.labels= c("Q5", "Q50", "Q95"), main=NULL, 32 | ylab="Probability", col="blue", leg.cex=1.2, leg.pos="bottomright", 33 | cex.axis=1.2, cex.main=1.2, cex.lab=1.2, verbose=TRUE, ...) 34 | 35 | \method{quant2ecdf}{data.frame}(sim, weights=NULL, byrow=TRUE, 36 | quantiles.desired= c(0.05, 0.5, 0.95), plot=TRUE, obs=NULL, 37 | quantiles.labels= c("Q5", "Q50", "Q95"), main=NULL, 38 | ylab="Probability", col="blue", leg.cex=1.2, leg.pos="bottomright", 39 | cex.axis=1.2, cex.main=1.2, cex.lab=1.2, verbose=TRUE, ...) 40 | } 41 | %- maybe also 'usage' for other objects documented here. 42 | \arguments{ 43 | \item{sim}{ 44 | matrix or data.frame with the simulated equivalents obtained with different parameter sets, which, by default, are stored in columns 45 | } 46 | \item{weights}{ 47 | numeric vector, values of the weights to be used for computing the quantiles \cr 48 | Omitting the \code{weights} argument or specifying \code{NULL} or a zero-length vector will result in the usual un-weighted estimates 49 | } 50 | \item{byrow}{ 51 | logical, indicates whether the computations have to be made for each column or for each row of \code{x} 52 | When the simulated equivalents are stored in columns, \code{byrow} must be \kbd{TRUE} \cr 53 | When the simulated equivalents are stored in rows, \code{byrow} must be \kbd{FALSE} 54 | } 55 | \item{quantiles.desired}{ 56 | numeric vector, quantiles to be computed. Default values are \kbd{c(.025, .5, .975)} ( => 2.5\%, 50\%, 97.5\% ) 57 | } 58 | \item{plot}{ 59 | logical, indicates if a plot with the ECDFs has to be produced 60 | } 61 | \item{obs}{ 62 | OPTIONAL. Only used when \code{plot=TRUE} \cr 63 | Numeric or zoo object with observed values, which are used in the output plot 64 | } 65 | \item{quantiles.labels}{ 66 | OPTIONAL. Only used when \code{plot=TRUE} \cr 67 | character vector, names to \code{quantiles.desired}. Default value is \kbd{c("Q5", "Q50", "Q95")} 68 | } 69 | \item{main}{ 70 | OPTIONAL. Only used when \code{plot=TRUE} \cr 71 | title for the plot 72 | } 73 | \item{ylab}{ 74 | OPTIONAL. Only used when \code{plot=TRUE} \cr 75 | title for the y axis. See \code{\link[graphics]{plot}} 76 | } 77 | \item{col}{ 78 | OPTIONAL. Only used when \code{plot=TRUE} \cr 79 | specification for the default plotting colour. See \code{par} 80 | } 81 | \item{leg.cex}{ 82 | OPTIONAL. Only used when \code{plot=TRUE} \cr 83 | character expansion factor *relative* to current 'par("cex")'. Used for text, and provides the default for 'pt.cex' and 'title.cex' Default value = 1.2 84 | } 85 | \item{leg.pos}{ 86 | OPTIONAL. Only used when \code{plot=TRUE} \cr 87 | keyword to be used to position the legend. See \code{\link[graphics]{legend}} 88 | } 89 | \item{cex.axis}{ 90 | OPTIONAL. Only used when \code{plot=TRUE} \cr 91 | numeric, magnification to be used for the axis annotation relative to 'cex'. See \code{\link[graphics]{par}} 92 | } 93 | \item{cex.main}{ 94 | OPTIONAL. Only used when \code{plot=TRUE} \cr 95 | numeric, representing the magnification to be used for main titles relative to the current setting of \code{cex} 96 | } 97 | \item{cex.lab}{ 98 | OPTIONAL. Only used when \code{plot=TRUE} \cr 99 | numeric, representing the magnification to be used for x and y labels relative to the current setting of 'cex'. See \code{\link[graphics]{par}} 100 | } 101 | \item{verbose}{ 102 | logical, if TRUE, progress messages are printed 103 | } 104 | \item{\dots}{ 105 | further arguments passed to the \code{plot} function or from other methods 106 | } 107 | } 108 | \details{ 109 | Steps used in this function are: \cr 110 | 1) Computation of un-weighted quantiles (e.g., Q5, Q50, Q95) for the simulated equivalents \cr 111 | 2) Computation of ECDFs for each desired quantile, by weighting the quantiles of each parameter set by its corresponding weights (or less-formal likelihood in GLUE terminology) 112 | } 113 | \value{ 114 | A list whose elements \code{x} and \code{ecdf} correspond to unique sorted values of \code{sim}. If the first CDF estimate is greater than zero, a point (min(sim),0) is placed at the beginning of the estimates 115 | 116 | %A list, with as many elements as the number of elements of \code{quantiles.desired} \cr 117 | %Each element of the list, has the following components: 118 | %\item{x}{ \kbd{n+1} elements (with \kbd{n} as the number of columns of \code{x}) } 119 | %\item{ecdf}{Description of 'comp2'} 120 | %% ... 121 | } 122 | %%\references{ 123 | %%} 124 | \author{ 125 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 126 | } 127 | \note{ 128 | It requires the \code{\link[Hmisc]{wtd.Ecdf}} function from the \pkg{Hmisc} package. 129 | } 130 | 131 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 132 | 133 | \seealso{ 134 | \code{\link[Hmisc]{wtd.Ecdf}}, \code{\link{params2ecdf}} 135 | } 136 | \examples{ 137 | # random matrix with 100 simulated values (in columns) corresponding to 10 138 | # different behavioural parameter sets 139 | x <- matrix(rnorm(1000), ncol=10, nrow=100) 140 | 141 | # empirical CDFs for the quantiles 0.05, 0.5 and 0.95, with equal weight for 142 | # each parameter set 143 | quant2ecdf(sim=x, weights=1:10, byrow=FALSE) 144 | } 145 | % Add one or more standard keywords, see file 'KEYWORDS' in the 146 | % R documentation directory. 147 | \keyword{math} 148 | \keyword{manip} 149 | \keyword{graph} 150 | -------------------------------------------------------------------------------- /R/plot_2parOF.R: -------------------------------------------------------------------------------- 1 | # File plot_2parOF.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2010-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'plot_2parOF' # 9 | ################################################################################ 10 | # Author : Mauricio Zambrano Bigarini # 11 | # Started: Nov 30th, 2010 # 12 | # Updates: 17-Jan-2010 ; 25-Jan-2011 # 13 | # 15-Feb-2012 ; 08-Mar-2012 ; 23-Mar-2012 ; 20-Nov-2012 # 14 | ################################################################################ 15 | # Purpose: For two user-defined parameters, it plots the values of the # 16 | # objective funtion in a two dimensional box, where the boundaries # 17 | # of each parameter are used as axis. # 18 | ################################################################################ 19 | 20 | # params : matrix or data.frame with the parameter sets used during calibration 21 | # p1.name: character with the name of the 1st parameter to be plotted 22 | # p2.name: character with the name of the 2nd parameter to be plotted 23 | # type : character, indicating the type of plot. Valid values are: 24 | # -) "sp" : spatial plot 25 | # -) "scatter3d": 3d scatterogram 26 | # auto.key : logical, indicating if the legend has to be drawn or not 27 | # key.space: character,indicating the position of the legend with respect to the plot 28 | # 29 | plot_2parOF <- function(params, 30 | gofs, 31 | p1.name, 32 | p2.name, 33 | type="sp", 34 | MinMax=c("min", "max"), 35 | gof.name="GoF", 36 | main=paste(gof.name, "Surface"), 37 | GOFcuts, 38 | colorRamp= colorRampPalette(c("darkred", "red", "orange", "yellow", "green", "darkgreen", "cyan")), 39 | points.cex=0.7, 40 | alpha=0.65, 41 | axis.rot=c(0, 0), 42 | auto.key=TRUE, 43 | key.space= "right" 44 | ) { 45 | 46 | # Checking 'params' 47 | if (missing(params)) 48 | stop("Missing argument: 'params' must be provided !!" ) 49 | 50 | # Number of parameter sets 51 | n <- nrow(params) 52 | 53 | # Checking 'gofs' 54 | if (missing(gofs)) { 55 | stop("Missing argument: 'gofs' must be provided !!" ) 56 | } else if (length(gofs) != n) 57 | stop("Invalid argument: 'length(gofs) != nrow(params)' (", length(gofs), "!=", n, ") !!" ) 58 | 59 | # Setting 'MinMax' 60 | MinMax <- match.arg(MinMax) 61 | 62 | # If the user provided 'p1.name', it checks that the field 'p1.name' exists in 'params' 63 | if (!missing(p1.name)) { 64 | if ( !(p1.name %in% colnames(params)) ) 65 | stop("Invalid argument: The field '", p1.name, "' doesn't exist in 'params'") 66 | } # IF end 67 | 68 | # If the user provided 'p2.name', it checks that the field 'p2.name' exists in 'params' 69 | if (!missing(p2.name)) { 70 | if ( !(p2.name %in% colnames(params)) ) 71 | stop("Invalid argument: The field '", p2.name, "' doesn't exist in 'params'") 72 | } # IF end 73 | 74 | # Checking the value of 'type' 75 | if (is.na(match(type, c("sp", "scatter3d") ) ) ) { 76 | stop( "Invalid argument: 'type' must be in c('sp', 'scatter3d')" ) 77 | } else if (type=="scatter3d") { 78 | if ( length(find.package("scatter3d", quiet=TRUE)) == 0 ) { 79 | warning("Package 'scatter3d' is not installed => type='sp'") 80 | type <- "sp" 81 | } # IF end 82 | } # IF end 83 | 84 | # Selecting only the 2 parameters provided by the user + the objective function 85 | p <- data.frame(params[ ,c(p1.name, p2.name)], GoF= gofs) 86 | colnames(p)[3] <- gof.name 87 | 88 | # Ordering parameter sets to have the best ones over the rest 89 | #ifelse(MinMax=="max", decreasing<-FALSE, decreasing<-TRUE) 90 | decreasing <- TRUE 91 | if (MinMax=="max") decreasing <- FALSE 92 | p <- p[order(p[, gof.name], decreasing = decreasing), ] 93 | 94 | if (type=="sp") { 95 | colnames(p) <- c("x", "y", gof.name) 96 | 97 | # If the user didn't provide 'GOFcuts', the 5 quantiles are used 98 | if (missing(GOFcuts)) 99 | GOFcuts <- unique(fivenum(as.numeric(p[, gof.name]), na.rm=TRUE)) 100 | 101 | sp::coordinates(p) <- ~ x+y 102 | 103 | # Reduced margins among figures. From: https://stat.ethz.ch/pipermail/r-help/2007-January/123556.html 104 | theme.novpadding <- list( 105 | layout.heights= list( 106 | top.padding = 2, main.key.padding = 0, 107 | key.axis.padding= 0, axis.xlab.padding= 0, 108 | xlab.key.padding= 0, key.sub.padding= 0, 109 | bottom.padding= 0 110 | ), 111 | layout.widths=list( 112 | left.padding= 3, key.ylab.padding= 0, 113 | ylab.axis.padding= 0, axis.key.padding=0, 114 | right.padding= 0 115 | ) 116 | ) 117 | sp::spplot(p, scales=list(draw=TRUE, cex=0.75, tick.number=4, x=list(rot=axis.rot[1]), 118 | y= list(rot=axis.rot[2]) ), cuts=GOFcuts, col.regions=colorRamp(13), 119 | aspect="fill", auto.key=auto.key, key.space= key.space, 120 | xlab=list(p1.name, font=2), ylab=list(p2.name, font=2), 121 | main=main, cex=points.cex, alpha=alpha, 122 | par.settings = theme.novpadding) 123 | 124 | } else if (type=="scatter3d") { 125 | 126 | x <- params[1:n,p1.name] 127 | y <- params[1:n,p2.name] 128 | z <- params[1:n,gof.name] 129 | 130 | scatterplot3d::scatterplot3d(x, y, z, highlight.3d=TRUE, col.axis="grey", 131 | type="p", col.grid="lightblue", pch=20, main=main, 132 | xlab=p1.name, ylab=p2.name, zlab=gof.name) 133 | } # IF end 134 | 135 | } # 'plot_2parOF' END 136 | -------------------------------------------------------------------------------- /R/read_convergence.R: -------------------------------------------------------------------------------- 1 | # File read_convergence.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2008-2011 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'read_convergence' # 9 | ################################################################################ 10 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 11 | # Started: 08-Nov-2011, # 12 | # Updates: 13-Ene-2012 ; 29-Ene-2012 ; 01-Feb-2012 ; 14-Nov-2012 ; 19-Nov-2012 # 13 | ################################################################################ 14 | # Purpose: To read the output file 'ConvergenceMeasures.txt' # 15 | ################################################################################ 16 | # Output: # 17 | # a data.frame with the following columns for each partile and each iteration: # 18 | # 1) Iter : iteration number # 19 | # 2) Gbest : global best for the iteration corresponding to 'iter' # 20 | # 3) GbestRate : ratio between the global best of the current iteration and # 21 | # the previous one # 22 | # 4) IterBestFit: best fitness value for the iteration corresponding to 'iter'# 23 | # 5) normSwarmRadius: rormalised swarm radious for the iteration corresponding # 24 | # to 'iter' # 25 | # 6) GbestPbestRatio: ratio between the global best and the mean of the # 26 | # personal best of all the particles for the iteration # 27 | # corresponding to 'iter' # 28 | ################################################################################ 29 | 30 | 31 | read_convergence <- function(file="ConvergenceMeasures.txt", 32 | MinMax=NULL, 33 | beh.thr=NA, 34 | verbose=TRUE, 35 | # Plotting arguments # 36 | plot=TRUE, 37 | col=c("black", "darkolivegreen"), 38 | lty=c(1,3), 39 | lwd=c(2,2), 40 | main="Global Optimum & Normalized Swarm Radius vs Iteration Number", 41 | xlab="Iteration Number", 42 | ylab=c("Global Optimum", expression(delta[norm]) ), 43 | pch=c(15, 18), 44 | cex=1, 45 | cex.main=1.4, 46 | cex.axis=1.2, 47 | cex.lab=1.2, 48 | legend.pos="topright", 49 | ..., 50 | #### PNG options ### 51 | do.png=FALSE, 52 | png.width=1500, 53 | png.height=900, 54 | png.res=90, 55 | png.fname="ConvergenceMeasures.png" 56 | ) { 57 | 58 | 59 | # Checking that 'file' exists 60 | if ( !file.exists(file) ) 61 | stop( "Invalid argument value: The file '", basename(file), "' does not exist !!") 62 | 63 | # Checking 'beh.thr' 64 | if ( !is.na(beh.thr) ) { 65 | if ( is.null(MinMax) ) 66 | stop("Missing argument: 'MinMax' has to be provided before using 'beh.thr' !!") 67 | } # IF end 68 | 69 | # Checking 'MinMax' 70 | if ( !is.null(MinMax) ) { 71 | if ( !(MinMax %in% c("min", "max")) ) 72 | stop("Invalid argument: 'MinMax' must be in c('min', 'max')") 73 | } # IF end 74 | 75 | # Reading the file 76 | if (verbose) message( " ") 77 | if (verbose) message( "[ Reading the file '", basename(file), "' ... ]" ) 78 | conv <- read.table(file=file, header=FALSE, skip=1) 79 | conv.names <- c("Iter", "Gbest", "GbestRate", "IterBestFit", "normSwarmRadius", "GbestPbestRatio" ) 80 | 81 | # Giving the right name to the column with the conveters 82 | colnames(conv) <- conv.names 83 | 84 | # computing the number of convergence measures 85 | nconv <- nrow(conv) 86 | if (verbose) message( "[ Total number of iterations: ", nconv, " ]" ) 87 | 88 | # Filtering out those parameter sets above/below a certain threshold 89 | if (!is.na(beh.thr)) { 90 | # Getting the goodness-of-fit of each particle 91 | gbests <- conv[, "Gbest"] 92 | 93 | # Checking 'beh.thr' 94 | mx <- max(gbests, na.rm=TRUE) 95 | if (beh.thr > mx) 96 | stop("Invalid argument: 'beh.thr' must be lower than ", mx ,"!!") 97 | 98 | # Computing the row index of the behavioural parameter sets 99 | if (MinMax=="min") { 100 | beh.row.index <- which(gbests <= beh.thr) 101 | beh.symb <- "<=" 102 | } else { 103 | beh.row.index <- which(gbests >= beh.thr) 104 | beh.symb <- ">=" 105 | } # ELSE end 106 | 107 | # Removing non-behavioural iterations 108 | conv <- conv[beh.row.index, ] 109 | gbests <- gbests[beh.row.index] 110 | 111 | # Amount of behavioural parameter sets 112 | nbeh <- nrow(conv) 113 | if (verbose) message( "[ Number of iterations with Gbest ", beh.symb, " ", beh.thr, 114 | ": ", nbeh, " ]" ) 115 | 116 | # To avoid problems with 'plot_params' 117 | if (plot) beh.thr <- NA 118 | } # IF end 119 | 120 | if (plot) { 121 | plot_convergence(x=conv, 122 | col=col, 123 | lty=lty, 124 | lwd=lwd, 125 | main=main, 126 | xlab=xlab, 127 | ylab=ylab, 128 | cex=cex, 129 | pch=pch, 130 | cex.main=cex.main, 131 | cex.axis=cex.axis, 132 | cex.lab=cex.lab, 133 | legend.pos=legend.pos, 134 | do.png=do.png, 135 | ..., 136 | png.width=png.width, 137 | png.height=png.height, 138 | png.res=png.res, 139 | png.fname=png.fname 140 | ) 141 | } # IF end 142 | 143 | return(conv) 144 | 145 | } # 'read_convergence' END 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /man/plot_NparOF.Rd: -------------------------------------------------------------------------------- 1 | %% file plot_NparOF.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{plot_NparOF} 8 | \alias{plot_NparOF} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | N 2-dimensional plots of parameter values against the values of the objective function. 12 | } 13 | \description{ 14 | For \kbd{n} user-defined parameters, the function creates \kbd{sum(1:(npar-1))} \code{\link{plot_2parOF}} plots, with the values of the objective function in a 2D box, where the boundaries of each parameter are used as axis \cr 15 | The \kbd{sum(1:(npar-1))} plots corresponds to all the possible combinations of 2 parameters among all the \kbd{n} parameters provided 16 | } 17 | \usage{ 18 | plot_NparOF(params, gofs, param.names=colnames(params), 19 | MinMax=c(NULL,"min","max"), beh.thr=NA, nrows="auto", 20 | gof.name="GoF", main=paste(gof.name, "Surface"), GOFcuts="auto", 21 | colorRamp= colorRampPalette(c("darkred", "red", "orange", "yellow", 22 | "green", "darkgreen", "cyan")), points.cex=0.7, alpha=0.65, 23 | axis.rot=c(0, 0), verbose=TRUE) 24 | } 25 | %- maybe also 'usage' for other objects documented here. 26 | \arguments{ 27 | \item{params}{ 28 | matrix or data.frame with the parameter values 29 | } 30 | \item{gofs}{ 31 | numeric with the values of goodness-of-fit values for each one of the parameters in \code{params} (in the same order!) 32 | } 33 | \item{param.names}{ 34 | character, names for the parameters in \code{params} that have to be plotted (\code{param.names} can be a subset of \code{params}) 35 | } 36 | \item{MinMax}{ 37 | character, indicates whether the optimum value in \code{gofs} corresponds to the minimum or maximum of the objective function. \cr 38 | It is required when \code{beh.thr} is provided. Valid values are in: \code{c(NULL, 'min', 'max')} \cr 39 | By default, \code{MinMax=NULL} which plot particles in the order they are provided in \code{params} and \code{gofs} in each one of the output figures \cr 40 | If \code{MinMax='min'} place particles with lower goodness-of-fit values are plotted on top of those with larger values, in each one of the output figures, and vice-versa for \code{MinMax='max'}. 41 | } 42 | \item{beh.thr}{ 43 | OPTIONAL \cr 44 | numeric, threshold value used for selecting parameter sets that have to be used in the analysis (\sQuote{behavioural parameters}, using the GLUE terminology) \cr 45 | If \code{MinMax='min'}, only parameter sets with a goodness-of-fit value (given by \code{gofs}) less than or equal to \code{beh.thr} will be considered for the subsequent analysis. \cr 46 | If \code{MinMax='max'}, only parameter sets with a goodness-of-fit value (given by \code{gofs}) greater than or equal to \code{beh.thr} will be considered for the subsequent analysis 47 | } 48 | \item{nrows}{ 49 | numeric, number of rows to be used in the plotting window \cr 50 | If \code{nrows='auto'} the number of columns is automatically computed depending on the number of parameters in \code{params} 51 | } 52 | \item{gof.name}{ 53 | character, name of the objective function to be plotted. It has to correspond to the name of one column of \code{params} \cr 54 | It is used as title for the legend of the final figure. 55 | } 56 | \item{main}{ 57 | character, currently not used %title for the plot 58 | } 59 | \item{GOFcuts}{ 60 | numeric, specifies at which values of the objective function given in \code{gofs} the colours of the plot have to change \cr 61 | If \code{GOFcuts="auto"} and \code{MinMax=NULL}, the intervals are defined by the (unique values of the) \code{gofs} quantiles corresponding to the following probabilities: \code{probs=c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)} \cr 62 | If \code{GOFcuts="auto"} and \code{MinMax='min'}, the intervals are defined by the (unique values of the) \code{gofs} quantiles corresponding to the following probabilities: \code{probs=c(0, 0.25, 0.5, 0.85, 0.9, 0.97, 1)} \cr 63 | If \code{GOFcuts="auto"} and \code{MinMax='max'}, the intervals are defined by the (unique values of the) \code{gofs} quantiles corresponding to the following probabilities: \code{probs=c(0, 0.03, 0.1, 0.15, 0.5, 0.75, 1)} 64 | } 65 | \item{colorRamp}{ 66 | R function defining the colour ramp to be used for colouring the pseudo-3D dotty plots of Parameter Values, OR character representing those colours 67 | } 68 | \item{points.cex}{ 69 | size of the points to be plotted 70 | } 71 | \item{alpha}{ 72 | numeric between 0 and 1 representing the transparency level to apply to \code{colorRamp}, \sQuote{0} means fully transparent and \sQuote{1} means opaque 73 | } 74 | \item{axis.rot}{ 75 | numeric vector of length 2 representing the angle (in degrees) by which the axis labels are to be rotated, left/bottom and right/top, respectively. 76 | } 77 | \item{verbose}{ 78 | logical; if TRUE, progress messages are printed 79 | } 80 | } 81 | %%\details{ 82 | %% ~~ If necessary, more details than the description above ~~ 83 | %%} 84 | \value{ 85 | A lattice-based figure with N 2-dimensional panels , where each panel has a figure with parameter values against the values of the objective function. Each figure is created by a call to the \code{\link{plot_2parOF}} function. 86 | %% If it is a LIST, use 87 | %% \item{comp1 }{Description of 'comp1'} 88 | %% \item{comp2 }{Description of 'comp2'} 89 | %% ... 90 | } 91 | %%\references{ 92 | %% ~put references to the literature/web site here ~ 93 | %%} 94 | \author{ 95 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 96 | } 97 | %%\note{ 98 | %% ~~further notes~~ 99 | %%} 100 | 101 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 102 | 103 | \seealso{ 104 | \code{\link{plot_2parOF}}, \code{\link{read_results}}, \code{\link{plot_results}}, \code{\link{plot_GofPerParticle}}, \code{\link{plot_params}}, \code{\link{plot_ParamsPerIter}} 105 | } 106 | \examples{ 107 | # Number of dimensions to be optimised 108 | D <- 5 109 | 110 | # Boundaries of the search space (Rosenbrock test function) 111 | lower <- rep(-30, D) 112 | upper <- rep(30, D) 113 | 114 | \dontrun{ 115 | # Setting the user's home directory as working directory 116 | setwd("~") 117 | 118 | # Setting the seed 119 | set.seed(100) 120 | 121 | # Optimising the 'Rosenbrock' test function, and writing the results to text files 122 | hydroPSO(fn=rosenbrock, lower=lower, upper=upper, control=list(write2disk=TRUE) ) 123 | 124 | # reading the 'Particles.txt' output file of hydroPSO 125 | setwd("PSO.out") 126 | particles <- read_particles(plot=FALSE) 127 | 128 | # plotting the value of each parameter and the objective function against the 129 | # values of the objective function 130 | plot_NparOF(params=particles[["part.params"]], gofs=particles[["part.gofs"]], 131 | gof.name="Rosenbrock", alpha=0.5) 132 | } 133 | } 134 | % Add one or more standard keywords, see file 'KEYWORDS' in the 135 | % R documentation directory. 136 | \keyword{math} 137 | \keyword{graph}% __ONLY ONE__ keyword per line 138 | -------------------------------------------------------------------------------- /man/ReadPlot_GofPerParticle.Rd: -------------------------------------------------------------------------------- 1 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 2 | %% http://cran.r-project.org/web/packages/hydroPSO 3 | %% Copyright 2011-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 4 | %% Distributed under GPL 2 or later 5 | 6 | \name{ReadPlot_GofPerParticle} 7 | \alias{read_GofPerParticle} 8 | \alias{plot_GofPerParticle} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | read_GofPerParticle, plot_GofPerParticle 12 | } 13 | \description{ 14 | This function reads/plots the parameter values of each particle and the objective function against the iteration number 15 | } 16 | \usage{ 17 | read_GofPerParticle(file="Particles_GofPerIter.txt", na.strings="NA", 18 | plot=TRUE, ptype="one", nrows="auto", main=NULL, 19 | xlab="Number of Iterations", cex=0.4, cex.main=1.5, cex.axis=1.7, 20 | cex.lab=1.5, col, lty=3, ylim, verbose=TRUE, do.png=FALSE, 21 | png.width=1500, png.height=900, png.res=90, 22 | png.fname="Particles_GofPerIter.png") 23 | 24 | plot_GofPerParticle(x, ptype="one", nrows="auto", main=NULL, 25 | xlab="Number of Iterations", cex=0.4, cex.main=1.5, cex.axis=1.7, 26 | cex.lab=1.5, col=rainbow(ncol(x)), lty=3, ylim=NULL, verbose=TRUE, ..., 27 | do.png=FALSE, png.width=1500, png.height=900, png.res=90, 28 | png.fname="Particles_GofPerIter.png") 29 | } 30 | %- maybe also 'usage' for other objects documented here. 31 | \arguments{ 32 | \item{file}{ 33 | character, name (including path) of the file to be read 34 | } 35 | \item{na.strings}{ 36 | character vector, strings which are to be interpreted as \code{NA} values. See \code{\link[utils]{read.table}} 37 | } 38 | \item{plot}{ 39 | logical, indicates if a plot with the convergence measures has to be produced 40 | } 41 | \item{x}{ 42 | data.frame with the goodness-of-fit measure of each particle per iteration. \cr 43 | The number of columns in \code{x} has to be equal to the number of particles, whereas the number of rows in \code{x} has to be equal to the number of iterations \cr( 44 | (\code{ncol(x)}= number of particles ; \code{nrow(x)} = number of iterations) 45 | } 46 | \item{ptype}{ 47 | character, representing the type of plot. Valid values are: in c("one", "many"), for plotting all the particles in the smae figure or in one windows per particle, respectively 48 | } 49 | \item{nrows}{ 50 | OPTIONAL. Only used when \code{plot=TRUE} \cr 51 | numeric, number of rows to be used in the plotting window \cr 52 | If \code{nrows}is set to \kbd{auto}, the number of rows is automatically computed depending on the number of columns of \code{x} 53 | } 54 | \item{main}{ 55 | OPTIONAL. Only used when \code{plot=TRUE} \cr 56 | character, title for the plot 57 | } 58 | \item{xlab}{ 59 | OPTIONAL. Only used when \code{plot=TRUE} \cr 60 | character, label for the 'x' axis 61 | } 62 | \item{cex}{ 63 | OPTIONAL. Only used when \code{plot=TRUE} \cr 64 | numeric, values controlling the size of text and points with respect to the default 65 | } 66 | \item{cex.main}{ 67 | OPTIONAL. Only used when \code{plot=TRUE} \cr 68 | numeric, magnification for main titles relative to the current setting of \code{cex} 69 | } 70 | \item{cex.axis}{ 71 | OPTIONAL. Only used when \code{plot=TRUE} \cr 72 | numeric, magnification for axis annotation relative to the current setting of \code{cex} 73 | } 74 | \item{cex.lab}{ 75 | OPTIONAL. Only used when \code{plot=TRUE} \cr 76 | numeric, magnification for x and y labels relative to the current setting of \code{cex} 77 | } 78 | \item{col}{ 79 | OPTIONAL. Only used when \code{plot=TRUE} \cr 80 | character, colour to be used for drawing the lines 81 | } 82 | \item{lty}{ 83 | OPTIONAL. Only used when \code{plot=TRUE} \cr 84 | numeric, line type to be used 85 | } 86 | \item{ylim}{ 87 | numeric with the the \sQuote{y} limits of the plot 88 | } 89 | \item{verbose}{ 90 | logical, if TRUE, progress messages are printed 91 | } 92 | \item{\dots}{ 93 | OPTIONAL. Only used when \code{plot=TRUE} \cr 94 | further arguments passed to the plot command or from other methods 95 | } 96 | \item{do.png}{ 97 | logical, indicates if all the figures have to be saved into PNG files instead of the screen device 98 | } 99 | \item{png.width}{ 100 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 101 | numeric, width of the PNG device. See \code{\link[grDevices]{png}} 102 | } 103 | \item{png.height}{ 104 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 105 | numeric, height of the PNG device. See \code{\link[grDevices]{png}} 106 | } 107 | \item{png.res}{ 108 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 109 | numeric, nominal resolution in ppi which will be recorded in the PNG file, if a positive integer of the device. See \code{\link[grDevices]{png}} 110 | } 111 | \item{png.fname}{ 112 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 113 | character, filename used to store the PNG file wih the dotty plots of the parameter values 114 | } 115 | } 116 | %%\details{ 117 | %% ~~ If necessary, more details than the description above ~~ 118 | %%} 119 | \value{ 120 | A data frame with the contents of the output file \sQuote{Particles_GofPerIter.txt} output file, where each column represents an individual model parameter and its corresponding GoF, and each row represents a different PSO iteration. 121 | 122 | Additionally, when \code{plot=TRUE} a a multi-panel figure is produced by a call to the \code{\link{plot_GofPerParticle}} function, where each panel corresponds to a different model parameter and shows the the iteration number against the corresponging GoF value for each iteration. 123 | %% If it is a LIST, use 124 | %% \item{comp1 }{Description of 'comp1'} 125 | %% \item{comp2 }{Description of 'comp2'} 126 | %% ... 127 | } 128 | %%\references{ 129 | %% ~put references to the literature/web site here ~ 130 | %%} 131 | \author{ 132 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 133 | } 134 | %%\note{ 135 | %% ~~further notes~~ 136 | %%} 137 | 138 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 139 | 140 | \seealso{ 141 | \code{\link{read_results}}, \code{\link{plot_results}}, \code{\link{plot_2parOF}}, \code{\link{plot_NparOF}}, \code{\link{plot_ParamsPerIter}} 142 | } 143 | \examples{ 144 | \dontrun{ 145 | # Setting the user home directory as working directory 146 | setwd("~") 147 | 148 | # Number of dimensions to be optimised 149 | D <- 4 150 | 151 | # Boundaries of the search space (Sphere test function) 152 | lower <- rep(-100, D) 153 | upper <- rep(100, D) 154 | 155 | # Setting the seed 156 | set.seed(100) 157 | 158 | # Runing PSO with the 'Sphere' test function, writting the results to text files 159 | hydroPSO(fn=sphere, lower=lower, upper=upper, 160 | control=list(maxit=100, write2disk=TRUE, plot=TRUE) ) 161 | 162 | # Reading the convergence measures got by running hydroPSO 163 | setwd("PSO.out") 164 | read_GofPerParticle() # all the particles in the same window 165 | read_GofPerParticle(ptype="many") # each particle in a different pannel 166 | 167 | } 168 | } 169 | % Add one or more standard keywords, see file 'KEYWORDS' in the 170 | % R documentation directory. 171 | \keyword{files} 172 | \keyword{graph}% __ONLY ONE__ keyword per line 173 | -------------------------------------------------------------------------------- /man/ReadPlot_convergence.Rd: -------------------------------------------------------------------------------- 1 | %% File ReadPlot_convergence.R 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2024 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{ReadPlot_convergence} 8 | \Rdversion{1.1} 9 | \alias{read_convergence} 10 | \alias{plot_convergence} 11 | %- Also NEED an '\alias' for EACH other topic documented here. 12 | \title{ 13 | Reading/Plotting the values of different parameter sets 14 | } 15 | \description{ 16 | This function reads a file containing different parameter sets and ther corresponfing goodness-of-fit values 17 | } 18 | \usage{ 19 | read_convergence(file="ConvergenceMeasures.txt", MinMax=NULL, beh.thr=NA, 20 | verbose=TRUE, plot=TRUE, col=c("black", "darkolivegreen"), lty=c(1,3), 21 | lwd=c(2,2), main="Global Optimum & Normalized Swarm Radius vs Iteration Number", 22 | xlab="Iteration Number", ylab=c("Global Optimum", expression(delta[norm])), 23 | pch=c(15, 18), cex=1, cex.main=1.4, cex.axis=1.2, cex.lab=1.2, 24 | legend.pos="topright", ..., do.png=FALSE, png.width=1500, png.height=900, 25 | png.res=90,png.fname="ConvergenceMeasures.png") 26 | 27 | plot_convergence(x, verbose=TRUE, col=c("black", "darkolivegreen"), lty=c(1,3), 28 | lwd=c(2,2), main="Global Optimum & Normalized Swarm Radius vs Iteration Number", 29 | xlab="Iteration Number", ylab=c("Global Optimum", expression(delta[norm])), 30 | pch=c(15, 18), cex=1, cex.main=1.4, cex.axis=1.2, cex.lab=1.2, 31 | legend.pos="topright", ..., do.png=FALSE, png.width=1500, png.height=900, 32 | png.res=90, png.fname="ConvergenceMeasures.png") 33 | } 34 | %- maybe also 'usage' for other objects documented here. 35 | \arguments{ 36 | \item{file}{ 37 | character, name (including path) of the file to be read 38 | } 39 | \item{verbose}{ 40 | logical; if TRUE, progress messages are printed 41 | } 42 | \item{x}{ 43 | data.frame with the convergence outputs obtained with \code{read_convergence}. 44 | } 45 | \item{MinMax}{ 46 | OPTIONAL \cr 47 | character, indicates if the optimum value in \code{params} corresponds to the minimum or maximum of the the objective function. Valid values are in: \code{c('min', 'max')} 48 | } 49 | \item{beh.thr}{ 50 | numeric, used for selecting only the behavioural parameter sets, i.e., those with a goodness-of-fit value larger/lowervalue than \code{beh.th}, depending on the value of \code{MinMax}. \cr 51 | It is only used for drawing a horizontal line used for separating behavioural from non behavioural parameter sets. 52 | } 53 | \item{plot}{ 54 | logical, indicates if a plot with the convergence measures has to be produced 55 | } 56 | \item{col}{ 57 | OPTIONAL. Only used when \code{plot=TRUE} \cr 58 | character, colour to be used for drawing the lines 59 | } 60 | \item{lty}{ 61 | OPTIONAL. Only used when \code{plot=TRUE} \cr 62 | numeric, line type to be used 63 | } 64 | \item{lwd}{ 65 | OPTIONAL. Only used when \code{plot=TRUE} \cr 66 | numeric, line width 67 | } 68 | \item{xlab}{ 69 | OPTIONAL. Only used when \code{plot=TRUE} \cr 70 | character, label for the 'x' axis 71 | } 72 | \item{ylab}{ 73 | OPTIONAL. Only used when \code{plot=TRUE} \cr 74 | character, label for the 'y' axis 75 | } 76 | \item{main}{ 77 | OPTIONAL. Only used when \code{plot=TRUE} \cr 78 | character, title for the plot 79 | } 80 | \item{pch}{ 81 | OPTIONAL. Only used when \code{plot=TRUE} \cr 82 | numeric, type of symbol for drawing the points of the dotty plots (e.g., 1: white circle) 83 | } 84 | \item{cex}{ 85 | OPTIONAL. Only used when \code{plot=TRUE} \cr 86 | numeric, values controlling the size of text and points with respect to the default 87 | } 88 | \item{cex.main}{ 89 | OPTIONAL. Only used when \code{plot=TRUE} \cr 90 | numeric, magnification to be used for main titles relative to the current setting of \code{cex} 91 | } 92 | \item{cex.axis}{ 93 | OPTIONAL. Only used when \code{plot=TRUE} \cr 94 | numeric, magnification to be used for axis annotation relative to the current setting of \code{cex} 95 | } 96 | \item{cex.lab}{ 97 | OPTIONAL. Only used when \code{plot=TRUE} \cr 98 | numeric, magnification to be used for x and y labels relative to the current setting of \code{cex} 99 | } 100 | \item{legend.pos}{ 101 | OPTIONAL. Only used when \code{plot=TRUE} \cr 102 | character, position of the legend. Valid values are in \code{c("bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right", "center")}. See \code{\link[graphics]{legend}} 103 | } 104 | \item{\dots}{ 105 | OPTIONAL. Only used when \code{plot=TRUE} \cr 106 | further arguments passed to the plot command or from other methods 107 | } 108 | \item{do.png}{ 109 | logical, indicates if the plot with the convergence measures has to be saved into a PNG file instead of the screen device 110 | } 111 | \item{png.width}{ 112 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 113 | numeric, width of the device. See \code{\link[grDevices]{png}} 114 | } 115 | \item{png.height}{ 116 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 117 | numeric, height of the device. See \code{\link[grDevices]{png}} 118 | } 119 | \item{png.res}{ 120 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 121 | numeric, nominal resolution in ppi which will be recorded in the PNG file, if a positive integer of the device. See \code{\link[grDevices]{png}} 122 | } 123 | \item{png.fname}{ 124 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 125 | character, name of the output PNG file. See \code{\link[grDevices]{png}} 126 | } 127 | } 128 | %%\details{ 129 | %% ~~ If necessary, more details than the description above ~~ 130 | %%} 131 | \value{ 132 | A list with the following elements: 133 | %% If it is a LIST, use 134 | \item{Iter}{iteration number'} 135 | \item{Gbest}{global optimum for each iteration} 136 | \item{GbestRate}{rate of change of the global optimum (current iter/previous iter)} 137 | \item{IterBestFit}{best performance for the current iteration} 138 | \item{normSwarmRadius}{normalised swarm radious} 139 | \item{[gbest-mean(pbest)]/mean(pbest)}{gbest: global optimum, mean(pbest): mean values of the personal best of all the particles} 140 | %% ... 141 | } 142 | %%\references{ 143 | %% 144 | %%} 145 | \author{ 146 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 147 | } 148 | %%\note{ 149 | %% ~~further notes~~ 150 | %%} 151 | 152 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 153 | 154 | \seealso{ 155 | \code{\link{read_results}}, \code{\link{plot_results}} 156 | } 157 | \examples{ 158 | \dontrun{ 159 | # Setting the user home directory as working directory 160 | setwd("~") 161 | 162 | # Number of dimensions to be optimised 163 | D <- 4 164 | 165 | # Boundaries of the search space (Sphere function) 166 | lower <- rep(-100, D) 167 | upper <- rep(100, D) 168 | 169 | # Setting the seed 170 | set.seed(100) 171 | 172 | # Runing PSO with the 'sphere' test function, writting the results to text files 173 | hydroPSO( 174 | fn=sphere, lower=lower, upper=upper, 175 | control=list(MinMax="min", write2disk=TRUE, plot=TRUE) 176 | ) 177 | 178 | # Reading the convergence measures got by running hydroPSO 179 | setwd("PSO.out") 180 | read_convergence() 181 | 182 | } 183 | } 184 | % Add one or more standard keywords, see file 'KEYWORDS' in the 185 | % R documentation directory. 186 | \keyword{graph} 187 | \keyword{manip}% __ONLY ONE__ keyword per line 188 | -------------------------------------------------------------------------------- /R/read_results.R: -------------------------------------------------------------------------------- 1 | # File read_results.R 2 | # Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # http://www.rforge.net/hydroPSO/ 5 | # Copyright 2010-2020 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | # Distributed under GPL 2 or later 7 | 8 | ################################################################################ 9 | # 'read_results' # 10 | ################################################################################ 11 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 12 | # Started: 09-Nov-2011, # 13 | # Updates: 13-Jan-2012 ; 23-Feb-2012 ; 06-Dec-2012 # 14 | # 28-Feb-2020 # 15 | # 02-Nov-2025 # 16 | ################################################################################ 17 | # Purpose: # 18 | # This funtion read the following output files of hydroPSO: # 19 | # 1) BestParameterSet.txt : best parameter set and its corresponding # 20 | # goodness-of-fit found during the optimisation # 21 | # 2) Particles.txt : parameter values and their corresponding # 22 | # goodness-of-fit for all the particles and # 23 | # iterations # 24 | # 3) Velocities.txt : velocity values and their corresponding # 25 | # goodness-of-fit for all the particles and # 26 | # iterations # 27 | # 4) Model_out.txt : values of the objective function / model for # 28 | # each particle and iteration # 29 | # 5) ConvergenceMeasures.txt : convergence measures # 30 | # 6) Particles_GofPerIter.txt: goodness-of-fit only for all the particles # 31 | # during all the iterations # 32 | ################################################################################ 33 | # Output: # 34 | # a list with the following elements # 35 | # 1) best.param: numeric with the best parameter set # 36 | # 2) best.gof : numeric with the best fitness value of the objective function # 37 | # 3) params : data.frame with all the parameter sets tested during the # 38 | # optimisation # 39 | # 4) gofs : numeric with all the fitness values computed during the # 40 | # optimisation (each elment in 'gofs' corresponds to one row of # 41 | # 'params') # 42 | # 5) model.values:numeric or matrix/data.frame with the values of the objective# 43 | # function / model for each particle and iteration # 44 | # 6) convergence.measures: matrix/data.frame with the convergence measues. # 45 | # See'read_convergence.R' function # 46 | # 7) Particles.GofPerIter: matrix/data.frame with the goodness-of-fit only for # 47 | # all the particles during all the iterations # 48 | ################################################################################ 49 | 50 | read_results <- function(drty.out="PSO.out", 51 | MinMax=NULL, 52 | beh.thr=NA, 53 | modelout.cols=NULL, # 'read_out' , 'plot_out' argument 54 | nsim=NULL, # 'read_out' argument 55 | obs.tzone=NULL, # 'read_out' argument 56 | verbose=TRUE) { 57 | 58 | ######################## Checkings ############################### 59 | # Checking 'MinMax' 60 | if ( !is.null(MinMax) ) { 61 | if ( !(MinMax %in% c("min", "max")) ) 62 | stop("Invalid argument: 'MinMax' must be in c('min', 'max')") 63 | } else { # MinMax was not provided: it is read from the output 'PSO_logfile.txt' file 64 | # It assumes that 'PSO_logfile.txt' is located in the same directory than the 'Model_out.txt' file 65 | fname <- paste0(drty.out, "/PSO_logfile.txt") 66 | PSOlog <- read.table(file=fname, skip=9, nrows=1) 67 | MinMax <- as.character(PSOlog[1, 3]) 68 | if (verbose) message("[ 'MinMax' was read from the 'PSO_logfile.txt' file, and set to '", MinMax, "' ]") 69 | } # ELSE end 70 | 71 | # Checking 'beh.thr' 72 | if ( !is.na(beh.thr) ) { 73 | if ( is.null(MinMax) ) 74 | stop("Missing argument: 'MinMax' has to be provided before using 'beh.thr' !!") 75 | } # IF end 76 | 77 | 78 | # Full path to 'drty.out' 79 | if (basename(drty.out) == drty.out) 80 | drty.out <- paste(getwd(), "/", drty.out, sep="") 81 | 82 | ######################## I) Reading ######################################### 83 | 84 | # Working directory 85 | wd.bak <- getwd() 86 | setwd(drty.out) 87 | on.exit(setwd(wd.bak)) 88 | 89 | if (verbose) message("[ ]") 90 | if (verbose) message("[ Reading output files ... ]") 91 | if (verbose) message("[ ]") 92 | 93 | 94 | # 1) File "BestParameterSet.txt" 95 | #best <- read_best() 96 | #best.param <- best[["best.param.values"]] 97 | #best.gof <- best[["best.param.gof"]] 98 | 99 | # 2) File "Particles.txt" 100 | part <- read_particles(MinMax=MinMax, beh.thr=beh.thr, plot=FALSE) 101 | params <- part[["part.params"]] 102 | gofs <- part[["part.gofs"]] 103 | best.param <- part[["best.param"]] 104 | best.gof <- part[["best.gof"]] 105 | 106 | # 3) File "Velocities.txt" 107 | veloc <- read_velocities(MinMax=MinMax, beh.thr=beh.thr, plot=FALSE) 108 | velocities <- veloc[["velocities"]] 109 | 110 | # 4) File "Model_out.txt" 111 | out <- read_out(modelout.cols=modelout.cols, obs.tzone=obs.tzone, MinMax=MinMax, 112 | beh.thr=beh.thr, verbose=verbose, plot=FALSE) 113 | model.values <- out[["model.values"]] 114 | model.best <- out[["model.best"]] 115 | model.obs <- out[["model.obs"]] 116 | 117 | # 5) File "ConvergenceMeasures.txt" 118 | conv <- read_convergence(MinMax=MinMax, beh.thr=beh.thr, plot=FALSE) 119 | 120 | # 6) File "Particles_GofPerIter.txt' 121 | Particles.GofPerIter <- read_GofPerParticle(plot=FALSE) 122 | 123 | # Creating the final output 124 | out <- list(best.param=best.param, 125 | best.gof=best.gof, 126 | params=params, 127 | gofs=gofs, 128 | velocities=velocities, 129 | model.values=model.values, 130 | model.best=model.best, 131 | model.obs=model.obs, 132 | convergence.measures=conv, 133 | part.GofPerIter=Particles.GofPerIter 134 | ) 135 | 136 | # Output 137 | return(out) 138 | 139 | } # 'read_results' END 140 | -------------------------------------------------------------------------------- /man/hydromod.Rd: -------------------------------------------------------------------------------- 1 | %% File hydromod.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{hydromod} 8 | \alias{hydromod} 9 | %- Also NEED an '\alias' for EACH other topic documented here. 10 | \title{ 11 | hydromod - Definition and execution of the model to be calibrated/optimised using an executable file that runs in the system console 12 | } 13 | \description{ 14 | It runs a user-defined model to be calibrated/optimised and returns a goodness-of-fit value as measure of model performance, by comparing observations against simulated equivalents. \\ 15 | This function it was designed to run an executable file from the system console, not a model implemented as an R function 16 | } 17 | \usage{ 18 | hydromod(param.values, param.files="ParamFiles.txt", 19 | param.ranges="ParamRanges.txt", 20 | model.drty = getwd(), 21 | exe.fname, exe.args= character(), stdout= FALSE, stderr="", 22 | verbose = FALSE, out.FUN, out.FUN.args, gof.FUN, gof.FUN.args=list(), 23 | gof.Ini, gof.Fin, date.fmt = "\%Y-\%m-\%d", obs, 24 | do.png=FALSE, png.fname, width = 1200, height = 600, res=90, 25 | main, leg.cex=1.2, tick.tstep= "auto", lab.tstep= "auto", 26 | lab.fmt=NULL) 27 | } 28 | %- maybe also 'usage' for other objects documented here. 29 | \arguments{ 30 | \item{param.values}{ 31 | numeric vector, a single parameter set used to run the model specified in \code{exe.fname} 32 | } 33 | \item{param.files}{ 34 | character, file name (with full path) storing locations and names of the files that have to be modified for each parameter. By default \code{param.files="ParamFiles.txt"} 35 | } 36 | \item{param.ranges}{ 37 | character, file name (with full path) storing the ranges (maximum and minum values) of the parameters to be used in the optimisation. By default \code{param.files="ParamRanges.txt"} 38 | } 39 | \item{model.drty}{ 40 | character, path to the executable file of the model specified in \code{exe.fname}. ALL the files required to run the model have to be located within this directory (input files for the model may be located in a different directory, if properly referenced). 41 | } 42 | \item{exe.fname}{ 43 | character, model command line arguments to be entered through a prompted string to execute the user-defined model 44 | } 45 | \item{exe.args}{ 46 | character, with optional arguments to be passed in the command line to the user-defined model. 47 | } 48 | \item{stdout, stderr}{ 49 | where output to \sQuote{stdout} or \sQuote{stderr} should be sent. Possible values are \code{FALSE} (discard output, the default), \code{""}, to the R console. See \code{\link[base]{system2}}\cr 50 | By default \code{stdout=FALSE} and any message printed by the model code to the screen will be omitted. This setting is recommended when calibrating the model with \code{\link{hydroPSO}}. However, when trying to run the model code with \code{hydromod} by the first time, it is recommend to set \code{stdout=""}, in order to detect if the model was properly executed or not. \cr 51 | By default \code{stderr=""} and any error message of the model code will be printed to the screen 52 | } 53 | \item{verbose}{ 54 | logical; if TRUE, progress messages are printed to the screen \cr 55 | If \code{verbose=TRUE}, the following messages will appear: i) parameter values for each particle; (ii) model execution; iii) extraction of simulated values; and iv) computation of the goodness-of-fit measure 56 | } 57 | \item{out.FUN}{ 58 | character, name of a valid R function to read the model outputs and transform them into a (zoo) object to be compared against \code{obs} (e.g., see \code{\link[utils]{read.table}}, \code{\link[utils]{read.csv}} 59 | } 60 | \item{out.FUN.args}{ 61 | list, arguments to be passed to \code{out.FUN} 62 | } 63 | \item{gof.FUN}{ 64 | character, name of a valid (goodness-of-fit) R function to obtain model performance (e.g., see \code{\link[hydroGOF]{NSE}}, \code{\link[hydroGOF]{rmse}}, etc).\cr 65 | It MUST HAVE -at least- the following two arguments in its definition:\cr 66 | -) \kbd{sim}: numeric with the value(s) simulated by the model specified in \code{exe.fname}\cr 67 | -) \kbd{obs}: numeric with the observation(s) used to compute model's performance by comparison against \kbd{sim} 68 | } 69 | \item{gof.FUN.args}{ 70 | list, arguments additional to \kbd{sim} and \kbd{obs} that need to be passed to \code{gof.FUN} (e.g., see \kbd{j} argument in \code{\link[hydroGOF]{mNSE}}) 71 | } 72 | \item{gof.Ini}{ 73 | OPTIONAL. Character with the starting date used in the goodness-of-fit function \cr 74 | It is used to subset \code{obs} (if necessary), AND to define the time period to compare simulated with observed values 75 | } 76 | \item{gof.Fin}{ 77 | OPTIONAL. Character with the ending date used in the goodness-of-fit function \cr 78 | It is used to subset \code{obs} (if necessary), AND to define the time period to compare simulated with observed values 79 | } 80 | \item{date.fmt}{ 81 | character, format in which the dates are stored in \code{Sim.Ini}, \code{Sim.Fin}, \code{gof.Ini}, \code{gof.Fin}, e.g. \kbd{\%Y-\%m-\%d}. See \code{format} in \code{\link[base]{as.Date}} 82 | } 83 | \item{obs}{ 84 | (zoo) object with the observed values 85 | } 86 | \item{do.png}{ 87 | logical indicating whether a PNG image with the comparison between \code{obs} and the best simulated values has to be created\cr 88 | If the \pkg{hydroGOF} package is available, the plot is produced with the \code{\link[hydroGOF]{ggof}} function. A correlation plot is produced otherwise with the \code{\link{plot_out}} function 89 | } 90 | \item{png.fname}{ 91 | OPTIONAL. Used only when \code{do.png=TRUE} \cr 92 | Name of the PNG file to be created within the \code{model.drty} directory. The default value is \sQuote{Obs_vs_Sim.png} 93 | } 94 | \item{width}{ 95 | OPTIONAL. Used only when \code{do.png=TRUE} \cr 96 | numeric, width of the output PNG image 97 | } 98 | \item{height}{ 99 | OPTIONAL. Used only when \code{do.png=TRUE} \cr 100 | numeric, height of the output PNG image 101 | } 102 | \item{res}{ 103 | OPTIONAL. Used only when \code{do.png=TRUE} \cr 104 | numeric, resolution of the output PNG image 105 | } 106 | \item{main}{ 107 | OPTIONAL. Used only when \code{do.png=TRUE} \cr 108 | character, representing the main title of the plot comparing observed and simulated values 109 | } 110 | \item{leg.cex}{ 111 | See \code{\link[hydroGOF]{ggof}} 112 | } 113 | \item{tick.tstep}{ 114 | See \code{\link[hydroGOF]{ggof}} 115 | } 116 | \item{lab.tstep}{ 117 | See \code{\link[hydroGOF]{ggof}} 118 | } 119 | \item{lab.fmt}{ 120 | See \code{\link[hydroGOF]{ggof}} 121 | } 122 | %% \item{\dots}{ 123 | %% ~~Describe \code{\dots} here~~ 124 | %%} 125 | } 126 | %%\details{ 127 | %% ~~ If necessary, more details than the description above ~~ 128 | %%} 129 | \value{ 130 | A list of two elements: 131 | \item{sim}{numeric, with the simulated values obtained by running the model} 132 | \item{GoF}{numeric, goodness-of-fit value representing how close each one of the simulated values in \code{sim} are to their observed counterparts, by using the USER-DEFINED \code{gof.FUN} function} 133 | } 134 | %%\references{ 135 | %% ~put references to the literature/web site here ~ 136 | %%} 137 | \author{ 138 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 139 | } 140 | %%\note{ 141 | %% ~~further notes~~ 142 | %%} 143 | 144 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 145 | 146 | \seealso{ 147 | \code{\link{hydroPSO}}, \code{\link{hydromodInR}} 148 | } 149 | %%\examples{ 150 | %%} 151 | % Add one or more standard keywords, see file 'KEYWORDS' in the 152 | % R documentation directory. 153 | \keyword{files} 154 | \keyword{optimisation}% __ONLY ONE__ keyword per line 155 | -------------------------------------------------------------------------------- /man/params2ecdf.Rd: -------------------------------------------------------------------------------- 1 | %% File params2ecdf.Rd 2 | %% Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | %% http://cran.r-project.org/web/packages/hydroPSO 4 | %% Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | %% Distributed under GPL 2 or later 6 | 7 | \name{params2ecdf} 8 | \Rdversion{1.1} 9 | \alias{params2ecdf} 10 | \alias{params2ecdf.default} 11 | \alias{params2ecdf.matrix} 12 | \alias{params2ecdf.data.frame} 13 | %- Also NEED an '\alias' for EACH other topic documented here. 14 | \title{ 15 | Parameter Values -> Empirical CDFs 16 | } 17 | \description{ 18 | This function computes (weighted) empirical CDFs (ECDFs) for each calibrated parameter, by using the parameter values obtained during the optimisation with \code{\link{hydroPSO}} (with optional plot) 19 | } 20 | \usage{ 21 | params2ecdf(params, ...) 22 | 23 | \method{params2ecdf}{default}(params, param.names=NULL, gofs=NULL, MinMax=NULL, 24 | beh.thr=NA, weights=NULL, byrow=FALSE, plot=TRUE, obs=NULL, main=NULL, 25 | nrows="auto", ylab="Probability", col="blue", leg.cex=1.2, 26 | leg.pos="topleft", cex.axis=1.2, cex.main=1.2, cex.lab=1.2, 27 | verbose=TRUE, ..., do.png=FALSE, png.width=1500, png.height=900, 28 | png.res=90, png.fname="Params_ECDFs.png") 29 | 30 | \method{params2ecdf}{matrix}(params, param.names=colnames(params), gofs=NULL, 31 | MinMax=NULL, beh.thr=NA, weights, byrow=FALSE, plot=TRUE, obs=NULL, 32 | main=NULL, nrows="auto", ylab="Probability", col="blue", leg.cex=1.2, 33 | leg.pos="topleft", cex.axis=1.2, cex.main=1.2, cex.lab=1.2, 34 | verbose=TRUE, ..., do.png=FALSE, png.width=1500, png.height=900, 35 | png.res=90, png.fname="Params_ECDFs.png") 36 | 37 | \method{params2ecdf}{data.frame}(params, param.names=colnames(params), gofs=NULL, 38 | MinMax=NULL, beh.thr=NA, weights, byrow=FALSE, plot=TRUE, obs=NULL, 39 | main=NULL, nrows="auto", ylab="Probability", col="blue", leg.cex=1.2, 40 | leg.pos="topleft", cex.axis=1.2, cex.main=1.2, cex.lab=1.2, 41 | verbose=TRUE, ..., do.png=FALSE, png.width=1500, png.height=900, 42 | png.res=90, png.fname="Params_ECDFs.png") 43 | } 44 | %- maybe also 'usage' for other objects documented here. 45 | \arguments{ 46 | \item{params}{ 47 | matrix or data.frame with the parameter values, where each row represent a different parameter set and each column represent the value of a different model parameter 48 | } 49 | \item{param.names}{ 50 | character vector, names to be used for each parameter in \code{params} (by default its column names) 51 | } 52 | \item{gofs}{ 53 | OPTIONAL. numeric with the values of goodness-of-fit values for each parameter in \code{params} (in the same order!) 54 | } 55 | \item{MinMax}{ 56 | OPTIONAL. character, indicates if the optimum value in \code{params} corresponds to the minimum or maximum of the the objective function. Only used to identify the optimum in the plot \cr 57 | Valid values are in: \code{c('min', 'max')} 58 | } 59 | \item{beh.thr}{ 60 | numeric, used for selecting only the behavioural parameter sets, i.e. those with a goodness-of-fit value (as given in \code{gofs}) greater/less than or equal to \code{beh.thr}, depending on the value of \code{MinMax}\cr 61 | By default \code{beh.thr=NA} and all the parameter sets are considered for the subsequent anlysis 62 | } 63 | \item{weights}{ 64 | numeric vector, values of the weights to be used for computing the empirical CDFs \cr 65 | Omitting the \code{weights} argument or specifying \code{NULL} or a zero-length vector will result in the usual un-weighted estimates 66 | } 67 | \item{byrow}{ 68 | logical, indicates whether the computations have to be made for each column or for each row of \code{params} \cr 69 | When the parameter sets are stored in rows, i.e. values for different model's parameter are stored in columns, \code{byrow} must be \kbd{FALSE} \cr 70 | When the parameter sets are stored in columns, i.e. values for different model's parameter are stored in rows, \code{byrow} must be \kbd{TRUE} 71 | } 72 | \item{plot}{ 73 | logical, indicates whether a plot with the Empirical CDF for each model's parameter has to be produced or not 74 | } 75 | \item{obs}{ 76 | OPTIONAL. Only used when \code{plot=TRUE} \cr 77 | Numeric or zoo object with observed values (one for each \code{params}), which are used in the output plot 78 | } 79 | \item{main}{ 80 | an overall title for the plot 81 | } 82 | \item{nrows}{ 83 | OPTIONAL. Only used when \code{plot=TRUE} \cr 84 | numeric, number of rows to be used in the plotting window. If \code{nrows} is set to \kbd{auto}, the number of rows is automatically computed depending on the number of columns of \code{params} 85 | } 86 | \item{ylab}{ 87 | OPTIONAL. Only used when \code{plot=TRUE} \cr 88 | a title for the y axis. See \code{\link[graphics]{plot}} 89 | } 90 | \item{col}{ 91 | OPTIONAL. Only used when \code{plot=TRUE} \cr 92 | a specification for the default plotting colour. See \code{\link[graphics]{par}} 93 | } 94 | \item{leg.cex}{ 95 | OPTIONAL. Only used when \code{plot=TRUE} \cr 96 | character expansion factor *relative* to current 'par("cex")'. Used for text, and provides the default for 'pt.cex' and 'title.cex'. Default value = 1.2 97 | } 98 | \item{leg.pos}{ 99 | OPTIONAL. Only used when \code{plot=TRUE} \cr 100 | keyword to be used to position the legend. See \code{\link[graphics]{legend}} 101 | } 102 | \item{cex.axis}{ 103 | OPTIONAL. Only used when \code{plot=TRUE} \cr 104 | numeric, magnification to be used for axis annotation relative to the current setting of \code{cex} 105 | } 106 | \item{cex.main}{ 107 | OPTIONAL. Only used when \code{plot=TRUE} \cr 108 | numeric, magnification to be used for main titles relative to the current setting of \code{cex} 109 | } 110 | \item{cex.lab}{ 111 | OPTIONAL. Only used when \code{plot=TRUE} \cr 112 | numeric, magnification to be used for x and y labels relative to the current setting of \code{cex} 113 | } 114 | \item{verbose}{ 115 | logical, if TRUE, progress messages are printed 116 | } 117 | \item{\dots}{ 118 | further arguments passed to the \code{plot} function or from other methods 119 | } 120 | \item{do.png}{ 121 | logical, indicates if all the figures have to be saved into PNG files instead of the screen device 122 | } 123 | \item{png.width}{ 124 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 125 | numeric with the width of the device. See \code{\link[grDevices]{png}} 126 | } 127 | \item{png.height}{ 128 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 129 | numeric with the height of the device. See \code{\link[grDevices]{png}} 130 | } 131 | \item{png.res}{ 132 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 133 | numeric with the nominal resolution in ppi which will be recorded in the PNG file, if a positive integer of the device. See \code{\link[grDevices]{png}} 134 | } 135 | \item{png.fname}{ 136 | OPTIONAL. Only used when \code{do.png=TRUE} \cr 137 | character, with the filename used to store the PNG file 138 | } 139 | } 140 | %%\details{ 141 | %% ~~ If necessary, more details than the description above ~~ 142 | %%} 143 | \value{ 144 | a list with \code{nparam} elements, where is the number of parameters given in \code{params}, computed as the number of columns in \code{params}. 145 | 146 | Each element of the list contains the (weighted) empirical CDFs (ECDFs) for each parameter in \code{params}. 147 | 148 | Additionally, if \code{plot=TRUE} a maximum of \kbd{nfigs} different figures with the Empirical CDF for each model's parameter is produced, where the maximum number of figures to be produced is computed as \code{nfigs=ceiling(nparam/21)}. 149 | %% \item{comp1 }{Description of 'comp1'} 150 | %% \item{comp2 }{Description of 'comp2'} 151 | %% ... 152 | } 153 | %%\references{ 154 | %%} 155 | \author{ 156 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 157 | } 158 | %%\note{ 159 | %% ~~further notes~~ 160 | %%} 161 | 162 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 163 | 164 | \seealso{ 165 | \code{\link[Hmisc]{wtd.Ecdf}}, \code{\link{quant2ecdf}} 166 | } 167 | \examples{ 168 | \dontrun{ 169 | # Setting the user's home directory as working directory 170 | setwd("~") 171 | 172 | # matrix with 100 random uniform parameter sets (in rows) for 10 different model's 173 | # parameters (in columns) 174 | params <- matrix(rnorm(1000), ncol=10, nrow=100) 175 | colnames(params) <- paste("Param", 1:10, sep="") 176 | 177 | # empirical CDFs for each one of the 10 parameters in 'params', with equal weight 178 | # for each one of the 100 parameter sets 179 | params2ecdf(params, weights=rep(1,100)) 180 | } 181 | } 182 | % Add one or more standard keywords, see file 'KEYWORDS' in the 183 | % R documentation directory. 184 | \keyword{math} 185 | \keyword{manip} 186 | \keyword{graph} 187 | -------------------------------------------------------------------------------- /R/plot_ParamsPerIter.R: -------------------------------------------------------------------------------- 1 | # File plot_ParamsPerIter.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'plot_ParamsPerIter' # 9 | ################################################################################ 10 | # Purpose: It plots the value of each parameter and the objective # 11 | # function against the Number of Model Evaluations # 12 | 13 | plot_ParamsPerIter <- function(params, ...) UseMethod("plot_ParamsPerIter") 14 | 15 | ################################################################################ 16 | # Author : Mauricio Zambrano-Bigarini # 17 | ################################################################################ 18 | # Started: 30-Nov-2010 at JRC, Ispra # 19 | # Updates: 13-Oct-2011 # 20 | # 21-Feb-2012 ; 23-Mar-2012 # 21 | ################################################################################ 22 | plot_ParamsPerIter.default <- function(params, 23 | param.names=colnames(params), 24 | main=NULL, 25 | xlab="Number of evaluations", 26 | nrows="auto", 27 | cex=0.5, 28 | cex.main=1.2, 29 | cex.axis=1.7, 30 | cex.lab=1.5, 31 | col=rainbow(ncol(params)), 32 | lty=3, 33 | verbose=TRUE, 34 | ..., 35 | #### PNG options ### 36 | do.png=FALSE, 37 | png.width=1500, 38 | png.height=900, 39 | png.res=90, 40 | png.fname="Params_ValuePerRun.png" 41 | ) { 42 | 43 | # number of parameters 44 | nparam <- ncol(params) 45 | 46 | # Checking 'param.names' 47 | if (!identical(param.names, colnames(params))) { 48 | if (length(param.names) != nparam) { 49 | stop(paste("Invalid argument: 'length(param.names) = ", length(param.names), " != ", nparam, " = nparam'", sep="")) 50 | } else colnames(params) <- param.names 51 | } # IF end 52 | 53 | # Number of parameter sets 54 | nparsets <- nrow(params) 55 | 56 | ############################################################################ 57 | # 2) Plotting # 58 | ############################################################################ 59 | if (verbose) message( " ") 60 | if (verbose) message( "[ Plotting ... ]") 61 | 62 | if (do.png) png(filename=png.fname, width=png.width, height=png.height, res=png.res) 63 | 64 | # Computing the number of rows for the plot 65 | if (nrows == "auto") { 66 | if ( nparam <= 5 ) lnr <- 1 67 | if ( (nparam > 5) & (nparam <= 14) ) lnr <- 2 68 | if ( nparam > 14 ) lnr <- ceiling(nparam/7) 69 | } else lnr <- nrows 70 | 71 | # Saving default plotting parameters 72 | old.par <- par(no.readonly=TRUE) 73 | if (!do.png) on.exit(par(old.par)) 74 | 75 | # Defining the plotting window 76 | nr <- lnr 77 | nc <- ceiling(nparam/lnr) 78 | par(mfrow=c(nr,nc)) 79 | par(mar=c(5,4.5,1,2)+0.1) # Default: par(mar=c(5,4,4,2)+0.1) 80 | if (!is.null(main)) par(oma=c(1,1,3,0)) 81 | 82 | for ( i in 1:nparam ) 83 | plot(1:nparsets, params[,i], type="o", lty=lty, col=col[i], 84 | cex.main=cex.main, cex=cex, cex.lab=cex.lab, cex.axis=cex.axis, font.lab=2, 85 | xlim=c(1,nparsets), ylim=range(params[,i], na.rm=TRUE), 86 | xlab=xlab, ylab=param.names[i] ) 87 | 88 | # Adding a main title for the plot 89 | if (!is.null(main)) mtext(main, side=3, line=1, cex=cex.main, outer=TRUE) 90 | 91 | if (do.png) dev.off() 92 | } # 'plot_ParamsPerIter.default' END 93 | 94 | 95 | ################################################################### 96 | # Author : Mauricio Zambrano Bigarini # 97 | # Started: 13-Oct-2011 at JRC, Ispra # 98 | # Updates: 13-Oct-2011 # 99 | ################################################################### 100 | plot_ParamsPerIter.data.frame <- function(params, 101 | param.names=colnames(params), 102 | main=NULL, 103 | xlab="Number of evaluations", 104 | nrows="auto", 105 | cex=0.5, 106 | cex.main=1.2, 107 | cex.axis=1.7, 108 | cex.lab=1.5, 109 | col=rainbow(ncol(params)), 110 | lty=3, 111 | verbose=TRUE, 112 | ..., 113 | #### PNG options ### 114 | do.png=FALSE, 115 | png.width=1500, 116 | png.height=900, 117 | png.res=90, 118 | png.fname="Params_ValuePerRun.png" 119 | ) { 120 | 121 | #params <- as.matrix(params) 122 | 123 | plot_ParamsPerIter.default(params=params, 124 | param.names=param.names, 125 | main=main, 126 | xlab=xlab, 127 | nrows=nrows, 128 | cex=cex, 129 | cex.main=cex.main, 130 | cex.axis=cex.axis, 131 | cex.lab=cex.lab, 132 | col=col, 133 | lty=lty, 134 | verbose=verbose, 135 | ..., 136 | #### PNG options ### 137 | do.png=do.png, 138 | png.width=png.width, 139 | png.height=png.height, 140 | png.res=png.res, 141 | png.fname=png.fname 142 | ) 143 | } # 'plot_ParamsPerIter.data.frame' END 144 | 145 | 146 | ################################################################### 147 | # Author : Mauricio Zambrano Bigarini # 148 | # Started: 20-Oct-2011 at JRC, Ispra # 149 | # Updates: 20-Oct-2011 # 150 | ################################################################### 151 | plot_ParamsPerIter.matrix <- function(params, 152 | param.names=colnames(params), 153 | main=NULL, 154 | xlab="Number of evaluations", 155 | nrows="auto", 156 | cex=0.5, 157 | cex.main=1.2, 158 | cex.axis=1.7, 159 | cex.lab=1.5, 160 | col=rainbow(ncol(params)), 161 | lty=3, 162 | verbose=TRUE, 163 | ..., 164 | #### PNG options ### 165 | do.png=FALSE, 166 | png.width=1500, 167 | png.height=900, 168 | png.res=90, 169 | png.fname="Params_ValuePerRun.png" 170 | ) { 171 | 172 | plot_ParamsPerIter.default(params=params, 173 | param.names=param.names, 174 | main=main, 175 | xlab=xlab, 176 | nrows=nrows, 177 | cex=cex, 178 | cex.main=cex.main, 179 | cex.axis=cex.axis, 180 | cex.lab=cex.lab, 181 | col=col, 182 | lty=lty, 183 | verbose=verbose, 184 | ..., 185 | #### PNG options ### 186 | do.png=do.png, 187 | png.width=png.width, 188 | png.height=png.height, 189 | png.res=png.res, 190 | png.fname=png.fname 191 | ) 192 | } # 'plot_ParamsPerIter.matrix' END 193 | -------------------------------------------------------------------------------- /R/read_particles.R: -------------------------------------------------------------------------------- 1 | # File read_particles.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2011-2012 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'read_particles' # 9 | ################################################################################ 10 | # Author : Mauricio Zambrano-Bigiarini & Rodrigo Rojas # 11 | # Started: 08-Nov-2011, # 12 | # Updates: 17-Feb-2012 ; 09-Mar-2012 ; 12-Nov-2012 # 13 | ################################################################################ 14 | # This function reads the 'Particles.txt' ouput file of hydroPSO and returns # 15 | # a data.frame with the position and fitness value of all the particles in the # 16 | # swarm for all the iterations # 17 | # IMPORTANT: the GoF of the particles HAS TO BE located in the 3rd column of # 18 | # the file # 19 | ################################################################################ 20 | 21 | 22 | read_particles <- function(file="Particles.txt", 23 | verbose=TRUE, 24 | plot=TRUE, 25 | # Plotting arguments 26 | gof.name="GoF", 27 | MinMax=NULL, 28 | beh.thr=NA, 29 | beh.col="red", 30 | beh.lty=1, 31 | beh.lwd=2, 32 | nrows="auto", 33 | col="black", 34 | ylab=gof.name, 35 | main=NULL, 36 | pch=19, 37 | cex=0.5, 38 | cex.main=1.5, 39 | cex.axis=1.5, 40 | cex.lab=1.5, 41 | #..., 42 | breaks="Scott", 43 | freq=TRUE, 44 | do.pairs=FALSE, 45 | # Parameters for the 3D dotty plots 46 | dp3D.names="auto", 47 | GOFcuts="auto", 48 | colorRamp= colorRampPalette(c("darkred", "red", 49 | "orange", "yellow", "green", "darkgreen", "cyan")), 50 | alpha=1, 51 | points.cex=0.7, 52 | legend.pos="topleft", # not used yet,but included for avoiding warnings from 'plot_results' 53 | ##################################################### 54 | #### PNG options 55 | do.png=FALSE, 56 | png.width=1500, 57 | png.height=900, 58 | png.res=90, 59 | dotty.png.fname="Params_DottyPlots.png", 60 | hist.png.fname="Params_Histograms.png", 61 | bxp.png.fname="Params_Boxplots.png", 62 | ecdf.png.fname="Params_ECDFs.png", 63 | runs.png.fname="Params_ValuesPerRun.png", 64 | dp3d.png.fname="Params_dp3d.png", 65 | pairs.png.fname="Params_Pairs.png" 66 | ) { 67 | 68 | ############################################################################## 69 | # 1) Checkings # 70 | ############################################################################## 71 | # Checking that 'file' exists 72 | if ( !file.exists(file) ) 73 | stop( "Invalid argument value: The file '", basename(file), "' doesn't exist" ) 74 | 75 | # Checking 'beh.thr' 76 | if ( !is.na(beh.thr) ) { 77 | if ( is.null(MinMax) ) 78 | stop("Missing argument: 'MinMax' has to be provided before using 'beh.thr' !!") 79 | } # IF end 80 | 81 | # Checking 'MinMax' 82 | if ( !is.null(MinMax) ) { 83 | if ( !(MinMax %in% c("min", "max")) ) 84 | stop("Invalid argument: 'MinMax' must be in c('min', 'max')") 85 | } # IF end 86 | 87 | ############################################################################## 88 | # 2) Reading ALL the PARAMETER SETS # 89 | ############################################################################## 90 | # Reading the file 91 | if (verbose) message( " ") 92 | if (verbose) message( "[ Reading the file '", basename(file), "' ... ]" ) 93 | params <- read.table(file=file, header=TRUE, skip=0) 94 | 95 | # computing the number of columns 96 | ncols <- ncol(params) 97 | 98 | # Getting the goodness-of-fit of each particle 99 | gofs <- params[, 3] 100 | 101 | # Removing the first two colums with Iter and Part + the last column with GoF 102 | params <- params[, -c(1:3)] 103 | 104 | # Amount of total parameter sets 105 | nparamsets <- nrow(params) 106 | if (verbose) message( "[ Total number of parameter sets: ", nparamsets, " ]" ) 107 | 108 | # computing the number of parameters 109 | nparams <- ncol(params) 110 | 111 | # Filtering out those parameter sets above/below a certain threshold 112 | if (!is.na(beh.thr)) { 113 | # Checking 'beh.thr' 114 | mx <- max(gofs, na.rm=TRUE) 115 | if (beh.thr > mx) 116 | stop("Invalid argument: 'beh.thr' must be lower than ", mx ,"!!") 117 | 118 | # Computing the row index of the behavioural parameter sets 119 | ifelse(MinMax=="min", beh.row.index <- which(gofs <= beh.thr), 120 | beh.row.index <- which(gofs >= beh.thr) ) 121 | 122 | # Removing non-behavioural parameter sets and gofs 123 | params <- params[beh.row.index, ] 124 | gofs <- gofs[beh.row.index] 125 | 126 | # Amount of behavioural parameter sets 127 | nbeh <- nrow(params) 128 | if (verbose) message( "[ Number of behavioural parameter sets: ", nbeh, " ]" ) 129 | 130 | # To avoid problems with 'plot_params' 131 | if (plot) beh.thr <- NA 132 | } # IF end 133 | 134 | # Selecting best particle 135 | if ( !is.null(MinMax) ) { 136 | ifelse(MinMax=="min", best.row.index <- which.min(gofs), 137 | best.row.index <- which.max(gofs) ) 138 | part.best <- params[best.row.index, ] 139 | gof.best <- gofs[best.row.index] 140 | } else { 141 | part.best <- NA 142 | gof.best <- NA 143 | } # ELSE end 144 | 145 | ############################################################################## 146 | # 3) Plotting # 147 | ############################################################################## 148 | 149 | if (plot) plot_particles(params=params, #parameter values 150 | gofs=gofs, 151 | gof.name=gof.name, 152 | MinMax=MinMax, 153 | beh.thr=beh.thr, 154 | beh.col=beh.col, 155 | beh.lty=beh.lty, 156 | beh.lwd=beh.lwd, 157 | nrows=nrows, 158 | col=col, 159 | ylab=ylab, 160 | main=main, 161 | pch=pch, 162 | cex=cex, 163 | cex.main=cex.main, 164 | cex.axis=cex.axis, 165 | cex.lab=cex.lab, 166 | #..., 167 | breaks=breaks, 168 | freq=freq, 169 | do.pairs=do.pairs, 170 | # Parameters for the 3D dotty plots 171 | dp3D.names=dp3D.names, 172 | GOFcuts=GOFcuts, 173 | colorRamp= colorRamp, 174 | alpha=alpha, 175 | points.cex=points.cex, 176 | legend.pos=legend.pos, 177 | verbose=verbose, 178 | ##################################################### 179 | #### PNG options 180 | do.png=do.png, 181 | png.width=png.width, 182 | png.height=png.height, 183 | png.res=png.res, 184 | dotty.png.fname=dotty.png.fname, 185 | hist.png.fname=hist.png.fname, 186 | bxp.png.fname=bxp.png.fname, 187 | ecdf.png.fname=ecdf.png.fname, 188 | runs.png.fname=runs.png.fname, 189 | dp3d.png.fname=dp3d.png.fname, 190 | pairs.png.fname=pairs.png.fname 191 | ) 192 | 193 | ############################################################################## 194 | # 4) Output # 195 | ############################################################################## 196 | out <- list(part.params=params, part.gofs=gofs, best.param=part.best, best.gof=gof.best) 197 | 198 | return(out) 199 | 200 | } # 'read_particles' END 201 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /R/plot_NparOF.R: -------------------------------------------------------------------------------- 1 | # File plot_NparOF.R 2 | # Part of the hydroPSO R package, http://www.rforge.net/hydroPSO/ ; 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # Copyright 2010-2014 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 5 | # Distributed under GPL 2 or later 6 | 7 | ################################################################################ 8 | # 'plot_NparOF' # 9 | ################################################################################ 10 | # Author : Mauricio Zambrano Bigiarini # 11 | # Started: Nov 30th, 2010 # 12 | # Updates: 17-Jan-2011 ; 28-Jan-2011 ; 09-Mar-2011 # 13 | # 17-Feb-2012 ; 21-Feb-2012 ; 09-Mar-2012 ; 23-Mar-2012 ; 19-Nov-2012 # 14 | # 20-Nov-2012 ; 28-Nov-2012 # 15 | # 09-May-2013 # 16 | # 09-Abr-2013 # 17 | ################################################################################ 18 | # Purpose: For 'n' user-defined parameters, it produces 'sum(1:(npar-1))' # 19 | # 'plot_2parOF' plots, with the values of the objective function in # 20 | # a 2D box, where the boundaries of each parameter are used as axis. # 21 | # The 'sum(1:(npar-1)) plots corresponds to all the possible # 22 | # combinations of 2 parameters among all the 'n' parameters provided # 23 | ################################################################################ 24 | # nrows : numeric, with the amount of rows to be used in the plotting window. 25 | # If \code{nrows='auto'} the number of columns is automatically computed 26 | # depending on the number of parameters in \code{params} 27 | 28 | plot_NparOF <- function(params, 29 | gofs, 30 | param.names=colnames(params), 31 | MinMax=c(NULL, "min", "max"), 32 | beh.thr=NA, 33 | nrows="auto", 34 | gof.name="GoF", 35 | main=paste(gof.name, "Surface"), 36 | GOFcuts="auto", 37 | colorRamp= colorRampPalette(c("darkred", "red", "orange", "yellow", "green", "darkgreen", "cyan")), 38 | points.cex=0.7, 39 | alpha=0.65, 40 | axis.rot=c(0, 0), 41 | verbose=TRUE 42 | ) { 43 | 44 | 45 | ############################################################################## 46 | # 1) Checkings # 47 | ############################################################################## 48 | 49 | # Checking 'params' 50 | if (missing(params)) 51 | stop("Missing argument: 'params' must be provided !!" ) 52 | 53 | # Number of parameter sets 54 | n <- NROW(params) 55 | 56 | # Checking 'gofs' 57 | if (missing(gofs)) { 58 | stop("Missing argument: 'gofs' must be provided !!" ) 59 | } else if (length(gofs) != n) 60 | stop("Invalid argument: 'length(gofs) != nrow(params)' (", length(gofs), "!=", n, ") !!" ) 61 | 62 | # Setting 'MinMax' 63 | MinMax <- match.arg(MinMax) 64 | 65 | # Checking 'beh.thr' 66 | if ( !is.na(beh.thr) ) { 67 | if ( is.null(MinMax) ) 68 | stop("Missing argument: 'MinMax' has to be provided before using 'beh.thr' !!") 69 | if ( is.null(gofs) ) 70 | stop("Missing argument: 'gofs' has to be provided before using 'beh.thr' !!") 71 | } # IF end 72 | 73 | # Number of parameters that will be analysed 74 | npar <- length(param.names) 75 | 76 | # creating the variable that will store the position of the selected parameters within 'params' 77 | par.pos <- numeric(npar) 78 | 79 | # Checking 'param.names' 80 | for ( i in 1:npar) { 81 | if ( !(param.names[i] %in% colnames(params)) ) 82 | stop("Invalid argument: the field '", param.names[i], "' does not exist in 'params'") 83 | 84 | par.pos[i] <- which(colnames(params) == param.names[i]) 85 | } # FOR end 86 | 87 | 88 | ############################################################################## 89 | # 2) Computations # 90 | ############################################################################## 91 | 92 | # Filtering out those parameter sets above/below a certain threshold 93 | if (!is.na(beh.thr)) { 94 | # Checking 'beh.thr' 95 | mx <- max(gofs, na.rm=TRUE) 96 | if (beh.thr > mx) 97 | stop("Invalid argument: 'beh.thr' must be lower than ", mx ,"!!") 98 | 99 | # Computing the row index of the behavioural parameter sets 100 | ifelse(MinMax=="min", beh.row.index <- which(gofs <= beh.thr), 101 | beh.row.index <- which(gofs >= beh.thr) ) 102 | 103 | # Removing non-behavioural parameter sets & gofs 104 | params <- params[beh.row.index, ] 105 | gofs <- gofs[beh.row.index] 106 | 107 | # Amount of behavioural parameter sets 108 | nbeh <- nrow(params) 109 | if (verbose) message( "[ Number of behavioural parameter sets: ", nbeh, " ]" ) 110 | } # IF end 111 | 112 | 113 | 114 | # If the user didn't provide 'GOFcuts', the 5 quantiles are used 115 | if (length(GOFcuts) == 1){ 116 | if (GOFcuts=="auto") { 117 | if (MinMax=="min") { 118 | GOFcuts <- unique( quantile( as.numeric(gofs), 119 | probs=c(0, 0.25, 0.5, 0.85, 0.9, 0.97, 1), na.rm=TRUE) ) 120 | } else if (MinMax=="max") { 121 | GOFcuts <- unique( quantile( as.numeric(gofs), 122 | probs=c(0, 0.03, 0.1, 0.15, 0.5, 0.75, 1), na.rm=TRUE) ) 123 | } else # MinMax==NULL 124 | GOFcuts <- unique( quantile( as.numeric(gofs), 125 | probs=c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1), na.rm=TRUE) ) 126 | 127 | suppressWarnings( 128 | if (verbose) message( "[ Computed GOFcuts: ", 129 | paste(as.numeric(formatC( GOFcuts, format="E", digits=3, flag=" ")), collapse=" "), " ]" ) 130 | ) 131 | 132 | } # IF end 133 | } # IF end 134 | 135 | ############################################################################## 136 | # 3) Plotting # 137 | ############################################################################## 138 | 139 | # Number of plots that will be drawn 140 | nplots <- sum(1:(npar-1)) 141 | 142 | plots <- vector("list", nplots) 143 | 144 | pos <- 1 145 | for ( i in 1:(npar-1) ) { 146 | for (j in ((i+1):npar) ) { 147 | if (verbose) message("[ Plotting '", param.names[i], "' vs '", param.names[j], "' ]") 148 | plots[[pos]] <- plot_2parOF(params=params, gofs=gofs, MinMax=MinMax, p1.name=param.names[i], 149 | p2.name=param.names[j], gof.name=gof.name, 150 | type="sp", main="", GOFcuts=GOFcuts, colorRamp=colorRamp, 151 | alpha=alpha, axis.rot=axis.rot, auto.key=FALSE, 152 | points.cex=points.cex ) 153 | 154 | pos <- pos + 1 155 | } # FOR j end 156 | } # For i end 157 | 158 | # Computing the number of rows for the plot 159 | nplots <- nplots + 1 160 | if (nrows == "auto") { 161 | if ( nplots <= 5 ) lnr <- 1 162 | if ( (nplots > 5) & (nplots <= 14) ) lnr <- 2 163 | if ( nplots > 14 ) lnr <- ceiling(nplots/7) 164 | } else lnr <- nrows 165 | 166 | # Defining the plotting window 167 | nr <- lnr 168 | nc <- ceiling(nplots/lnr) 169 | #par(oma=c(1,1,3,0)) 170 | 171 | pos <- 1 172 | for (row in 1:nr) { 173 | for (col in 1:nc) { 174 | if (pos <= nplots) { 175 | if ( ( (row==nr) & (col==nc) ) | (pos==nplots) ) { 176 | #print(plots[[pos]], split = c(col, row, nc, nr), more = FALSE) 177 | } else print(plots[[pos]], split = c(col, row, nc, nr), more = TRUE) 178 | } # IF end 179 | pos <- pos + 1 180 | } # FOR end 181 | } # FOR end 182 | 183 | # Drawing the legend, with a dummy empty plot 184 | #gof.levels <- cut(gofs, GOFcuts) 185 | suppressWarnings( 186 | gof.levels <- cut(gofs, unique(as.numeric(formatC( GOFcuts, format="E", digits=4, flag=" ")))) 187 | ) 188 | nlevels <- length(levels(gof.levels)) 189 | 190 | #require(grid) 191 | a <- lattice::xyplot(1~1, 192 | groups=gof.levels, 193 | type="n", xlab="", ylab="", scales=list(draw=FALSE), 194 | key = list(x = .5, y = .5, corner = c(0.5, 0.5), 195 | title=gof.name, 196 | points = list(pch=16, col=colorRamp(nlevels), cex=1.5), 197 | text = list(levels(gof.levels), cex=0.8) # MZB: cex=0.8=leg.cex 198 | #text = list(formatC( as.numeric(levels(gof.levels)), format="E", digits=2, flag=" ")) 199 | ), 200 | # removing outter box. From: https://stat.ethz.ch/pipermail/r-help/2007-September/140098.html 201 | par.settings = list(axis.line = list(col = "transparent")), 202 | axis = function(side, ...) { 203 | lattice::axis.default(side = side, ...) 204 | } 205 | ) 206 | col <- nc -(nc*nr-nplots) 207 | print(a, split = c(col, nr, nc, nr), more = FALSE) 208 | 209 | } # 'plot_NparOF' END 210 | -------------------------------------------------------------------------------- /man/test_functions.Rd: -------------------------------------------------------------------------------- 1 | %% Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 2 | %% Copyright 2011-2021 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 3 | %% Distributed under GPL 2 or later 4 | 5 | \name{test_functions} 6 | \alias{ackley} 7 | \alias{griewank} 8 | \alias{rastrigrin} 9 | \alias{rastrigin} 10 | \alias{rosenbrock} 11 | \alias{schafferF6} 12 | \alias{schwefel} 13 | \alias{sphere} 14 | \alias{sackley} 15 | \alias{sgriewank} 16 | \alias{srastrigin} 17 | \alias{srosenbrock} 18 | \alias{sschwefel1_2} 19 | \alias{ssphere} 20 | 21 | %- Also NEED an '\alias' for EACH other topic documented here. 22 | \title{ 23 | Test Functions for Global Optimisation 24 | } 25 | \description{ 26 | Test functions commonly used as benchmark for global optimisation problems 27 | } 28 | \usage{ 29 | ackley(x) 30 | griewank(x) 31 | rastrigin(x) 32 | rosenbrock(x) 33 | schafferF6(x) 34 | schwefel(x) 35 | sphere(x) 36 | sackley(x, o=-32+64*runif(length(x)), fbias=-140) 37 | sgriewank(x, o=-600+1200*runif(length(x)), fbias=-180) 38 | srastrigin(x, o=-5+10*runif(length(x)), fbias=-330) 39 | srosenbrock(x, o=-100+200*runif(length(x)), fbias=390) 40 | sschwefel1_2(x, o=-100+200*runif(length(x)), fbias=-450) 41 | ssphere(x, o=-100+200*runif(length(x)), fbias=-450) 42 | 43 | } 44 | %- maybe also 'usage' for other objects documented here. 45 | \arguments{ 46 | \item{x}{ 47 | numeric vector to be evaluated 48 | } 49 | \item{o}{ 50 | numeric shifting vector to be used, with the same length of \code{x} 51 | } 52 | \item{fbias}{ 53 | numeric with the bias to be imposed 54 | } 55 | } 56 | \details{ 57 | The \bold{Ackley} test function is multimodal and separable, with several local optima that, for the search range [-32, 32], look more like noise, although they are located at regular intervals. The Ackley function only has one global optimum located at the point \kbd{o=(0,...,0)}. It is defined by: 58 | \deqn{ ackley = 20+\exp(1)-20\exp\left( -0.2\sqrt{\frac{1}{n}\sum_{i=1}^{n}x_{i}^2} \right)-\exp\left(\frac{1}{n}\sum_{i=1}^{n}\cos(2\pi x_{i})\right) ; -32 \leq x_i \leq 32 \ ; \ i=1,2,\ldots,n } 59 | 60 | 61 | The generalized \bold{Rastrigin} test function is non-convex, multimodal and additively separable. It has several local optima arranged in a regular lattice, but it only has one global optimum located at the point \kbd{o=(0,...,0)}. The search range for the Rastrigin function is [-5.12, 5.12] in each variable. This function is a fairly difficult problem due to its large search space and its large number of local minima. It is defined by: 62 | 63 | \deqn{ rastrigin = 10n+\sum_{i=1}^{n}\left[x_{i}^{2}-10\cos(2\pi x_{i})\right] \ ; \ -5.12 \leq x_i \leq 5.12 \ ; \ i=1,2,\ldots,n } 64 | 65 | 66 | The \bold{Griewank} test function is multimodal and non-separable, with several local optima within the search region defined by [-600, 600]. It is similar to the Rastrigin function, but the number of local optima is larger in this case. It only has one global optimum located at the point \kbd{o=(0,...,0)}. The function interpretation changes with the scale; the general overview suggests convex function, medium-scale view suggests existence of local minima, and finally zoom on the details indicates complex structure of numerous local minima. While this function has an exponentially increasing number of local minima as its dimension increases, it turns out that a simple multistart algorithm is able to detect its global minimum more and more easily as the dimension increases (Locatelli, 2003). It is defined by: 67 | 68 | \deqn{ griewank = \frac{1}{4000}\sum_{i=1}^{n}x_{i}^{2}-\prod_{i=1}^{n}\cos\left(\frac{x_i}{\sqrt{i}}\right)+1 \ ; \ -600 \leq x_i \leq 600 \ ; \ i=1,2,\ldots,n } 69 | 70 | 71 | The \bold{Rosenbrock} function is non-convex, unimodal and non-separable. It is also known as \emph{Rosenbrock's valley} or \emph{Rosenbrock's banana} function. The global minimum is inside a long, narrow, parabolic shaped flat valley. To find the valley is trivial. To converge to the global minimum, however, is difficult. It only has one optimum located at the point \kbd{o=(1,...,1)}. It is a quadratic function, and its search range is [-30, 30] for each variable. It is defined by: 72 | 73 | \deqn{ rosenbrock = \sum_{i=1}^{n-1}\left[100(x_{i+1}-x_{i}^{2})^{2}+(1-x_{i})^{2}\right] \ ; \ -30 \leq x_i \leq 30 \ ; \ i=1,2,\ldots,n } 74 | 75 | 76 | The main difficulty of the \bold{Schaffer's F6} test function is that the size of the potential maxima that need to be overcome to get to a minimum increases the closer 77 | one gets to the global minimum. It is defined by: 78 | 79 | \deqn{ schafferF6 = 0.5+\frac{\sin^{2}\sqrt{\sum_{i=1}^{n}x_{i}^{2}}-0.5}{(1+0.001\sum_{i=1}^{n}x_{i}^{2})^{2}} \ ; \ -100 \leq x_i \leq 100 \ ; \ i=1,2,\ldots,n } \cr 80 | 81 | 82 | The \emph{first function of De Jong's} or \bold{Sphere} function is one of the most simple test functions available in the specialized literature. This continuous, convex, unimodal and additively separable test function can be scaled up to any number of variables. It belongs to a family of functions called quadratic functions and only has one optimum in the point \kbd{o=(0,...,0)}. The search range commonly used for the Sphere function is [-100, 100] for each decision variable. It is defined by: 83 | 84 | \deqn{ sphere = \sum_{i=1}^{n} x_{i}^2 \ ; \ -100 \leq x_i \leq 100 \ ; \ i=1,2,\ldots,n } \cr 85 | 86 | 87 | The \bold{Schwefel's} function is non-convex, multimodal, and additively separable. It is deceptive in that the global minimum is geometrically distant, over the parameter space, from the next best local minima. Therefore, the search algorithms are potentially prone to convergence in the wrong direction. In addition, it is less symmetric than the Rastrigin function and has the global minimum at the edge of the search space [-500, 500] at position \kbd{o=(420.9687,...,420.9687)}. Additionally, there is no overall, guiding slope towards the global minimum like in Ackley's, or less extreme, in Rastrigin's function. It is defined by: 88 | 89 | \deqn{ schwefel = 418.982887274338n + \sum_{i=1}^{n} -x_{i} \sin(\sqrt{|x_{i}|} \ ; \ -500 \leq x_i \leq 500 \ ; \ i=1,2,\ldots,n } 90 | 91 | 92 | The \bold{Shifted Schwefel's Problem 1.2} function is unimodal, non-separable, and scalable. It is defined by: 93 | 94 | \deqn{ sschwefel1\_2 = \sum_{i=1}^{n} { \left(\sum_{j=1}^{i} {x_{j}} \right)^2 } + f\_bias \ ; \ -500 \leq x_i \leq 500 \ ; \ i=1,2,\ldots,n } \cr 95 | 96 | 97 | Some optimisation algorithms take advantage of known properties of the benchmark functions, such as local optima lying along the coordinate axes, global optimum having the same values for many variables and so on. In order to avoid the previous shortcomings, shifting vector and a single bias is introduced for some benchmark functions, reported afterwards. 98 | 99 | The \bold{Shifted Ackley} is defined by: 100 | \deqn{ sackley = 20+\exp(1)-20\exp\left(-0.2\sqrt{\frac{1}{n}\sum_{i=1}^{n}z_{i}^2}\right)-\exp\left(\frac{1}{n}\sum_{i=1}^{n}\cos(2\pi z_{i})\right) + f\_bias , z=x-o ; \ i=1,2,\ldots,n } \cr 101 | 102 | The \bold{Shifted Griewank} is defined by: 103 | \deqn{ sgriewank = \frac{1}{4000}\sum_{i=1}^{n}z_{i}^{2}-\prod_{i=1}^{n}\cos\left(\frac{z_i}{\sqrt{i}}\right)+1 + f\_bias \ , \ z=x-o ; \ i=1,2,\ldots,n } \cr 104 | 105 | The \bold{Shifted Sphere} is defined by: 106 | \deqn{ ssphere = \sum_{i=1}^{n} z_{i}^2 + f\_bias \ , \ z=x-o ; \ i=1,2,\ldots,n }{% 107 | sphere = sum( x^2 ) } 108 | } 109 | \value{ 110 | Each test function returns a single numeric value corresponding to the function evaluated on the vector \code{x} 111 | %% If it is a LIST, use 112 | %% \item{comp1 }{Description of 'comp1'} 113 | %% \item{comp2 }{Description of 'comp2'} 114 | %% ... 115 | } 116 | \references{ 117 | 118 | \cite{Dieterich, J.M. and B.Hartke. 2012. Empirical review of standard benchmark functions using evolutionary global optimization. Appl.Math. 3. 1552-1564, DOI:10.4236/am.2012.330215}\cr 119 | 120 | \cite{Barrera, J., and C. Coello Coello. 2010, Test function generators for assessing the performance of PSO algorithms in multimodal optimization, in Handbook of Swarm Intelligence, vol. 8, edited by B. Panigrahi, Y. Shi, and M.-H. Lim, chap. Adaptation, Learning, and Optimization, pp. 89-117, Springer Berlin Heidelberg, doi:10.1007/978-3-642-17390-5 4}\cr 121 | 122 | Problem Definitions and Evaluation Criteria for the CEC 2005 Special Session on Real-Parameter Optimization \cite{\url{http://www.cmap.polytechnique.fr/~nikolaus.hansen/Tech-Report-May-30-05.pdf}}\cr 123 | 124 | Test functions for optimization needs: \cite{\url{https://robertmarks.org/Classes/ENGR5358/Papers/functions.pdf}}\cr 125 | 126 | 127 | \bold{Web pages}: 128 | 129 | Test functions for optimization. \cite{\url{https://en.wikipedia.org/wiki/Test_functions_for_optimization}} 130 | 131 | Benchmark Problems \cite{\url{http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume24/ortizboyer05a-html/node6.html}} 132 | 133 | Test Functions for Unconstrained Global Optimization \cite{\url{http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/Page364.htm}} 134 | 135 | Rosenbrock: \cite{\url{https://www.sfu.ca/~ssurjano/rosen.html}}, \cite{\url{https://en.wikipedia.org/wiki/Rosenbrock_function}} 136 | 137 | Sphere: \cite{\url{https://www.sfu.ca/~ssurjano/spheref.html}} 138 | 139 | Rastrigin: \cite{\url{https://www.sfu.ca/~ssurjano/rastr.html}}, \cite{\url{https://en.wikipedia.org/wiki/Rastrigin_function}} 140 | 141 | Ackley: \cite{\url{https://www.sfu.ca/~ssurjano/ackley.html}} 142 | 143 | Griewank: \cite{Locatelli, M. 2003. A note on the griewank test function, Journal of Global Optimization, 25 (2), 169-174, doi:10.1023/A:1021956306041} 144 | 145 | Schaffer's F6 \cite{Xiaohong Qiu, Jun Liu. 2009. A Novel Adaptive PSO Algorithm on Schaffer's F6 Function. Hybrid Intelligent Systems, International Conference on, pp. 94-98, 2009 Ninth International Conference on Hybrid Intelligent Systems} 146 | 147 | Schwefel: \cite{\url{https://www.sfu.ca/~ssurjano/schwef.html}} 148 | } 149 | 150 | \author{ 151 | Mauricio Zambrano-Bigiarini, \email{mzb.devel@gmail.com} 152 | } 153 | %%\note{ 154 | %% ~~further notes~~ 155 | %%} 156 | 157 | %% ~Make other sections like Warning with \section{Warning }{....} ~ 158 | 159 | \seealso{ 160 | \code{\link{hydroPSO}} 161 | } 162 | %%\examples{ 163 | 164 | %%} 165 | % Add one or more standard keywords, see file 'KEYWORDS' in the 166 | % R documentation directory. 167 | \keyword{optim} 168 | \keyword{math}% __ONLY ONE__ keyword per line 169 | -------------------------------------------------------------------------------- /R/plot_out.R: -------------------------------------------------------------------------------- 1 | # File plot_out.R 2 | # Part of the hydroPSO R package, https://github.com/hzambran/hydroPSO 3 | # http://cran.r-project.org/web/packages/hydroPSO 4 | # http://www.rforge.net/hydroPSO/ 5 | # Copyright 2012-2020 Mauricio Zambrano-Bigiarini & Rodrigo Rojas 6 | # Distributed under GPL 2 or later 7 | 8 | ################################################################################ 9 | # 'plot_out' # 10 | ################################################################################ 11 | # Purpose: This function plot the values of the objective function / model for # 12 | # each particle and iteration # 13 | ################################################################################ 14 | # Output : list with two elements: # 15 | # -) sim: numeric with the best simulated values of the model / # 16 | # objective function among all the particles and iterations # 17 | # -) obs: numeric with the observed values used during the optimisation# 18 | ################################################################################ 19 | # Author : Mauricio Zambrano-Bigiarini # 20 | # Started: 03-Feb-2012 # 21 | # Updates: 15-Feb-2012 ; 22-Feb-2012 ; 28-Jun-2012 ; 26-Sep-2012 # 22 | # 21-Feb-2013 # 23 | # 10-Jun-2018 # 24 | # 29-Feb-2020 # 25 | # 02-Nov-2025 # 26 | ################################################################################ 27 | 28 | plot_out <- function(sim, obs, 29 | dates=NULL, 30 | ptype=c("corr", "ts", "ecdf", "quant2ecdf"), 31 | MinMax=NULL, 32 | #beh.thr=NA, 33 | ftype="o", # OPTIONAL, only used when 'ptype=="ts"'.See [hydroGOF]{ggof} 34 | FUN=mean, # OPTIONAL, only used when 'ptype=="ts"'.See [hydroGOF]{ggof} 35 | verbose=TRUE, 36 | 37 | #### OPTIONS for ptype="quant2ecdf' ##### 38 | weights=NULL, 39 | byrow=TRUE, 40 | quantiles.desired= c(0.05, 0.5, 0.95), 41 | quantiles.labels= c("Q5", "Q50", "Q95"), 42 | main=NULL, 43 | ylab="Probability", 44 | col="blue", 45 | 46 | # General plotting options 47 | leg.cex=1.2, 48 | leg.pos="bottomright", 49 | cex.axis=1.2, 50 | cex.main=1.2, 51 | cex.lab=1.2, 52 | 53 | #### PNG options ### 54 | do.png=FALSE, 55 | png.width=1500, 56 | png.height=900, 57 | png.res=90, 58 | png.fname="ModelOut_vs_Obs.png") { 59 | 60 | 61 | ############################################################################## 62 | # 1) Checkings # 63 | ############################################################################## 64 | # Checking 'sim' 65 | if ( missing(sim) ) stop( "Missing argument: 'sim'" ) 66 | 67 | # Checking 'obs' 68 | if ( missing(obs) ) stop( "Missing argument: 'obs'" ) 69 | 70 | # Setting 'ptype' 71 | ptype <- match.arg(ptype) 72 | 73 | # The following type of plots do not require zoo objects 74 | if (ptype %in% c("corr", "ecdf", "quant2ecdf") ) { 75 | if ( is.zoo(sim) ) sim <- zoo::coredata(sim) 76 | if ( is.zoo(obs) ) obs <- zoo::coredata(obs) 77 | } # IF end 78 | 79 | # The following type of plot do require zoo objects 80 | if (ptype == "ts") { 81 | if ( is.zoo(obs) & !is.integer(time(obs)) ) { 82 | if ( !is.zoo(sim) ) { 83 | sim <- zoo::as.zoo(sim) 84 | time(sim) <- time(obs) 85 | } # IF end 86 | } # IF end 87 | } # IF end 88 | 89 | # number of model outputs for each parameter set 90 | ifelse( (is.matrix(sim) | is.data.frame(sim)), nouts <- ncol(sim), 91 | nouts <- length(sim)) 92 | 93 | # Checking dates' length 94 | if (!is.null(dates)) { 95 | if ( length(dates) != nouts) 96 | stop("Invalid argument: 'length(dates) != length(sim)' ", length(dates), "!=", nouts, " !!") 97 | } #IF end 98 | 99 | # # Checking 'MinMax' 100 | # if ( is.null(MinMax) ) { 101 | # stop("Missing argument: 'MinMax' must be provided !!") 102 | # } else if ( !(MinMax %in% c("min", "max")) ) 103 | # stop("Invalid argument: 'MinMax' must be in c('min', 'max')") 104 | 105 | # Checking 'hydroGOF' pacakge when ptype=="ts" 106 | if (ptype=="ts") { 107 | if ( length(find.package("hydroGOF", quiet=TRUE)) == 0 ) 108 | stop("Invalid argument: You don't have the 'hydroGOF' package => You can not use 'ptype='ts' !!") 109 | } # IF end 110 | 111 | # Checking 'class(sim)' 112 | if ( ptype=="corr") { 113 | if ( !(class(sim) %in% c("numeric", "integer") ) ) 114 | stop("Invalid argument: 'class(sim)' must be in c('numeric', 'integer') for 'ptype' in c('corr', 'ts') !!") 115 | } else if ( (ptype=="ecdf") | (ptype=="quant2ecdf") ) { 116 | # if ( (class(sim) != "matrix") & (class(sim) != "data.frame") ) 117 | # stop("Invalid argument: 'class(sim)' must be in c('matrix', 'data.frame') for 'ptype' in c('ecdf', 'quant2ecdf') !!") 118 | } # ELSe end 119 | 120 | 121 | ############################################################################## 122 | # 2) Plotting # 123 | ############################################################################## 124 | 125 | # 1) Plotting Observed against Simulated values 126 | if ( (ptype=="corr") | (ptype=="ts") ) { 127 | msg <- "[ Plotting best simulated values vs observations" 128 | } else if ( (ptype=="ecdf") | (ptype=="quant2ecdf") ) { 129 | msg <- "[ Plotting ECDFs of simulated quantiles vs observations" 130 | } # ELSE end 131 | if (do.png) msg <- paste(msg, " into '", basename(png.fname), sep="") 132 | msg <- paste(msg, "' ... ]", sep="") 133 | if (verbose) message(msg) 134 | 135 | # PNG output ? 136 | if (do.png) { 137 | if (ptype=="corr") { png(filename= png.fname, width= min(png.width, png.height), height= min(png.width, png.height), res=png.res) 138 | } else if (ptype!="ecdf") png(filename= png.fname, width = png.width, height = png.height, res=png.res) 139 | } #IF end 140 | 141 | if (ptype=="corr") { 142 | 143 | lm.os <- lm(sim ~ obs) 144 | axis.lims <- range(sim, obs, na.rm=TRUE) 145 | plot(obs, sim, xlab="Observations", ylab="Best Simulation", 146 | ylim=axis.lims, xlim=axis.lims, cex.axis=1.2, cex.main=1.2, cex.lab=1.2, panel.first=grid() ) 147 | abline(lm.os, col="grey", lty=3) 148 | r2 <- (cor(sim, obs, use="complete.obs"))^2 149 | legend("right", legend=paste("R2=", round(r2,4), sep=""), inset=0.02 ) 150 | 151 | } else if (ptype=="ts") { 152 | if (is.null(main)) main="Observed vs 'best' Simulation" 153 | 154 | if (!is.null(dates)) { 155 | if (!is.zoo(obs)) obs <- zoo(obs, dates) # zoo::is.zoo ; zoo::zoo 156 | if (!is.zoo(sim)) sim <- zoo(sim, dates) # zoo::is.zoo ; zoo::zoo 157 | } # IF end 158 | 159 | # Plotting Sim vs Obs 160 | hydroGOF::ggof(sim=sim, obs=obs, main=main, ftype=ftype, FUN=FUN, 161 | cex.main=cex.main, cex.axis=cex.axis, cex.lab=cex.lab, leg.cex=leg.cex) # dates.fmt="%Y-%m-%d") 162 | 163 | # Computing several GoFs between the best behavioural simulation and the observed values 164 | #if (verbose) message(" ") 165 | #if (verbose) message("GoFs between 'obs' and 'best' simulation: ") 166 | #if (verbose) print( gof(sim=sim, obs=obs, ...) ) 167 | #if (verbose) print( gof(sim=sim, obs=obs) ) 168 | 169 | } else if (ptype=="ecdf") { 170 | 171 | params2ecdf(params=sim, 172 | #param.names=NULL, 173 | weights=weights, 174 | byrow=byrow, 175 | plot=TRUE, 176 | obs=obs, 177 | main=main, 178 | nrows="auto", 179 | ylab=ylab, 180 | col=col, 181 | leg.cex=leg.cex, 182 | leg.pos=leg.pos, 183 | cex.axis=cex.axis, 184 | cex.main=cex.main, 185 | cex.lab=cex.lab, 186 | verbose=TRUE, 187 | do.png=do.png, 188 | png.width=png.width, 189 | png.height=png.height, 190 | png.res=png.res, 191 | png.fname=png.fname) 192 | 193 | } else if (ptype=="quant2ecdf") { 194 | 195 | quant2ecdf(sim=sim, 196 | weights=weights, 197 | byrow=byrow, 198 | quantiles.desired= quantiles.desired, 199 | plot=TRUE, 200 | obs=obs, 201 | quantiles.labels= quantiles.labels, 202 | main=main, 203 | ylab=ylab, 204 | col=col, 205 | leg.cex=leg.cex, 206 | leg.pos=leg.pos, 207 | cex.axis=cex.axis, 208 | cex.main=cex.main, 209 | cex.lab=cex.lab, 210 | verbose=verbose) 211 | 212 | 213 | } # ELSE end 214 | 215 | if (do.png & (ptype!="ecdf")) dev.off() 216 | 217 | } # 'plot_out' END 218 | --------------------------------------------------------------------------------