├── .Rbuildignore ├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── RcppExports.R ├── api_check.R ├── bayes_colors.R ├── bayes_label.R ├── bayes_plot.R ├── bayes_read.R ├── bayes_smooth.R ├── bayes_utils.R ├── bayes_variance.R └── zzz.R ├── README.Rmd ├── README.md ├── bayesEO.Rproj ├── inst └── extdata │ ├── config.yml │ ├── config_colors.yml │ ├── example │ └── example.R │ ├── probs │ └── SENTINEL-2_MSI_20LLQ_2020-06-04_2021-08-26_probs_v0.tif │ └── rgb │ ├── SENTINEL-2_MSI_20LLQ_B02_2021-09-22.tif │ ├── SENTINEL-2_MSI_20LLQ_B11_2021-09-22.tif │ └── SENTINEL-2_MSI_20LLQ_B8A_2021-09-22.tif ├── man ├── bayes_colors.Rd ├── bayes_colors_show.Rd ├── bayes_label.Rd ├── bayes_plot_hist.Rd ├── bayes_plot_map.Rd ├── bayes_plot_probs.Rd ├── bayes_plot_rgb.Rd ├── bayes_plot_var.Rd ├── bayes_read_image.Rd ├── bayes_read_probs.Rd ├── bayes_run_examples.Rd ├── bayes_run_tests.Rd ├── bayes_smooth.Rd ├── bayes_summary.Rd ├── bayes_variance.Rd ├── bilateral_smooth.Rd ├── dot-smooth_gauss_kernel.Rd ├── figures │ ├── README-pcube-1.png │ ├── README-unnamed-chunk-4-1.png │ └── README-unnamed-chunk-5-1.png └── gaussian_smooth.Rd ├── src ├── Makevars ├── Makevars.win ├── RcppExports.cpp ├── bayes_smooth.cpp ├── label_class.cpp └── other_smoothers.cpp └── tests ├── testthat.R └── testthat └── test-bayes.R /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^.*\.py$ 3 | ^\.Rproj\.user$ 4 | ^\.drone.yml$ 5 | ^packrat/ 6 | ^\.Rprofile$ 7 | ^\.RData$ 8 | ^\.tmp$ 9 | ^README\.Rmd$ 10 | ^README\.md$ 11 | ^README_cache$ 12 | ^man/figures/*$ 13 | ^doc$ 14 | ^Meta$ 15 | ^tic\.R$ 16 | ^CODE_OF_CONDUCT.md$ 17 | ^contributing.md$ 18 | ^\.gcda$ 19 | ^\.gcno$ 20 | ^tags 21 | ^\.swp 22 | ^codemeta.json 23 | LICENSE 24 | 25 | ^\.github$ 26 | ^codecov\.yml$ 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | .Rapp.history 4 | .Rproj.user 5 | .Rprofile 6 | .Ruserdata 7 | 8 | # Session Data files 9 | .RData 10 | .RDataTmp 11 | 12 | # User-specific files 13 | .Ruserdata 14 | 15 | # Example code in package build process 16 | *-Ex.R 17 | 18 | # Output files from R CMD build 19 | /*.tar.gz 20 | 21 | # Output files from R CMD check 22 | /*.Rcheck/ 23 | 24 | # RStudio files 25 | .Rproj.user/ 26 | 27 | # produced vignettes 28 | vignettes/*.html 29 | vignettes/*.pdf 30 | 31 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 32 | .httr-oauth 33 | 34 | # knitr and R markdown default cache directories 35 | *_cache/ 36 | /cache/ 37 | 38 | # Temporary files created by R markdown 39 | *.utf8.md 40 | *.knit.md 41 | 42 | # R Environment Variables 43 | .Renviron 44 | 45 | # pkgdown site 46 | docs/ 47 | 48 | # translation temp files 49 | po/*~ 50 | 51 | # RStudio Connect folder 52 | rsconnect/ 53 | # Other 54 | README_cache/* 55 | README_files/* 56 | .DS_Store 57 | src/*.o 58 | src/*.dll 59 | src/*.so 60 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: bayesEO 2 | Type: Package 3 | Version: 0.2.1 4 | Title: Bayesian Smoothing of Remote Sensing Image Classification 5 | Authors@R: c(person('Gilberto', 'Camara', role = c('aut', 'cre'), email = 'gilberto.camara.inpe@gmail.com'), 6 | person('Renato', 'Assuncao', role = c('aut'), email = 'assuncaoest@gmail.com'), 7 | person('Rolf', 'Simoes', role = c('aut'), email = 'rolf.simoes@inpe.br'), 8 | person('Felipe', 'Souza', role = c('aut'), email = 'felipe.carvalho@inpe.br') 9 | ) 10 | Maintainer: Gilberto Camara 11 | Description: A Bayesian smoothing method for post-processing of remote 12 | sensing image classification which refines the 13 | labelling in a classified image in order to enhance its classification accuracy. 14 | Combines pixel-based classification methods with a spatial post-processing 15 | method to remove outliers and misclassified pixels. 16 | Encoding: UTF-8 17 | Language: en-US 18 | Depends: R (>= 4.0.0) 19 | URL: https://github.com/e-sensing/bayesEO/ 20 | BugReports: https://github.com/e-sensing/bayesEO/issues 21 | License: GPL-3 22 | ByteCompile: true 23 | LazyData: true 24 | Imports: 25 | dplyr, 26 | ggplot2, 27 | grDevices, 28 | purrr, 29 | Rcpp, 30 | stars, 31 | stats, 32 | terra, 33 | tibble, 34 | tidyr, 35 | tmap, 36 | yaml 37 | Suggests: 38 | RcppArmadillo, 39 | testthat 40 | LinkingTo: 41 | Rcpp, 42 | RcppArmadillo 43 | RoxygenNote: 7.3.1 44 | Collate: 45 | 'api_check.R' 46 | 'bayes_colors.R' 47 | 'bayes_label.R' 48 | 'bayes_plot.R' 49 | 'bayes_read.R' 50 | 'bayes_smooth.R' 51 | 'bayes_utils.R' 52 | 'bayes_variance.R' 53 | 'RcppExports.R' 54 | 'zzz.R' 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(bayes_colors) 4 | export(bayes_colors_show) 5 | export(bayes_label) 6 | export(bayes_plot_hist) 7 | export(bayes_plot_map) 8 | export(bayes_plot_probs) 9 | export(bayes_plot_rgb) 10 | export(bayes_plot_var) 11 | export(bayes_read_image) 12 | export(bayes_read_probs) 13 | export(bayes_run_examples) 14 | export(bayes_run_tests) 15 | export(bayes_smooth) 16 | export(bayes_summary) 17 | export(bayes_variance) 18 | export(bilateral_smooth) 19 | export(gaussian_smooth) 20 | importFrom(Rcpp,sourceCpp) 21 | importFrom(dplyr,.data) 22 | useDynLib(bayesEO, .registration = TRUE) 23 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | bayes_smoother_fraction <- function(logits, nrows, ncols, window_size, smoothness, neigh_fraction) { 5 | .Call(`_bayesEO_bayes_smoother_fraction`, logits, nrows, ncols, window_size, smoothness, neigh_fraction) 6 | } 7 | 8 | bayes_var <- function(m, m_nrow, m_ncol, w, neigh_fraction) { 9 | .Call(`_bayesEO_bayes_var`, m, m_nrow, m_ncol, w, neigh_fraction) 10 | } 11 | 12 | C_label_max_prob <- function(x) { 13 | .Call(`_bayesEO_C_label_max_prob`, x) 14 | } 15 | 16 | kernel_smoother <- function(m, m_nrow, m_ncol, w, normalised) { 17 | .Call(`_bayesEO_kernel_smoother`, m, m_nrow, m_ncol, w, normalised) 18 | } 19 | 20 | bilateral_smoother <- function(m, m_nrow, m_ncol, w, tau) { 21 | .Call(`_bayesEO_bilateral_smoother`, m, m_nrow, m_ncol, w, tau) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /R/api_check.R: -------------------------------------------------------------------------------- 1 | #' @title Check functions 2 | #' 3 | #' @name check_functions 4 | #' 5 | #' @description 6 | #' Functions used to check parameters in a systematic way. 7 | #' 8 | #' @param caller A \code{character} value with the caller name. 9 | #' @param x Any object that will be evaluated. 10 | #' @param local_msg A \code{character} with the generic error message that 11 | #' will be shown inside parenthesis. 12 | #' @param msg A \code{character} with the error message that will be 13 | #' shown as the main message to the user. 14 | #' @param is_named A \code{logical} indicating if the check permits unnamed 15 | #' list. 16 | #' @param len_min A \code{numeric} indicating the minimum length of vector 17 | #' or list users provides for functions. Default is \code{0}. 18 | #' @param len_max A \code{numeric} indicating the maximum length of vector 19 | #' or list users provides for functions. Default is \code{2^31}. 20 | #' @param fn_check A \code{function} used to test each element of an 21 | #' object. 22 | #' @param is_integer A \code{logical} indicating if the value should be 23 | #' integer. 24 | #' @param allow_na A \code{logical} indicating if the check permits empty 25 | #' NA values. Default is FALSE. 26 | #' @param allow_null A \code{logical} indicating if the check permits empty 27 | #' NULL values. Default is FALSE. 28 | #' @param min A atomic \code{vector} of numeric indicating the 29 | #' inclusive minimum value that the user can provide in function parameter. 30 | #' Only works for numeric check. By default it is \code{-Inf}. 31 | #' @param max A atomic \code{vector} of numeric indicating the 32 | #' inclusive maximum value that the user can provide in function parameter. 33 | #' Only works for numeric check. By default it is \code{Inf}. 34 | #' @param exclusive_min A atomic \code{vector} of numeric indicating the 35 | #' exclusive minimum value that the user can provide in function parameter. 36 | #' Only works for numeric check. By default it is \code{-Inf}. 37 | #' @param exclusive_max A atomic \code{vector} of numeric indicating the 38 | #' exclusive maximum value that the user can provide in function parameter. 39 | #' Only works for numeric check. By default it is \code{Inf}. 40 | #' @param allow_empty A \code{logical} indicating if the check permits empty 41 | #' list. Default is TRUE. 42 | #' @param regex A \code{character} value with regular expression to be 43 | #' evaluated against data. 44 | #' @param min_len A \code{numeric} indicating the minimum length of vector 45 | #' or list users provides for functions. Default is \code{0}. 46 | #' @param max_len A \code{numeric} indicating the maximum length of vector 47 | #' or list users provides for functions. Default is \code{2^31}. 48 | #' @param within A \code{character} vector indicating a set of elements 49 | #' from which \code{x} is a kind of subset. The actual behavior is pointed by 50 | #' \code{discriminator} parameter. 51 | #' @param discriminator A \code{character} value indicating how subset 52 | #' verification will be done (see details). 53 | #' @param contains A \code{character} vector indicating a set of elements 54 | #' to which \code{x} is a kind of superset. The actual behavior is pointed by 55 | #' \code{discriminator} parameter. 56 | #' @param case_sensitive A \code{logical} indicating if the check is compared 57 | #' with case sensitive. Default is \code{TRUE}. 58 | #' @param can_repeat A \code{logical} value indicating if vector \code{x} 59 | #' can have repeated elements or not. 60 | #' @param extensions A \code{character} vector with all allowed file 61 | #' extensions. 62 | #' @param expr A R \code{expression} to be evaluated. 63 | #' @param show_pks_name A \code{logical} value indicating if 64 | #' uninstalled packages can be shown. 65 | #' @param tolerance A \code{numeric} with the tolerance to be 66 | #' accepted in range test. The default value is NULL. 67 | #' @param ... Additional parameters for \code{fn_check} function. 68 | #' 69 | #' @return 70 | #' Unless otherwise specified, all checking functions return the same 71 | #' argument as \code{x} if a \code{TRUE} evaluation occurs. 72 | #' @rdname check_functions 73 | #' @noRd 74 | #' @details 75 | #' Error message functions: 76 | #' \itemize{ 77 | #' \item{\code{.check_set_caller()} should be used to set the caller name 78 | #' that appears in error messages. Any error raised by a check function 79 | #' will show the caller function in its error message. The caller name will 80 | #' be determined by the last call to this function before error occurs. 81 | #' If no call was made, the first function in the calling stack will be 82 | #' used. 83 | #' } 84 | #' \item{\code{.check_identify_caller()} searches for the caller 85 | #' name to be shown in error messages. The function searches in calling stack 86 | #' if a call to \code{check_set_caller()} was made and returns its value. If 87 | #' no call was found, it returns the first function in calling stack. 88 | #' } 89 | #' } 90 | #' 91 | #' @return \code{.check_set_caller()} returns \code{NULL}. 92 | .check_set_caller <- function(caller) { 93 | envir <- parent.frame() 94 | if (length(sys.frames()) > 1) { 95 | envir <- sys.frame(-1) 96 | } 97 | assign(".check_caller", caller, envir = envir) 98 | 99 | return(invisible(NULL)) 100 | } 101 | 102 | #' @rdname check_functions 103 | #' @name .check_identify_caller 104 | #' @noRd 105 | #' @return the name of the function that is being tested. 106 | .check_identify_caller <- function() { 107 | 108 | # check calling stack 109 | for (f in rev(sys.frames())) { 110 | if (exists(".check_caller", envir = f, inherits = FALSE)) { 111 | caller <- get(".check_caller", envir = f, inherits = FALSE) 112 | return(caller) 113 | } 114 | } 115 | 116 | # check parent frame 117 | if (exists(".check_caller", envir = parent.frame())) { 118 | caller <- get(".check_caller", envir = f) 119 | return(caller) 120 | } 121 | 122 | # no caller defined, get first function in calling stack 123 | caller <- sys.calls()[[1]] 124 | caller <- gsub( 125 | pattern = "^(.*)\\(.*$", replacement = "\\1", 126 | x = paste(caller)[[1]] 127 | ) 128 | return(caller) 129 | } 130 | 131 | #' @rdname check_functions 132 | #' @noRd 133 | #' @details 134 | #' 135 | #' General check functions: 136 | #' \itemize{ 137 | #' \item{ 138 | #' \code{.check_that()} function checks if the argument in 139 | #' \code{x} is \code{logical} or not. If it is \code{logical}, it will be 140 | #' evaluated as \code{TRUE} if all values are \code{TRUE}, \code{FALSE} 141 | #' otherwise. If the argument is not \code{logical}, it will be evaluated 142 | #' as \code{TRUE} if its length is greater than zero, 143 | #' \code{FALSE} otherwise. If a \code{FALSE} evaluation occurs, an error 144 | #' will be raised. 145 | #' } 146 | #' \item{ 147 | #' \code{.check_null()} throws an error if \code{x} argument 148 | #' is \code{NULL}. 149 | #' } 150 | #' \item{ 151 | #' \code{.check_na()} throws an error if any element of \code{x} 152 | #' is \code{NA}. 153 | #' } 154 | #' \item{ 155 | #' \code{.check_names()} throws an error if \code{x} does not have 156 | #' names and \code{is_named} argument is \code{TRUE} (and vice-versa). This 157 | #' function checks for empty or duplicated names if \code{is_named} is 158 | #' \code{TRUE}. 159 | #' } 160 | #' \item{ 161 | #' \code{.check_length()} throws an error if length of \code{x} 162 | #' is out of the range specified by \code{len_min} and \code{len_max} 163 | #' (both inclusive). 164 | #' } 165 | #' \item{ 166 | #' \code{.check_apply()} throws an error only if \code{fn_check} 167 | #' function throws an error when applied to each \code{x} element. 168 | #' } 169 | #' \item{ 170 | #' \code{.check_lgl_type()} throws an error if \code{x} type is not 171 | #' \code{logical}. 172 | #' } 173 | #' \item{ 174 | #' \code{.check_num_type()} throws an error if \code{x} 175 | #' type is not \code{numeric}. Also, an error will be throw if \code{x} values 176 | #' are not \code{integer} and \code{is_integer} parameter is \code{TRUE}. 177 | #' } 178 | #' \item{ 179 | #' \code{.check_int_type()} throws an error if \code{x} 180 | #' type is not \code{numeric} with integer values. 181 | #' } 182 | #' \item{ 183 | #' \code{.check_chr_type()} throws an error if \code{x} 184 | #' type is not \code{character}. 185 | #' } 186 | #' \item{ 187 | #' \code{.check_lst_type()} throws an error if \code{x} 188 | #' type is not \code{list}. 189 | #' } 190 | #' } 191 | #' @keywords internal 192 | #' @noRd 193 | #' @return The same input value if no error occurs 194 | #' 195 | .check_that <- function(x, ..., 196 | local_msg = NULL, 197 | msg = NULL) { 198 | value <- (is.logical(x) && all(x)) || (!is.logical(x) && length(x) > 0) 199 | 200 | if (!value) { 201 | 202 | # get caller function name 203 | caller <- .check_identify_caller() 204 | 205 | # format error message 206 | if (is.null(msg)) { 207 | msg <- sprintf("%s: %%s", caller) 208 | } else { 209 | msg <- sprintf("%s: %s (%%s)", caller, msg) 210 | } 211 | 212 | if (is.null(local_msg)) { 213 | expr <- deparse(substitute(expr = x, env = environment())) 214 | local_msg <- sprintf("%s is not TRUE", expr) 215 | } 216 | 217 | # process message 218 | stop(sprintf(msg, local_msg), call. = FALSE) 219 | } 220 | 221 | return(invisible(x)) 222 | } 223 | 224 | #' @rdname check_functions 225 | #' @keywords internal 226 | #' @noRd 227 | .check_null <- function(x, ..., 228 | msg = NULL) { 229 | 230 | # make default message 231 | if (purrr::is_null(msg)) { 232 | # get x as expression 233 | x_expr <- deparse(substitute(x, environment())) 234 | msg <- paste0("invalid '", x_expr, "' parameter") 235 | } 236 | 237 | .check_that( 238 | !is.null(x), 239 | local_msg = "value cannot be NULL", 240 | msg = msg 241 | ) 242 | 243 | return(invisible(x)) 244 | } 245 | 246 | #' @rdname check_functions 247 | #' @keywords internal 248 | #' @noRd 249 | .check_na <- function(x, ..., allow_na = FALSE, msg = NULL) { 250 | 251 | # make default message 252 | if (purrr::is_null(msg)) { 253 | # get x as expression 254 | x_expr <- deparse(substitute(x, environment())) 255 | msg <- paste0("invalid '", x_expr, "' parameter") 256 | } 257 | 258 | if (!allow_na) { 259 | .check_that( 260 | !any(is.na(x)), 261 | local_msg = "NA value is not allowed", 262 | msg = msg 263 | ) 264 | } 265 | 266 | return(invisible(x)) 267 | } 268 | 269 | 270 | 271 | #' @rdname check_functions 272 | #' @keywords internal 273 | #' @noRd 274 | .check_names <- function(x, ..., 275 | is_named = TRUE, 276 | is_unique = TRUE, 277 | msg = NULL) { 278 | 279 | # make default message 280 | if (purrr::is_null(msg)) { 281 | # get x as expression 282 | x_expr <- deparse(substitute(x, environment())) 283 | msg <- paste0("invalid '", x_expr, "' parameter") 284 | } 285 | 286 | # cannot test zero length arguments 287 | if (length(x) == 0) { 288 | return(invisible(x)) 289 | } 290 | 291 | if (is_named) { 292 | .check_that( 293 | !is.null(names(x)) && !any(is.na(names(x))), 294 | local_msg = "value should have names", 295 | msg = msg 296 | ) 297 | if (is_unique) { 298 | .check_that( 299 | length(names(x)) == length(unique(names(x))), 300 | local_msg = "names should be unique", 301 | msg = msg 302 | ) 303 | } 304 | 305 | } else { 306 | .check_that( 307 | is.null(names(x)), 308 | local_msg = "value should be unnamed", 309 | msg = msg 310 | ) 311 | } 312 | 313 | return(invisible(x)) 314 | } 315 | 316 | #' @rdname check_functions 317 | #' @keywords internal 318 | #' @noRd 319 | .check_length <- function(x, ..., 320 | len_min = 0, 321 | len_max = 2^31 - 1, 322 | msg = NULL) { 323 | 324 | # make default message 325 | if (purrr::is_null(msg)) { 326 | # get x as expression 327 | x_expr <- deparse(substitute(x, environment())) 328 | msg <- paste0("invalid '", x_expr, "' parameter") 329 | } 330 | 331 | # pre-condition 332 | .check_num_type( 333 | len_min, 334 | is_integer = TRUE, 335 | msg = "invalid 'len_min' parameter" 336 | ) 337 | .check_num_type( 338 | len_max, 339 | is_integer = TRUE, 340 | msg = "invalid 'len_max' parameter" 341 | ) 342 | 343 | if (len_min == len_max) { 344 | .check_that( 345 | length(x) == len_min, 346 | local_msg = paste0("length should be ", len_min), 347 | msg = msg 348 | ) 349 | } 350 | 351 | # these checks are separate because the messages are different 352 | .check_that( 353 | length(x) >= len_min, 354 | local_msg = paste0("length should be >= ", len_min), 355 | msg = msg 356 | ) 357 | 358 | .check_that( 359 | length(x) <= len_max, 360 | local_msg = paste0("length should be <= ", len_max), 361 | msg = msg 362 | ) 363 | 364 | return(invisible(x)) 365 | } 366 | 367 | #' @rdname check_functions 368 | #' @keywords internal 369 | #' @noRd 370 | .check_apply <- function(x, fn_check, ...) { 371 | if (!is.function(fn_check)) { 372 | stop(".check_apply: fn_check should be a function.", call. = TRUE) 373 | } 374 | 375 | # check all elements 376 | lapply(x, fn_check, ...) 377 | 378 | return(invisible(x)) 379 | } 380 | 381 | #' @rdname check_functions 382 | #' 383 | #' @keywords internal 384 | #' @noRd 385 | .check_lgl_type <- function(x, ..., 386 | msg = NULL) { 387 | 388 | # make default message 389 | if (purrr::is_null(msg)) { 390 | # get x as expression 391 | x_expr <- deparse(substitute(x, environment())) 392 | msg <- paste0("invalid '", x_expr, "' parameter") 393 | } 394 | 395 | .check_that( 396 | is.logical(x), 397 | local_msg = "value is not logical", 398 | msg = msg 399 | ) 400 | 401 | return(invisible(x)) 402 | } 403 | 404 | #' @rdname check_functions 405 | #' @keywords internal 406 | #' @noRd 407 | .check_num_type <- function(x, ..., 408 | is_integer = FALSE, 409 | msg = NULL) { 410 | 411 | # make default message 412 | if (purrr::is_null(msg)) { 413 | # get x as expression 414 | x_expr <- deparse(substitute(x, environment())) 415 | msg <- paste0("invalid '", x_expr, "' parameter") 416 | } 417 | 418 | .check_that( 419 | is.numeric(x), 420 | local_msg = "value is not a number", 421 | msg = msg 422 | ) 423 | 424 | # test integer 425 | if (is_integer) { 426 | 427 | # if length is zero there is nothing to check 428 | if (length(x) == 0) { 429 | return(invisible(x)) 430 | } 431 | 432 | .check_that( 433 | is.numeric(x) && all(x == suppressWarnings(as.integer(x))), 434 | local_msg = "value is not integer", 435 | msg = msg 436 | ) 437 | } 438 | 439 | return(invisible(x)) 440 | } 441 | 442 | #' @rdname check_functions 443 | #' @keywords internal 444 | #' @noRd 445 | .check_chr_type <- function(x, ..., 446 | msg = NULL) { 447 | 448 | # make default message 449 | if (purrr::is_null(msg)) { 450 | # get x as expression 451 | x_expr <- deparse(substitute(x, environment())) 452 | msg <- paste0("invalid '", x_expr, "' parameter") 453 | } 454 | 455 | .check_that( 456 | is.character(x), 457 | local_msg = "value is not character type", 458 | msg = msg 459 | ) 460 | 461 | return(invisible(x)) 462 | } 463 | 464 | #' @rdname check_functions 465 | #' @keywords internal 466 | #' @noRd 467 | .check_lst_type <- function(x, ..., 468 | msg = NULL) { 469 | 470 | # make default message 471 | if (purrr::is_null(msg)) { 472 | # get x as expression 473 | x_expr <- deparse(substitute(x, environment())) 474 | msg <- paste0("invalid '", x_expr, "' parameter") 475 | } 476 | 477 | .check_that( 478 | is.list(x), 479 | local_msg = "value is not a list", 480 | msg = msg 481 | ) 482 | 483 | return(invisible(x)) 484 | } 485 | 486 | #' @rdname check_functions 487 | #' 488 | #' @details 489 | #' Combined check functions. These function combine some checks mentioned 490 | #' above in one place. In general, these functions can check for \code{NA} 491 | #' (if \code{allow_na=FALSE}), for value length (if either \code{len_min} 492 | #' and \code{len_max} are defined - for \code{list} the parameters are 493 | #' \code{min_len} and \code{max_len}, respectively), for \code{NULL} value 494 | #' (if \code{allow_null=FALSE}), and for names (if \code{is_named} is 495 | #' \code{TRUE} or \code{FALSE}). Depending on specific type, the functions 496 | #' also check for: 497 | #' 498 | #' \itemize{ 499 | #' \item{ 500 | #' \code{.check_lgl()} checks for \code{logical} values. 501 | #' } 502 | #' \item{ 503 | #' \code{.check_num()} checks for \code{numeric} values and its range (if 504 | #' either \code{min}, \code{max}, \code{exclusive_min}, or \code{exclusive_max} 505 | #' parameters are defined). It also checks \code{integer} values 506 | #' (if \code{is_integer=TRUE}). 507 | #' } 508 | #' \item{ 509 | #' \code{.check_chr()} checks for \code{character} type and empty strings (if 510 | #' \code{allow_empty=FALSE}). It also checks strings through regular 511 | #' expression (if \code{regex} parameter is defined). 512 | #' } 513 | #' \item{ 514 | #' \code{.check_lst()} checks for \code{list} type. By default, it checks if 515 | #' the list is named. Additionally, a function can be passed to 516 | #' \code{fn_check} parameter to check its elements. This enables to pass 517 | #' other checking functions like \code{.check_num()} to verify the type of 518 | #' its elements. In this case, extra parameters can be passed by \code{...}. 519 | #' } 520 | #' } 521 | #' @keywords internal 522 | #' @noRd 523 | .check_lgl <- function(x, ..., 524 | allow_na = FALSE, 525 | len_min = 0, 526 | len_max = 2^31 - 1, 527 | allow_null = FALSE, 528 | is_named = FALSE, 529 | msg = NULL) { 530 | 531 | # make default message 532 | if (purrr::is_null(msg)) { 533 | # get x as expression 534 | x_expr <- deparse(substitute(x, environment())) 535 | msg <- paste0("invalid '", x_expr, "' parameter") 536 | } 537 | 538 | # check for NULL and exit if it is allowed 539 | if (allow_null && is.null(x)) { 540 | return(invisible(x)) 541 | } 542 | 543 | # check NULL 544 | .check_null(x, msg = msg) 545 | 546 | # check type 547 | .check_lgl_type(x, msg = msg) 548 | 549 | # check length 550 | .check_length(x, len_min = len_min, len_max = len_max, msg = msg) 551 | 552 | # check NA 553 | if (!allow_na) { 554 | .check_na(x, msg = msg) 555 | } 556 | 557 | # check names 558 | .check_names(x, is_named = is_named, msg = msg) 559 | 560 | return(invisible(x)) 561 | } 562 | 563 | #' @rdname check_functions 564 | #' @keywords internal 565 | #' @noRd 566 | .check_num <- function(x, ..., 567 | allow_na = FALSE, 568 | min = -Inf, 569 | max = Inf, 570 | exclusive_min = -Inf, 571 | exclusive_max = Inf, 572 | len_min = 0, 573 | len_max = 2^31 - 1, 574 | allow_null = FALSE, 575 | is_integer = FALSE, 576 | is_named = FALSE, 577 | tolerance = 0, 578 | msg = NULL) { 579 | 580 | # make default message 581 | if (purrr::is_null(msg)) { 582 | # get x as expression 583 | x_expr <- deparse(substitute(x, environment())) 584 | msg <- paste0("invalid '", x_expr, "' parameter") 585 | } 586 | 587 | # check for NULL and exit if it is allowed 588 | if (allow_null && is.null(x)) { 589 | return(invisible(x)) 590 | } 591 | 592 | # check NULL 593 | .check_null(x, msg = msg) 594 | 595 | # check type 596 | .check_num_type(x, is_integer = is_integer, msg = msg) 597 | 598 | # check length 599 | .check_length(x, len_min = len_min, len_max = len_max, msg = msg) 600 | 601 | # check NA 602 | .check_na(x, allow_na = allow_na, msg = msg) 603 | 604 | # check names 605 | .check_names(x, is_named = is_named, msg = msg) 606 | 607 | # check range 608 | .check_num_min_max( 609 | x = x, 610 | min = min, 611 | max = max, 612 | exclusive_min = exclusive_min, 613 | exclusive_max = exclusive_max, 614 | tolerance = tolerance, 615 | msg = msg 616 | ) 617 | 618 | return(invisible(x)) 619 | } 620 | 621 | .check_num_min_max <- function(x, ..., 622 | min = -Inf, 623 | max = Inf, 624 | exclusive_min = -Inf, 625 | exclusive_max = Inf, 626 | tolerance = 0, 627 | msg = NULL) { 628 | 629 | # make default message 630 | if (purrr::is_null(msg)) { 631 | # get x as expression 632 | x_expr <- deparse(substitute(x, environment())) 633 | msg <- paste0("invalid '", x_expr, "' parameter") 634 | } 635 | 636 | # pre-condition 637 | .check_num_type(min, msg = "invalid 'min' parameter") 638 | .check_num_type(max, msg = "invalid 'max' parameter") 639 | .check_num_type(exclusive_min, msg = "invalid 'exclusive_min' parameter") 640 | .check_num_type(exclusive_max, msg = "invalid 'exclusive_max' parameter") 641 | .check_num_type(x = tolerance, msg = "invalid 'tolerance' parameter") 642 | 643 | # remove NAs before check to test tolerance 644 | result <- x 645 | x <- x[!is.na(x)] 646 | 647 | # adjust min and max to tolerance 648 | if (!is.null(tolerance)) { 649 | min <- min - tolerance 650 | max <- max + tolerance 651 | exclusive_min <- exclusive_min - tolerance 652 | exclusive_max <- exclusive_max + tolerance 653 | } 654 | 655 | # min and max checks 656 | if (min == max) { 657 | .check_that( 658 | all(x == min), 659 | local_msg = paste0("value should be ", min), 660 | msg = msg 661 | ) 662 | } 663 | .check_that( 664 | all(x >= min), 665 | local_msg = paste0("value should be >= ", min), 666 | msg = msg 667 | ) 668 | .check_that( 669 | all(x <= max), 670 | local_msg = paste0("value should be <= ", max), 671 | msg = msg 672 | ) 673 | 674 | # exclusive_min and exclusive_max checks 675 | .check_that( 676 | all(x > exclusive_min), 677 | local_msg = paste0("value should be > ", exclusive_min), 678 | msg = msg 679 | ) 680 | .check_that( 681 | all(x < exclusive_max), 682 | local_msg = paste0("value should be < ", exclusive_max), 683 | msg = msg 684 | ) 685 | 686 | return(invisible(result)) 687 | } 688 | 689 | #' @rdname check_functions 690 | #' @keywords internal 691 | #' @noRd 692 | .check_chr <- function(x, ..., 693 | allow_na = FALSE, 694 | allow_empty = TRUE, 695 | len_min = 0, 696 | len_max = 2^31 - 1, 697 | allow_null = FALSE, 698 | is_named = FALSE, 699 | has_unique_names = TRUE, 700 | regex = NULL, 701 | msg = NULL) { 702 | 703 | # make default message 704 | if (purrr::is_null(msg)) { 705 | # get x as expression 706 | x_expr <- deparse(substitute(x, environment())) 707 | msg <- paste0("invalid '", x_expr, "' parameter") 708 | } 709 | 710 | # check for null and exit if it is allowed 711 | if (allow_null && is.null(x)) { 712 | return(invisible(x)) 713 | } 714 | 715 | # check NULL 716 | .check_null(x, msg = msg) 717 | 718 | # check type 719 | .check_chr_type(x, msg = msg) 720 | 721 | # check length 722 | .check_length(x, len_min = len_min, len_max = len_max, msg = msg) 723 | 724 | # check NA 725 | if (!allow_na) { 726 | .check_na(x, msg = msg) 727 | } 728 | 729 | # check empty 730 | if (!allow_empty) { 731 | .check_that( 732 | all(nchar(x[!is.na(x)]) > 0), 733 | local_msg = "empty value is not allowed", 734 | msg = msg 735 | ) 736 | } 737 | 738 | 739 | # check names 740 | .check_names(x, 741 | is_named = is_named, 742 | is_unique = has_unique_names, 743 | msg = msg) 744 | 745 | # check regular expression pattern 746 | if (!is.null(regex)) { 747 | .check_that( 748 | all(grepl(pattern = regex, x = x)), 749 | local_msg = "value did not match pattern", 750 | msg = msg 751 | ) 752 | } 753 | 754 | return(invisible(x)) 755 | } 756 | 757 | #' @rdname check_functions 758 | #' @keywords internal 759 | #' @noRd 760 | .check_lst <- function(x, ..., 761 | min_len = 0, 762 | max_len = 2^31 - 1, 763 | allow_null = FALSE, 764 | is_named = TRUE, 765 | fn_check = NULL, 766 | msg = NULL) { 767 | 768 | # make default message 769 | if (purrr::is_null(msg)) { 770 | # get x as expression 771 | x_expr <- deparse(substitute(x, environment())) 772 | msg <- paste0("invalid '", x_expr, "' parameter") 773 | } 774 | 775 | # check for null and exit if it is allowed 776 | if (allow_null && is.null(x)) { 777 | return(invisible(x)) 778 | } 779 | 780 | # check NULL 781 | .check_null(x, msg = msg) 782 | 783 | # check type 784 | .check_lst_type(x, msg = msg) 785 | 786 | # check length 787 | .check_length(x, len_min = min_len, len_max = max_len, msg = msg) 788 | 789 | # check names 790 | .check_names(x, is_named = is_named, msg = msg) 791 | 792 | # check using function 793 | if (!is.null(fn_check)) { 794 | .check_apply(x, fn_check = fn_check, msg = msg, ...) 795 | } 796 | 797 | return(invisible(x)) 798 | } 799 | 800 | #' @rdname check_functions 801 | #' 802 | #' @details 803 | #' Subset check functions. Two functions are provided to check for 804 | #' subset elements in \code{character} vectors. These functions are the 805 | #' symmetrical equivalent to each other, but the error messages are different. 806 | #' For the \code{.check_chr_within()}, the error message focus on the 807 | #' \code{within} values. For the \code{.check_chr_contains()}, the error 808 | #' message focus on the \code{contains} values. The verification is done 809 | #' accordingly to the \code{discriminator} parameter, that can be: 810 | #' \code{one_of}, \code{any_of}, \code{all_of}, \code{none_of}, or 811 | #' \code{exactly}. 812 | #' 813 | #' \itemize{ 814 | #' \item{ 815 | #' \code{.check_chr_within()} throws an error if provided \code{within} vector 816 | #' does not correspond to the \code{discriminator} with respect to \code{x} 817 | #' parameter (e.g. "one of x within...", "all of x within...). 818 | #' \code{one_of}: only one value (can it repeat?) of \code{x} appears 819 | #' in \code{within} vector. \code{any_of}: at least one value (can it 820 | #' repeat?) of \code{x} appears in \code{within} vector. \code{all_of} 821 | #' (default): all values (can it repeat?) of \code{x} appears in \code{within} 822 | #' vector. \code{none_of}: no value of \code{x} is in \code{within} vector. 823 | #' \code{exactly}: value of \code{x} (can it repeat?) is equal to 824 | #' \code{within} vector. 825 | #' } 826 | #' \item{ 827 | #' \code{.check_chr_contains()} throws an error if provided \code{x} 828 | #' vector does not correspond to the \code{discriminator} with respect to 829 | #' \code{contains} parameter (e.g. "x contains one of...", 830 | #' "x contains all of..."). \code{one_of}: only one value (can it repeat?) of 831 | #' \code{contains} appears in \code{x} vector. \code{any_of}: at least one 832 | #' value (can it repeat?) of \code{contains} appears in \code{x} vector. 833 | #' \code{all_of} (default): all values (can it repeat?) of \code{contains} 834 | #' appears in \code{x} vector. \code{none_of}: no value of \code{contains} is 835 | #' in \code{x} vector. \code{exactly}: value of \code{contains} is exactly 836 | #' (can it repeat?) equal to \code{x}. 837 | #' } 838 | #' } 839 | #' @keywords internal 840 | #' @noRd 841 | .check_chr_within <- function(x, 842 | within, ..., 843 | case_sensitive = TRUE, 844 | discriminator = "all_of", 845 | can_repeat = TRUE, 846 | msg = NULL) { 847 | 848 | # make default message 849 | if (purrr::is_null(msg)) { 850 | # get x as expression 851 | x_expr <- deparse(substitute(x, environment())) 852 | msg <- paste0("invalid '", x_expr, "' parameter") 853 | } 854 | 855 | # pre-condition 856 | .check_chr(within, 857 | len_min = 1, 858 | msg = "invalid 'within' parameter" 859 | ) 860 | 861 | # allowed discriminators and its print values 862 | discriminators <- c( 863 | one_of = "be only one of", 864 | any_of = "be at least one of", 865 | all_of = "be", 866 | none_of = "be none of", 867 | exactly = "be exactly" 868 | ) 869 | 870 | if (length(discriminator) != 1 || 871 | !discriminator %in% names(discriminators)) { 872 | stop(paste( 873 | ".check_chr_within: discriminator should be one of", 874 | "'one_of', 'any_of', 'all_of', 'none_of', or 'exactly'." 875 | ), 876 | call. = TRUE 877 | ) 878 | } 879 | 880 | # check type 881 | .check_chr_type(x, msg = msg) 882 | 883 | # check for repeated values 884 | if (!can_repeat) { 885 | .check_that( 886 | length(x) == length(unique(x)), 887 | local_msg = "values can not repeat", 888 | msg = msg 889 | ) 890 | } 891 | 892 | result <- x 893 | 894 | # simplify 895 | x <- unique(x) 896 | within <- unique(within) 897 | 898 | # transform inputs to verify without case sensitive 899 | original_within <- within 900 | if (!case_sensitive) { 901 | x <- tolower(x) 902 | within <- tolower(within) 903 | } 904 | 905 | # prepare local message 906 | local_msg <- sprintf( 907 | "values should %s: %s", 908 | discriminators[[discriminator]], 909 | paste0("'", original_within, "'", 910 | collapse = ", " 911 | ) 912 | ) 913 | 914 | # check discriminator 915 | if (discriminator == "one_of") { 916 | .check_that( 917 | sum(x %in% within) == 1, 918 | local_msg = local_msg, 919 | msg = msg 920 | ) 921 | } else if (discriminator == "any_of") { 922 | .check_that( 923 | any(x %in% within), 924 | local_msg = local_msg, 925 | msg = msg 926 | ) 927 | } else if (discriminator == "all_of") { 928 | .check_that( 929 | all(x %in% within), 930 | local_msg = local_msg, 931 | msg = msg 932 | ) 933 | } else if (discriminator == "none_of") { 934 | .check_that( 935 | !any(x %in% within), 936 | local_msg = local_msg, 937 | msg = msg 938 | ) 939 | } else if (discriminator == "exactly") { 940 | .check_that( 941 | all(x %in% within) && all(within %in% x), 942 | local_msg = local_msg, 943 | msg = msg 944 | ) 945 | } 946 | 947 | return(invisible(result)) 948 | } 949 | 950 | #' @rdname check_functions 951 | #' @keywords internal 952 | #' @noRd 953 | .check_chr_contains <- function(x, 954 | contains, ..., 955 | case_sensitive = TRUE, 956 | discriminator = "all_of", 957 | can_repeat = TRUE, 958 | msg = NULL) { 959 | 960 | # make default message 961 | if (purrr::is_null(msg)) { 962 | # get x as expression 963 | x_expr <- deparse(substitute(x, environment())) 964 | msg <- paste0("invalid '", x_expr, "' parameter") 965 | } 966 | 967 | # pre-condition 968 | .check_chr(contains, 969 | len_min = 1, 970 | msg = "invalid 'contains' parameter" 971 | ) 972 | 973 | # allowed discriminators and its print values 974 | discriminators <- c( 975 | one_of = "contain only one of", 976 | any_of = "contain at least one of", 977 | all_of = "contain", 978 | none_of = "not contain any of", 979 | exactly = "be exactly" 980 | ) 981 | 982 | if (length(discriminator) != 1 || 983 | !discriminator %in% names(discriminators)) { 984 | stop(paste( 985 | ".check_chr_contains: discriminator should be one of", 986 | "'one_of', 'any_of', or 'all_of'." 987 | ), 988 | call. = TRUE 989 | ) 990 | } 991 | 992 | # check type 993 | .check_chr_type(x, msg = msg) 994 | 995 | # check for repeated values 996 | if (!can_repeat) { 997 | .check_that( 998 | length(contains) == length(unique(contains)), 999 | local_msg = "values cannot repeat", 1000 | msg = msg 1001 | ) 1002 | } 1003 | 1004 | result <- x 1005 | 1006 | # simplify 1007 | x <- unique(x) 1008 | contains <- unique(contains) 1009 | 1010 | # transform inputs to verify without case sensitive 1011 | original_contains <- contains 1012 | if (!case_sensitive) { 1013 | x <- tolower(x) 1014 | contains <- tolower(contains) 1015 | } 1016 | 1017 | # prepare local message 1018 | local_msg <- sprintf( 1019 | "value should %s: %s", 1020 | discriminators[[discriminator]], 1021 | paste0("'", original_contains, "'", collapse = ", ") 1022 | ) 1023 | 1024 | # check discriminator 1025 | if (discriminator == "one_of") { 1026 | .check_that( 1027 | sum(contains %in% x) == 1, 1028 | local_msg = local_msg, 1029 | msg = msg 1030 | ) 1031 | } else if (discriminator == "any_of") { 1032 | .check_that( 1033 | any(contains %in% x), 1034 | local_msg = local_msg, 1035 | msg = msg 1036 | ) 1037 | } else if (discriminator == "all_of") { 1038 | .check_that( 1039 | all(contains %in% x), 1040 | local_msg = local_msg, 1041 | msg = msg 1042 | ) 1043 | } else if (discriminator == "none_of") { 1044 | .check_that( 1045 | !any(contains %in% x), 1046 | local_msg = local_msg, 1047 | msg = msg 1048 | ) 1049 | } else if (discriminator == "exactly") { 1050 | .check_that( 1051 | all(contains %in% x) && all(x %in% contains), 1052 | local_msg = local_msg, 1053 | msg = msg 1054 | ) 1055 | } 1056 | 1057 | return(invisible(result)) 1058 | } 1059 | 1060 | #' @rdname check_functions 1061 | #' 1062 | #' @details 1063 | #' Special checking function: 1064 | #' 1065 | #' \itemize{ 1066 | #' \item{ 1067 | #' \code{.check_file()} throws an error if provided value is not a valid and 1068 | #' existing file path. 1069 | #' } 1070 | #' } 1071 | #' @keywords internal 1072 | #' @noRd 1073 | .check_file <- function(x, ..., 1074 | extensions = NULL, 1075 | msg = NULL) { 1076 | 1077 | # make default message 1078 | if (purrr::is_null(msg)) { 1079 | # get x as expression 1080 | x_expr <- deparse(substitute(x, environment())) 1081 | msg <- paste0("invalid '", x_expr, "' parameter") 1082 | } 1083 | 1084 | # file extension 1085 | ext_file <- function(x) { 1086 | gsub( 1087 | pattern = "[^?]+\\.([^?/.]+).*$", 1088 | replacement = "\\1", 1089 | basename(x) 1090 | ) 1091 | } 1092 | 1093 | # check parameter 1094 | .check_chr(x, 1095 | allow_empty = FALSE, len_min = 1, 1096 | allow_null = FALSE, msg = msg 1097 | ) 1098 | 1099 | # check extension 1100 | if (!is.null(extensions)) { 1101 | .check_chr_within(ext_file(x), 1102 | within = extensions, 1103 | case_sensitive = FALSE, 1104 | msg = "invalid file extension" 1105 | ) 1106 | } 1107 | 1108 | existing_files <- file.exists(x) 1109 | existing_dirs <- dir.exists(x) 1110 | .check_that( 1111 | all(existing_files | existing_dirs), 1112 | local_msg = paste( 1113 | "file does not exist:", 1114 | paste0("'", x[!existing_files], "'", 1115 | collapse = ", " 1116 | ) 1117 | ), 1118 | msg = msg 1119 | ) 1120 | 1121 | return(invisible(x)) 1122 | } 1123 | 1124 | #' @rdname check_functions 1125 | #' 1126 | #' @details 1127 | #' Special checking function: 1128 | #' 1129 | #' \itemize{ 1130 | #' \item{ 1131 | #' \code{.check_env_var()} throws an error if provided environment variable is 1132 | #' not existing. 1133 | #' } 1134 | #' } 1135 | #' @keywords internal 1136 | #' @noRd 1137 | .check_env_var <- function(x, ..., 1138 | msg = NULL) { 1139 | 1140 | # make default message 1141 | if (purrr::is_null(msg)) { 1142 | # get x as expression 1143 | x_expr <- deparse(substitute(x, environment())) 1144 | msg <- paste0("invalid '", x_expr, "' environment variable") 1145 | } 1146 | 1147 | .check_null(x, msg = msg) 1148 | 1149 | .check_chr_type(x, msg = msg) 1150 | 1151 | if (length(x) > 0) { 1152 | .check_apply( 1153 | x, 1154 | fn_check = function(x) { 1155 | .check_that( 1156 | x = nzchar(Sys.getenv(x)), 1157 | msg = paste( 1158 | sprintf("%s: ", x), 1159 | msg 1160 | ) 1161 | ) 1162 | } 1163 | ) 1164 | } else { 1165 | .check_that(x = nzchar(Sys.getenv(x)), msg = msg) 1166 | } 1167 | 1168 | return(invisible(x)) 1169 | } 1170 | 1171 | #' @rdname check_functions 1172 | #' 1173 | #' @details 1174 | #' Contextual check and error conversion functions: 1175 | #' 1176 | #' \itemize{ 1177 | #' \item{ 1178 | #' \code{.check_warn()} converts an error raised by an R expression in 1179 | #' \code{expr} parameter into a warning message. 1180 | #' } 1181 | #' \item{ 1182 | #' \code{.check_error()} captures any error raised by an R expression in 1183 | #' \code{expr} parameter, and shows a personalized message. 1184 | #' } 1185 | #' } 1186 | #' @keywords internal 1187 | #' @noRd 1188 | .check_warn <- function(expr) { 1189 | result <- tryCatch( 1190 | { 1191 | expr 1192 | }, 1193 | error = function(e) { 1194 | warning(e$message, call. = FALSE) 1195 | } 1196 | ) 1197 | 1198 | return(invisible(result)) 1199 | } 1200 | 1201 | #' @rdname check_functions 1202 | #' @keywords internal 1203 | #' @noRd 1204 | .check_error <- function(expr, ..., 1205 | msg = NULL) { 1206 | result <- tryCatch( 1207 | { 1208 | expr 1209 | }, 1210 | error = function(e) { 1211 | .check_that(FALSE, local_msg = e$message, msg = msg) 1212 | } 1213 | ) 1214 | 1215 | return(invisible(result)) 1216 | } 1217 | 1218 | #' @title Check is numerical parameter is valid using reasonable defaults 1219 | #' @name .check_num_parameter 1220 | #' @param x parameter to be checked 1221 | #' @param min minimum value 1222 | #' @param max maximum value 1223 | #' @param len_min minimum length of vector 1224 | #' @param len_max maximum length of vector 1225 | #' @param allow_na allow NA? 1226 | #' @param exclusive_min is there an exclusive minimum? 1227 | #' @param tolerance tolerance for equality comparison 1228 | #' 1229 | #' @return No return value, called for side effects. 1230 | #' @keywords internal 1231 | #' @noRd 1232 | .check_num_parameter <- function(param, min = -Inf, max = Inf, 1233 | len_min = 1, len_max = 1, 1234 | allow_na = FALSE, 1235 | exclusive_min = -Inf, tolerance = 0) { 1236 | .check_num( 1237 | x = param, 1238 | allow_na = allow_na, 1239 | min = min, 1240 | max = max, 1241 | len_min = len_min, 1242 | len_max = len_max, 1243 | exclusive_min = exclusive_min, 1244 | tolerance = tolerance 1245 | ) 1246 | } 1247 | 1248 | .check_lgl_parameter <- function(param, len_min = 1, len_max = 1, 1249 | allow_na = FALSE, allow_null = FALSE, 1250 | is_named = FALSE) { 1251 | .check_lgl( 1252 | x = param, 1253 | len_min = len_min, 1254 | len_max = len_max, 1255 | allow_na = allow_na, 1256 | allow_null = allow_null, 1257 | is_named = is_named 1258 | ) 1259 | } 1260 | 1261 | #' @title Check is integer parameter is valid using reasonable defaults 1262 | #' @name .check_int_parameter 1263 | #' @param x parameter to be checked 1264 | #' @param min minimum value 1265 | #' @param max maximum value 1266 | #' @param len_min minimum length of vector 1267 | #' @param len_max maximum length of vector 1268 | #' 1269 | #' @return No return value, called for side effects. 1270 | #' @keywords internal 1271 | #' @noRd 1272 | .check_int_parameter <- function(param, min = 1, max = 2^31 - 1, 1273 | len_min = 1, len_max = 1) { 1274 | .check_num( 1275 | x = param, 1276 | min = min, 1277 | max = max, 1278 | len_min = len_min, 1279 | len_max = len_max, 1280 | is_integer = TRUE 1281 | ) 1282 | } 1283 | #' @title Check is integer parameter is valid using reasonable defaults 1284 | #' @name .check_chr_parameter 1285 | #' @param x parameter to be checked 1286 | #' @param len_min minimum length of vector 1287 | #' @param len_max maximum length of vector 1288 | #' @return No return value, called for side effects. 1289 | #' @keywords internal 1290 | #' @noRd 1291 | .check_chr_parameter <- function(param, len_min = 1, len_max = 1) { 1292 | .check_chr( 1293 | param, 1294 | len_min = len_min, 1295 | len_max = len_max 1296 | ) 1297 | } 1298 | #' @title Check is window size is valid using reasonable defaults 1299 | #' @name .check_window_size 1300 | #' @param window_size size of the local window 1301 | #' @param min minimum value 1302 | #' @param max maximum value 1303 | #' @return No return value, called for side effects. 1304 | #' @keywords internal 1305 | #' @noRd 1306 | .check_window_size <- function(window_size, min = 1, max = 2^32 - 1) { 1307 | .check_int_parameter(window_size, min = min, max = max) 1308 | .check_that( 1309 | x = window_size %% 2 != 0, 1310 | msg = "window_size must be an odd number" 1311 | ) 1312 | } 1313 | 1314 | #' @title Check is multicores parameter is valid using reasonable defaults 1315 | #' @name .check_multicores 1316 | #' @param multicores number of cores to be used 1317 | #' 1318 | #' @return No return value, called for side effects. 1319 | #' @keywords internal 1320 | #' @noRd 1321 | .check_multicores <- function(multicores) { 1322 | .check_num( 1323 | x = multicores, 1324 | min = 1, 1325 | len_min = 1, 1326 | len_max = 1, 1327 | is_integer = TRUE, 1328 | msg = "invalid 'multicores' parameter" 1329 | ) 1330 | } 1331 | #' @title Check is memsize parameter is valid using reasonable defaults 1332 | #' @name .check_memsize 1333 | #' @param memsize size of memory in GB 1334 | #' @return No return value, called for side effects. 1335 | #' @keywords internal 1336 | #' @noRd 1337 | .check_memsize <- function(memsize) { 1338 | # precondition - memory 1339 | .check_num( 1340 | x = memsize, 1341 | exclusive_min = 0, 1342 | len_min = 1, 1343 | len_max = 1, 1344 | msg = "invalid 'memsize' parameter" 1345 | ) 1346 | } 1347 | #' @title Does the data contain the cols of sample data and is not empty? 1348 | #' @name .check_smoothness 1349 | #' @param smoothness a vector or numeric value 1350 | #' @param nlabels a numeric value 1351 | #' @return No return value, called for side effects. 1352 | #' @keywords internal 1353 | #' @noRd 1354 | .check_smoothness <- function(smoothness, nlabels) { 1355 | .check_that( 1356 | length(smoothness) == 1 || length(smoothness) == nlabels, 1357 | msg = paste( 1358 | "smoothness must be either one value or", 1359 | "a vector of length", nlabels 1360 | ) 1361 | ) 1362 | } 1363 | 1364 | 1365 | -------------------------------------------------------------------------------- /R/bayes_colors.R: -------------------------------------------------------------------------------- 1 | #' @title Function to retrieve bayesEO color table 2 | #' @name bayes_colors 3 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 4 | #' @description Returns a color table 5 | #' @return A tibble with color names and values 6 | #' 7 | #' 8 | #' @export 9 | #' 10 | bayes_colors <- function() { 11 | # load the color configuration file 12 | color_yml_file <- system.file("./extdata/config_colors.yml", package = "bayesEO") 13 | config_colors <- yaml::yaml.load_file( 14 | input = color_yml_file, 15 | merge.precedence = "override" 16 | ) 17 | config_colors <- config_colors$colors 18 | base_names <- names(config_colors) 19 | color_table <- purrr::map2_dfr(config_colors, base_names, function(cl, bn) { 20 | cc_tb <- tibble::tibble(name = names(cl), 21 | color = unlist(cl), 22 | group = bn) 23 | return(cc_tb) 24 | }) 25 | # set the color table 26 | bayesEO_env$color_table <- color_table 27 | return(invisible(NULL)) 28 | } 29 | #' @title Function to show colors in SITS 30 | #' @name bayes_colors_show 31 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 32 | #' @description Shows the default SITS colors 33 | #' 34 | #' @return no return, called for side effects 35 | #' 36 | #' @export 37 | #' 38 | bayes_colors_show <- function() { 39 | color_tb <- bayesEO_env$color_table 40 | n_colors <- nrow(color_tb) 41 | n_rows_show <- n_colors %/% 3 42 | 43 | color_tb <- tibble::add_column(color_tb, 44 | y = seq(0, n_colors - 1) %% n_rows_show, 45 | x = seq(0, n_colors - 1) %/% n_rows_show) 46 | y_size <- 1.2 47 | g <- ggplot2::ggplot() + 48 | ggplot2::scale_x_continuous(name = "", 49 | breaks = NULL, 50 | expand = c(0, 0)) + 51 | ggplot2::scale_y_continuous(name = "", 52 | breaks = NULL, 53 | expand = c(0, 0)) + 54 | ggplot2::geom_rect(data = color_tb, 55 | mapping = ggplot2::aes( 56 | xmin = .data[["x"]] + 0.05, 57 | xmax = .data[["x"]] + 0.95, 58 | ymin = .data[["y"]] + 0.05, 59 | ymax = .data[["y"]] + y_size 60 | ), 61 | fill = color_tb$color 62 | ) + 63 | ggplot2::geom_text(data = color_tb, 64 | mapping = ggplot2::aes( 65 | x = .data[["x"]] + 0.5, 66 | y = .data[["y"]] + 0.8, 67 | label = .data[["name"]]), 68 | colour = "grey15", 69 | hjust = 0.5, 70 | vjust = 1, 71 | size = 9 / ggplot2::.pt) 72 | 73 | g + ggplot2::theme( 74 | panel.background = ggplot2::element_rect(fill = "#FFFFFF")) 75 | 76 | return(g) 77 | } 78 | 79 | 80 | #' @title Get colors associated to the labels 81 | #' @name .color_get_labels 82 | #' @param labels labels associated to the training classes 83 | #' @param palette palette from `grDevices::hcl.pals()` 84 | #' replaces default colors 85 | #' when labels are not included in the config palette 86 | #' @param rev revert the order of colors? 87 | #' @keywords internal 88 | #' @noRd 89 | #' @return colors required to display the labels 90 | .color_get_labels <- function(labels, 91 | palette = "Spectral", 92 | legend = NULL, 93 | rev = TRUE) { 94 | 95 | # Get the Color table 96 | color_tb <- bayesEO_env$color_table 97 | # Try to find colors in thecolor palette 98 | names_tb <- dplyr::filter(color_tb, .data[["name"]] %in% labels)$name 99 | # find the labels that exist in the color table 100 | labels_exist <- labels[labels %in% names_tb] 101 | # get the colors for the names that exist 102 | colors <- purrr::map_chr(labels_exist, function(l) { 103 | col <- color_tb |> 104 | dplyr::filter(.data[["name"]] == l) |> 105 | dplyr::pull(.data[["color"]]) 106 | return(col) 107 | }) 108 | # get the names of the colors that exist in the SITS color table 109 | names(colors) <- labels_exist 110 | 111 | # if there is a legend? 112 | if (!purrr::is_null(legend)) { 113 | # what are the names in the legend that are in the labels? 114 | labels_leg <- labels[labels %in% names(legend)] 115 | # what are the color labels that are included in the legend? 116 | colors_leg <- legend[labels_leg] 117 | # join color names in the legend to those in default colors 118 | colors <- c( 119 | colors_leg, 120 | colors[!names(colors) %in% names(colors_leg)] 121 | ) 122 | } 123 | # are there any colors missing? 124 | if (!all(labels %in% names(colors))) { 125 | missing <- labels[!labels %in% names(colors)] 126 | warning("missing colors for labels ", 127 | paste(missing, collapse = ", ") 128 | ) 129 | warning("using palette ", palette, " for missing colors") 130 | # grDevices does not work with one color missing 131 | colors_pal <- grDevices::hcl.colors( 132 | n = max(2, length(missing)), 133 | palette = palette, 134 | alpha = 1, 135 | rev = rev 136 | ) 137 | # if there is only one color, get it 138 | colors_pal <- colors_pal[seq_len(length(missing))] 139 | names(colors_pal) <- missing 140 | # put all colors together 141 | colors <- c(colors, colors_pal) 142 | } 143 | # rename colors to fit the label order 144 | # and deal with duplicate labels 145 | colors <- colors[labels] 146 | # post-condition 147 | .check_chr(colors, 148 | len_min = length(labels), 149 | len_max = length(labels), 150 | is_named = TRUE, 151 | has_unique_names = FALSE, 152 | msg = "invalid color values" 153 | ) 154 | 155 | return(colors) 156 | } 157 | 158 | -------------------------------------------------------------------------------- /R/bayes_label.R: -------------------------------------------------------------------------------- 1 | #' @title Label probability images to create categorical maps 2 | #' 3 | #' @name bayes_label 4 | #' 5 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 6 | #' 7 | #' @description Takes a classified image with probabilities, and 8 | #' labels the image with the pixel of higher probability 9 | #' 10 | #' @param x SpatRaster object with probabilities images 11 | #' 12 | #' @return A SpatRaster object 13 | #' 14 | #' @examples 15 | #' if (bayes_run_examples()) { 16 | #' # select a file with probability values 17 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 18 | #' file <- list.files(data_dir) 19 | #' # create a SpatRaster object from the file 20 | #' probs_file <- paste0(data_dir, "/", file) 21 | #' # provide the labels 22 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 23 | #' "ClearCut_Veg", "Forest", "Wetland") 24 | #' # read the probs file 25 | #' probs <- bayes_read_probs(probs_file, labels) 26 | #' # produce a labelled map 27 | #' map <- bayes_label(probs) 28 | #' # plot the labelled map 29 | #' bayes_plot_map(map) 30 | #'} 31 | #' 32 | #' @export 33 | bayes_label <- function(x){ 34 | # check input image 35 | .check_that( 36 | "SpatRaster" %in% class(x), 37 | msg = "input is not SpatRaster type" 38 | ) 39 | # read values 40 | values <- terra::values(x) 41 | # get maximum prob 42 | values <- C_label_max_prob(values) 43 | # create SpatRaster 44 | y <- terra::rast(x, nlyrs = 1) 45 | terra::values(y) <- values 46 | # label the classified image 47 | nlabels <- length(names(x)) 48 | levels(y) <- data.frame(id = 1:nlabels, class = names(x)) 49 | return(y) 50 | } 51 | 52 | #' @title Summary of categorical maps 53 | #' 54 | #' @name bayes_summary 55 | #' 56 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 57 | #' 58 | #' @description Takes a classified image with probabilities, and 59 | #' labels the image with the pixel of higher probability 60 | #' 61 | #' @param x SpatRaster categorical object 62 | #' @param scale Scale to apply to data 63 | #' @param sample_size Sample size 64 | #' 65 | #' @return A tibble with information 66 | #' 67 | #' @examples 68 | #' if (bayes_run_examples()) { 69 | #' # select a file with probability values 70 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 71 | #' file <- list.files(data_dir) 72 | #' # create a SpatRaster object from the file 73 | #' probs_file <- paste0(data_dir, "/", file) 74 | #' # provide the labels 75 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 76 | #' "ClearCut_Veg", "Forest", "Wetland") 77 | #' # read the probs file 78 | #' probs <- bayes_read_probs(probs_file, labels) 79 | #' # produce a labelled map 80 | #' map <- bayes_label(probs) 81 | #' # plot the labelled map 82 | #' bayes_summary(map) 83 | #'} 84 | #' 85 | #' @export 86 | bayes_summary <- function(x, scale = 1, sample_size = 15000){ 87 | # check input image 88 | .check_that( 89 | "SpatRaster" %in% class(x), 90 | msg = "input is not SpatRaster type" 91 | ) 92 | signif_ignore_integer <- function(x, digits = 2) { 93 | as.integer(x) + signif(x - as.integer(x), digits) 94 | } 95 | if (all(terra::is.factor(x))) { 96 | freq <- terra::freq(x) 97 | area_pixel <- terra::xres(x)*terra::yres(x) 98 | area_km2 <- freq$count*area_pixel/1e+06 99 | area_km2 <- signif_ignore_integer(area_km2) 100 | sum <- tibble::tibble( 101 | class = terra::levels(x)[[1]]$class, 102 | area = area_km2 103 | ) 104 | } 105 | else { 106 | # get the a sample of the values 107 | values <- x |> 108 | terra::spatSample(size = sample_size, na.rm = TRUE) 109 | # scale the values 110 | sum <- summary(values*scale) 111 | colnames(sum) <- names(x) 112 | } 113 | return(sum) 114 | } 115 | -------------------------------------------------------------------------------- /R/bayes_plot.R: -------------------------------------------------------------------------------- 1 | #' @title Plot RGB data cubes 2 | #' @name bayes_plot_rgb 3 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 4 | #' 5 | #' @description Plot RGB raster cube 6 | #' 7 | #' @param image Object of class SpatRaster. 8 | #' @param red Band for red color. 9 | #' @param green Band for green color. 10 | #' @param blue Band for blue color. 11 | #' @param xmin Subset to be shown (xmin) 12 | #' @param xmax Subset to be shown (xmax) 13 | #' @param ymin Subset to be shown (ymin) 14 | #' @param ymax Subset to be shown (ymax) 15 | #' @return A plot object with an RGB image 16 | #' @examples 17 | #' if (bayes_run_examples()) { 18 | #' # Define location of a RGB files 19 | #' rgb_dir <- system.file("/extdata/rgb", package = "bayesEO") 20 | #' # list the file 21 | #' files <- list.files(rgb_dir) 22 | #' # build the full path 23 | #' image_files <- paste0(rgb_dir, "/", files) 24 | #' rgb_image <- bayes_read_image(image_files) 25 | #' bayes_plot_rgb(rgb_image, red = "B11", green = "B8A", blue = "B03") 26 | #' } 27 | #' @export 28 | bayes_plot_rgb <- function(image, 29 | red, 30 | green, 31 | blue, 32 | xmin = NULL, 33 | xmax = NULL, 34 | ymin = NULL, 35 | ymax = NULL) { 36 | 37 | # get RGB files for the requested timeline 38 | red_file <- terra::sources(image[[red]]) 39 | green_file <- terra::sources(image[[green]]) 40 | blue_file <- terra::sources(image[[blue]]) 41 | rgb_files <- c(r = red_file, g = green_file, b = blue_file) 42 | 43 | # size of data to be read 44 | size <- .plot_read_size(image = image) 45 | 46 | # read raster data as a stars object with separate RGB bands 47 | rgb_st <- stars::read_stars( 48 | c(red_file, green_file, blue_file), 49 | along = "band", 50 | RasterIO = list( 51 | "nBufXSize" = size[["xsize"]], 52 | "nBufYSize" = size[["ysize"]] 53 | ), 54 | proxy = FALSE 55 | ) 56 | if (!purrr::is_null(xmin) && 57 | !purrr::is_null(xmax) && 58 | !purrr::is_null(ymin) && 59 | !purrr::is_null(ymax)) { 60 | 61 | rgb_st <- stars::st_rgb(rgb_st[,xmin:xmax, ymin:ymax, 1:3], 62 | dimension = "band", 63 | maxColorValue = 10000, 64 | use_alpha = FALSE, 65 | probs = c(0.05, 0.95), 66 | stretch = TRUE 67 | ) 68 | } else { 69 | rgb_st <- stars::st_rgb(rgb_st[,,, 1:3], 70 | dimension = "band", 71 | maxColorValue = 10000, 72 | use_alpha = FALSE, 73 | probs = c(0.05, 0.95), 74 | stretch = TRUE 75 | ) 76 | } 77 | 78 | p <- tmap::tm_shape(rgb_st, 79 | raster.downsample = FALSE) + 80 | tmap::tm_raster() + 81 | tmap::tm_graticules( 82 | labels.size = 0.7 83 | ) + 84 | tmap::tm_compass() 85 | return(p) 86 | } 87 | 88 | #' @title Plot probability maps 89 | #' @name bayes_plot_probs 90 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 91 | #' @param x SpatRaster to be plotted. 92 | #' @param scale Scaling factor to apply to the data 93 | #' @param labels Labels to be plotted 94 | #' @param palette An RColorBrewer palette 95 | #' @param tmap_scale Global scale parameter for map (default: 1.0) 96 | #' 97 | #' @return A plot object 98 | #' 99 | #' @examples 100 | #' if (bayes_run_examples()) { 101 | #' # get the probability file 102 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 103 | #' file <- list.files(data_dir) 104 | #' # build the full path 105 | #' probs_file <- paste0(data_dir, "/", file) 106 | #' # include the labels 107 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 108 | #' "ClearCut_Veg", "Forest", "Wetland") 109 | #' # associate the labels to the names of the SpatRaster 110 | #' probs <- bayes_read_probs(probs_file, labels) 111 | #' # Plot the probability image 112 | #' bayes_plot_probs(probs, 113 | #' scale = 0.0001, 114 | #' tmap_scale = 1.0) 115 | #' } 116 | #' 117 | #' @export 118 | bayes_plot_probs <- function(x, 119 | scale = 0.0001, 120 | labels = NULL, 121 | palette = "YlGnBu", 122 | tmap_scale = 1.0){ 123 | 124 | # check input image 125 | .check_that( 126 | "SpatRaster" %in% class(x), 127 | msg = "input is not SpatRaster type" 128 | ) 129 | # get all labels to be plotted 130 | all_labels <- names(x) 131 | names(all_labels) <- seq_len(length(all_labels)) 132 | # check the labels to be plotted 133 | # if NULL, use all labels 134 | if (purrr::is_null(labels)) 135 | labels <- all_labels 136 | else 137 | .check_that(all(labels %in% all_labels), 138 | msg = "labels not in image") 139 | 140 | # read the file using stars 141 | probs_st <- stars::st_as_stars(x) 142 | # scale the data 143 | if (scale != 1) { 144 | probs_st <- probs_st * scale 145 | } 146 | # rename stars object dimensions to labels 147 | probs_st <- stars::st_set_dimensions(probs_st, "band", 148 | values = all_labels) 149 | # select stars bands to be plotted 150 | bds <- as.numeric(names(all_labels[all_labels %in% labels])) 151 | 152 | p <- suppressMessages( 153 | tmap::tm_shape(probs_st[, , , bds], 154 | raster.downsample = FALSE) + 155 | tmap::tm_raster(style = "cont", 156 | palette = palette, 157 | midpoint = 0.5, 158 | title = all_labels[all_labels %in% labels]) + 159 | tmap::tm_facets(free.coords = TRUE) + 160 | tmap::tm_compass() + 161 | tmap::tm_layout( 162 | scale = tmap_scale, 163 | legend.show = TRUE, 164 | legend.outside = FALSE, 165 | legend.bg.color = "white", 166 | legend.bg.alpha = 0.5 167 | ) 168 | ) 169 | 170 | return(p) 171 | } 172 | #' @title Plot variance maps 173 | #' @name bayes_plot_var 174 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 175 | #' @param x SpatRaster to be plotted. 176 | #' @param labels Labels to be plotted 177 | #' @param quantile Thereshold of values to be plotted 178 | #' @param n Preferred number of classes 179 | #' @param style Method to process the color scale 180 | #' @param palette An RColorBrewer palette 181 | #' @param tmap_scale Global scale parameter for map (default: 1.5) 182 | #' 183 | #' @return A plot object 184 | #' 185 | #' @examples 186 | #' if (bayes_run_examples()) { 187 | #' # get the probability file 188 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 189 | #' file <- list.files(data_dir) 190 | #' # build the full path 191 | #' probs_file <- paste0(data_dir, "/", file) 192 | #' # include the labels 193 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 194 | #' "ClearCut_Veg", "Forest", "Wetland") 195 | #' # associate the labels to the names of the SpatRaster 196 | #' probs <- bayes_read_probs(probs_file, labels) 197 | #' # calculate the variance 198 | #' var <- bayes_variance(probs) 199 | #' # Plot the variance image 200 | #' bayes_plot_var(var, 201 | #' n = 15, 202 | #' style = "order", 203 | #' quantile = 0.75, 204 | #' palette = "YlGn", 205 | #' labels = c("Forest", "ClearCut_Veg")) 206 | #' } 207 | #' 208 | #' @export 209 | bayes_plot_var <- function(x, 210 | labels = NULL, 211 | quantile = 0.75, 212 | n = 15, 213 | style = "equal", 214 | palette = "YlGnBu", 215 | tmap_scale = 1.0){ 216 | 217 | # check input image 218 | .check_that( 219 | "SpatRaster" %in% class(x), 220 | msg = "input is not SpatRaster type" 221 | ) 222 | # get all labels to be plotted 223 | all_labels <- names(x) 224 | names(all_labels) <- seq_len(length(all_labels)) 225 | # check the labels to be plotted 226 | # if NULL, use all labels 227 | if (purrr::is_null(labels)) 228 | labels <- all_labels 229 | else 230 | .check_that(all(labels %in% all_labels), 231 | msg = "labels not in image") 232 | 233 | if (!purrr::is_null(quantile)) { 234 | # get values 235 | values <- terra::values(x) 236 | # show only the chosen quantile 237 | values <- lapply( 238 | colnames(values), function(name) { 239 | vls <- values[,name] 240 | quant <- stats::quantile(vls, quantile, na.rm = TRUE) 241 | vls[vls < quant] <- NA 242 | return(vls) 243 | }) 244 | values <- do.call(cbind, values) 245 | colnames(values) <- names(x) 246 | terra::values(x) <- values 247 | } 248 | # read the file using stars 249 | var_st <- stars::st_as_stars(x) 250 | # rename stars object dimensions to labels 251 | var_st <- stars::st_set_dimensions(var_st, "band", 252 | values = all_labels) 253 | # select stars bands to be plotted 254 | bds <- as.numeric(names(all_labels[all_labels %in% labels])) 255 | 256 | p <- suppressMessages( 257 | tmap::tm_shape(var_st[, , , bds], 258 | raster.downsample = FALSE) + 259 | tmap::tm_raster(style = style, 260 | n = n, 261 | palette = palette, 262 | midpoint = 0.5, 263 | title = all_labels[all_labels %in% labels]) + 264 | tmap::tm_facets(free.coords = TRUE) + 265 | tmap::tm_compass() + 266 | tmap::tm_layout( 267 | scale = tmap_scale, 268 | legend.show = TRUE, 269 | legend.outside = FALSE, 270 | legend.bg.color = "white", 271 | legend.bg.alpha = 0.5 272 | ) 273 | ) 274 | return(p) 275 | } 276 | 277 | #' @title Plot labelled map 278 | #' @name bayes_plot_map 279 | #' @author Gilberto Camara \email{gilberto.camara@@inpe.br} 280 | #' @param x SpatRaster to be plotted. 281 | #' @param legend Named vector that associates labels to colors. 282 | #' @param palette A sequential RColorBrewer palette 283 | #' @param xmin Subset to be shown (xmin) 284 | #' @param xmax Subset to be shown (xmax) 285 | #' @param ymin Subset to be shown (ymin) 286 | #' @param ymax Subset to be shown (ymax) 287 | #' @param tmap_graticules_labels_size Size of graticules labels 288 | #' (default: 0.7) 289 | #' @param tmap_legend_title_size Size of legend title (default: 1.5) 290 | #' @param tmap_legend_text_size Size of legend text (default: 1.2) 291 | #' @param tmap_legend_bg_color Color of legend backgound 292 | #' (default: "white") 293 | #' @param tmap_legend_bg_alpha Transparency of legend background 294 | #' (default: 0.5) 295 | #' @param tmap_max_cells Maximum number of cells for tmap 296 | #' (default = 1e+06) 297 | #' 298 | #' @return A plot object 299 | #' 300 | #' @examples 301 | #' if (bayes_run_examples()) { 302 | #' # Define location of a probability file 303 | #' data_dir <- system.file("/extdata/probs", 304 | #' package = "bayesEO") 305 | #' # list the file 306 | #' file <- list.files(data_dir) 307 | #' # build the full path 308 | #' probs_file <- paste0(data_dir, "/", file) 309 | #' # define labels 310 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 311 | #' "ClearCut_Veg", "Forest", "Wetland") 312 | #' 313 | #' probs_image <- bayes_read_probs(probs_file, labels) 314 | #' # Label the probs image 315 | #' y <- bayes_label(x) 316 | #' # produce a map of the labelled image 317 | #' bayes_plot_map(y) 318 | #' } 319 | #' 320 | #' @export 321 | bayes_plot_map <- function(x, 322 | legend = NULL, 323 | palette = "Spectral", 324 | xmin = NULL, 325 | xmax = NULL, 326 | ymin = NULL, 327 | ymax = NULL, 328 | tmap_graticules_labels_size = 0.6, 329 | tmap_legend_title_size = 0.7, 330 | tmap_legend_text_size = 0.7, 331 | tmap_legend_bg_color = "white", 332 | tmap_legend_bg_alpha = 0.5, 333 | tmap_max_cells = 1e+06) { 334 | # check input image 335 | .check_that( 336 | "SpatRaster" %in% class(x), 337 | msg = "input is not SpatRaster type" 338 | ) 339 | # check that input is a map 340 | .check_that( 341 | terra::nlyr(x) == 1, 342 | msg = "input is not a categorical map" 343 | ) 344 | labels <- terra::levels(x)[[1]]$class 345 | # obtain the colors 346 | colors <- .color_get_labels( 347 | labels = labels, 348 | legend = legend, 349 | palette = palette 350 | ) 351 | # read the file using stars 352 | stars_obj <- stars::st_as_stars(x) 353 | 354 | if (!purrr::is_null(xmin) && 355 | !purrr::is_null(xmax) && 356 | !purrr::is_null(ymin) && 357 | !purrr::is_null(ymax)) { 358 | stars_obj <- stars_obj[,xmin:xmax, ymin:ymax] 359 | } 360 | 361 | # plot using tmap 362 | # tmap requires numbers, not names # rename stars object 363 | stars_obj <- stats::setNames(stars_obj, "labels") 364 | p <- suppressMessages(tmap::tm_shape(stars_obj, 365 | raster.downsample = FALSE) + 366 | tmap::tm_raster( 367 | style = "cat", 368 | palette = colors, 369 | labels = labels) + 370 | tmap::tm_graticules( 371 | labels.size = tmap_graticules_labels_size 372 | ) + 373 | tmap::tm_compass() + 374 | tmap::tm_layout( 375 | legend.show = TRUE, 376 | legend.outside = FALSE, 377 | legend.title.size = tmap_legend_title_size, 378 | legend.text.size = tmap_legend_text_size, 379 | legend.bg.color = tmap_legend_bg_color, 380 | legend.bg.alpha = tmap_legend_bg_alpha) 381 | ) 382 | return(p) 383 | 384 | } 385 | #' @title Plot histogram 386 | #' @name bayes_plot_hist 387 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 388 | #' @param x SpatRaster to be plotted. 389 | #' @param scale Scale factor for SpatRaster 390 | #' @param quantile Threshold of values that will be plotted 391 | #' @param sample_size Number of samples to extract values 392 | #' 393 | #' @return A plot object 394 | #' @examples 395 | #' if (bayes_run_examples()) { 396 | #' # get the probability file 397 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 398 | #' file <- list.files(data_dir) 399 | #' # read the probability file into a SpatRaster 400 | #' x <- terra::rast(paste0(data_dir, "/", file)) 401 | #' # include the labels 402 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 403 | #' "ClearCut_Veg", "Forest", "Wetland") 404 | #' # associate the labels to the names of the SpatRaster 405 | #' names(x) <- labels 406 | #' # calculate the variance 407 | #' v <- bayes_variance(x) 408 | #' # Plot the variance histogram 409 | #' bayes_hist(v, quantile = 0.75) 410 | #'} 411 | #' 412 | #' @export 413 | bayes_plot_hist <- function(x, 414 | scale = 1, 415 | quantile = NULL, 416 | sample_size = 15000) { 417 | 418 | # take a sample from points inside the SpatVector 419 | vec <- terra::vect(terra::ext(x), crs = terra::crs(x)) 420 | points <- terra::spatSample(vec, size = sample_size) 421 | # extract values 422 | values <- terra::extract(x, points, na.rm = TRUE) 423 | # remove first column 424 | values <- values[,-1] 425 | # scale the values 426 | if (scale != 1) 427 | values <- values * scale 428 | # select the values above the quantile 429 | if (!purrr::is_null(quantile)) { 430 | values <- lapply( 431 | colnames(values), function(x) { 432 | vls <- values[,x] 433 | quant <- stats::quantile(vls, quantile) 434 | vls[vls < quant] <- NA 435 | return(vls) 436 | }) 437 | values <- do.call(cbind, values) 438 | colnames(values) <- names(x) 439 | } 440 | # convert to tibble 441 | values <- tibble::as_tibble(values) 442 | # include label names 443 | colnames(values) <- names(x) 444 | # dissolve the data for plotting 445 | values <- tidyr::pivot_longer(values, 446 | cols = tidyr::everything(), 447 | names_to = "labels", 448 | values_to = "variance") 449 | # Histogram with density plot 450 | p <- suppressWarnings( 451 | ggplot2::ggplot(values, 452 | ggplot2::aes(x = .data[["variance"]])) + 453 | ggplot2::geom_histogram(binwidth = 1, 454 | fill = "#69b3a2", 455 | color = "#e9ecef", 456 | alpha = 0.9) + 457 | ggplot2::scale_x_continuous() 458 | ) 459 | p <- p + ggplot2::facet_wrap(facets = "labels") 460 | 461 | return(p) 462 | } 463 | 464 | #' @title Return the cell size for the image to be reduced for plotting 465 | #' @name .plot_read_size 466 | #' @keywords internal 467 | #' @noRd 468 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 469 | #' 470 | #' @param image Image to be plotted. 471 | #' @return Cell size for x and y coordinates. 472 | #' 473 | #' 474 | .plot_read_size <- function(image) { 475 | # get the maximum number of bytes to be displayed 476 | max_cells <- 6e+07 477 | # numbers of nrows and ncols 478 | nrows <- nrow(image) 479 | ncols <- ncol(image) 480 | 481 | # do we need to compress? 482 | ratio <- max((nrows * ncols / max_cells), 1) 483 | # only create local files if required 484 | if (ratio > 1) { 485 | new_nrows <- round(nrows / sqrt(ratio)) 486 | new_ncols <- round(ncols * (new_nrows / nrows)) 487 | } else { 488 | new_nrows <- round(nrows) 489 | new_ncols <- round(ncols) 490 | } 491 | return(c( 492 | "xsize" = new_ncols, "ysize" = new_nrows 493 | )) 494 | } 495 | -------------------------------------------------------------------------------- /R/bayes_read.R: -------------------------------------------------------------------------------- 1 | #' @title Read probability maps 2 | #' @name bayes_read_image 3 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 4 | #' @param files Full path to raster files 5 | #' @return A SpatRaster object 6 | #' @examples 7 | #' if (bayes_run_examples()) { 8 | #' # Define location of a probability file 9 | #' data_dir <- system.file("/extdata/rgb", package = "bayesEO") 10 | #' # list the file 11 | #' files <- list.files(data_dir) 12 | #' # build the full path 13 | #' image_files <- paste0(data_dir, "/", files) 14 | #' rgb_image <- bayes_read_image(image_files) 15 | #' } 16 | #' @export 17 | bayes_read_image <- function(files){ 18 | # read the probability file into a SpatRaster 19 | x <- terra::rast(files) 20 | # associate the labels to the names of the SpatRaster 21 | return(x) 22 | } 23 | #' @title Read probability maps 24 | #' @name bayes_read_probs 25 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 26 | #' @param probs_file Full path to raster multi-band file 27 | #' containing probability matrices 28 | #' @param labels Labels to be assigned to the bands 29 | #' @return A SpatRaster object 30 | #' @examples 31 | #' if (bayes_run_examples()) { 32 | #' # Define location of a probability file 33 | #' data_dir <- system.file("/extdata/probs", package = "bayesEO") 34 | #' # list the file 35 | #' file <- list.files(data_dir) 36 | #' # build the full path 37 | #' probs_file <- paste0(data_dir, "/", file) 38 | #' # define labels 39 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 40 | #' "ClearCut_Veg", "Forest", "Wetland") 41 | #' 42 | #' probs_image <- bayes_read_probs(probs_file, labels) 43 | #' } 44 | #' @export 45 | bayes_read_probs <- function(probs_file, labels){ 46 | # read the probability file into a SpatRaster 47 | x <- terra::rast(probs_file) 48 | # associate the labels to the names of the SpatRaster 49 | names(x) <- labels 50 | return(x) 51 | } 52 | -------------------------------------------------------------------------------- /R/bayes_smooth.R: -------------------------------------------------------------------------------- 1 | #' @title Smooth probability images 2 | #' 3 | #' @name bayes_smooth 4 | #' 5 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 6 | #' 7 | #' @description Takes a classified image with probabilities, and reduces outliers 8 | #' and smoothens probability according to Bayesian statistics 9 | #' 10 | #' @param x SpatRaster object with probabilities images 11 | #' @param window_size Size of the neighborhood. 12 | #' @param neigh_fraction Fraction of neighbors with high probabilities 13 | #' to be used in Bayesian inference. 14 | #' @param smoothness Estimated variance of logit of class probabilities 15 | #' (Bayesian smoothing parameter). It can be either 16 | #' a vector or a scalar. 17 | #' 18 | #' @return A SpatRaster object 19 | #' 20 | #' @examples 21 | #' if (bayes_run_examples()) { 22 | #' # select a file with probability values 23 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 24 | #' file <- list.files(data_dir) 25 | #' # create a full path for the file 26 | #' probs_file <- paste0(data_dir, "/", file) 27 | #' # provide the labels 28 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 29 | #' "ClearCut_Veg", "Forest", "Wetland") 30 | #' # read the probs file 31 | #' probs <- bayes_read_probs(probs_file, labels) 32 | #' # smooth the probability image 33 | #' probs_smooth <- bayes_smooth(probs, 34 | #' window_size = 7, 35 | #' smoothness = 20 36 | #' ) 37 | #' # plot the probability image 38 | #' bayes_plot_probs(probs_smooth) 39 | #'} 40 | #' 41 | #' @export 42 | bayes_smooth <- function(x, 43 | window_size = 7, 44 | neigh_fraction = 0.5, 45 | smoothness = 10){ 46 | # check input image 47 | .check_that( 48 | "SpatRaster" %in% class(x), 49 | msg = "input is not SpatRaster type" 50 | ) 51 | labels <- names(x) 52 | # Check window size 53 | .check_window_size(window_size, min = 5) 54 | # Check neigh_fraction 55 | .check_num_parameter(neigh_fraction, exclusive_min = 0, max = 1) 56 | # Check smoothness 57 | .check_smoothness(smoothness, length(labels)) 58 | # Prepare smoothness parameter 59 | if (length(smoothness == 1)) { 60 | smoothness <- rep(smoothness, length(labels)) 61 | } 62 | # deal with named vector for smoothness 63 | if (!purrr::is_null(names(smoothness))) { 64 | smoothness <- smoothness[labels] 65 | smoothness <- unname(smoothness) 66 | } 67 | # read values 68 | values <- terra::values(x) 69 | # deduce scale 70 | scale <- 1/max(values) 71 | # scale values 72 | values <- values * scale 73 | # avoid zero 74 | values[values < 0.0001] <- 0.0001 75 | # avoid one 76 | values[values > 0.9999] <- 0.9999 77 | # Compute logit 78 | values <- log(values / (rowSums(values) - values)) 79 | # Process Bayesian 80 | values <- bayes_smoother_fraction( 81 | logits = values, 82 | nrows = terra::nrow(x), 83 | ncols = terra::ncol(x), 84 | window_size = window_size, 85 | smoothness = smoothness, 86 | neigh_fraction = neigh_fraction 87 | ) 88 | # Compute inverse logit 89 | values <- exp(values) / (exp(values) + 1) 90 | # rescale the data 91 | values <- values / scale 92 | # create SpatRaster 93 | y <- terra::rast(x) 94 | terra::values(y) <- values 95 | names(y) <- names(x) 96 | return(y) 97 | } 98 | #' @title Smooth probability images with Gaussian filter 99 | #' 100 | #' @name gaussian_smooth 101 | #' 102 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 103 | #' 104 | #' @description Takes a classified image with probabilities, and reduces outliers 105 | #' and smoothens probability according to a Gaussian filter 106 | #' 107 | #' @param x SpatRaster object with probabilities images 108 | #' @param window_size Size of the neighborhood. 109 | #' @param sigma Standard deviation of the spatial Gaussian kernel 110 | #' 111 | #' @return A SpatRaster object 112 | #' 113 | #' @examples 114 | #' if (bayes_run_examples()) { 115 | #' # select a file with probability values 116 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 117 | #' file <- list.files(data_dir) 118 | #' # create a full path for the file 119 | #' probs_file <- paste0(data_dir, "/", file) 120 | #' # provide the labels 121 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 122 | #' "ClearCut_Veg", "Forest", "Wetland") 123 | #' # read the probs file 124 | #' probs <- bayes_read(probs_file, labels) 125 | #' # smooth the probability image 126 | #' gauss <- gaussian_smooth(probs, 127 | #' window_size = 5, 128 | #' sigma = 1 129 | #' ) 130 | #' # plot the probability image 131 | #' bayes_plot_probs(gauss) 132 | #'} 133 | #' 134 | #' @export 135 | gaussian_smooth <- function(x, 136 | window_size = 5, 137 | sigma = 1){ 138 | # check input image 139 | .check_that( 140 | "SpatRaster" %in% class(x), 141 | msg = "input is not SpatRaster type" 142 | ) 143 | labels <- names(x) 144 | # Check window size 145 | .check_window_size(window_size, min = 5) 146 | # Check neigh_fraction 147 | .check_num_parameter(sigma, min = 1) 148 | # read values 149 | values <- terra::values(x) 150 | # deduce scale 151 | scale <- 1/max(values) 152 | # scale values 153 | values <- values * scale 154 | # avoid zero 155 | values[values < 0.0001] <- 0.0001 156 | # avoid one 157 | values[values > 0.9999] <- 0.9999 158 | # create output window 159 | gauss_kernel <- .smooth_gauss_kernel(window_size = window_size, 160 | sigma = sigma) 161 | # process Gaussian smoother 162 | values <- kernel_smoother(m = values, 163 | m_nrow = nrow(x), 164 | m_ncol = ncol(x), 165 | w = gauss_kernel, 166 | normalised = TRUE) 167 | # rescale the data 168 | values <- values / scale 169 | # create SpatRaster 170 | y <- terra::rast(x) 171 | terra::values(y) <- values 172 | names(y) <- names(x) 173 | return(y) 174 | } 175 | #' @title Smooth probability images with Gaussian filter 176 | #' 177 | #' @name bilateral_smooth 178 | #' 179 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 180 | #' 181 | #' @description Takes a classified image with probabilities, and reduces outliers 182 | #' and smoothens probability according to a Gaussian filter 183 | #' 184 | #' @param x SpatRaster object with probabilities images 185 | #' @param window_size Size of the neighborhood. 186 | #' @param sigma Standard deviation of the spatial Gaussian kernel 187 | #' @param tau Standard deviation of the class probs value 188 | #' 189 | #' 190 | #' @return A SpatRaster object 191 | #' 192 | #' @examples 193 | #' if (bayes_run_examples()) { 194 | #' # select a file with probability values 195 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 196 | #' file <- list.files(data_dir) 197 | #' # create a full path for the file 198 | #' probs_file <- paste0(data_dir, "/", file) 199 | #' # provide the labels 200 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 201 | #' "ClearCut_Veg", "Forest", "Wetland") 202 | #' # read the probs file 203 | #' probs <- bayes_read(probs_file, labels) 204 | #' # smooth the probability image 205 | #' bilat <- bilateral_smooth(probs, 206 | #' window_size = 5, 207 | #' sigma = 8, 208 | #' tau = 0.1 209 | #' ) 210 | #' # plot the probability image 211 | #' bayes_plot(bilat, scale = 0.0001) 212 | #'} 213 | #' 214 | #' @export 215 | bilateral_smooth <- function(x, 216 | window_size = 5, 217 | sigma = 8, 218 | tau = 0.1){ 219 | # check input image 220 | .check_that( 221 | "SpatRaster" %in% class(x), 222 | msg = "input is not SpatRaster type" 223 | ) 224 | labels <- names(x) 225 | # Check window size 226 | .check_window_size(window_size, min = 5) 227 | # Check neigh_fraction 228 | .check_num_parameter(sigma, min = 1) 229 | # read values 230 | values <- terra::values(x) 231 | # deduce scale 232 | scale <- 1/max(values) 233 | # scale values 234 | values <- values * scale 235 | # avoid zero 236 | values[values < 0.0001] <- 0.0001 237 | # avoid one 238 | values[values > 0.9999] <- 0.9999 239 | # create output window 240 | gauss_kernel <- .smooth_gauss_kernel(window_size = window_size, 241 | sigma = sigma) 242 | # process Gaussian smoother 243 | values <- bilateral_smoother(m = values, 244 | m_nrow = nrow(x), 245 | m_ncol = ncol(x), 246 | w = gauss_kernel, 247 | tau = tau) 248 | # rescale the data 249 | values <- values / scale 250 | # create SpatRaster 251 | y <- terra::rast(x) 252 | terra::values(y) <- values 253 | names(y) <- names(x) 254 | return(y) 255 | } 256 | #' @title Compute the 2-D Gaussian kernel 257 | #' @name .smooth_gauss_kernel 258 | #' @keywords internal 259 | #' 260 | #' @param window_size Size of the neighbourhood. 261 | #' @param sigma Standard deviation of the spatial Gaussian kernel 262 | #' 263 | #' @return returns a squared matrix filled with Gaussian function 264 | #' 265 | .smooth_gauss_kernel <- function(window_size, sigma) { 266 | 267 | stopifnot(window_size %% 2 != 0) 268 | 269 | w_center <- ceiling(window_size / 2) 270 | w_seq <- seq_len(window_size) 271 | x <- stats::dnorm( 272 | (abs(rep(w_seq, each = window_size) - w_center) ^ 2 + 273 | abs(rep(w_seq, window_size) - w_center) ^ 2) ^ (1 / 2), 274 | sd = sigma) / stats::dnorm(0) 275 | matrix(x / sum(x), nrow = window_size, byrow = T) 276 | } 277 | -------------------------------------------------------------------------------- /R/bayes_utils.R: -------------------------------------------------------------------------------- 1 | #' @title Informs if tests should run 2 | #' 3 | #' @name bayes_run_tests 4 | #' 5 | #' @description 6 | #' This function informs if tests should run. 7 | #' To run the examples, set "BAYES_RUN_TESTS" environment 8 | #' variable to "YES" using 9 | #' Sys.setenv("BAYES_RUN_TESTS" = "YES") 10 | #' To come back to the default behaviour, please unset 11 | #' the enviroment variable 12 | #' Sys.unsetenv("BAYES_RUN_TESTS") 13 | #' @return TRUE/FALSE 14 | #' 15 | #' @export 16 | bayes_run_tests <- function() { 17 | return(!Sys.getenv("BAYES_RUN_TESTS") %in% c("", "NO", "FALSE", "OFF")) 18 | } 19 | 20 | #' @title Informs if examples should run 21 | #' 22 | #' @name bayes_run_examples 23 | #' 24 | #' @description 25 | #' This function informs if examples should run. 26 | #' To run the examples, set "BAYES_RUN_EXAMPLES" environment 27 | #' variable to "YES" using 28 | #' Sys.setenv("BAYES_RUN_EXAMPLES" = "YES") 29 | #' To come back to the default behaviour, please unset 30 | #' the enviroment variable 31 | #' Sys.unsetenv("BAYES_RUN_EXAMPLES") 32 | #' 33 | #' @return A logical value 34 | #' @export 35 | bayes_run_examples <- function() { 36 | return(!Sys.getenv("BAYES_RUN_EXAMPLES") %in% c("", "NO", "FALSE", "OFF")) 37 | } 38 | -------------------------------------------------------------------------------- /R/bayes_variance.R: -------------------------------------------------------------------------------- 1 | #' @title Calculate the variance of a probability cube 2 | #' 3 | #' @author Gilberto Camara, \email{gilberto.camara@@inpe.br} 4 | #' @author Rolf Simoes, \email{rolf.simoes@@inpe.br} 5 | #' 6 | #' @description Takes a probability cube and estimate the local variance 7 | #' of the logit of the probability, 8 | #' to support the choice of parameters for Bayesian smoothing. 9 | #' 10 | #' @param x SpatRaster object containing probabilities. 11 | #' @param window_size Size of the neighborhood. 12 | #' @param neigh_fraction Fraction of neighbors with highest probability 13 | #' to be used in Bayesian inference. 14 | #' @return A variance SpatRaster object. 15 | #' 16 | #' @examples 17 | #' if (bayes_run_examples()) { 18 | #' # select a file with probability values 19 | #' data_dir <- system.file("/extdata/probs/", package = "bayesEO") 20 | #' file <- list.files(data_dir) 21 | #' # create a SpatRaster object from the file 22 | #' x <- terra::rast(paste0(data_dir, "/", file)) 23 | #' # provide the labels 24 | #' labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 25 | #' "ClearCut_Veg", "Forest", "Wetland") 26 | #' # name the layers in the SpatRaster with the labels 27 | #' names(x) <- labels 28 | #' # calculate the variance 29 | #' v <- bayes_variance(x) 30 | #' # plot the variance 31 | #' bayes_plot_var(v, quantile = 0.75) 32 | #' } 33 | #' @export 34 | bayes_variance <- function(x, 35 | window_size = 9, 36 | neigh_fraction = 0.5) { 37 | 38 | # check input image 39 | .check_that( 40 | "SpatRaster" %in% class(x), 41 | msg = "input is not SpatRaster type" 42 | ) 43 | # Check window size 44 | .check_window_size(window_size, min = 5) 45 | # Check neigh_fraction 46 | .check_num_parameter(neigh_fraction, exclusive_min = 0, max = 1) 47 | 48 | # Create a window 49 | window <- matrix(1, nrow = window_size, ncol = window_size) 50 | # read values 51 | values <- terra::values(x) 52 | # deduce scale 53 | scale <- 1/max(values) 54 | # scale values 55 | values <- values * scale 56 | # avoid zero 57 | values[values < 0.0001] <- 0.0001 58 | # avoid one 59 | values[values > 0.9999] <- 0.9999 60 | # Define transform to logits 61 | values <- log(values / (rowSums(values) - values)) 62 | # Process variance 63 | values <- bayes_var( 64 | m = values, 65 | m_nrow = terra::nrow(x), 66 | m_ncol = terra::ncol(x), 67 | w = window, 68 | neigh_fraction = neigh_fraction) 69 | # Return SpatRaster 70 | y <- terra::rast(x) 71 | terra::values(y) <- values 72 | names(y) <- names(x) 73 | return(y) 74 | } 75 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | # On load 2 | .onAttach <- function(lib, pkg) { 3 | packageStartupMessage("bayesEO - Bayesian Smoothing of Remote Sensing Image Classification.") 4 | packageStartupMessage( 5 | sprintf( 6 | "Loaded bayesEO v%s. 7 | See ?bayesEO for help, citation(\"bayesEO\") for use in publication.", 8 | utils::packageDescription("bayesEO")$Version 9 | ) 10 | ) 11 | } 12 | .onLoad <- function(lib, pkg) { 13 | bayes_colors() 14 | } 15 | # Creates a package environment to store global variables 16 | bayesEO_env <- new.env() 17 | #' @importFrom Rcpp sourceCpp 18 | #' @importFrom dplyr .data 19 | #' @useDynLib bayesEO, .registration = TRUE 20 | NULL 21 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Bayesian Smoothing of Remote Sensing Image Classification 3 | authors: Gilberto Camara, Renato Assuncao, Rolf Simoes, Felipe Souza, Pedro Andrade, Alexandre Carvalho 4 | output: github_document 5 | date: "2023-05-21" 6 | --- 7 | 8 | ```{r, echo=FALSE} 9 | knitr::opts_chunk$set( 10 | collapse = TRUE, 11 | comment = "#>", 12 | fig.path = "man/figures/README-" 13 | ) 14 | library(bayesEO) 15 | options(warn = -1) 16 | ``` 17 | 18 | ## Overview 19 | 20 | Methods such as support vector machines, random forests, and deep learning have become the popular for remote sensing image classification. Images resulting from these classifiers frequently have outliers or misclassified pixels. For this reason, image post-processing techniques are widely used to refine the labelling in a classified image in order to enhance its classification accuracy. 21 | 22 | The `bayesEO` package provides a new method for Bayesian post-processing of images produced by machine learning algorithms. The input to the package is an image containing the probabilities of that pixel belonging to each of the classes. The package provides efficient methods for removing outliers and improving class labelling. 23 | 24 | ## Reading a probability data cube 25 | 26 | The input for post-classification is an image with probabilities produced by a machine learning algorithm. This file should be multi-band, where each band contains the pixel probabilities of a single class. The file name must have information on reference dates and include a version number. In the examples, we use a file produced by a random forests algorithm applied to a data cube of Sentinel-2 images for tile "20LLQ" in the period 2020-06-04 to 2021-08-26. The image has been stored as INT2S data type with integer values between [0..10000] to represent probabilities ranging from 0 ro 1. 27 | 28 | ```{r, echo = TRUE, eval = TRUE} 29 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 30 | file <- paste0(data_dir, list.files(data_dir)) 31 | # set the labels for the data 32 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 33 | "ClearCut_Veg", "Forest", "Wetland") 34 | # read the file with the terra package 35 | probs_image <- bayes_read_probs(file, labels) 36 | ``` 37 | The training data has six classes: (a) \code{Forest} for natural tropical forest; (b) \code{Water} for lakes and rivers; (c) \code{Wetlands} for areas where water covers the soil in the wet season; (d) \code{ClearCut_Burn} for areas where fires cleared the land after tree removal. (e) \code{ClearCut_Soil} where the forest has been removed; (f) \code{ClearCut_Veg} where some vegetation remains after most trees have been removed. The class labels should also be informed by the user and associated with the SpatRaster terra object, since they are not stored in image files. 38 | 39 | The figure below shows the plot of all layer of the probability image. The map for class \code{Forest} shows high probability values associated with compact patches and linear stretches in riparian areas. Class \code{ClearCut_Soil} is mostly composed of dense areas of high probability whose geometrical boundaries result from forest cuts. By contrast, the probability maps for classes \code{Water}, \code{ClearCut_Burn}, and \code{ClearCut_Veg} have mostly low values. 40 | 41 | ```{r pcube, width = 8, tidy="styler", fig.align = 'center', fig.cap = "Class probabilities produced by random forest algorithm."} 42 | bayes_plot_probs(probs_image) 43 | ``` 44 | The non-smoothed labeled map shows the need for post-processing. This map is obtained by taking the class of higher probability to each pixel, without considering the spatial context. The resulting map contains a significant number of outliers and misclassified pixels. 45 | 46 | ```{r, tidy = "styler", echo=TRUE, eval=TRUE, fig.width = 10, fig.align = 'center', fig.cap = "Labelled map without smoothing."} 47 | map_no_smooth <- bayes_label(probs_image) 48 | bayes_plot_map(map_no_smooth) 49 | ``` 50 | 51 | ## Removing Outliers for the Probability Image 52 | 53 | To remove the outliers in the classification map, \pkg{bayesEO} provides \code{bayes_smooth()}. This function uses a Bayesian estimator. After the procedure has been applied, the resulting smoothed probability image can be converted into a map. 54 | 55 | ```{r, tidy = "styler", echo=TRUE, eval=TRUE, fig.width = 10, fig.align = 'center', fig.cap = "Labelled map with smoothing."} 56 | smooth_image <- bayes_smooth(probs_image) 57 | smooth_map <- bayes_label(smooth_image) 58 | bayes_plot_map(smooth_map) 59 | ``` 60 | 61 | The outliers have been removed and the resulting labelled map has improved accuracy. 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Bayesian Smoothing of Remote Sensing Image Classification 2 | ================ 3 | 2023-05-21 4 | 5 | ## bayesEO - Bayesian Smoothing of Remote Sensing Image Classification. 6 | 7 | ## Loaded bayesEO v1.4.0. 8 | ## See ?bayesEO for help, citation("bayesEO") for use in publication. 9 | 10 | ## Overview 11 | 12 | Methods such as support vector machines, random forests, and deep 13 | learning have become the popular for remote sensing image 14 | classification. Images resulting from these classifiers frequently have 15 | outliers or misclassified pixels. For this reason, image post-processing 16 | techniques are widely used to refine the labelling in a classified image 17 | in order to enhance its classification accuracy. 18 | 19 | 20 | The `bayesEO` package provides a new method for Bayesian post-processing 21 | of images produced by machine learning algorithms. The input to the 22 | package is an image containing the probabilities of that pixel belonging 23 | to each of the classes. The package provides efficient methods for 24 | removing outliers and improving class labelling. 25 | 26 | ## Reading a probability data cube 27 | 28 | The input for post-classification is an image with probabilities 29 | produced by a machine learning algorithm. This file should be 30 | multi-band, where each band contains the pixel probabilities of a single 31 | class. The file name must have information on reference dates and 32 | include a version number. In the examples, we use a file produced by a 33 | random forests algorithm applied to a data cube of Sentinel-2 images for 34 | tile “20LLQ” in the period 2020-06-04 to 2021-08-26. The image has been 35 | stored as INT2S data type with integer values between \[0..10000\] to 36 | represent probabilities ranging from 0 ro 1. 37 | 38 | ``` r 39 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 40 | file <- list.files(data_dir) 41 | # read the file with the terra package 42 | probs_image <- terra::rast(paste0(data_dir, "/", file)) 43 | ``` 44 | 45 | The training data has six classes: (a) for natural tropical forest; (b) 46 | for lakes and rivers; (c) for areas where water covers the soil in the 47 | wet season; (d) for areas where fires cleared the land after tree 48 | removal. (e) where the forest has been removed; (f) where some 49 | vegetation remains after most trees have been removed. The class labels 50 | should also be informed by the user and associated with the SpatRaster 51 | terra object, since they are not stored in image files. 52 | 53 | ``` r 54 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 55 | "ClearCut_Veg", "Forest", "Wetland") 56 | names(probs_image) <- labels 57 | ``` 58 | 59 | The figure below shows the plot of all layer of the probability image. 60 | The map for class shows high probability values associated with compact 61 | patches and linear stretches in riparian areas. Class is mostly composed 62 | of dense areas of high probability whose geometrical boundaries result 63 | from forest cuts. By contrast, the probability maps for classes , , and 64 | have mostly low values. Note that we need to inform the scaling 65 | parameter that converts the image to \[0..1\] interval. 66 | 67 | ``` r 68 | bayes_plot(probs_image, scale = 0.0001) 69 | ``` 70 | 71 |
72 | 73 | Class probabilities produced by random forest algorithm. 74 |

75 | Class probabilities produced by random forest algorithm. 76 |

77 | 78 |
79 | 80 | The non-smoothed labeled map shows the need for post-processing. This 81 | map is obtained by taking the class of higher probability to each pixel, 82 | without considering the spatial context. The resulting map contains a 83 | significant number of outliers and misclassified pixels. 84 | 85 | ``` r 86 | map_no_smooth <- bayes_label(probs_image) 87 | bayes_map(map_no_smooth) 88 | ``` 89 | 90 |
91 | 92 | Labelled map without smoothing. 93 |

94 | Labelled map without smoothing. 95 |

96 | 97 |
98 | 99 | ## Removing Outliers for the Probability Image 100 | 101 | To remove the outliers in the classification map, provides . This 102 | function uses a Bayesian estimator. After the procedure has been 103 | applied, the resulting smoothed probability image can be converted into 104 | a map. 105 | 106 | ``` r 107 | smooth_image <- bayes_smooth(probs_image) 108 | smooth_map <- bayes_label(smooth_image) 109 | bayes_map(smooth_map) 110 | ``` 111 | 112 |
113 | 114 | Labelled map with smoothing. 115 |

116 | Labelled map with smoothing. 117 |

118 | 119 |
120 | 121 | The outliers have been removed and the resulting labelled map has 122 | improved accuracy. 123 | -------------------------------------------------------------------------------- /bayesEO.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 4 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source --no-lock 21 | PackageBuildArgs: --resave-data=best --compact-vignettes=both 22 | PackageBuildBinaryArgs: --resave-data 23 | PackageCheckArgs: --as-cran 24 | PackageRoxygenize: rd,collate,namespace,vignette 25 | 26 | UseNativePipeOperator: Yes 27 | -------------------------------------------------------------------------------- /inst/extdata/config.yml: -------------------------------------------------------------------------------- 1 | # GDAL GTiff default creation options 2 | gdal_creation_options : [ "COMPRESS=LZW", "PREDICTOR=2", 3 | "BIGTIFF=YES", "TILED=YES", 4 | "BLOCKXSIZE=512", "BLOCKYSIZE=512" ] 5 | 6 | gdalcubes_options : ["COMPRESS=LZW", "PREDICTOR=2", 7 | "BIGTIFF=YES", "BLOCKXSIZE=512", 8 | "BLOCKYSIZE=512"] 9 | 10 | # maxbytes per plot (in MB) 11 | plot_max_Mbytes: 10 12 | # tmap max_cells (in number of cells) 13 | tmap_max_cells: 1e+06 14 | # tmap configuration parameters 15 | tmap_graticules_labels_size: 0.7 16 | tmap_legend_title_size: 1.5 17 | tmap_legend_text_size: 1.2 18 | tmap_legend_bg_color: "white" 19 | tmap_legend_bg_alpha: 0.5 20 | 21 | # maxbytes for leaflet (in MB) 22 | leaflet_max_megabytes : 64 23 | # estimated compression factor for leaflet 24 | leaflet_comp_factor : 0.50 25 | -------------------------------------------------------------------------------- /inst/extdata/config_colors.yml: -------------------------------------------------------------------------------- 1 | # Default Palette includes: 2 | # Most classes of the "Brazilian Vegetation Manual" (IBGE,2001) 3 | # IPCC AFOLU, TerraClass project, IGBP Discover, Copernicus Global Land Cover 4 | 5 | # Source https://htmlcolorcodes.com/color-chart/flat-design-color-chart/ 6 | 7 | colors: 8 | Tropical_Forest: 9 | # Based on "nephritis" palette of Flat Design Color Chart 10 | Evergreen_Broadleaf_Forest : &forest "#1E8449" 11 | # Forest 12 | Forest : *forest 13 | Closed_Forest : *forest 14 | # Dense Woodlands and similar 15 | Woodland : &woodlands "#27AE60" 16 | Dense_Woodland : *woodlands 17 | Woody_Savanna : *woodlands 18 | Open_Forest : *woodlands 19 | Cerradao : *woodlands 20 | # Mixed Forest 21 | Mixed_Forest : *woodlands 22 | Sparse_Forest : *woodlands 23 | 24 | Savanna: 25 | # Savanna and Cerrado 26 | # Based on "emerald" palette of Flat Design Color Chart 27 | Savanna : &savanna "#58D68D" 28 | Wooded_Grassland : *savanna 29 | Cerrado_Strictu_Sensu : *savanna 30 | Cerrado : *savanna 31 | Campo_Cerrado : &campo_cerrado "#ABEBC6" 32 | Savanna_Parkland : *campo_cerrado 33 | Open_Cerrado : *campo_cerrado 34 | 35 | Deciduous_Tropical_Forests: 36 | # Caatinga and decidous tropical forest 37 | # Based on "green sea" palette of Flat Design Color Chart 38 | Caatinga : &caatinga "#A2D9CE" 39 | Deciduous_Forest : *caatinga 40 | 41 | Planted_Forest: 42 | # Silviculture and Planted Forest 43 | # Based on "green sea" palette of Flat Design Color Chart 44 | Planted_Forest : &planted_forest "#45B39D" 45 | Silviculture : *planted_forest 46 | # Secondary Vegetation 47 | # Based on "turqouise" palette from Flat Design Color Chart 48 | Secondary_Vegetation : "#48C9B0" 49 | 50 | Boreal_Temperate_Forests: 51 | # Based on "turquoise" palette of Flat Design Color Chart 52 | Evergreen_Needleleaf_Forest : &enf "#1ABC9C" 53 | Deciduous_Needleleaf_Forest : &dnf "#76D7C4" 54 | Deciduous_Broadleaf_Forest : &dnf "#A3E4D7" 55 | 56 | Grassland: 57 | # Based on "sunflower" palette of Flat Design Color Chart 58 | Grassland : &grassland "#F7DC6F" 59 | Steppe : *grassland 60 | Natural_Herbaceous : *grassland 61 | # Pasture is a special case 62 | # based on "green sea" palette of Flat Design Color Chart 63 | Pasture : &pasture "#FCF3CF" 64 | Dense_Herbaceous : *pasture 65 | Herbaceous_Vegetation : *pasture 66 | 67 | Shrubland: 68 | # Based on "orange" palette of Flat Design Color Chart 69 | Closed_Shrubland : &closed_shrubland "#F39C12" 70 | Wooded_Shrubland : *closed_shrubland 71 | Dense_Shrubland : *closed_shrubland 72 | Shrubland : &shrubland "#F8C471" 73 | Open_Shrubland : *shrubland 74 | Sparse_Shrubland : *shrubland 75 | Rocky_Savanna : *shrubland 76 | 77 | Barren: 78 | # Based on "orange" palette of Flat Design Color Chart 79 | Barren : &barren "#FDEBD0" 80 | Sparsely_Vegetated : *barren 81 | Natural_Non_Forested : *barren 82 | Nat_NonVeg : *barren 83 | Natural_Non_Vegetated : *barren 84 | Dunes : "#FEF9E7" 85 | 86 | Cropland: 87 | # Based on "carrot" palette from Flat Design Color Chart 88 | Cropland : &cropland "#F0B27A" 89 | Temporary_Crop : *cropland 90 | Temporary_Agriculture : *cropland 91 | Agriculture_1_cycle : *cropland 92 | Cropland_1_cycle : *cropland 93 | Agriculture_2_cycle : &ag_2_cycle "#EB984E" 94 | Cropland_2_cycle : *ag_2_cycle 95 | Semi_Perennial_Crop : &semi_perennial_crop "#E67E22" 96 | # Sugarcane is semi perennial crop 97 | Sugarcane : *semi_perennial_crop 98 | Perennial_Crop : &perennial_crop "#CA6F1E" 99 | Perennial_Agriculture. : *perennial_crop 100 | Annual_Crop : *perennial_crop 101 | # Coffee is perennial agriculture 102 | Coffee : *perennial_crop 103 | 104 | # Soybean and its variations 105 | # Based on "orange" palette from Flat Design Color Chart 106 | Soybeans : &soy "#FAD7A0" 107 | Soy_Fallow : *soy 108 | Soy : *soy 109 | Soy_Sunflower : "#F8C471" 110 | Soy_Millet : &soy_millet "#F5B041" 111 | Soy_Sorghum : *soy_millet 112 | Soy_Corn : "#D68910" 113 | Soy_Cotton : "#9C640C" 114 | 115 | # Other crops 116 | # Based on "pumpkin" palette from Flat Design Color Chart 117 | # Cotton 118 | Cotton : &cotton "#D35400" 119 | Fallow_Cotton : *cotton 120 | Millet_Cotton : *cotton 121 | # Grains 122 | Corn : &corn "#DC7633" 123 | Maize : *corn 124 | Sorghum : &sorghum "#E59866" 125 | Millet : *sorghum 126 | Beans : "#EDBB99" 127 | Wheat : "#F6DDCC" 128 | # Based on "turquoise" palette of Flat Design Color Chart 129 | Rice : "#FBEEE6" 130 | 131 | Mosaic: 132 | # Mosaic classes use color 2 of "YlGn-9" Brewer palette 133 | Forest_Cropland_Mosaic : "#F7FCB9" 134 | Cropland_Natural_Vegetation: "#F7FCB9" 135 | 136 | Wetland: 137 | # Based on "belize hole" palette from Flat Design Color Chart 138 | Water : "#2980B9" 139 | Wetland : &wetlands "#7FB3D5" 140 | Permanent_Wetland : *wetlands 141 | # Based on "peter river" palette from Flat Design Color Chart 142 | Mangrove : "#D4E6F1" 143 | 144 | Deforestation: 145 | 146 | # Deforestation, Degradation, Mining 147 | # Based on "Alizarin" palette from Flat Design Color Chart 148 | Deforestation : &deforestation "#FDEDEC" 149 | Deforestation_Mask : *deforestation 150 | Degradation : "#F5B7B1" 151 | # PRODES 152 | # Based on "Alizarin" palette from Flat Design Color Chart 153 | Burned_Area : &burned_area "#EC7063" 154 | ClearCut_Burn : *burned_area 155 | # Based on "sunflower" palette of Flat Design Color Chart 156 | Cleared_Area : &clear_cut_soil "#F1C40F" 157 | ClearCut_Soil : *clear_cut_soil 158 | Bare_Soil : *clear_cut_soil 159 | # Based on "nephritis" palette of Flat Design Color Chart 160 | Highly_Degraded : &clear_cut_deg "#D4EFDF" 161 | ClearCut_Veg : *clear_cut_deg 162 | # Based on "amethyst" palette from Flat Design Color Chart 163 | Mining : "#C39BD3" 164 | # Based on "silver" palette from Flat Design Color Chart 165 | Non_Forest : "#BDC3C7" 166 | Urban: 167 | # Based on "wet asphalt" palette from Flat Design Color Chart 168 | Urban_Area : "#85929E" 169 | 170 | Snow_Ice: 171 | # Based on "asbestos" palette from Flat Design Color Chart 172 | Snow_Ice : &snow "#E5E8E8" 173 | 174 | Others: 175 | # No Class uses "silver" palette from Flat Design Color Chart 176 | No_Class : &no_class "#F2F3F4" 177 | No_Samples : *no_class 178 | Unclassified : *no_class 179 | # Cloud uses "cloud" palette from Flat Design Color Chart 180 | Cloud : &cloud "#D0D3D4" 181 | 182 | -------------------------------------------------------------------------------- /inst/extdata/example/example.R: -------------------------------------------------------------------------------- 1 | data_dir <- system.file("/extdata/Rondonia-20LLQ/", package = "sitsdata") 2 | probs_file <- paste0(data_dir, 3 | "SENTINEL-2_MSI_20LLQ_2020-06-04_2021-08-26_probs_v1.tif") 4 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 5 | "ClearCut_Veg", "Forest", "Wetland") 6 | 7 | probs_image <- bayes_read_probs(probs_file, labels) 8 | bayes_plot_probs(probs_image) 9 | 10 | label_map_no_smooth <- bayes_label(probs_image) 11 | bayes_plot_map(label_map_no_smooth) 12 | 13 | green_file <- paste0(data_dir, "SENTINEL-2_MSI_20LLQ_B8A_2021-09-06.tif") 14 | red_file <- paste0(data_dir, "SENTINEL-2_MSI_20LLQ_B11_2021-09-06.tif") 15 | blue_file <- paste0(data_dir, "SENTINEL-2_MSI_20LLQ_B02_2021-09-06.tif") 16 | 17 | rgb_files <- c(green_file, red_file, blue_file) 18 | 19 | rgb_image <- bayes_read_image(rgb_files) 20 | 21 | bayes_plot_rgb(rgb_image, red = "B11", green = "B8A", blue = "B02") 22 | 23 | bayes_view(rgb_image, label_map_no_smooth, 24 | red = "B11", green = "B8A", blue = "B02") 25 | 26 | LLQ_cube <- sits_cube( 27 | source = "MPC", 28 | collection = "SENTINEL-2-L2A", 29 | bands = c("B02", "B8A", "B11"), 30 | data_dir = data_dir 31 | ) 32 | 33 | 34 | LLQ_cube_copy <- sits_cube_copy( 35 | LLQ_cube, 36 | roi = c(xmin = 340000, xmax = 350000, ymin = 8930240, ymax = 8940240), 37 | output_dir = "~/bayesEO/inst/extdata/rgb2/" 38 | ) 39 | -------------------------------------------------------------------------------- /inst/extdata/probs/SENTINEL-2_MSI_20LLQ_2020-06-04_2021-08-26_probs_v0.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/inst/extdata/probs/SENTINEL-2_MSI_20LLQ_2020-06-04_2021-08-26_probs_v0.tif -------------------------------------------------------------------------------- /inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B02_2021-09-22.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B02_2021-09-22.tif -------------------------------------------------------------------------------- /inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B11_2021-09-22.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B11_2021-09-22.tif -------------------------------------------------------------------------------- /inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B8A_2021-09-22.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/inst/extdata/rgb/SENTINEL-2_MSI_20LLQ_B8A_2021-09-22.tif -------------------------------------------------------------------------------- /man/bayes_colors.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_colors.R 3 | \name{bayes_colors} 4 | \alias{bayes_colors} 5 | \title{Function to retrieve bayesEO color table} 6 | \usage{ 7 | bayes_colors() 8 | } 9 | \value{ 10 | A tibble with color names and values 11 | } 12 | \description{ 13 | Returns a color table 14 | } 15 | \author{ 16 | Gilberto Camara, \email{gilberto.camara@inpe.br} 17 | } 18 | -------------------------------------------------------------------------------- /man/bayes_colors_show.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_colors.R 3 | \name{bayes_colors_show} 4 | \alias{bayes_colors_show} 5 | \title{Function to show colors in SITS} 6 | \usage{ 7 | bayes_colors_show() 8 | } 9 | \value{ 10 | no return, called for side effects 11 | } 12 | \description{ 13 | Shows the default SITS colors 14 | } 15 | \author{ 16 | Gilberto Camara, \email{gilberto.camara@inpe.br} 17 | } 18 | -------------------------------------------------------------------------------- /man/bayes_label.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_label.R 3 | \name{bayes_label} 4 | \alias{bayes_label} 5 | \title{Label probability images to create categorical maps} 6 | \usage{ 7 | bayes_label(x) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster object with probabilities images} 11 | } 12 | \value{ 13 | A SpatRaster object 14 | } 15 | \description{ 16 | Takes a classified image with probabilities, and 17 | labels the image with the pixel of higher probability 18 | } 19 | \examples{ 20 | if (bayes_run_examples()) { 21 | # select a file with probability values 22 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 23 | file <- list.files(data_dir) 24 | # create a SpatRaster object from the file 25 | probs_file <- paste0(data_dir, "/", file) 26 | # provide the labels 27 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 28 | "ClearCut_Veg", "Forest", "Wetland") 29 | # read the probs file 30 | probs <- bayes_read_probs(probs_file, labels) 31 | # produce a labelled map 32 | map <- bayes_label(probs) 33 | # plot the labelled map 34 | bayes_plot_map(map) 35 | } 36 | 37 | } 38 | \author{ 39 | Gilberto Camara, \email{gilberto.camara@inpe.br} 40 | } 41 | -------------------------------------------------------------------------------- /man/bayes_plot_hist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_plot.R 3 | \name{bayes_plot_hist} 4 | \alias{bayes_plot_hist} 5 | \title{Plot histogram} 6 | \usage{ 7 | bayes_plot_hist(x, scale = 1, quantile = NULL, sample_size = 15000) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster to be plotted.} 11 | 12 | \item{scale}{Scale factor for SpatRaster} 13 | 14 | \item{quantile}{Threshold of values that will be plotted} 15 | 16 | \item{sample_size}{Number of samples to extract values} 17 | } 18 | \value{ 19 | A plot object 20 | } 21 | \description{ 22 | Plot histogram 23 | } 24 | \examples{ 25 | if (bayes_run_examples()) { 26 | # get the probability file 27 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 28 | file <- list.files(data_dir) 29 | # read the probability file into a SpatRaster 30 | x <- terra::rast(paste0(data_dir, "/", file)) 31 | # include the labels 32 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 33 | "ClearCut_Veg", "Forest", "Wetland") 34 | # associate the labels to the names of the SpatRaster 35 | names(x) <- labels 36 | # calculate the variance 37 | v <- bayes_variance(x) 38 | # Plot the variance histogram 39 | bayes_hist(v, quantile = 0.75) 40 | } 41 | 42 | } 43 | \author{ 44 | Gilberto Camara, \email{gilberto.camara@inpe.br} 45 | } 46 | -------------------------------------------------------------------------------- /man/bayes_plot_map.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_plot.R 3 | \name{bayes_plot_map} 4 | \alias{bayes_plot_map} 5 | \title{Plot labelled map} 6 | \usage{ 7 | bayes_plot_map( 8 | x, 9 | legend = NULL, 10 | palette = "Spectral", 11 | xmin = NULL, 12 | xmax = NULL, 13 | ymin = NULL, 14 | ymax = NULL, 15 | tmap_graticules_labels_size = 0.6, 16 | tmap_legend_title_size = 0.7, 17 | tmap_legend_text_size = 0.7, 18 | tmap_legend_bg_color = "white", 19 | tmap_legend_bg_alpha = 0.5, 20 | tmap_max_cells = 1e+06 21 | ) 22 | } 23 | \arguments{ 24 | \item{x}{SpatRaster to be plotted.} 25 | 26 | \item{legend}{Named vector that associates labels to colors.} 27 | 28 | \item{palette}{A sequential RColorBrewer palette} 29 | 30 | \item{xmin}{Subset to be shown (xmin)} 31 | 32 | \item{xmax}{Subset to be shown (xmax)} 33 | 34 | \item{ymin}{Subset to be shown (ymin)} 35 | 36 | \item{ymax}{Subset to be shown (ymax)} 37 | 38 | \item{tmap_graticules_labels_size}{Size of graticules labels 39 | (default: 0.7)} 40 | 41 | \item{tmap_legend_title_size}{Size of legend title (default: 1.5)} 42 | 43 | \item{tmap_legend_text_size}{Size of legend text (default: 1.2)} 44 | 45 | \item{tmap_legend_bg_color}{Color of legend backgound 46 | (default: "white")} 47 | 48 | \item{tmap_legend_bg_alpha}{Transparency of legend background 49 | (default: 0.5)} 50 | 51 | \item{tmap_max_cells}{Maximum number of cells for tmap 52 | (default = 1e+06)} 53 | } 54 | \value{ 55 | A plot object 56 | } 57 | \description{ 58 | Plot labelled map 59 | } 60 | \examples{ 61 | if (bayes_run_examples()) { 62 | # Define location of a probability file 63 | data_dir <- system.file("/extdata/probs", 64 | package = "bayesEO") 65 | # list the file 66 | file <- list.files(data_dir) 67 | # build the full path 68 | probs_file <- paste0(data_dir, "/", file) 69 | # define labels 70 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 71 | "ClearCut_Veg", "Forest", "Wetland") 72 | 73 | probs_image <- bayes_read_probs(probs_file, labels) 74 | # Label the probs image 75 | y <- bayes_label(x) 76 | # produce a map of the labelled image 77 | bayes_plot_map(y) 78 | } 79 | 80 | } 81 | \author{ 82 | Gilberto Camara \email{gilberto.camara@inpe.br} 83 | } 84 | -------------------------------------------------------------------------------- /man/bayes_plot_probs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_plot.R 3 | \name{bayes_plot_probs} 4 | \alias{bayes_plot_probs} 5 | \title{Plot probability maps} 6 | \usage{ 7 | bayes_plot_probs( 8 | x, 9 | scale = 1e-04, 10 | labels = NULL, 11 | palette = "YlGnBu", 12 | tmap_scale = 1 13 | ) 14 | } 15 | \arguments{ 16 | \item{x}{SpatRaster to be plotted.} 17 | 18 | \item{scale}{Scaling factor to apply to the data} 19 | 20 | \item{labels}{Labels to be plotted} 21 | 22 | \item{palette}{An RColorBrewer palette} 23 | 24 | \item{tmap_scale}{Global scale parameter for map (default: 1.0)} 25 | } 26 | \value{ 27 | A plot object 28 | } 29 | \description{ 30 | Plot probability maps 31 | } 32 | \examples{ 33 | if (bayes_run_examples()) { 34 | # get the probability file 35 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 36 | file <- list.files(data_dir) 37 | # build the full path 38 | probs_file <- paste0(data_dir, "/", file) 39 | # include the labels 40 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 41 | "ClearCut_Veg", "Forest", "Wetland") 42 | # associate the labels to the names of the SpatRaster 43 | probs <- bayes_read_probs(probs_file, labels) 44 | # Plot the probability image 45 | bayes_plot_probs(probs, 46 | scale = 0.0001, 47 | tmap_scale = 1.0) 48 | } 49 | 50 | } 51 | \author{ 52 | Gilberto Camara, \email{gilberto.camara@inpe.br} 53 | } 54 | -------------------------------------------------------------------------------- /man/bayes_plot_rgb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_plot.R 3 | \name{bayes_plot_rgb} 4 | \alias{bayes_plot_rgb} 5 | \title{Plot RGB data cubes} 6 | \usage{ 7 | bayes_plot_rgb( 8 | image, 9 | red, 10 | green, 11 | blue, 12 | xmin = NULL, 13 | xmax = NULL, 14 | ymin = NULL, 15 | ymax = NULL 16 | ) 17 | } 18 | \arguments{ 19 | \item{image}{Object of class SpatRaster.} 20 | 21 | \item{red}{Band for red color.} 22 | 23 | \item{green}{Band for green color.} 24 | 25 | \item{blue}{Band for blue color.} 26 | 27 | \item{xmin}{Subset to be shown (xmin)} 28 | 29 | \item{xmax}{Subset to be shown (xmax)} 30 | 31 | \item{ymin}{Subset to be shown (ymin)} 32 | 33 | \item{ymax}{Subset to be shown (ymax)} 34 | } 35 | \value{ 36 | A plot object with an RGB image 37 | } 38 | \description{ 39 | Plot RGB raster cube 40 | } 41 | \examples{ 42 | if (bayes_run_examples()) { 43 | # Define location of a RGB files 44 | rgb_dir <- system.file("/extdata/rgb", package = "bayesEO") 45 | # list the file 46 | files <- list.files(rgb_dir) 47 | # build the full path 48 | image_files <- paste0(rgb_dir, "/", files) 49 | rgb_image <- bayes_read_image(image_files) 50 | bayes_plot_rgb(rgb_image, red = "B11", green = "B8A", blue = "B03") 51 | } 52 | } 53 | \author{ 54 | Gilberto Camara, \email{gilberto.camara@inpe.br} 55 | } 56 | -------------------------------------------------------------------------------- /man/bayes_plot_var.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_plot.R 3 | \name{bayes_plot_var} 4 | \alias{bayes_plot_var} 5 | \title{Plot variance maps} 6 | \usage{ 7 | bayes_plot_var( 8 | x, 9 | labels = NULL, 10 | quantile = 0.75, 11 | n = 15, 12 | style = "equal", 13 | palette = "YlGnBu", 14 | tmap_scale = 1 15 | ) 16 | } 17 | \arguments{ 18 | \item{x}{SpatRaster to be plotted.} 19 | 20 | \item{labels}{Labels to be plotted} 21 | 22 | \item{quantile}{Thereshold of values to be plotted} 23 | 24 | \item{n}{Preferred number of classes} 25 | 26 | \item{style}{Method to process the color scale} 27 | 28 | \item{palette}{An RColorBrewer palette} 29 | 30 | \item{tmap_scale}{Global scale parameter for map (default: 1.5)} 31 | } 32 | \value{ 33 | A plot object 34 | } 35 | \description{ 36 | Plot variance maps 37 | } 38 | \examples{ 39 | if (bayes_run_examples()) { 40 | # get the probability file 41 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 42 | file <- list.files(data_dir) 43 | # build the full path 44 | probs_file <- paste0(data_dir, "/", file) 45 | # include the labels 46 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 47 | "ClearCut_Veg", "Forest", "Wetland") 48 | # associate the labels to the names of the SpatRaster 49 | probs <- bayes_read_probs(probs_file, labels) 50 | # calculate the variance 51 | var <- bayes_variance(probs) 52 | # Plot the variance image 53 | bayes_plot_var(var, 54 | n = 15, 55 | style = "order", 56 | quantile = 0.75, 57 | palette = "YlGn", 58 | labels = c("Forest", "ClearCut_Veg")) 59 | } 60 | 61 | } 62 | \author{ 63 | Gilberto Camara, \email{gilberto.camara@inpe.br} 64 | } 65 | -------------------------------------------------------------------------------- /man/bayes_read_image.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_read.R 3 | \name{bayes_read_image} 4 | \alias{bayes_read_image} 5 | \title{Read probability maps} 6 | \usage{ 7 | bayes_read_image(files) 8 | } 9 | \arguments{ 10 | \item{files}{Full path to raster files} 11 | } 12 | \value{ 13 | A SpatRaster object 14 | } 15 | \description{ 16 | Read probability maps 17 | } 18 | \examples{ 19 | if (bayes_run_examples()) { 20 | # Define location of a probability file 21 | data_dir <- system.file("/extdata/rgb", package = "bayesEO") 22 | # list the file 23 | files <- list.files(data_dir) 24 | # build the full path 25 | image_files <- paste0(data_dir, "/", files) 26 | rgb_image <- bayes_read_image(image_files) 27 | } 28 | } 29 | \author{ 30 | Gilberto Camara, \email{gilberto.camara@inpe.br} 31 | } 32 | -------------------------------------------------------------------------------- /man/bayes_read_probs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_read.R 3 | \name{bayes_read_probs} 4 | \alias{bayes_read_probs} 5 | \title{Read probability maps} 6 | \usage{ 7 | bayes_read_probs(probs_file, labels) 8 | } 9 | \arguments{ 10 | \item{probs_file}{Full path to raster multi-band file 11 | containing probability matrices} 12 | 13 | \item{labels}{Labels to be assigned to the bands} 14 | } 15 | \value{ 16 | A SpatRaster object 17 | } 18 | \description{ 19 | Read probability maps 20 | } 21 | \examples{ 22 | if (bayes_run_examples()) { 23 | # Define location of a probability file 24 | data_dir <- system.file("/extdata/probs", package = "bayesEO") 25 | # list the file 26 | file <- list.files(data_dir) 27 | # build the full path 28 | probs_file <- paste0(data_dir, "/", file) 29 | # define labels 30 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 31 | "ClearCut_Veg", "Forest", "Wetland") 32 | 33 | probs_image <- bayes_read_probs(probs_file, labels) 34 | } 35 | } 36 | \author{ 37 | Gilberto Camara, \email{gilberto.camara@inpe.br} 38 | } 39 | -------------------------------------------------------------------------------- /man/bayes_run_examples.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_utils.R 3 | \name{bayes_run_examples} 4 | \alias{bayes_run_examples} 5 | \title{Informs if examples should run} 6 | \usage{ 7 | bayes_run_examples() 8 | } 9 | \value{ 10 | A logical value 11 | } 12 | \description{ 13 | This function informs if examples should run. 14 | To run the examples, set "BAYES_RUN_EXAMPLES" environment 15 | variable to "YES" using 16 | Sys.setenv("BAYES_RUN_EXAMPLES" = "YES") 17 | To come back to the default behaviour, please unset 18 | the enviroment variable 19 | Sys.unsetenv("BAYES_RUN_EXAMPLES") 20 | } 21 | -------------------------------------------------------------------------------- /man/bayes_run_tests.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_utils.R 3 | \name{bayes_run_tests} 4 | \alias{bayes_run_tests} 5 | \title{Informs if tests should run} 6 | \usage{ 7 | bayes_run_tests() 8 | } 9 | \value{ 10 | TRUE/FALSE 11 | } 12 | \description{ 13 | This function informs if tests should run. 14 | To run the examples, set "BAYES_RUN_TESTS" environment 15 | variable to "YES" using 16 | Sys.setenv("BAYES_RUN_TESTS" = "YES") 17 | To come back to the default behaviour, please unset 18 | the enviroment variable 19 | Sys.unsetenv("BAYES_RUN_TESTS") 20 | } 21 | -------------------------------------------------------------------------------- /man/bayes_smooth.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_smooth.R 3 | \name{bayes_smooth} 4 | \alias{bayes_smooth} 5 | \title{Smooth probability images} 6 | \usage{ 7 | bayes_smooth(x, window_size = 7, neigh_fraction = 0.5, smoothness = 10) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster object with probabilities images} 11 | 12 | \item{window_size}{Size of the neighborhood.} 13 | 14 | \item{neigh_fraction}{Fraction of neighbors with high probabilities 15 | to be used in Bayesian inference.} 16 | 17 | \item{smoothness}{Estimated variance of logit of class probabilities 18 | (Bayesian smoothing parameter). It can be either 19 | a vector or a scalar.} 20 | } 21 | \value{ 22 | A SpatRaster object 23 | } 24 | \description{ 25 | Takes a classified image with probabilities, and reduces outliers 26 | and smoothens probability according to Bayesian statistics 27 | } 28 | \examples{ 29 | if (bayes_run_examples()) { 30 | # select a file with probability values 31 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 32 | file <- list.files(data_dir) 33 | # create a full path for the file 34 | probs_file <- paste0(data_dir, "/", file) 35 | # provide the labels 36 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 37 | "ClearCut_Veg", "Forest", "Wetland") 38 | # read the probs file 39 | probs <- bayes_read_probs(probs_file, labels) 40 | # smooth the probability image 41 | probs_smooth <- bayes_smooth(probs, 42 | window_size = 7, 43 | smoothness = 20 44 | ) 45 | # plot the probability image 46 | bayes_plot_probs(probs_smooth) 47 | } 48 | 49 | } 50 | \author{ 51 | Gilberto Camara, \email{gilberto.camara@inpe.br} 52 | } 53 | -------------------------------------------------------------------------------- /man/bayes_summary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_label.R 3 | \name{bayes_summary} 4 | \alias{bayes_summary} 5 | \title{Summary of categorical maps} 6 | \usage{ 7 | bayes_summary(x, scale = 1, sample_size = 15000) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster categorical object} 11 | 12 | \item{scale}{Scale to apply to data} 13 | 14 | \item{sample_size}{Sample size} 15 | } 16 | \value{ 17 | A tibble with information 18 | } 19 | \description{ 20 | Takes a classified image with probabilities, and 21 | labels the image with the pixel of higher probability 22 | } 23 | \examples{ 24 | if (bayes_run_examples()) { 25 | # select a file with probability values 26 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 27 | file <- list.files(data_dir) 28 | # create a SpatRaster object from the file 29 | probs_file <- paste0(data_dir, "/", file) 30 | # provide the labels 31 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 32 | "ClearCut_Veg", "Forest", "Wetland") 33 | # read the probs file 34 | probs <- bayes_read_probs(probs_file, labels) 35 | # produce a labelled map 36 | map <- bayes_label(probs) 37 | # plot the labelled map 38 | bayes_summary(map) 39 | } 40 | 41 | } 42 | \author{ 43 | Gilberto Camara, \email{gilberto.camara@inpe.br} 44 | } 45 | -------------------------------------------------------------------------------- /man/bayes_variance.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_variance.R 3 | \name{bayes_variance} 4 | \alias{bayes_variance} 5 | \title{Calculate the variance of a probability cube} 6 | \usage{ 7 | bayes_variance(x, window_size = 9, neigh_fraction = 0.5) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster object containing probabilities.} 11 | 12 | \item{window_size}{Size of the neighborhood.} 13 | 14 | \item{neigh_fraction}{Fraction of neighbors with highest probability 15 | to be used in Bayesian inference.} 16 | } 17 | \value{ 18 | A variance SpatRaster object. 19 | } 20 | \description{ 21 | Takes a probability cube and estimate the local variance 22 | of the logit of the probability, 23 | to support the choice of parameters for Bayesian smoothing. 24 | } 25 | \examples{ 26 | if (bayes_run_examples()) { 27 | # select a file with probability values 28 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 29 | file <- list.files(data_dir) 30 | # create a SpatRaster object from the file 31 | x <- terra::rast(paste0(data_dir, "/", file)) 32 | # provide the labels 33 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 34 | "ClearCut_Veg", "Forest", "Wetland") 35 | # name the layers in the SpatRaster with the labels 36 | names(x) <- labels 37 | # calculate the variance 38 | v <- bayes_variance(x) 39 | # plot the variance 40 | bayes_plot_var(v, quantile = 0.75) 41 | } 42 | } 43 | \author{ 44 | Gilberto Camara, \email{gilberto.camara@inpe.br} 45 | 46 | Rolf Simoes, \email{rolf.simoes@inpe.br} 47 | } 48 | -------------------------------------------------------------------------------- /man/bilateral_smooth.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_smooth.R 3 | \name{bilateral_smooth} 4 | \alias{bilateral_smooth} 5 | \title{Smooth probability images with Gaussian filter} 6 | \usage{ 7 | bilateral_smooth(x, window_size = 5, sigma = 8, tau = 0.1) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster object with probabilities images} 11 | 12 | \item{window_size}{Size of the neighborhood.} 13 | 14 | \item{sigma}{Standard deviation of the spatial Gaussian kernel} 15 | 16 | \item{tau}{Standard deviation of the class probs value} 17 | } 18 | \value{ 19 | A SpatRaster object 20 | } 21 | \description{ 22 | Takes a classified image with probabilities, and reduces outliers 23 | and smoothens probability according to a Gaussian filter 24 | } 25 | \examples{ 26 | if (bayes_run_examples()) { 27 | # select a file with probability values 28 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 29 | file <- list.files(data_dir) 30 | # create a full path for the file 31 | probs_file <- paste0(data_dir, "/", file) 32 | # provide the labels 33 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 34 | "ClearCut_Veg", "Forest", "Wetland") 35 | # read the probs file 36 | probs <- bayes_read(probs_file, labels) 37 | # smooth the probability image 38 | bilat <- bilateral_smooth(probs, 39 | window_size = 5, 40 | sigma = 8, 41 | tau = 0.1 42 | ) 43 | # plot the probability image 44 | bayes_plot(bilat, scale = 0.0001) 45 | } 46 | 47 | } 48 | \author{ 49 | Gilberto Camara, \email{gilberto.camara@inpe.br} 50 | } 51 | -------------------------------------------------------------------------------- /man/dot-smooth_gauss_kernel.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_smooth.R 3 | \name{.smooth_gauss_kernel} 4 | \alias{.smooth_gauss_kernel} 5 | \title{Compute the 2-D Gaussian kernel} 6 | \usage{ 7 | .smooth_gauss_kernel(window_size, sigma) 8 | } 9 | \arguments{ 10 | \item{window_size}{Size of the neighbourhood.} 11 | 12 | \item{sigma}{Standard deviation of the spatial Gaussian kernel} 13 | } 14 | \value{ 15 | returns a squared matrix filled with Gaussian function 16 | } 17 | \description{ 18 | Compute the 2-D Gaussian kernel 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /man/figures/README-pcube-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/man/figures/README-pcube-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-4-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/man/figures/README-unnamed-chunk-4-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-5-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e-sensing/bayesEO/7bc2471a842722a0d0a27f690b75416aa4a24d03/man/figures/README-unnamed-chunk-5-1.png -------------------------------------------------------------------------------- /man/gaussian_smooth.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bayes_smooth.R 3 | \name{gaussian_smooth} 4 | \alias{gaussian_smooth} 5 | \title{Smooth probability images with Gaussian filter} 6 | \usage{ 7 | gaussian_smooth(x, window_size = 5, sigma = 1) 8 | } 9 | \arguments{ 10 | \item{x}{SpatRaster object with probabilities images} 11 | 12 | \item{window_size}{Size of the neighborhood.} 13 | 14 | \item{sigma}{Standard deviation of the spatial Gaussian kernel} 15 | } 16 | \value{ 17 | A SpatRaster object 18 | } 19 | \description{ 20 | Takes a classified image with probabilities, and reduces outliers 21 | and smoothens probability according to a Gaussian filter 22 | } 23 | \examples{ 24 | if (bayes_run_examples()) { 25 | # select a file with probability values 26 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 27 | file <- list.files(data_dir) 28 | # create a full path for the file 29 | probs_file <- paste0(data_dir, "/", file) 30 | # provide the labels 31 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 32 | "ClearCut_Veg", "Forest", "Wetland") 33 | # read the probs file 34 | probs <- bayes_read(probs_file, labels) 35 | # smooth the probability image 36 | gauss <- gaussian_smooth(probs, 37 | window_size = 5, 38 | sigma = 1 39 | ) 40 | # plot the probability image 41 | bayes_plot_probs(gauss) 42 | } 43 | 44 | } 45 | \author{ 46 | Gilberto Camara, \email{gilberto.camara@inpe.br} 47 | } 48 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | ## Armadillo requires it 2 | # CXX_STD = CXX11 3 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 4 | PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 5 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | # CXX_STD = CXX11 2 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 3 | PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 4 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | #include 6 | 7 | using namespace Rcpp; 8 | 9 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 10 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 11 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 12 | #endif 13 | 14 | // bayes_smoother_fraction 15 | NumericVector bayes_smoother_fraction(const NumericMatrix& logits, const int& nrows, const int& ncols, const int& window_size, const NumericVector& smoothness, const double& neigh_fraction); 16 | RcppExport SEXP _bayesEO_bayes_smoother_fraction(SEXP logitsSEXP, SEXP nrowsSEXP, SEXP ncolsSEXP, SEXP window_sizeSEXP, SEXP smoothnessSEXP, SEXP neigh_fractionSEXP) { 17 | BEGIN_RCPP 18 | Rcpp::RObject rcpp_result_gen; 19 | Rcpp::RNGScope rcpp_rngScope_gen; 20 | Rcpp::traits::input_parameter< const NumericMatrix& >::type logits(logitsSEXP); 21 | Rcpp::traits::input_parameter< const int& >::type nrows(nrowsSEXP); 22 | Rcpp::traits::input_parameter< const int& >::type ncols(ncolsSEXP); 23 | Rcpp::traits::input_parameter< const int& >::type window_size(window_sizeSEXP); 24 | Rcpp::traits::input_parameter< const NumericVector& >::type smoothness(smoothnessSEXP); 25 | Rcpp::traits::input_parameter< const double& >::type neigh_fraction(neigh_fractionSEXP); 26 | rcpp_result_gen = Rcpp::wrap(bayes_smoother_fraction(logits, nrows, ncols, window_size, smoothness, neigh_fraction)); 27 | return rcpp_result_gen; 28 | END_RCPP 29 | } 30 | // bayes_var 31 | arma::mat bayes_var(const arma::mat& m, const arma::uword m_nrow, const arma::uword m_ncol, const arma::mat& w, const double neigh_fraction); 32 | RcppExport SEXP _bayesEO_bayes_var(SEXP mSEXP, SEXP m_nrowSEXP, SEXP m_ncolSEXP, SEXP wSEXP, SEXP neigh_fractionSEXP) { 33 | BEGIN_RCPP 34 | Rcpp::RObject rcpp_result_gen; 35 | Rcpp::RNGScope rcpp_rngScope_gen; 36 | Rcpp::traits::input_parameter< const arma::mat& >::type m(mSEXP); 37 | Rcpp::traits::input_parameter< const arma::uword >::type m_nrow(m_nrowSEXP); 38 | Rcpp::traits::input_parameter< const arma::uword >::type m_ncol(m_ncolSEXP); 39 | Rcpp::traits::input_parameter< const arma::mat& >::type w(wSEXP); 40 | Rcpp::traits::input_parameter< const double >::type neigh_fraction(neigh_fractionSEXP); 41 | rcpp_result_gen = Rcpp::wrap(bayes_var(m, m_nrow, m_ncol, w, neigh_fraction)); 42 | return rcpp_result_gen; 43 | END_RCPP 44 | } 45 | // C_label_max_prob 46 | arma::colvec C_label_max_prob(const arma::mat& x); 47 | RcppExport SEXP _bayesEO_C_label_max_prob(SEXP xSEXP) { 48 | BEGIN_RCPP 49 | Rcpp::RObject rcpp_result_gen; 50 | Rcpp::RNGScope rcpp_rngScope_gen; 51 | Rcpp::traits::input_parameter< const arma::mat& >::type x(xSEXP); 52 | rcpp_result_gen = Rcpp::wrap(C_label_max_prob(x)); 53 | return rcpp_result_gen; 54 | END_RCPP 55 | } 56 | // kernel_smoother 57 | arma::mat kernel_smoother(const arma::mat& m, const arma::uword m_nrow, const arma::uword m_ncol, const arma::mat& w, const bool normalised); 58 | RcppExport SEXP _bayesEO_kernel_smoother(SEXP mSEXP, SEXP m_nrowSEXP, SEXP m_ncolSEXP, SEXP wSEXP, SEXP normalisedSEXP) { 59 | BEGIN_RCPP 60 | Rcpp::RObject rcpp_result_gen; 61 | Rcpp::RNGScope rcpp_rngScope_gen; 62 | Rcpp::traits::input_parameter< const arma::mat& >::type m(mSEXP); 63 | Rcpp::traits::input_parameter< const arma::uword >::type m_nrow(m_nrowSEXP); 64 | Rcpp::traits::input_parameter< const arma::uword >::type m_ncol(m_ncolSEXP); 65 | Rcpp::traits::input_parameter< const arma::mat& >::type w(wSEXP); 66 | Rcpp::traits::input_parameter< const bool >::type normalised(normalisedSEXP); 67 | rcpp_result_gen = Rcpp::wrap(kernel_smoother(m, m_nrow, m_ncol, w, normalised)); 68 | return rcpp_result_gen; 69 | END_RCPP 70 | } 71 | // bilateral_smoother 72 | arma::mat bilateral_smoother(const arma::mat& m, const arma::uword m_nrow, const arma::uword m_ncol, const arma::mat& w, double tau); 73 | RcppExport SEXP _bayesEO_bilateral_smoother(SEXP mSEXP, SEXP m_nrowSEXP, SEXP m_ncolSEXP, SEXP wSEXP, SEXP tauSEXP) { 74 | BEGIN_RCPP 75 | Rcpp::RObject rcpp_result_gen; 76 | Rcpp::RNGScope rcpp_rngScope_gen; 77 | Rcpp::traits::input_parameter< const arma::mat& >::type m(mSEXP); 78 | Rcpp::traits::input_parameter< const arma::uword >::type m_nrow(m_nrowSEXP); 79 | Rcpp::traits::input_parameter< const arma::uword >::type m_ncol(m_ncolSEXP); 80 | Rcpp::traits::input_parameter< const arma::mat& >::type w(wSEXP); 81 | Rcpp::traits::input_parameter< double >::type tau(tauSEXP); 82 | rcpp_result_gen = Rcpp::wrap(bilateral_smoother(m, m_nrow, m_ncol, w, tau)); 83 | return rcpp_result_gen; 84 | END_RCPP 85 | } 86 | 87 | static const R_CallMethodDef CallEntries[] = { 88 | {"_bayesEO_bayes_smoother_fraction", (DL_FUNC) &_bayesEO_bayes_smoother_fraction, 6}, 89 | {"_bayesEO_bayes_var", (DL_FUNC) &_bayesEO_bayes_var, 5}, 90 | {"_bayesEO_C_label_max_prob", (DL_FUNC) &_bayesEO_C_label_max_prob, 1}, 91 | {"_bayesEO_kernel_smoother", (DL_FUNC) &_bayesEO_kernel_smoother, 5}, 92 | {"_bayesEO_bilateral_smoother", (DL_FUNC) &_bayesEO_bilateral_smoother, 5}, 93 | {NULL, NULL, 0} 94 | }; 95 | 96 | RcppExport void R_init_bayesEO(DllInfo *dll) { 97 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 98 | R_useDynamicSymbols(dll, FALSE); 99 | } 100 | -------------------------------------------------------------------------------- /src/bayes_smooth.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace Rcpp; 4 | 5 | // compute outside indices of a vector as a mirror 6 | IntegerVector locus_neigh(int size, int leg) { 7 | IntegerVector res(size + 2 * leg); 8 | for (int i = 0; i < res.length(); ++i) { 9 | if (i < leg) 10 | res(i) = leg - i - 1; 11 | else if (i < size + leg) 12 | res(i) = i - leg; 13 | else 14 | res(i) = 2 * size + leg - i - 1; 15 | } 16 | return res; 17 | } 18 | 19 | // [[Rcpp::export]] 20 | NumericVector bayes_smoother_fraction(const NumericMatrix& logits, 21 | const int& nrows, 22 | const int& ncols, 23 | const int& window_size, 24 | const NumericVector& smoothness, 25 | const double& neigh_fraction 26 | ) { 27 | // initialize result vectors 28 | NumericMatrix res(logits.nrow(), logits.ncol()); 29 | NumericVector neigh(window_size * window_size); 30 | // compute window leg 31 | int leg = window_size / 2; 32 | // compute locus mirror 33 | IntegerVector loci = locus_neigh(nrows, leg); 34 | IntegerVector locj = locus_neigh(ncols, leg); 35 | // compute number of neighbors to be used 36 | int neigh_high = std::ceil(neigh_fraction * window_size * window_size); 37 | // compute values for each pixel 38 | for (int i = 0; i < nrows; ++i) { 39 | for (int j = 0; j < ncols; ++j) { 40 | // for all bands 41 | for (int band = 0; band < logits.ncol(); ++band) { 42 | // compute the neighborhood 43 | for (int wi = 0; wi < window_size; ++wi) 44 | for (int wj = 0; wj < window_size; ++wj) 45 | neigh(wi * window_size + wj) = 46 | logits(loci(wi + i) * ncols + locj(wj + j), band); 47 | if (neigh_fraction < 1.0) 48 | // Sort the neighbor logit values 49 | neigh.sort(true); 50 | // Create a vector to store the highest values 51 | NumericVector high_values(neigh_high); 52 | // copy the highest values to the new vector 53 | int nh = 0; 54 | for(NumericVector::iterator it = neigh.begin(); 55 | it != neigh.begin() + neigh_high; ++it) { 56 | high_values(nh++) = (*it); 57 | } 58 | // get the estimates for prior 59 | // normal with mean m0 and variance s0 60 | double s0 = var(high_values); 61 | double m0 = mean(high_values); 62 | // get the current value 63 | double x0 = logits(i * ncols + j, band); 64 | // weight for Bayesian estimator 65 | double w = s0/(s0 + smoothness(band)); 66 | // apply Bayesian smoother 67 | res(i * ncols + j, band) = w * x0 + (1 - w) * m0; 68 | } 69 | } 70 | } 71 | return res; 72 | } 73 | // 74 | // Data structures to compute variance 75 | struct _neigh { 76 | arma::mat data; 77 | arma::colvec weights; 78 | arma::uword n_rows; 79 | _neigh(const arma::mat& m, const arma::mat& w): 80 | data(w.n_elem, m.n_cols, arma::fill::zeros), 81 | weights(w.n_elem, arma::fill::zeros), 82 | n_rows(0) {} 83 | }; 84 | 85 | typedef _neigh neigh_t; 86 | // 87 | void neigh_vec(neigh_t& n, 88 | const arma::mat& m, 89 | const arma::uword m_nrow, 90 | const arma::uword m_ncol, 91 | const arma::mat& w, 92 | const arma::uword m_b, 93 | const arma::uword m_i, 94 | const arma::uword m_j) { 95 | 96 | arma::uword w_leg_i = w.n_rows / 2, w_leg_j = w.n_cols / 2; 97 | 98 | // copy values 99 | arma::uword k = 0; 100 | for (arma::uword i = 0; i < w.n_rows; ++i) 101 | for (arma::uword j = 0; j < w.n_cols; ++j) 102 | if (m_i + i >= w_leg_i && m_j + j >= w_leg_j && 103 | m_i + i < w_leg_i + m_nrow && 104 | m_j + j < w_leg_j + m_ncol && 105 | arma::is_finite(m(m_j + m_i * m_ncol, 0)) && 106 | arma::is_finite(m((m_j + j - w_leg_j) + (m_i + i - w_leg_i) * m_ncol, m_b))) { 107 | 108 | n.data(k, m_b) = m((m_j + j - w_leg_j) + 109 | (m_i + i - w_leg_i) * m_ncol, m_b); 110 | n.weights(k++) = w(i, j); 111 | } 112 | n.n_rows = k; 113 | } 114 | // [[Rcpp::export]] 115 | arma::mat bayes_var(const arma::mat& m, 116 | const arma::uword m_nrow, 117 | const arma::uword m_ncol, 118 | const arma::mat& w, 119 | const double neigh_fraction){ 120 | 121 | // initialize result matrix 122 | arma::mat res(arma::size(m), arma::fill::none); 123 | res.fill(arma::datum::nan); 124 | 125 | // variance 126 | arma::rowvec var0(m.n_cols, arma::fill::zeros); 127 | 128 | // neighbourhood 129 | neigh_t neigh(m, w); 130 | 131 | // compute values for each pixel 132 | for (arma::uword i = 0; i < m_nrow; ++i) { 133 | for (arma::uword j = 0; j < m_ncol; ++j) { 134 | 135 | // fill neighbor values 136 | for (arma::uword b = 0; b < m.n_cols; ++b) 137 | neigh_vec(neigh, m, m_nrow, m_ncol, w, b, i, j); 138 | 139 | if (neigh.n_rows * neigh_fraction < 1) continue; 140 | 141 | if (neigh_fraction < 1.0 ) { 142 | // sort the data 143 | neigh.data.rows(0, neigh.n_rows - 1) = 144 | arma::sort(neigh.data.rows(0, neigh.n_rows - 1), "descend"); 145 | 146 | // number of sorted values 147 | arma::uword n_sort = neigh.n_rows * neigh_fraction; 148 | 149 | // compute variance 150 | var0 = arma::var(neigh.data.rows(0, n_sort - 1), 0, 0).as_row(); 151 | } 152 | else { 153 | // compute variance 154 | var0 = arma::var(neigh.data.rows(0, neigh.n_rows - 1), 0, 0).as_row(); 155 | } 156 | 157 | // return values 158 | res.row(j + i * m_ncol) = var0; 159 | } 160 | } 161 | return res; 162 | } 163 | -------------------------------------------------------------------------------- /src/label_class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // [[Rcpp::depends(RcppArmadillo)]] 3 | 4 | using namespace Rcpp; 5 | 6 | // [[Rcpp::export]] 7 | arma::colvec C_label_max_prob(const arma::mat& x) { 8 | arma::colvec y(x.n_rows); 9 | arma::mat z = x; 10 | z.replace(arma::datum::nan, 0); 11 | for (arma::uword i = 0; i < x.n_rows; i++) { 12 | arma::rowvec x_values = z.row(i); 13 | if (all(x_values == 0)) { 14 | y.at(i) = arma::datum::nan; 15 | } else { 16 | y.at(i) = index_max(x_values) + 1; 17 | } 18 | } 19 | return y; 20 | } 21 | -------------------------------------------------------------------------------- /src/other_smoothers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // [[Rcpp::depends(RcppArmadillo)]] 3 | 4 | using namespace Rcpp; 5 | 6 | struct _neigh_gauss { 7 | arma::mat data; 8 | arma::colvec weights; 9 | arma::uword n_rows; 10 | _neigh_gauss(const arma::mat& m, const arma::mat& w): 11 | data(w.n_elem, m.n_cols, arma::fill::zeros), 12 | weights(w.n_elem, arma::fill::zeros), 13 | n_rows(0) {} 14 | }; 15 | 16 | typedef _neigh_gauss neigh_gauss_t; 17 | 18 | void neigh_vec_gauss(neigh_gauss_t& n, 19 | const arma::mat& m, 20 | const arma::uword m_nrow, 21 | const arma::uword m_ncol, 22 | const arma::mat& w, 23 | const arma::uword m_b, 24 | const arma::uword m_i, 25 | const arma::uword m_j) { 26 | 27 | arma::uword w_leg_i = w.n_rows / 2, w_leg_j = w.n_cols / 2; 28 | 29 | // copy values 30 | arma::uword k = 0; 31 | for (arma::uword i = 0; i < w.n_rows; ++i) 32 | for (arma::uword j = 0; j < w.n_cols; ++j) 33 | if (m_i + i >= w_leg_i && m_j + j >= w_leg_j && 34 | m_i + i < w_leg_i + m_nrow && 35 | m_j + j < w_leg_j + m_ncol && 36 | arma::is_finite(m(m_j + m_i * m_ncol, 0))) { 37 | 38 | n.data(k, m_b) = m((m_j + j - w_leg_j) + 39 | (m_i + i - w_leg_i) * m_ncol, m_b); 40 | n.weights(k++) = w(i, j); 41 | } 42 | n.n_rows = k; 43 | } 44 | 45 | arma::colvec nm_post_mean_x(const arma::colvec& x, 46 | const arma::mat& sigma, 47 | const arma::colvec& mu0, 48 | const arma::mat& sigma0) { 49 | 50 | // inverse sigma0 51 | arma::mat inv_sum_weights(arma::size(sigma0)); 52 | inv_sum_weights = arma::inv(sigma + sigma0); 53 | 54 | return sigma * inv_sum_weights * mu0 + sigma0 * inv_sum_weights * x; 55 | } 56 | 57 | // [[Rcpp::export]] 58 | arma::mat kernel_smoother(const arma::mat& m, 59 | const arma::uword m_nrow, 60 | const arma::uword m_ncol, 61 | const arma::mat& w, 62 | const bool normalised) { 63 | 64 | // initialize result matrix 65 | arma::mat res(arma::size(m), arma::fill::none); 66 | res.fill(arma::datum::nan); 67 | 68 | // neighbourhood 69 | neigh_gauss_t neigh(m, w); 70 | 71 | // compute values for each pixel 72 | for (arma::uword b = 0; b < m.n_cols; ++b) 73 | for (arma::uword i = 0; i < m_nrow; ++i) 74 | for (arma::uword j = 0; j < m_ncol; ++j) { 75 | 76 | // fill neighbours values 77 | neigh_vec_gauss(neigh, m, m_nrow, m_ncol, w, b, i, j); 78 | 79 | if (neigh.n_rows == 0) continue; 80 | 81 | // normalise weight values 82 | if (normalised) 83 | neigh.weights = neigh.weights / 84 | arma::sum(neigh.weights.subvec(0, neigh.n_rows - 1)); 85 | 86 | // compute kernel neighbourhood weighted mean 87 | res(j + i * m_ncol, b) = arma::as_scalar( 88 | neigh.weights.subvec(0, neigh.n_rows - 1).as_row() * 89 | neigh.data.col(b).subvec(0, neigh.n_rows - 1)); 90 | } 91 | return res; 92 | } 93 | 94 | // [[Rcpp::export]] 95 | arma::mat bilateral_smoother(const arma::mat& m, 96 | const arma::uword m_nrow, 97 | const arma::uword m_ncol, 98 | const arma::mat& w, 99 | double tau) { 100 | 101 | // initialize result matrix 102 | arma::mat res(arma::size(m), arma::fill::none); 103 | res.fill(arma::datum::nan); 104 | 105 | // neighbourhood 106 | neigh_gauss_t neigh(m, w); 107 | 108 | // compute values for each pixel 109 | for (arma::uword b = 0; b < m.n_cols; ++b) 110 | for (arma::uword i = 0; i < m_nrow; ++i) 111 | for (arma::uword j = 0; j < m_ncol; ++j) { 112 | 113 | // fill neighbours values 114 | neigh_vec_gauss(neigh, m, m_nrow, m_ncol, w, b, i, j); 115 | 116 | if (neigh.n_rows == 0) continue; 117 | 118 | // compute bilinear weight 119 | arma::colvec bln_weight = neigh.weights % arma::normpdf( 120 | neigh.data.col(b) - m(j + i * m_ncol, b), 0, tau); 121 | 122 | // normalise weight values 123 | bln_weight = bln_weight / 124 | arma::sum(bln_weight.subvec(0, neigh.n_rows - 1)); 125 | 126 | // compute kernel neighbourhood weighted mean 127 | res(j + i * m_ncol, b) = arma::as_scalar( 128 | bln_weight.subvec(0, neigh.n_rows - 1).as_row() * 129 | neigh.data.col(b).subvec(0, neigh.n_rows - 1)); 130 | } 131 | return res; 132 | } 133 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(bayesEO) 3 | if (bayes_run_tests()) { 4 | test_check("bayesEO") 5 | } 6 | -------------------------------------------------------------------------------- /tests/testthat/test-bayes.R: -------------------------------------------------------------------------------- 1 | test_that("BayesEO", { 2 | 3 | data_dir <- system.file("/extdata/probs/", package = "bayesEO") 4 | file <- list.files(data_dir) 5 | probs_file <- paste0(data_dir, "/", file) 6 | labels <- c("Water", "ClearCut_Burn", "ClearCut_Soil", 7 | "ClearCut_Veg", "Forest", "Wetland") 8 | 9 | x <- bayes_read_probs(probs_file, labels) 10 | expect_equal(names(x), labels) 11 | expect_true("SpatRaster" %in% class(x)) 12 | expect_equal(terra::xmax(x), 350000) 13 | 14 | rgb_dir <- system.file("/extdata/rgb/", package = "bayesEO") 15 | rgb_files <- paste0(rgb_dir, "/", list.files(rgb_dir)) 16 | 17 | rgb_image <- bayes_read_image(rgb_files) 18 | expect_equal(terra::nlyr(rgb_image), 3) 19 | expect_true("SpatRaster" %in% class(rgb_image)) 20 | expect_equal(terra::xmax(rgb_image), 350000) 21 | 22 | p <- bayes_plot_probs(x, labels = c("Forest", "ClearCut_Soil")) 23 | expect_true(p$tm_layout$legend.bg.color == "white") 24 | expect_true(p$tm_shape$line.center == "midpoint") 25 | 26 | y <- bayes_smooth( 27 | x, 28 | window_size = 7, 29 | neigh_fraction = 0.5, 30 | smoothness = 10 31 | ) 32 | expect_equal(names(y), labels) 33 | expect_equal(terra::xmax(y), 350000) 34 | expect_true(max(y[,1]) < 10000) 35 | expect_true(max(y[,1]) > 9500) 36 | 37 | z <- bayes_label(x) 38 | expect_equal(terra::levels(z)[[1]]$class, labels) 39 | expect_equal(terra::xmax(z), 350000) 40 | expect_equal(terra::nlyr(z), 1) 41 | 42 | p2 <- bayes_plot_map(z) 43 | expect_true(p2$tm_layout$legend.bg.color == "white") 44 | expect_true(p2$tm_shape$line.center == "midpoint") 45 | expect_equal(p2$tm_raster$labels, labels) 46 | 47 | v <- bayes_variance(y) 48 | expect_equal(names(v), labels) 49 | expect_equal(terra::xmax(v), 350000) 50 | expect_true(max(v[,1]) < 50) 51 | expect_true(max(v[,1]) > 0) 52 | 53 | p3 <- bayes_plot_probs(v, labels = c("Forest", "ClearCut_Soil")) 54 | expect_true(p3$tm_layout$legend.bg.color == "white") 55 | expect_true(p3$tm_shape$line.center == "midpoint") 56 | expect_equal(p3$tm_raster$palette, "YlGnBu") 57 | 58 | p4 <- bayes_plot_hist(v, quantile = 0.75) 59 | expect_true(p4$labels$x == "variance") 60 | expect_true(p4$labels$y == "count") 61 | 62 | yg <- gaussian_smooth( 63 | x, 64 | window_size = 5 65 | ) 66 | expect_equal(names(yg), labels) 67 | expect_equal(terra::xmax(yg), 350000) 68 | expect_true(max(yg[,1]) < 10000) 69 | expect_true(max(yg[,1]) > 9500) 70 | 71 | yb <- bilateral_smooth( 72 | x, 73 | window_size = 5 74 | ) 75 | expect_equal(names(yb), labels) 76 | expect_equal(terra::xmax(yb), 350000) 77 | expect_true(max(yb[,1]) < 10000) 78 | expect_true(max(yb[,1]) > 9500) 79 | 80 | 81 | 82 | 83 | }) 84 | --------------------------------------------------------------------------------