├── .Rbuildignore ├── .gitattributes ├── .github └── workflows │ └── r.yml ├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── RcppExports.R ├── jss2711.R ├── recmap.R └── zzz.R ├── README.md ├── _config.yml ├── data ├── jss2711.RData └── jss2711.RData.bak ├── inst ├── CITATION ├── Dockerfile ├── NEWS.Rd ├── extdata │ ├── recmap_us_state_ev.polygon │ └── us_state_election_2004.csv ├── include │ └── recmap.cpp └── shiny-examples │ ├── server.R │ └── ui.R ├── man ├── as.SpatialPolygonsDataFrame.recmap.Rd ├── as.recmap.SpatialPolygonsDataFrame.Rd ├── checkerboard.Rd ├── dot-draw_recmap_us_state_ev.Rd ├── dot-get_7triangles.Rd ├── is.recmap.Rd ├── jss2711.Rd ├── plot.recmap.Rd ├── recmap.Rd ├── recmapGA.Rd ├── recmapGRASP.Rd └── summary.recmap.Rd ├── src ├── RcppExports.cpp └── Recmap.cpp ├── tests ├── testthat.R └── testthat │ ├── test-get_angle.R │ ├── test-jss2711.R │ ├── test-recmap.R │ ├── test-recmapGRASP.R │ ├── test-sp.R │ └── test-topoloy_error.R └── vignettes ├── graphics └── rectangular_statistical_cartogram_construction_animation.gif ├── ieee.csl ├── jss2711.Rnw ├── jss2711.bib ├── recmap.Rmd └── recmap.bib /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^.*id_rsa.*$ 4 | ^.*Dockerfile$ 5 | ^.*_config.yml$ 6 | ^.*.travis.yml$ 7 | ^.*vignettes/jss2711.Rnw$ 8 | ^.*R/jss2711.R$ 9 | ^.*data/jss2711.RData.+$ 10 | ^.*LICENSE$ 11 | ^.*vignettes/graphics/.*$ 12 | ^.github/.*$ 13 | README.md 14 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * linguist-vendored 2 | *.cpp linguist-vendored=false 3 | *.h linguist-vendored=false 4 | R/recmap.R linguist-vendored=false 5 | *sh 6 | -------------------------------------------------------------------------------- /.github/workflows/r.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # 6 | # See https://github.com/r-lib/actions/tree/master/examples#readme for 7 | # additional example workflows available for the R community. 8 | 9 | name: R-CMD-check-recmap 10 | env: 11 | ACTIONS_ALLOW_UNSECURE_COMMANDS: 'true' 12 | on: 13 | push: 14 | branches: [ master ] 15 | pull_request: 16 | branches: [ master ] 17 | 18 | jobs: 19 | build: 20 | runs-on: ubuntu-20.04 21 | strategy: 22 | matrix: 23 | r-version: [4.3] 24 | steps: 25 | - uses: actions/checkout@v2 26 | - name: Set up R ${{ matrix.r-version }} 27 | uses: r-lib/actions/setup-r@v1 28 | with: 29 | r-version: ${{ matrix.r-version }} 30 | - name: Install Linux packages 31 | run: sudo apt-get install -y libcurl4-openssl-dev libicu-dev pandoc pandoc-citeproc texlive texlive-latex-extra texlive-fonts-extra 32 | shell: bash {0} 33 | - name: Install dependencies 34 | run: | 35 | install.packages(c("remotes", "rcmdcheck", "rmarkdown")) 36 | remotes::install_deps(dependencies = TRUE) 37 | shell: Rscript {0} 38 | - name: Check 39 | run: rcmdcheck::rcmdcheck(build_args = "", args = "", error_on = "error", check_dir = "/tmp/recmap.Rcheck") 40 | shell: Rscript {0} 41 | - name: codecov 42 | run: install.packages('covr'); covr::codecov(type = "all", token=Sys.getenv('CODECOV_TOKEN')) 43 | shell: Rscript {0} 44 | - uses: actions/upload-artifact@v2 45 | with: 46 | name: recmap.Rcheck 47 | path: /tmp/recmap.Rcheck 48 | if-no-files-found: warn 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | src/*.o 6 | src/*.so 7 | src/*.dll 8 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: recmap 2 | Type: Package 3 | Title: Compute the Rectangular Statistical Cartogram 4 | Version: 1.0.17 5 | Authors@R: person("Christian", "Panse", 6 | email = "Christian.Panse@gmail.com", 7 | role = c("aut", "cre"), 8 | comment = c(ORCID = "0000-0003-1975-3064")) 9 | Maintainer: Christian Panse 10 | Description: Implements the RecMap MP2 construction heuristic 11 | . 12 | This algorithm draws maps according to a given statistical 13 | value, e.g., election results, population, or epidemiological data. 14 | The basic idea of the RecMap algorithm is that each map region, 15 | e.g., different countries, is represented by a rectangle. 16 | The area of each rectangle represents the statistical value given 17 | as input (maintain zero cartographic error). 18 | C++ is used to implement the computationally intensive tasks. 19 | The vignette included in this package provides documentation 20 | about the usage of the recmap algorithm. 21 | License: GPL-3 22 | Depends: R (>= 4.3), GA (>= 3.1), Rcpp (>= 1.0), sp(>= 1.3) 23 | Suggests: doParallel, knitr, rmarkdown, shiny, testthat, tufte 24 | LinkingTo: Rcpp (>= 1.0) 25 | VignetteBuilder: knitr 26 | NeedsCompilation: yes 27 | BugReports: https://github.com/cpanse/recmap/issues 28 | Encoding: UTF-8 29 | RoxygenNote: 7.2.3 30 | -------------------------------------------------------------------------------- /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 | S3method(all.equal,recmap) 4 | S3method(as.SpatialPolygonsDataFrame,recmap) 5 | S3method(as.recmap,SpatialPolygonsDataFrame) 6 | S3method(plot,recmap) 7 | S3method(plot,recmapGA) 8 | S3method(plot,recmapGRASP) 9 | S3method(summary,recmap) 10 | export(.get_7triangles) 11 | export(all.equal.recmap) 12 | export(as.SpatialPolygonsDataFrame) 13 | export(as.recmap) 14 | export(checkerboard) 15 | export(is.recmap) 16 | export(plot.recmap) 17 | export(plot.recmapGA) 18 | export(plot.recmapGRASP) 19 | export(recmap) 20 | export(recmapGA) 21 | export(recmapGRASP) 22 | export(summary.recmap) 23 | export(summary.recmapGA) 24 | import(Rcpp) 25 | importFrom(GA,ga) 26 | importFrom(GA,gaMonitor) 27 | importFrom(GA,summary.ga) 28 | importFrom(graphics,abline) 29 | importFrom(graphics,axis) 30 | importFrom(graphics,plot) 31 | importFrom(graphics,polygon) 32 | importFrom(graphics,rect) 33 | importFrom(graphics,strwidth) 34 | importFrom(graphics,text) 35 | importFrom(sp,Polygon) 36 | importFrom(sp,Polygons) 37 | importFrom(sp,SpatialPolygons) 38 | importFrom(sp,SpatialPolygonsDataFrame) 39 | importFrom(sp,bbox) 40 | importFrom(sp,spplot) 41 | importFrom(utils,combn) 42 | importFrom(utils,packageVersion) 43 | importFrom(utils,read.table) 44 | useDynLib(recmap, .registration=TRUE) 45 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #' @import Rcpp 5 | get_angle <- function(x0, y0, x1, y1) { 6 | .Call('_recmap_get_angle', PACKAGE = 'recmap', x0, y0, x1, y1) 7 | } 8 | 9 | place_rectangle <- function(x0, y0, dx0, dy0, dx1, dy1, alpha) { 10 | .Call('_recmap_place_rectangle', PACKAGE = 'recmap', x0, y0, dx0, dy0, dx1, dy1, alpha) 11 | } 12 | 13 | #' Compute a Rectangular Statistical Cartogram 14 | #' 15 | #' @description 16 | #' The input consists of a map represented by overlapping rectangles. 17 | #' The algorithm requires as input for each map region: 18 | #' \itemize{ 19 | #' \item{a tuple of (x, y) values corresponding to the 20 | #' (longitude, latitude) position,} 21 | #' \item{a tuple of (dx, dy) of expansion along (longitude, latitude),} 22 | #' \item{and a statistical value z.} 23 | #' } 24 | #' The (x, y) coordinates represent the center of the minimal bounding boxes 25 | #' (MBB), The coordinates of the MBB are derived by adding or subtracting the 26 | #' (dx, dy) / 2 tuple accordingly. The tuple (dx, dy) also defines the ratio of the 27 | #' map region. The statistical values define the desired area of each map region. 28 | #' 29 | #' The output is a rectangular cartogram where the map regions are: 30 | #' 31 | #' \itemize{ 32 | #' \item{Non-overlapping,} 33 | #' \item{connected,} 34 | #' \item{ratio and area of each rectangle correspond to the desired areas,} 35 | #' \item{rectangles are placed parallel to the axes.} 36 | #' } 37 | #' 38 | #' The construction heuristic places each rectangle in a way that important spatial 39 | #' constraints, in particular 40 | #' \itemize{ 41 | #' \item{the topology of the pseudo dual graph,} 42 | #' \item{the relative position of MBB centers.} 43 | #' } 44 | #' are tried to be preserved. 45 | #' 46 | #' The ratios are preserved and the area of each region corresponds to the as 47 | #' input given statistical value z. 48 | #' 49 | #' @param V defines the input map regions formatted as \code{\link{data.frame}} 50 | #' having the column names \code{c('x', 'y', 'dx', 'dy', 'z', 'name')} 51 | #' as described above. V could also be considered as the nodes of the pseudo dual. 52 | #' 53 | #' @param E defines the edges of the map region's pseudo dual graph. 54 | #' If \code{E} is not provided, this is the default; the pseudo dual graph is 55 | #' composed of overlapping rectangles. If used, E must be a 56 | #' \code{\link{data.frame}} containing two columns named \code{c('u', 'v')} 57 | #' of type integer referencing the row number of \code{V}. 58 | #' 59 | #' @details The basic idea of the current recmap \emph{implementation}: 60 | #' \enumerate{ 61 | #' \item{Compute the pseudo dual out of the overlapping map regions.} 62 | #' \item{Determine the \emph{core region} by \code{index <- int(n / 2)}.} 63 | #' \item{Place region by region along DFS skeleton of pseudo dual starting 64 | #' with the \emph{core region}.}} 65 | #' 66 | #' Note: if a rectangle can not be placed, accept a non-\emph{feasible solution} 67 | #' (avoid solutions having a topology error higher than 100) 68 | #' Solving this constellation can be intensive in the computation, and due to the 69 | #' assumably low fitness value the candidate cartogram 70 | #' will be likely rejected by the metaheuristic. 71 | #' 72 | #' \emph{Time Complexity:} 73 | #' The time complexity is \eqn{O(n^2)}, where n is the number of regions. 74 | #' DFS is visiting each map region only once and therefore has 75 | #' time complexity \eqn{O(n)}. For each placement, a constant number of 76 | #' MBB intersection are called (max 360). MBB check is implemented using 77 | #' \code{std::set}, \code{insert}, \code{upper_bound}, \code{upper_bound} 78 | #' costs are \eqn{O(\log(n))}{O(log(n))}. 79 | #' However, the worst case for a range query is \eqn{O(n)}, if and only if dx or dy 80 | #' cover the whole x or y range. Q.E.D. 81 | #' 82 | #' \emph{Performance:} 83 | #' In praxis, computing on a 2.4 GHz Intel Core i7 machine (using only one core), using the 84 | #' 50 state U.S. map example, recmap can compute approximately 100 cartograms in one second. 85 | #' The number of MBB calls were 86 | #' (Min., Median, Mean, Max) = (1448, 2534, 3174, 17740), using in each run 87 | #' a different index order using the (\code{\link{sample}}) method. 88 | #' 89 | #' \emph{Geodetic datum:} the \code{recmap} algorithm is not transforming the 90 | #' geodetic datum, e.g., WGS84 or Swissgrid. 91 | #' 92 | #' @return 93 | #' Returns a \code{recmap} S3 object of the transformed map with new coordinates 94 | #' (x, y, dx, dy) plus additional columns containing information for topology 95 | #' error, relative position error, and the DFS number. 96 | #' The error values are thought to be used for fitness function of the 97 | #' metaheuristic. 98 | #' 99 | #' @aliases RecMap cartogram all.equal.recmap 100 | #' 101 | #' @author Christian Panse, 2016 102 | #' 103 | #' @examples 104 | #' map <- checkerboard(2) 105 | #' cartogram <- recmap(map) 106 | #' 107 | #' map 108 | #' cartogram 109 | #' 110 | #' op <- par(mfrow = c(1, 2)) 111 | #' plot(map) 112 | #' plot(cartogram) 113 | #' 114 | #' ## US example 115 | #' usa <- data.frame(x = state.center$x, 116 | #' y = state.center$y, 117 | #' # make the rectangles overlapping by correcting 118 | #' # lines of longitude distance. 119 | #' dx = sqrt(state.area) / 2 120 | #' / (0.8 * 60 * cos(state.center$y * pi / 180)), 121 | #' dy = sqrt(state.area) / 2 / (0.8 * 60), 122 | #' z = sqrt(state.area), 123 | #' name = state.name) 124 | #' 125 | #' usa$z <- state.x77[, 'Population'] 126 | #' US.Map <- usa[match(usa$name, 127 | #' c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 128 | #' 129 | #' plot.recmap(US.Map) 130 | #' US.Map |> recmap() |> plot() 131 | #' par(op) 132 | #' 133 | #' # define a fitness function 134 | #' recmap.fitness <- function(idxOrder, Map, ...){ 135 | #' Cartogram <- recmap(Map[idxOrder, ]) 136 | #' # a map region could not be placed; 137 | #' # accept only feasible solutions! 138 | #' if (sum(Cartogram$topology.error == 100) > 0){return (0)} 139 | #' 1 / sum(Cartogram$z / (sqrt(sum(Cartogram$z^2))) 140 | #' * Cartogram$relpos.error) 141 | #' } 142 | #' 143 | #' @export 144 | recmap <- function(V, E = NULL) { 145 | .Call('_recmap_recmap', PACKAGE = 'recmap', V, E) 146 | } 147 | 148 | -------------------------------------------------------------------------------- /R/jss2711.R: -------------------------------------------------------------------------------- 1 | jss2711_figure4 <- function(nrep = 5, size = c(2, 3, 5, 10, 20)){ 2 | recmap_debug_code <- ' 3 | // [[Rcpp::plugins(cpp11)]] 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace Rcpp; 10 | 11 | // [[Rcpp::depends(recmap)]] 12 | // [[Rcpp::export]] 13 | int recmap_debug(DataFrame df, bool map_region_intersect_multiset = true) { 14 | // access the columns 15 | NumericVector x = df["x"]; 16 | NumericVector y = df["y"]; 17 | NumericVector dx = df["dx"]; 18 | NumericVector dy = df["dy"]; 19 | 20 | 21 | NumericVector z = df["z"]; 22 | CharacterVector name = df["name"]; 23 | 24 | NumericVector cartogram_x(x.size()); 25 | NumericVector cartogram_y(x.size()); 26 | NumericVector cartogram_dx(x.size()); 27 | NumericVector cartogram_dy(x.size()); 28 | 29 | NumericVector dfs_num(x.size()); 30 | NumericVector topology_error(x.size()); 31 | NumericVector relpos_error(x.size()); 32 | NumericVector relpos_nh_error(x.size()); 33 | 34 | crecmap::RecMap X; 35 | X.set_map_region_intersect_multiset(map_region_intersect_multiset); 36 | 37 | for (int i = 0; i < x.size(); i++) { 38 | std::string sname = Rcpp::as(name[i]); 39 | X.push_region(x[i], y[i], dx[i], dy[i], z[i], sname); 40 | } 41 | 42 | X.run(true); 43 | 44 | return(X.get_intersect_count()); 45 | } 46 | ' 47 | 48 | sourceCpp(code = recmap_debug_code, rebuild = TRUE, verbose = TRUE) 49 | 50 | do.call('rbind', lapply(size, function(size){ 51 | set.seed(1); 52 | CB <- checkerboard(size); 53 | 54 | do.call('rbind',lapply(rep(size, nrep), function(n){ 55 | 56 | CB.smp <- CB[sample(nrow(CB), nrow(CB)), ] 57 | start_time <- Sys.time() 58 | ncall.multiset <- recmap_debug(CB.smp, map_region_intersect_multiset = TRUE) 59 | end_time <- Sys.time() 60 | diff_time.multiset <- as.numeric(difftime(end_time, start_time, units = "secs")) 61 | 62 | 63 | start_time <- Sys.time() 64 | ncall.list <- recmap_debug(CB.smp, map_region_intersect_multiset = FALSE) 65 | end_time <- Sys.time() 66 | diff_time.list <- as.numeric(difftime(end_time, start_time, units = "secs")) 67 | 68 | #do.call('rbind', list(data.frame(algorithm = "multiset", number = ncall.multiset, size = nrow(CB)), 69 | # data.frame(algorithm = "list", number = ncall.list, size = nrow(CB)))) 70 | #data.frame(algorithm = "multiset", number = ncall.multiset, size = nrow(CB)) 71 | rv <- rbind(data.frame(number = ncall.multiset, algorithm="multiset", size = nrow(CB), time_in_secs = diff_time.multiset), 72 | data.frame(number = ncall.list, algorithm="list", size = nrow(CB), time_in_secs = diff_time.list)) 73 | 74 | rv$machine <- Sys.info()['machine'] 75 | rv$sysname <- Sys.info()['sysname'] 76 | rv 77 | })) 78 | })) 79 | } 80 | -------------------------------------------------------------------------------- /R/recmap.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | #' @useDynLib recmap, .registration=TRUE 4 | #' @importFrom utils packageVersion 5 | #' @importFrom graphics plot polygon rect text strwidth abline axis 6 | #' @importFrom utils combn read.table 7 | NULL 8 | 9 | 10 | #' this function reproduces the original election cartogram from 2004 using 11 | #' the cartogram output from the 2003 implementation. 12 | #' 13 | #' @param plot default is TRUE 14 | #' 15 | #' @return the plot 16 | .draw_recmap_us_state_ev <- function(plot=TRUE){ 17 | 18 | 19 | # red-blue bi-poloar colormap 100; used in all CartoDraw / RecMap 20 | # publications since 2001 for visualizing cartographic error / scaling factor 21 | # and elelction data; exported from CartoView 22 | 23 | cm <- c("#FF0000", "#FF0505", "#FF0A0A", "#FF1010", "#FF1515", "#FF1A1A", "#FF1F1F", 24 | "#FF2424", "#FF2A2A", "#FF2F2F", "#FF3434", "#FF3939", "#FF3E3E", "#FF4444", 25 | "#FF4949", "#FF4E4E", "#FF5353", "#FF5858", "#FF5E5E", "#FF6363", "#FF6868", 26 | "#FF6D6D", "#FF7272", "#FF7878", "#FF7D7D", "#FF8282", "#FF8787", "#FF8D8D", 27 | "#FF9292", "#FF9797", "#FF9C9C", "#FFA1A1", "#FFA7A7", "#FFACAC", "#FFB1B1", 28 | "#FFB6B6", "#FFBBBB", "#FFC1C1", "#FFC6C6", "#FFCBCB", "#FFD0D0", "#FFD5D5", 29 | "#FFDBDB", "#FFE0E0", "#FFE5E5", "#FFEAEA", "#FFEFEF", "#FFF5F5", "#FFFAFA", 30 | "#FFFFFF", "#FFFFFF", "#FAFAFF", "#F5F5FF", "#EFEFFF", "#EAEAFF", "#E5E5FF", 31 | "#E0E0FF", "#DBDBFF", "#D5D5FF", "#D0D0FF", "#CBCBFF", "#C6C6FF", "#C1C1FF", 32 | "#BBBBFF", "#B6B6FF", "#B1B1FF", "#ACACFF", "#A7A7FF", "#A1A1FF", "#9C9CFF", 33 | "#9797FF", "#9292FF", "#8D8DFF", "#8787FF", "#8282FF", "#7D7DFF", "#7878FF", 34 | "#7272FF", "#6D6DFF", "#6868FF", "#6363FF", "#5E5EFF", "#5858FF", "#5353FF", 35 | "#4E4EFF", "#4949FF", "#4444FF", "#3E3EFF", "#3939FF", "#3434FF", "#2F2FFF", 36 | "#2A2AFF", "#2424FF", "#1F1FFF", "#1A1AFF", "#1515FF", "#1010FF", "#0A0AFF", 37 | "#0505FF", "#0000FF") 38 | 39 | # does not look so impressive 40 | # cm <- rev(diverge_hcl(100)) 41 | recmap_us_state_ev.file <- system.file("extdata", 42 | "recmap_us_state_ev.polygon", 43 | package = "recmap") 44 | 45 | recmap_us_state_ev <- read.table(recmap_us_state_ev.file, sep = '|', 46 | col.names=c('x', 'y')) 47 | 48 | us_state_election_2004.file <- system.file("extdata", 49 | "us_state_election_2004.csv", 50 | package = "recmap") 51 | 52 | us_state_election_2004 <- read.table(us_state_election_2004.file, 53 | sep = ',') 54 | if(plot){ 55 | 56 | idx <- seq(1, nrow(recmap_us_state_ev), by=5) 57 | 58 | x.max <- apply(cbind(recmap_us_state_ev$x[idx], 59 | recmap_us_state_ev$x[idx+1], 60 | recmap_us_state_ev$x[idx+2], 61 | recmap_us_state_ev$x[idx+3]), 1, max) 62 | x.min <- apply(cbind(recmap_us_state_ev$x[idx], 63 | recmap_us_state_ev$x[idx+1], 64 | recmap_us_state_ev$x[idx+2], 65 | recmap_us_state_ev$x[idx+3]), 1, min) 66 | 67 | y.max <- apply(cbind(recmap_us_state_ev$y[idx], 68 | recmap_us_state_ev$y[idx+1], 69 | recmap_us_state_ev$y[idx+2], 70 | recmap_us_state_ev$y[idx+3]), 1, max) 71 | 72 | y.min <- apply(cbind(recmap_us_state_ev$y[idx], 73 | recmap_us_state_ev$y[idx+1], 74 | recmap_us_state_ev$y[idx+2], 75 | recmap_us_state_ev$y[idx+3]), 1, min) 76 | 77 | 78 | dx <- 0.5 * (x.max - x.min) 79 | dy <- 0.5 * (y.max - y.min) 80 | 81 | 82 | M <- data.frame(x=x.min + dx, 83 | y=y.min + dy, 84 | dx=dx, dy=dy, 85 | z=(us_state_election_2004$V8/(us_state_election_2004$V8 + us_state_election_2004$V9)), 86 | name=gsub(' ', '\n', as.character(us_state_election_2004$V3))) 87 | 88 | tcol <- rep('black', nrow(us_state_election_2004)) 89 | tcol[8] <- 'white' 90 | 91 | plot.recmap(M, 92 | col.text = tcol, 93 | border=NULL, 94 | col=cm[round(length(cm) * (us_state_election_2004$V8/(us_state_election_2004$V8 + us_state_election_2004$V9)))+1]) 95 | }else{ 96 | M 97 | } 98 | } 99 | 100 | 101 | #' construct polygon mesh displayed in Figure 4a in 102 | #' 103 | #' @param A defines the area of a region in the center 104 | #' 105 | #' @return a \link{SpatialPolygons} object 106 | #' @references \doi{10.1109/TVCG.2004.1260761} 107 | #' @export 108 | #' 109 | #' @examples 110 | #' triangle.map <- recmap:::.get_7triangles() 111 | #' z <- c(rep(4, 4), rep(1, 3)) 112 | #' cols <- c(rep('white', 4), rep('grey',3)) 113 | #' 114 | #' op <- par(mfrow=c(1,2), mar=c(0, 0, 0, 0)) 115 | #' plot(triangle.map, col=cols) 116 | #' 117 | #' \dontrun{ 118 | #' # requires libfft.so installed in linux 119 | #' if (require(getcartr) & require(Rcartogram)){ 120 | #' cartogram <- quick.carto(triangle.map, z, res=64) 121 | #' plot(cartogram, col=cols) 122 | #' } 123 | #' } 124 | .get_7triangles <- function(A=1){ 125 | t<-list() 126 | 127 | tan30 <- tan(30 / 180 * pi) 128 | tan60 <- tan(60 / 180 * pi) 129 | sin30 <- sin(30 / 180 * pi) 130 | sin60 <- sin(60 / 180 * pi) 131 | cos30 <- cos(30 / 180 * pi) 132 | 133 | l <- sqrt(2 * A / sin60) 134 | 135 | t[[1]] <- Polygons(list(Polygon(cbind(c( 0.0, l, l/2), c( 0.0, 0.0, h <- tan60 * l / 2)))), 1) 136 | 137 | 138 | b <- h - (tan30 * l / 2) 139 | c <- -tan30 * A 140 | 141 | h2 <- - b /2 + sqrt((b/2)^2 -c) 142 | 143 | y <- h + h2 144 | 145 | x <- y / tan30 146 | 147 | h3 <- (y / sin30) - h 148 | h4 <- sqrt((x - cos30 * h)^2 + (y - sin30 * h)^2) 149 | stopifnot (abs(h3 - h4) < 0.01) 150 | 151 | t[[2]] <- Polygons(list(Polygon(cbind(c( l / 2, x, l/2 - (x-l / 2)), c(h, y, y)))), 2) 152 | t[[3]] <- Polygons(list(Polygon(cbind(c(l / 2, l, x), c(-h3,0,y)))), 3) 153 | t[[4]] <- Polygons(list(Polygon(cbind(c(l / 2, l / 2 - (x-l / 2), 0), c(-h3, y, 0)))), 4) 154 | t[[5]] <- Polygons(list(Polygon(cbind(c(0, l / 2 - (x-l / 2), l / 2), c(0, y, h)))), 5) 155 | t[[6]] <- Polygons(list(Polygon(cbind(c(l, x, l / 2), c(0, y, h)))), 6) 156 | t[[7]] <- Polygons(list(Polygon(cbind(c( 0.0, l, l / 2), c(0, 0, -h3)))), 7) 157 | 158 | triangle.map <- SpatialPolygons(t) 159 | 160 | triangle.map 161 | } 162 | 163 | 164 | #' @export 165 | checkerboard <- function(n = 8, ratio = 4){ 166 | xy <- (t(combn(1:n, 2))) 167 | xy <- rbind(cbind(xy[,1], xy[,2]), cbind(xy[,2], xy[,1]), cbind(1:n, 1:n)) 168 | 169 | 170 | z.bool <- (xor(xy[,1] %% 2 == 1 , xy[,2] %% 2 == 0)) 171 | z <- rep(1, length(xy[,1])) 172 | 173 | z[which(z.bool)] <- z[which(z.bool)] * ratio 174 | z[which(!z.bool)] <- z[which(!z.bool)] 175 | 176 | res <- data.frame(x = xy[, 1], 177 | y = xy[,2], 178 | dx = 0.5, 179 | dy = 0.5, 180 | z = z, 181 | name=paste(letters[1:n][xy[,1]], xy[,2], sep='')) 182 | 183 | 184 | 185 | res <- res[with(res, order(x, y)), ] 186 | row.names(res) <- 1:nrow(res); # paste(letters[1:n][xy[,1]], xy[,2], sep='') 187 | attr(res, 'Map.name') <- paste("checkerboard", n, "x", n) 188 | attr(res, 'Map.area') <- "1:4" 189 | class(res) = c('recmap', class(res)) 190 | res 191 | } 192 | 193 | #' @exportS3Method all.equal recmap 194 | #' @export all.equal.recmap 195 | all.equal.recmap <- function(target, current, ...){ 196 | isTRUE(all.equal(target$x, current$x, ...)) & 197 | isTRUE(all.equal(target$y, current$y, ...)) & 198 | isTRUE(all.equal(target$dx, current$dx, ...)) & 199 | isTRUE(all.equal(target$dy, current$dy, ...)) & 200 | isTRUE(all.equal(target$z, current$z, ...)) & 201 | isTRUE(all.equal(target$name, current$name, ...)) 202 | } 203 | 204 | #' Is an Object from a Class recmap? 205 | #' @inheritParams methods::is 206 | #' @export 207 | is.recmap <- function(object){ 208 | if(sum(c("x", "y", "dx", "dy", "z") %in% names(object)) != 5) { 209 | message("column names 'x', 'y', 'dx', 'dy', and 'z' are required.") 210 | return (FALSE) 211 | } 212 | 213 | if (!is.numeric(object$x)){ 214 | message("x is not numeric.") 215 | return(FALSE) 216 | } 217 | 218 | if (!is.numeric(object$y)) { 219 | message("y is not numeric.") 220 | return(FALSE) 221 | } 222 | 223 | if (!is.numeric(object$dx)){ 224 | message("dx is not numeric.") 225 | return(FALSE) 226 | } 227 | 228 | if (!is.numeric(object$dy)){ 229 | message("dy is not numeric.") 230 | return(FALSE) 231 | } 232 | 233 | if (!is.numeric(object$z)){ 234 | message("z is not numeric.") 235 | return(FALSE) 236 | } 237 | 238 | if (sum(object$dx < 0) != 0) { 239 | message('dx values have to be greater than 0.') 240 | return(FALSE) 241 | } 242 | 243 | if (sum(object$dy < 0) != 0){ 244 | message('dy values have to be greater than 0.') 245 | return(FALSE) 246 | } 247 | 248 | if (sum(object$z <= 0) != 0){ 249 | message('z values have to be greater equal than 0.') 250 | return(FALSE) 251 | } 252 | 253 | if (nrow(object) < 2) { 254 | message('requires at least two map regions.') 255 | return(FALSE) 256 | } 257 | 258 | return (TRUE) 259 | } 260 | 261 | 262 | as.SpatialPolygonsDataFrame <- function (x, ...) { 263 | UseMethod("as.SpatialPolygonsDataFrame", x) 264 | } 265 | 266 | #' Convert a recmap Object to SpatialPolygonsDataFrame Object. 267 | #' 268 | #' @description 269 | #' The method generates a SpatialPolygons object of a as input given 270 | #' \code{\link{recmap}} object. Both \code{data.frame}s are merged by the index order. 271 | #' 272 | #' @param x a \code{\link{recmap}} object. 273 | #' @param df a \code{data.frame} object. default is NULL. 274 | #' @param \dots \dots 275 | #' 276 | #' @importFrom sp Polygon Polygons SpatialPolygons SpatialPolygonsDataFrame spplot bbox 277 | #' 278 | #' @examples 279 | #' SpDf <- as.SpatialPolygonsDataFrame(recmap(checkerboard(8))) 280 | #' summary(SpDf) 281 | #' spplot(SpDf) 282 | #' 283 | #' @export as.SpatialPolygonsDataFrame 284 | #' @exportS3Method as.SpatialPolygonsDataFrame recmap 285 | #' @aliases as.SpatialPolygonsDataFrame 286 | as.SpatialPolygonsDataFrame.recmap <- function(x, df = NULL, ...){ 287 | if (is.recmap(x)){ 288 | SpP <- SpatialPolygons(lapply(1:nrow(x), function(i){ 289 | r <- x[i, ] 290 | Sr <- Polygon(cbind(c(r$x - r$dx, 291 | r$x - r$dx, 292 | r$x + r$dx, 293 | r$x + r$dx), 294 | c(r$y + r$dy, 295 | r$y - r$dy, 296 | r$y - r$dy, 297 | r$y + r$dy))) 298 | 299 | Polygons(list(Sr), r$name) 300 | })) 301 | 302 | if (is.null(df)){ 303 | return(SpatialPolygonsDataFrame(SpP, 304 | data.frame(z = x$z, 305 | row.names = x$name)))} 306 | 307 | return(SpatialPolygonsDataFrame(SpP, df)) 308 | } 309 | 310 | message("as.SpatialPolygonsDataFrame.recmap failed.") 311 | 312 | NULL 313 | } 314 | 315 | 316 | as.recmap <- function(X){ 317 | UseMethod("as.recmap", X) 318 | } 319 | 320 | #' Convert a SpatialPolygonsDataFrame Object to recmap Object 321 | #' 322 | #' @description 323 | #' The method generates a recmap class out of a \code{\link{SpatialPolygonsDataFrame}} object. 324 | #' 325 | #' @param X \code{\link{SpatialPolygonsDataFrame}} object. 326 | #' 327 | #' @return 328 | #' returns a \code{\link{recmap}} object. 329 | #' 330 | #' @references 331 | #' Roger S. Bivand, Edzer Pebesma, Virgilio Gomez-Rubio, 2013. 332 | #' Applied spatial data analysis with R, Second edition. Springer, NY. 333 | #' 334 | #' @examples 335 | #' SpDf <- as.SpatialPolygonsDataFrame(recmap(checkerboard(8))) 336 | #' summary(SpDf) 337 | #' spplot(SpDf) 338 | #' summary(as.recmap(SpDf)) 339 | #' 340 | #' @export as.recmap 341 | #' @exportS3Method as.recmap SpatialPolygonsDataFrame 342 | #' @aliases as.recmap 343 | as.recmap.SpatialPolygonsDataFrame <- function(X){ 344 | 345 | if (inherits(X, "SpatialPolygonsDataFrame")){ 346 | n <- length(X@polygons) 347 | 348 | df <- do.call('rbind', lapply(1:n, function(id){ 349 | 350 | 351 | do.call('rbind', lapply(X@polygons[id], function(p){ 352 | mbb <- bbox(p) 353 | 354 | x.min <- mbb['x','min'] 355 | x.max <- mbb['x','max'] 356 | y.min <- mbb['y','min'] 357 | y.max <- mbb['y','max'] 358 | 359 | dx <- 0.5 * (x.max - x.min) 360 | dy <- 0.5 * (y.max - y.min) 361 | 362 | data.frame(x = x.min + dx, y = y.min + dy, dx = dx, dy = dy, name=p@ID) 363 | })) 364 | 365 | })) 366 | 367 | df <- cbind(df, X@data) 368 | 369 | if (is.recmap(df)){ 370 | if (is.null(attr(X, 'Map.name'))){ 371 | attr(df, 'Map.name') <- "" 372 | } 373 | if (is.null(attr(X, 'Map.area'))){ 374 | attr(df, 'Map.area') <- "" 375 | } 376 | df <- df[, c('x', 'y', 'dx', 'dy', 'z', 'name')] 377 | row.names(df) <- 1:nrow(df) 378 | class(df) <- c('recmap', class(df)) 379 | return(df) 380 | } else if (!'z' %in% names(df)){ 381 | warning("Can not find 'z' column name in data.frame. Define 'z' and continue." ) 382 | } 383 | return(df) 384 | 385 | }else{ 386 | message('requires a "SpatialPolygonsDataFrame" class as argument.') 387 | } 388 | return (NULL) 389 | 390 | } 391 | 392 | .compute_area_error <- function(x){ 393 | 394 | area <- 4 * x$dx * x$dy 395 | sumZ <- sum(x$z) 396 | 397 | areaDesired <- x$z * sum(area) / sumZ 398 | 399 | error <- abs(areaDesired - area) / (areaDesired + area) 400 | 401 | sum(error * x$z) / sumZ 402 | } 403 | 404 | .compute_topology_error <- function(x){ 405 | 406 | if (sum(x$topology.error == -1) > 0) 407 | return(Inf) 408 | 409 | sum(x$topology.error) 410 | } 411 | 412 | 413 | .compute_relpos_error <- function(x){ 414 | sum(x$relpos.error) / nrow(x) 415 | } 416 | 417 | #' Summary for recmap object 418 | #' 419 | #' @description 420 | #' Summary method for S3 class \code{\link{recmap}}. 421 | #' The area error is computed as described in the CartoDraw paper. 422 | #' 423 | #' @inheritParams base::summary 424 | #' 425 | #' @inherit recmap references author 426 | #' 427 | #' @return 428 | #' returns a \code{data.frame} containing summary information, e.g., 429 | #' objective functions or number of map regions. 430 | #' 431 | #' @method summary recmap 432 | #' @exportS3Method summary recmap 433 | #' @export summary.recmap 434 | #' @aliases summary.recmapGA 435 | #' 436 | #' @examples 437 | #' summary(checkerboard(4)); 438 | #' summary(recmap(checkerboard(4))) 439 | summary.recmap <- function(object, ...) { 440 | 441 | x <- object 442 | 443 | if (!is.recmap(x)){ return (NULL) } 444 | 445 | if (is.recmap(x)){ 446 | 447 | nRegions <- nrow(x) 448 | errorArea <- round(.compute_area_error(x), 2) 449 | errorTopology <- NA 450 | errorRelPos <- NA 451 | spaceFilling <- 100 * sum(4 * x$dx * x$dy) / ((max(x$x + x$dx) - min(x$x - x$dx)) * (max(x$y + x$dy) - min(x$y - x$dy))) 452 | 453 | if ("dfs.num" %in% names(x)){ 454 | errorTopology <- .compute_topology_error(x) 455 | errorRelPos <- round(.compute_relpos_error(x), 2) 456 | } 457 | 458 | 459 | 460 | data.frame(row.names = c("number of map regions", 461 | "area error", 462 | "topology error", 463 | "relative position error", 464 | "screen filling [in %]", 465 | "xmin", 466 | "xmax", 467 | "ymin", 468 | "ymax"), 469 | values = c(nRegions, errorArea, errorTopology, errorRelPos, 470 | spaceFilling, 471 | min(x$x - x$dx), 472 | max(x$x + x$dx), 473 | min(x$y - x$dy), 474 | max(x$y + x$dy))) 475 | 476 | } 477 | 478 | } 479 | #' Plot a recmap object. 480 | #' 481 | #' @description 482 | #' plots input and output of the \code{\link{recmap}} function. 483 | #' The function requires column names (x, y, dx, dy). 484 | #' 485 | #' @param x \code{recmap} object - can be input or output of \code{recmap}. 486 | #' @param col a vector of colors. 487 | #' @param border 488 | #' This parameter is passed to the \code{\link{rect}} function. 489 | #' color for rectangle border(s). The default means par("fg"). 490 | #' Use border = NA to omit borders. If there are shading lines, border = TRUE 491 | #' means use the same colour for the border as for the shading lines. 492 | #' The default value is set to \code{'darkgreen'}. 493 | #' @param col.text a vector of colors. 494 | #' @param \ldots whatsoever 495 | #' 496 | #' @inherit recmap references author 497 | #' @return graphical output 498 | #' 499 | #' @exportS3Method plot recmap 500 | #' @export plot.recmap 501 | #' @aliases plot.recmapGA plot.recmapGRASP 502 | #' @examples 503 | #' checkerboard(2) |> recmap() |> plot() 504 | plot.recmap <- function(x, col='#00000011', col.text = 'grey', border = 'darkgreen', ...){ 505 | 506 | if (!is.recmap(x)){ return (NULL) } 507 | 508 | label.text <- TRUE 509 | S <- x 510 | 511 | plot(S$x, S$y, 512 | xlim = c(min(S$x - S$dx), max(S$x + S$dx)), 513 | ylim = c(min(S$y - S$dy), max(S$y + S$dy)), 514 | type = 'n', 515 | asp = 1, 516 | xlab = '', 517 | ylab = '', 518 | axes = FALSE, ...) 519 | 520 | rect(xleft = S$x - S$dx, 521 | ybottom = S$y - S$dy, 522 | xright = S$x + S$dx, 523 | ytop = S$y + S$dy, 524 | col = col, 525 | border = border) 526 | 527 | if (sqrt(length(S$x)) < 10 & label.text){ 528 | text(S$x, S$y, 529 | S$name, 530 | cex = S$dx / strwidth(S$name), 531 | col = col.text) 532 | } 533 | } 534 | 535 | .plot_recmap_error <- function(S){ 536 | 537 | plot(sort(S$relpos.error), 538 | main="relpos.error", 539 | ylab=expression(paste("normalized angle [in ", pi,"]"))) 540 | 541 | axis(4, c(0.25,0.5,0.75)*pi, c(0.25,0.5,0.75)) 542 | abline(h=c(0.25,0.5,0.75)*pi, col="#55555555") 543 | 544 | plot(sort(S$relposnh.error), 545 | main="relposnh.error", 546 | ylab=expression(paste("normalized angle [in ", pi,"]"))) 547 | 548 | axis(4, c(0.25,0.5,0.75)*pi, c(0.25,0.5,0.75)) 549 | abline(h=c(0.25,0.5,0.75)*pi, col="#55555555") 550 | 551 | } 552 | 553 | 554 | # define a fitness function 555 | .recmap.fitness <- function(idxOrder, Map, ...){ 556 | Cartogram <- recmap(Map[idxOrder, ]) 557 | # a map region could not be placed; 558 | # accept only feasible solutions! 559 | 560 | if (sum(Cartogram$topology.error == -1) > 0){return (0)} 561 | 562 | 1 / sum(Cartogram$relpos.error) 563 | } 564 | 565 | #' @export 566 | recmapGRASP <- 567 | function(Map, 568 | fitness = .recmap.fitness, 569 | n.samples = nrow(Map) * 2, 570 | fitness.cutoff = 1.7, 571 | iteration.max = 10){ 572 | 573 | input <- Map 574 | solution.best <- NULL; iteration <- 0; f.max <- 0.0; 575 | 576 | # GRASP stopping criterion not satisfied 577 | while (f.max < fitness.cutoff && iteration < iteration.max){ 578 | iteration <- iteration + 1 579 | 580 | # Construct Greedy Randomized Solution 581 | # res <- parallel::mclapply(1:n.samples, function(x){ 582 | res <- lapply(1:n.samples, function(x){ 583 | smp <- sample.int(nrow(input)) 584 | list(solution = smp, 585 | fitness = fitness(smp, input)) 586 | }) 587 | 588 | f.mean <- mean(sapply(res, function(x){x$fitness})) 589 | 590 | idx <- order(sapply(res, function(x){x$fitness}), 591 | decreasing = TRUE)[1] 592 | 593 | solution <- res[[idx]] 594 | 595 | f <- solution$fitness 596 | 597 | # UpdateSolution 598 | if (f > f.max){ f.max <- f; solution.best <- solution; } 599 | cat(paste(format(Sys.time(), "%s GRASP"), 600 | round(f.max, 2), 601 | round(f.mean, 2), 602 | iteration, "\n")) 603 | } 604 | 605 | r <- list(GRASP = solution.best, 606 | Map = Map, 607 | Cartogram = recmap(Map[solution.best$solution, ]) 608 | ) 609 | 610 | class(r) <- c(class(r), 'recmapGRASP') 611 | r 612 | } 613 | 614 | 615 | #' Genetic Algorithm Wrapper Function for recmap 616 | #' 617 | #' @description 618 | #' higher-level function for \code{\link{recmap}} using a Genetic Algorithm as 619 | #' metaheuristic. 620 | #' 621 | #' @inheritParams recmap 622 | #' @inheritParams GA::ga 623 | #' 624 | #' @importFrom GA ga gaMonitor summary.ga 625 | #' @return 626 | #' returns a list of the input \code{Map}, the solution of the \code{\link[GA]{ga}} 627 | #' function, and a \code{\link{recmap}} object containing the cartogram. 628 | #' 629 | #' @references 630 | #' Luca Scrucca (2013). GA: A Package for Genetic Algorithms in R. 631 | #' Journal of Statistical Software, 53(4), 1-37. 632 | #' \doi{10.18637/jss.v053.i04}. 633 | #' 634 | #' @examples 635 | #' ## The default fitnes function is currently defined as 636 | #' function(idxOrder, Map, ...){ 637 | #' 638 | #' Cartogram <- recmap(Map[idxOrder, ]) 639 | #' # a map region could not be placed; 640 | #' # accept only feasible solutions! 641 | #' 642 | #' if (sum(Cartogram$topology.error == 100) > 0){return (0)} 643 | #' 644 | #' 1 / sum(Cartogram$relpos.error) 645 | #' } 646 | #' 647 | #' 648 | #' ## use Genetic Algorithms (GA >=3.0.0) as metaheuristic 649 | #' set.seed(1) 650 | #' 651 | #' ## https://github.com/luca-scr/GA/issues/52 652 | #' if (Sys.info()['machine'] == "arm64") GA::gaControl(useRcpp = FALSE) 653 | #' res <- recmapGA(V = checkerboard(4), pmutation = 0.25) 654 | #' 655 | #' op <- par(mfrow = c(1, 3)) 656 | #' plot(res$Map, main = "Input Map") 657 | #' plot(res$GA, main="Genetic Algorithm") 658 | #' plot(res$Cartogram, main = "Output Cartogram") 659 | #' 660 | #' 661 | #' ## US example 662 | #' getUS_map <- function(){ 663 | #' usa <- data.frame(x = state.center$x, 664 | #' y = state.center$y, 665 | #' # make the rectangles overlapping by correcting 666 | #' # lines of longitude distance. 667 | #' dx = sqrt(state.area) / 2 668 | #' / (0.8 * 60 * cos(state.center$y * pi / 180)), 669 | #' dy = sqrt(state.area) / 2 / (0.8 * 60), 670 | #' z = sqrt(state.area), 671 | #' name = state.name) 672 | #' 673 | #' usa$z <- state.x77[, 'Population'] 674 | #' US.Map <- usa[match(usa$name, 675 | #' c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 676 | #' 677 | #' class(US.Map) <- c('recmap', 'data.frame') 678 | #' US.Map 679 | #' } 680 | #' 681 | #' \dontrun{ 682 | #' # takes 34.268 seconds on CRAN 683 | #' res <- recmapGA(V = getUS_map(), maxiter = 5) 684 | #' op <- par(ask = TRUE) 685 | #' plot(res) 686 | #' par(op) 687 | #' summary(res) 688 | #' } 689 | #' @export 690 | recmapGA <- function(V, 691 | fitness = .recmap.fitness, 692 | pmutation = 0.25, 693 | popSize = 10 * nrow(Map), 694 | maxiter = 10, 695 | run = maxiter, 696 | monitor = if(interactive()) 697 | { gaMonitor } 698 | else FALSE, 699 | parallel = FALSE, ...){ 700 | Map <- V 701 | start_time <- Sys.time() 702 | GA <- ga(type = "permutation", 703 | fitness = fitness, 704 | Map = Map, 705 | monitor = monitor, 706 | lower = 1, upper = nrow(Map) , 707 | popSize = popSize, 708 | maxiter = maxiter, 709 | run = run, 710 | parallel = parallel, 711 | pmutation = pmutation, 712 | ...) 713 | end_time <- Sys.time() 714 | diff_time <- as.numeric(difftime(end_time, start_time, units = "secs")) 715 | if (is.null(attr(Map, 'Map.name'))){ 716 | attr(Map, 'Map.name') <- "" 717 | } 718 | if (is.null(attr(Map, 'Map.area'))){ 719 | attr(Map, 'Map.area') <- "" 720 | } 721 | res <- list(GA = GA, 722 | Map = Map[GA@solution[1, ], ], 723 | Cartogram = recmap(Map[GA@solution[1, ], ]), 724 | Summary = data.frame( 725 | Map.name = attr(Map, 'Map.name'), 726 | Map.area = tolower(attr(Map, 'Map.area')), 727 | Map.number.regions = length(GA@solution[1,]), 728 | Map.error.area = round(.compute_area_error(Map), 2), 729 | GA.population.size = as.integer(GA@popSize), 730 | GA.number.generation = nrow(GA@summary), 731 | GA.pmutation = GA@pmutation, 732 | GA.fitness = round(GA@fitnessValue, 2), 733 | GA.parallel = parallel, 734 | GA.number.recmaps_a_second = round((as.integer(GA@popSize) * nrow(GA@summary) / diff_time), 1), 735 | Sys.compute.time = round(diff_time, 1), 736 | Sys.machine = Sys.info()['machine'], 737 | Sys.sysname = Sys.info()['sysname']) 738 | ) 739 | 740 | 741 | class(res) = c('recmapGA', class(res)) 742 | res 743 | } 744 | 745 | 746 | #' @exportS3Method plot recmapGA 747 | #' @export plot.recmapGA 748 | plot.recmapGA <- function(x, ...){ 749 | GA::plot(x$GA, main="GA") 750 | plot.recmap(x$Map, main="input map", ...) 751 | plot.recmap(x$Cartogram, main = "output cartogram", ...) 752 | } 753 | 754 | #' @exportS3Method plot recmapGRASP 755 | #' @export plot.recmapGRASP 756 | plot.recmapGRASP <- function(x, ...){ 757 | plot.recmap(x$Map, main="input map", ...) 758 | plot.recmap(x$Cartogram, main = "output cartogram", ...) 759 | } 760 | 761 | #' @export summary.recmapGA 762 | summary.recmapGA <- function(object, ...){ 763 | cat("summary of class recmapGA:\n") 764 | cat("summary of the GA:\n") 765 | print(summary.ga(object$GA)) 766 | 767 | S <- summary.recmap(object$Map) 768 | names(S) <- "Map" 769 | S$Cartogram <- summary.recmap(object$Cartogram)$values 770 | print(S) 771 | } 772 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | .onAttach <- function(lib, pkg){ 4 | if(interactive()){ 5 | version <- packageVersion('recmap') 6 | packageStartupMessage("Package 'recmap' version ", version) 7 | invisible() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/recmap)](https://cran.r-project.org/package=recmap) 2 | [![Research software impact](http://depsy.org/api/package/cran/recmap/badge.svg)](http://depsy.org/package/r/recmap) 3 | [![](http://cranlogs.r-pkg.org/badges/grand-total/recmap)](https://cran.r-project.org/package=recmap) 4 | [![](http://cranlogs.r-pkg.org/badges/recmap)](https://cran.r-project.org/package=recmap) 5 | ![](https://github.com/cpanse/recmap/workflows/R-CMD-check-recmap/badge.svg) 6 | [![JSS](https://img.shields.io/badge/JSS-10.18637%2Fjss.v086.c01-brightgreen)](http://dx.doi.org/10.18637/jss.v086.c01) 7 | [![codecov](https://codecov.io/github/cpanse/recmap/branch/master/graph/badge.svg?token=QbuhWl5bx5)](https://codecov.io/github/cpanse/recmap) 8 | 9 | # recmap - Compute the Rectangular Statistical Cartogram 10 | 11 | This package implements the [RecMap construction algorithm (MP2)](http://dx.doi.org/10.1109/INFVIS.2004.57) using the [GA]( https://CRAN.R-project.org/package=GA) CRAN package as metaheuristic. 12 | 13 | 14 | ![rectangular population cartogram construction demo - animated gif](https://user-images.githubusercontent.com/4901987/64121133-3dfc9100-cd9e-11e9-8c35-078678966100.gif) 15 | 16 | ## 1. Installation 17 | 18 | use [CRAN](https://CRAN.R-project.org/package=recmap) 19 | 20 | `recmap` requires R 3.6 or later. 21 | 22 | Released and tested versions of `recmap` are available via 23 | [CRAN](https://CRAN.R-project.org/package=recmap), 24 | and can be installed using the following code 25 | 26 | ```{r} 27 | install.packages('recmap') 28 | ``` 29 | 30 | before running `R CMD build` and `R CMD check` or running the shiny demo execute 31 | ```{r} 32 | pkgs <- c('colorspace', 'doParallel', 'DT', 'knitr', 'maps', 33 | 'shiny', 'testthat', 'tufte') 34 | pkgs <- pkgs[(!pkgs %in% unique(installed.packages()[,'Package']))] 35 | if(length(pkgs) > 0){install.packages(pkgs)} 36 | ``` 37 | 38 | ## 2. Documentation 39 | 40 | The package ships with a package 41 | [vignette](https://CRAN.R-project.org/package=recmap/vignettes/recmap.html) 42 | (`browseVignettes('recmap')`) 43 | and a reference manual (just type `?recmap` on the R shell). 44 | Both documents are also available on the package's 45 | [CRAN](https://CRAN.R-project.org/package=recmap) page. 46 | A white paper containing more technical information and examples is 47 | available through [jss.v086.c01](http://dx.doi.org/10.18637/jss.v086.c01). 48 | 49 | ## 3. Demonstration 50 | 51 | Run an interactive shiny application 52 | 53 | ```{r} 54 | library(recmap) 55 | GA::gaControl("useRcpp" = FALSE) # apple M1 56 | recmap_shiny <- system.file('shiny-examples', package = 'recmap') 57 | shiny::runApp(recmap_shiny, display.mode = 'normal') 58 | ``` 59 | 60 | Run the recmap shiny demonstration as a stand-alone application 61 | using Linux and macOS systems use the `Terminal` application add the following 62 | code to your alias file, e.g., `$HOME/.bashrc` 63 | 64 | ``` 65 | alias recmapShiny="R -e \"library(shiny); \ 66 | recmap_shiny <- system.file('shiny-examples', package = 'recmap'); \ 67 | shiny::runApp(recmap_shiny, display.mode = 'normal', launch.browser=TRUE)\"" 68 | ``` 69 | 70 | execute 71 | 72 | `. $HOME/.bashrc && recmapShiny` 73 | 74 | ## 4. (Frequently) Asked Questions 75 | 76 | ### 4.1 Is there an easy way to convert a `recmap` object to an [`sf`](https://CRAN.R-project.org/package=sf ) object? 77 | 78 | 79 | Use [`as.SpatialPolygonsDataFrame`](https://github.com/cpanse/recmap/blob/da2f90d2edb3feda7464bb543147d2908851e92b/R/recmap.R#L265), 80 | see also issue [#13](https://github.com/cpanse/recmap/issues/13). 81 | The `as.recmap` function performs the transformation from a 82 | `SpatialPolygonsDataFrame` into a `recmap` compatible object. 83 | 84 | ## 5. Related approaches 85 | 86 | * [Rectangular Cartograms: the game](https://bspeckmann.win.tue.nl/demos/game/index.html), [Rectangular Cartograms](https://bspeckmann.win.tue.nl/Cartograms/SoccerCarto.html) 87 | * cartogram: Create Cartograms with R [https://CRAN.R-project.org/package=cartogram](https://CRAN.R-project.org/package=cartogram) 88 | * [Rcartogram](https://github.com/omegahat/Rcartogram) 89 | * [High-performance software to produce flow-based cartograms.](https://github.com/Flow-Based-Cartograms/go_cart) 90 | * see also [CRAN Task View: Analysis of Spatial Data](https://CRAN.R-project.org/view=Spatial) 91 | * Computing Stable Demers Cartograms - https://arxiv.org/abs/1908.07291 92 | * Wang, L., Yuan, H., Li, X., Lu, P., & Li, Y. (2025). A New Construction Method for Rectangular Cartograms. ISPRS International Journal of Geo-Information, 14(1), 25. [doi 10.3390/ijgi14010025](https://doi.org/10.3390/ijgi14010025) 93 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /data/jss2711.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpanse/recmap/92cfe7d254792b411d4f270f83a076761893a6d7/data/jss2711.RData -------------------------------------------------------------------------------- /data/jss2711.RData.bak: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpanse/recmap/92cfe7d254792b411d4f270f83a076761893a6d7/data/jss2711.RData.bak -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | 2 | recmapref <- c( 3 | bibentry( 4 | bibtype = "Article", 5 | title = "Rectangular Statistical Cartograms in {R}: The {recmap} Package", 6 | author = person(given = "Christian", 7 | family = "Panse", 8 | email = "cp@fgcz.ethz.ch"), 9 | journal = "Journal of Statistical Software, Code Snippets", 10 | year = "2018", 11 | volume = "86", 12 | number = "1", 13 | pages = "1--27", 14 | doi = "10.18637/jss.v086.c01", 15 | ), 16 | bibentry( 17 | bibtype = "Inproceedings", 18 | title = "RecMap: Rectangular Map Approximations", 19 | author = c(person("Roland", "Heilmann"), 20 | person("Daniel", "Keim"), 21 | person("Christian", "Panse"), 22 | person("Mike", "Sips")), 23 | booktitle = "10th {IEEE} Symposium on Information Visualization (InfoVis 2004), 10-12 October 2004, Austin, TX, {USA}", 24 | pages = "33-40", 25 | month = "October", 26 | year = 2004, 27 | doi = "10.1109/INFVIS.2004.57" 28 | ) 29 | ) 30 | 31 | -------------------------------------------------------------------------------- /inst/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rocker/geospatial:4.0.3-daily 2 | MAINTAINER Christian Panse 3 | RUN install2.r --error \ 4 | GA \ 5 | colorspace \ 6 | doParallel \ 7 | knitr \ 8 | maps \ 9 | rcmdcheck \ 10 | shiny \ 11 | testthat 12 | # RUN apt-get install texlive-fonts-extra -y 13 | RUN apt-get update --fix-missing 14 | RUN apt-get install curl -y && cd /tmp \ 15 | && curl -s https://codeload.github.com/cpanse/recmap/zip/master \ 16 | > recmap.zip && unzip recmap.zip \ 17 | && R CMD build recmap-master --no-build-vignettes \ 18 | && R CMD check recmap_*.tar.gz --no-manual --no-build-vignettes \ 19 | && R CMD INSTALL recmap*.gz 20 | -------------------------------------------------------------------------------- /inst/NEWS.Rd: -------------------------------------------------------------------------------- 1 | \name{NEWS} 2 | \title{News for Package 'recmap'} 3 | 4 | \newcommand{\ghit}{\href{https://github.com/cpanse/recmap/issues/#1}{##1}} 5 | 6 | \section{Changes until version 1.0.17 (2023-09-16)}{ 7 | \itemize{ 8 | \item Use RoxygenNote for man page and Rcpp wrapper \ghit{21}. 9 | } 10 | } 11 | 12 | \section{Changes until version 1.0.12 (2021-11-20)}{ 13 | \itemize{ 14 | \item GA Rcpp issue on apply M1; replace skip_on_os with \code{GA::gaControl("useRcpp" = FALSE)} \href{https://github.com/luca-scr/GA/issues/52}{#52} 15 | } 16 | } 17 | 18 | \section{Changes until version 1.0.10 (2021-09-20)}{ 19 | \itemize{ 20 | \item url fix in man page urls 21 | \item skip recmapGA test case on mac os \href{https://github.com/luca-scr/GA/issues/52}{#52} 22 | } 23 | } 24 | 25 | \section{Changes until version 1.0.9 (2021-05-07)}{ 26 | \itemize{ 27 | \item Moving towards defining STRICT_R_HEADERS in Rcpp.h \url{https://github.com/RcppCore/Rcpp/issues/1158} \url{https://github.com/cpanse/recmap/commit/5ae6aade93026b96238804e06593fa9088dda763} 28 | \item url fix in man page urls 29 | } 30 | } 31 | 32 | \section{Changes until version 1.0.8 (2020-02-20)}{ 33 | \itemize{ 34 | \item remove shiny colorspace and xtable package in suggest 35 | \item R (>=3.6) and hard coded colormaps or 36 | use `grDevices::hcl.colors()` \ghit{19} 37 | \item added construction animated gif 38 | \url{https://user-images.githubusercontent.com/4901987/64121133-3dfc9100-cd9e-11e9-8c35-078678966100.gif} to README.md. 39 | } 40 | } 41 | \section{Changes until version 1.0.5 (2019-06-03)}{ 42 | \itemize{ 43 | \item fix recmapGRASP testcase \ghit{14}. 44 | \item text cosmetics \ghit{14}. 45 | \item fixed \ghit{15}. 46 | \item fixed \ghit{16}. 47 | \item fixed \ghit{17}. 48 | \item added DOI in Description. 49 | } 50 | } 51 | 52 | \section{Changes until version 1.0.0 (2018-09-16)}{ 53 | \itemize{ 54 | \item incorporate CITATION file to refer back to 55 | the JSS manuscript \doi{10.18637/jss.v086.c01}. 56 | } 57 | } 58 | 59 | \section{Changes until version 0.5.35 (2018-06-01)}{ 60 | \itemize{ 61 | \item \ghit{11}. 62 | \item replaced items in data/jss2711.RData. 63 | } 64 | } 65 | 66 | \section{Changes until version 0.5.33 (2018-05-01)}{ 67 | \itemize{ 68 | \item mv src/recmap.h inst/include/recmap 69 | \item man page cosmetics 70 | } 71 | } 72 | 73 | \section{Changes until version 0.5.32 (2018-03-24)}{ 74 | \itemize{ 75 | \item added test-jss2711(renamed test-recmapGA.R) checking Figure 7, 11, 12 ,13. 76 | } 77 | } 78 | 79 | \section{Changes until version 0.5.31 (2018-03-23)}{ 80 | \itemize{ 81 | \item added jss2711 submission as vignette file. 82 | \item added jss2711 data. 83 | \item replace gaMonitor2 by gaMonitor (GA3.1). 84 | \item added test-recmapGA.R for reproducibility. 85 | } 86 | } 87 | 88 | \section{Changes until version 0.5.24 (2017-09-16)}{ 89 | \itemize{ 90 | \item spell check cosmetics. 91 | \item added a progress window in the shiny apps. 92 | \item added \code{is.recmap} function. 93 | \item replaced \code{recmap2sp} and \code{sp2recmap} functions by S3methods \code{as.SpatialPolygonsDataFrame} and \code{as.recmap}. 94 | } 95 | } 96 | 97 | \section{Changes until version 0.5.20 (2017-04-10)}{ 98 | \itemize{ 99 | \item added argument for the definition of the pseudo dual graph in \code{recmap}. 100 | \item fixed register native routine issue by using \code{tools::package_native_routine_registration_skeleton(".")} 101 | \item added shiny example including 102 | \href{https://shiny.rstudio.com/reference/shiny/1.4.0/hoverOpts.html}{hoverOpts} 103 | using \code{state.x77} data executable through 104 | \code{recmap_state.x77 <- system.file("shiny-examples", "state.x77", package = "recmap")} 105 | and 106 | \code{recmap_US.county <- system.file("shiny-examples", "US.county", package = "recmap")} 107 | } 108 | } 109 | \section{Changes until version 0.5.16 (2017-01-15)}{ 110 | improvements concerning \href{https://www.jstatsoft.org}{JSS} reviewer comments: 111 | \itemize{ 112 | 113 | \item added a \code{sp2recmap} method including a testthat method. 114 | \item added 'meta' plot methods \code{plot.recmapGA} and 115 | \code{plot.recmapGRAP}. 116 | 117 | \item added a \code{border} attribute to the \code{plot.recmap} method. 118 | \item \code{plot.recmap} labels are now scaled by using \code{S$dx / strwidth(S$name)}. 119 | } 120 | } 121 | 122 | \section{Changes until version 0.5.5 (2016-12-13)}{ 123 | \itemize{ 124 | \item added a screen-filling parameter in \code{summary.recmap} function. 125 | \item man page cosmetics. 126 | \item bugfix in \code{summary.recmap} function for MBB computation. 127 | } 128 | } 129 | 130 | \section{Changes version 0.5.4 (2016-07-24)}{ 131 | improvements concerning \href{https://www.jstatsoft.org}{JSS} editorial comments 132 | prescreening stage: 133 | \itemize{ 134 | \item added dependencies from \href{https://cran.r-project.org/package=GA}{GA} 135 | and \href{https://cran.r-project.org/package=sp}{sp} 136 | \item added S3 methods \code{plot.recmap()} and \code{recmap.summary}. 137 | \item added \code{recmapGA} to glue \code{ga} and \code{recmap} functions. 138 | \item added \code{recmapGRASP} method. 139 | \item exported \code{checkerboard()} function. 140 | \item added method \code{recmap2sp} to export a 141 | \href{https://cran.r-project.org/package=sp}{sp} object. 142 | } 143 | } 144 | 145 | \section{Changes version 0.5.0 (2016-07-01)}{ 146 | \itemize{ 147 | \item add docker Public | Automated Build 148 | \url{https://hub.docker.com/r/cpanse/recmap/}. 149 | \item manual and vignette cosmetics. 150 | \item added \code{zzz.R}. 151 | } 152 | } 153 | 154 | \section{Changes version 0.4.0 (2016-06-12)}{ 155 | 156 | \itemize{ 157 | \item \emph{bugfix} - \code{valgrind} 158 | 'Conditional jump or move depends on uninitialized value(s)'. 159 | 160 | \item added test case for topology error 161 | 162 | \item added startup message for package version 163 | 164 | \item \emph{bugfix} - topology error; if a region cannot be placed 165 | return topology error 100. 166 | this has a major impact on the return value of the fitness function. 167 | 168 | \code{# accept only feasible solutions!} 169 | 170 | \code{if (sum(cartogram$topology.error == 100) > 0){return (0)}} 171 | 172 | \item make \code{recmap.h} pass google/styleguides using 173 | \href{https://github.com/google/styleguide/tree/gh-pages/cpplint}{cpplint}. 174 | 175 | \item manual and vignette cosmetics. 176 | 177 | } 178 | } 179 | 180 | 181 | \section{Changes in version 0.3.0 (2016-05-30)}{ 182 | \itemize{ 183 | \item refactor linear MBB intersection test by introducing using 184 | \code{std::multiset}. 185 | 186 | \item added local relative position and topology objective function. 187 | \item added GA metaheuristic example in man page. 188 | \item improved documentation (man page and vignette). 189 | \item added unit test case for recmap. 190 | \item added NEWS.Rd file. 191 | } 192 | } 193 | 194 | \section{Changes in version 0.2.1 (2016-05-01)}{ 195 | \itemize{ 196 | \item cosmetics in the DESCRIPTION; on CRAN. 197 | } 198 | } 199 | 200 | 201 | \section{Changes in version 0.2.0 (2016-05-01)}{ 202 | \itemize{ 203 | \item 1st submit to CRAN. 204 | } 205 | } 206 | 207 | 208 | -------------------------------------------------------------------------------- /inst/extdata/recmap_us_state_ev.polygon: -------------------------------------------------------------------------------- 1 | 145.189|25.5454 2 | 145.189|43.8993 3 | 158.939|43.8993 4 | 158.939|25.5454 5 | NA|NA 6 | 41.0231|60.4363 7 | 41.0231|77.0343 8 | 57.9172|77.0343 9 | 57.9172|60.4363 10 | NA|NA 11 | 107.165|68.9801 12 | 107.165|79.9173 13 | 122.547|79.9173 14 | 122.547|68.9801 15 | NA|NA 16 | 0|52.2716 17 | 0|89.866 18 | 41.0231|89.866 19 | 41.0231|52.2716 20 | NA|NA 21 | 63.7934|78.0284 22 | 63.7934|90.0443 23 | 84.7963|90.0443 24 | 84.7963|78.0284 25 | NA|NA 26 | 289.345|84.0327 27 | 289.345|94.6103 28 | 307.901|94.6103 29 | 307.901|84.0327 30 | NA|NA 31 | 233.68|74.6198 32 | 233.68|86.7483 33 | 240.616|86.7483 34 | 240.616|74.6198 35 | NA|NA 36 | 237.211|65.4474 37 | 237.211|73.0233 38 | 248.315|73.0233 39 | 248.315|65.4474 40 | NA|NA 41 | 154.613|0 42 | 154.613|25.5454 43 | 184.251|25.5454 44 | 184.251|0 45 | NA|NA 46 | 158.939|25.5454 47 | 158.939|45.5877 48 | 179.925|45.5877 49 | 179.925|25.5454 50 | NA|NA 51 | 51.9494|89.866 52 | 51.9494|101.129 53 | 61.9083|101.129 54 | 61.9083|89.866 55 | NA|NA 56 | 125.203|69.1406 57 | 125.203|97.8759 58 | 145.695|97.8759 59 | 145.695|69.1406 60 | NA|NA 61 | 155.145|78.0229 62 | 155.145|97.5374 63 | 170.951|97.5374 64 | 170.951|78.0229 65 | NA|NA 66 | 105.01|88.1554 67 | 105.01|97.8759 68 | 125.203|97.8759 69 | 125.203|88.1554 70 | NA|NA 71 | 84.7963|79.9173 72 | 84.7963|88.1554 73 | 105.219|88.1554 74 | 105.219|79.9173 75 | NA|NA 76 | 145.695|69.1406 77 | 145.695|78.0229 78 | 170.951|78.0229 79 | 170.951|69.1406 80 | NA|NA 81 | 107.165|54.7183 82 | 107.165|68.9801 83 | 124.86|68.9801 84 | 124.86|54.7183 85 | NA|NA 86 | 298.092|119.481 87 | 298.092|130.414 88 | 308.351|130.414 89 | 308.351|119.481 90 | NA|NA 91 | 211.172|63.851 92 | 211.172|74.6198 93 | 237.211|74.6198 94 | 237.211|63.851 95 | NA|NA 96 | 289.345|94.6103 97 | 289.345|107.235 98 | 315.998|107.235 99 | 315.998|94.6103 100 | NA|NA 101 | 170.951|90.6723 102 | 170.951|106.947 103 | 188.181|106.947 104 | 188.181|90.6723 105 | NA|NA 106 | 105.01|97.8759 107 | 105.01|112.475 108 | 124.218|112.475 109 | 124.218|97.8759 110 | NA|NA 111 | 134.052|30.4804 112 | 134.052|45.5877 113 | 145.189|45.5877 114 | 145.189|30.4804 115 | NA|NA 116 | 124.925|54.4868 117 | 124.925|69.1406 118 | 145.973|69.1406 119 | 145.973|54.4868 120 | NA|NA 121 | 61.9083|96.9794 122 | 61.9083|102.682 123 | 76.6606|102.682 124 | 76.6606|96.9794 125 | NA|NA 126 | 84.7963|88.1554 127 | 84.7963|95.0914 128 | 105.01|95.0914 129 | 105.01|88.1554 130 | NA|NA 131 | 41.0231|77.0343 132 | 41.0231|89.866 133 | 51.9494|89.866 134 | 51.9494|77.0343 135 | NA|NA 136 | 298.092|107.235 137 | 298.092|119.481 138 | 307.251|119.481 139 | 307.251|107.235 140 | NA|NA 141 | 233.68|86.7483 142 | 233.68|112.055 143 | 250.301|112.055 144 | 250.301|86.7483 145 | NA|NA 146 | 60.7019|59.6799 147 | 60.7019|71.1422 148 | 72.9335|71.1422 149 | 72.9335|59.6799 150 | NA|NA 151 | 250.301|89.7909 152 | 250.301|112.055 153 | 289.345|112.055 154 | 289.345|89.7909 155 | NA|NA 156 | 179.925|41.6158 157 | 179.925|53.0633 158 | 216.667|53.0633 159 | 216.667|41.6158 160 | NA|NA 161 | 90.6776|106.605 162 | 90.6776|112.475 163 | 105.01|112.475 164 | 105.01|106.605 165 | NA|NA 166 | 170.951|69.1406 167 | 170.951|90.6723 168 | 196.997|90.6723 169 | 196.997|69.1406 170 | NA|NA 171 | 84.7963|71.1422 172 | 84.7963|79.9173 173 | 107.165|79.9173 174 | 107.165|71.1422 175 | NA|NA 176 | 32.4794|89.866 177 | 32.4794|99.9474 178 | 51.9494|99.9474 179 | 51.9494|89.866 180 | NA|NA 181 | 196.997|74.6198 182 | 196.997|90.6723 183 | 233.68|90.6723 184 | 233.68|74.6198 185 | NA|NA 186 | 307.901|84.6064 187 | 307.901|94.6103 188 | 319.113|94.6103 189 | 319.113|84.6064 190 | NA|NA 191 | 179.925|29.5173 192 | 179.925|41.6158 193 | 198.467|41.6158 194 | 198.467|29.5173 195 | NA|NA 196 | 91.3894|95.0914 197 | 91.3894|101.267 198 | 105.01|101.267 199 | 105.01|95.0914 200 | NA|NA 201 | 140.272|45.5877 202 | 140.272|53.3664 203 | 179.925|53.3664 204 | 179.925|45.5877 205 | NA|NA 206 | 72.9335|43.2908 207 | 72.9335|71.1422 208 | 107.165|71.1422 209 | 107.165|43.2908 210 | NA|NA 211 | 51.9494|78.0284 212 | 51.9494|89.866 213 | 63.7934|89.866 214 | 63.7934|78.0284 215 | NA|NA 216 | 289.345|107.235 217 | 289.345|117.222 218 | 297.768|117.222 219 | 297.768|107.235 220 | NA|NA 221 | 179.925|53.0633 222 | 179.925|64.7293 223 | 211.172|64.7293 224 | 211.172|53.0633 225 | NA|NA 226 | 25.399|99.9474 227 | 25.399|111.565 228 | 51.9494|111.565 229 | 51.9494|99.9474 230 | NA|NA 231 | 196.997|64.7293 232 | 196.997|74.6198 233 | 211.172|74.6198 234 | 211.172|64.7293 235 | NA|NA 236 | 124.218|97.8759 237 | 124.218|112.433 238 | 143.48|112.433 239 | 143.48|97.8759 240 | NA|NA 241 | 61.9083|90.0443 242 | 61.9083|96.9794 243 | 74.038|96.9794 244 | 74.038|90.0443 245 | NA|NA 246 | 143.48|104.202 247 | 143.48|112.433 248 | 167.327|112.433 249 | 167.327|104.202 250 | NA|NA 251 | -------------------------------------------------------------------------------- /inst/extdata/us_state_election_2004.csv: -------------------------------------------------------------------------------- 1 | 152.064,34.7223,"Alabama",9,1.96429,Alabama,9,37,63,,,,,,,,,9,99 2 | 49.4702,68.7353,"Arizona",10,2.41344,Arizona,10,44,55,1,,,,,,,,10,96 3 | 114.856,74.4487,"Arkansas",6,1.92284,Arkansas,6,45,54,1,,,,,,,6,,68 4 | 20.5116,71.0688,"California",55,4.10231,California,55,54,45,,,,55,,,,,,68 5 | 74.2948,84.0363,"Colorado",9,2.62536,Colorado,9,46,53,1,,,,,,,9,,88 6 | 298.623,89.3215,"Connecticut",7,1.68698,Connecticut,7,54,44,1,,7,,,,,,,96 7 | 237.148,80.6841,"Delaware",3,0.866984,Delaware,3,53,46,1,,,3,,,,,,95 8 | 242.763,69.2354,"D.C.",3,0.555195,D.C.,3,90,9,1,,3,,,,,,,100 9 | 169.432,12.7727,"Florida",27,4.23392,Florida,27,47,52,1,,,,,,,27,,99 10 | 169.432,35.5665,"Georgia",15,2.99802,Georgia,15,41,59,0,,,,,,,,15,99 11 | 56.9289,95.4973,"Idaho",4,1.99177,Idaho,4,29,69,,,,,,,,,4,79 12 | 135.449,83.5083,"Illinois",21,2.56155,Illinois,21,55,44,1,,21,,,,,,,98 13 | 163.048,87.7801,"Indiana",11,2.25802,Indiana,11,39,60,,,,,,,,,11,99 14 | 115.106,93.0157,"Iowa",7,5.04818,Iowa,7,49,50,1,,,,,,7,,,98 15 | 95.0077,84.0363,"Kansas",6,3.40382,Kansas,6,36,63,1,,,,,,,,6,97 16 | 158.323,73.5818,"Kentucky",8,3.15693,Kentucky,8,40,60,0,,,,,,,,8,99 17 | 116.012,61.8492,"Louisiana",9,1.96614,Louisiana,9,42,57,0,,,,,,,,9,99 18 | 303.221,124.947,"Maine",4,2.05185,Maine,4,53,45,1,,,4,,,,,,81 19 | 224.192,69.2354,"Maryland",10,3.25486,Maryland,10,56,43,1,,10,,,,,,,99 20 | 302.671,100.923,"Massachusetts",12,2.05022,Massachusetts,12,62,37,,,12,,,,,,,99 21 | 179.566,98.8095,"Michigan",10,2.15374,Michigan,17,51,48,1,,,,17,,,,,83 22 | 114.614,105.175,"Minnesota",10,2.13417,Minnesota,10,52,47,1,,,10,,,,,,85 23 | 139.62,38.034,"Mississippi",6,1.01242,Mississippi,6,40,60,0,,,,,,,,6,97 24 | 135.449,61.8137,"Missouri",11,2.63112,Missouri,11,46,54,,,,,,,,11,,96 25 | 69.2844,99.8306,"Montana",3,2.10747,Montana,3,39,59,1,,,,,,,,3,80 26 | 94.9032,91.6234,"Nebraska",5,2.52673,Nebraska,5,32,67,0,,,,,,,,5,85 27 | 46.4863,83.4501,"Nevada",5,1.82105,Nevada,5,48,51,1,,,,,,5,,,90 28 | 302.671,113.358,"New Hampshire",4,0.704563,"New Hampshire",4,50,49,1,,,,4,,,,,95 29 | 241.99,99.4014,"New Jersey",15,1.66209,"New Jersey",15,53,46,1,,,15,,,,,,99 30 | 66.8177,65.4111,"New Mexico",5,1.22317,"New Mexico",5,49,50,1,,,,,,5,,,99 31 | 269.823,100.923,"New York",31,4.88051,"New York",31,58,40,2,,31,,,,,,,99 32 | 198.296,47.3395,"North Carolina",15,2.62446,"North Carolina",15,43,57,,,,,,,,,15,99 33 | 97.8439,109.54,"North Dakota",3,1.19437,"North Dakota",3,36,63,1,,,,,,,,3,98 34 | 183.974,79.9065,"Ohio",20,6.51151,Ohio,20,49,51,,,,,,,20,,,99 35 | 95.9805,75.5298,"Oklahoma",7,2.79605,Oklahoma,7,34,66,,,,,,,,,7,100 36 | 42.2144,94.9067,"Oregon",7,3.245,Oregon,7,53,47,,,,7,,,,,,78 37 | 215.338,82.646,"Pennsylvania",21,3.05692,Pennsylvania,21,51,49,,,,,21,,,,,98 38 | 313.507,89.6083,"Rhode Island",4,0.934331,"Rhode Island",4,60,39,1,,4,,,,,,,99 39 | 189.196,35.5665,"South Carolina",8,1.3244,"South Carolina",8,41,58,1,,,,,,,,8,98 40 | 98.1998,98.1794,"South Dakota",3,1.13506,"South Dakota",3,38,61,1,,,,,,,,3,97 41 | 160.098,49.477,"Tennessee",11,4.40588,Tennessee,11,43,57,0,,,,,,,,11,99 42 | 90.0491,57.2165,"Texas",34,6.84623,Texas,34,38,61,,,,,,,,,34,96 43 | 57.8714,83.9472,"Utah",5,2.96099,Utah,5,26,72,1,,,,,,,,5,79 44 | 293.557,112.228,"Vermont",3,1.20338,Vermont,3,59,39,2,,3,,,,,,,98 45 | 195.549,58.8963,"Virginia",13,3.90592,Virginia,13,46,54,,,,,,,,13,,99 46 | 38.6742,105.756,"Washington",11,2.65504,Washington,11,53,46,1,,,11,,,,,,92 47 | 204.084,69.6745,"West Virginia",5,1.09043,"West Virginia",5,43,56,1,,,,,,,,5,94 48 | 133.849,105.154,"Wisconsin",10,2.1403,Wisconsin,10,50,49,1,,,,10,,,,,95 49 | 67.9732,93.5119,"Wyoming",3,1.73282,Wyoming,3,29,69,1,,,,,,,,3,98 50 | 155.404,108.317,"Michigan",7,2.98084,Michigan,17,51,48,1,,,,17,,,,,83 51 | -------------------------------------------------------------------------------- /inst/include/recmap.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2016 2 | // 3 | // This file is part of the recmap package on CRAN. 4 | // https://CRAN.R-project.org/package=recmap 5 | // 6 | // recmap is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // recmap is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with recmap. If not, see . 18 | 19 | 20 | // Author: Christian Panse 21 | // 2016-04-19/20/21/22 ACCU2016 Bristol, UK 22 | // see also doi: 10.18637/jss.v086.c01 23 | 24 | #ifndef SRC_RECMAP_H_ 25 | #define SRC_RECMAP_H_ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | namespace crecmap { 40 | 41 | // keeps map and pseudo dual graph 42 | typedef struct { 43 | double x, y, dx, dy, z; 44 | int id; 45 | double area_desired; 46 | int placed; 47 | std::string name; 48 | std::vector connected; 49 | double topology_error; 50 | double relative_position_error; 51 | double relative_position_neighborhood_error; 52 | int dfs_num; 53 | } map_region; 54 | 55 | struct mbb_node { 56 | double key; 57 | int id; 58 | 59 | mbb_node(const double& strKey = 0, const int& intId = 0) 60 | : key(strKey), 61 | id(intId) {} 62 | 63 | bool operator<(const mbb_node& rhs) const { 64 | return key < rhs.key; 65 | } 66 | }; 67 | // keeps all (x, y) centers 68 | // use it as sorted list 69 | // insert/upper_bound: O(ln(n)) 70 | typedef struct { 71 | double max_dx; 72 | double max_dy; 73 | std::multiset x; 74 | std::multiset y; 75 | } mbb_set; 76 | 77 | typedef std::vector recmapvector; 78 | 79 | // computes the bearing of two points in R^2 80 | // source: http://en.cppreference.com/w/cpp/numeric/math/atan2 81 | // http://www.cplusplus.com/reference/cmath/atan2/ 82 | double get_angle(const map_region &a, const map_region &b) { 83 | double alpha = std::atan2(b.x - a.x, b.y - a.y); 84 | return (alpha); 85 | } 86 | 87 | // detects whether two minimal bounding boxes (MBB) overlap 88 | // source: http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/ 89 | inline bool mbb_check(const map_region &a, const map_region &b) { 90 | if (a.x + a.dx < b.x - b.dx) return false; // a is left of b 91 | else if (a.x - a.dx > b.x + b.dx) return false; // a is right of b 92 | else if (a.y + a.dy < b.y - b.dy) return false; // a is above b 93 | else if (a.y - a.dy > b.y + b.dy) return false; // a is below b 94 | 95 | // rectangles can touch each other but do not overlap 96 | return true; 97 | } 98 | 99 | // computes the new center (x, y) values on the cartogram map region c 100 | // map_region a has a fix position 101 | // uses c.dx and c.dy for the computation 102 | // TODO(cp): consider giving eps as argument 103 | // to have space between the map regions 104 | void place_rectangle(const map_region &a, double alpha, map_region &c) { 105 | double tanx, tany; 106 | double eps = 0.01; 107 | 108 | double dy = a.dy + c.dy + eps; 109 | double dx = a.dx + c.dx + eps; 110 | 111 | if (std::sin(alpha) >= 0 && std::cos(alpha) >= 0) { 112 | // Quad I 113 | tanx = a.x + (dx * std::tan(alpha)); 114 | tany = a.y + (dy * std::tan(M_PI/2 - alpha)); 115 | 116 | c.x = a.x + dx; 117 | c.y = a.y + dy; 118 | 119 | // there are always two intersection; choose the right one 120 | if (tany >= c.y) c.x = tanx; 121 | else 122 | c.y = tany; 123 | 124 | } else if (std::sin(alpha) >= 0 && std::cos(alpha) < 0) { 125 | // Quad II 126 | tanx = a.x + (dx * std::tan(M_PI - alpha)); 127 | tany = a.y - (dy * std::tan(alpha - M_PI/2)); 128 | 129 | c.x = a.x + dx; 130 | c.y = a.y - dy; 131 | 132 | if (tanx <= c.x) c.x = tanx; 133 | else 134 | c.y = tany; 135 | 136 | } else if (std::sin(alpha) < 0 && std::cos(alpha) < 0) { 137 | // Quad III 138 | tanx = a.x - (dx * std::tan(alpha - M_PI)); 139 | tany = a.y - (dy * std::tan(3 * M_PI / 2 - alpha)); 140 | 141 | c.x = a.x - dx; 142 | c.y = a.y - dy; 143 | 144 | if (tany > c.y) c.y = tany; 145 | else 146 | c.x = tanx; 147 | 148 | } else if (std::sin(alpha) < 0 && std::cos(alpha) > 0) { 149 | // Quad IV 150 | tanx = a.x - (dy * std::tan(2 * M_PI - alpha)); 151 | tany = a.y + (dx * std::tan(alpha - 3 * M_PI /2)); 152 | 153 | c.x = a.x - dx; 154 | c.y = a.y + dy; 155 | 156 | if (tanx < c.x) c.y = tany; 157 | else 158 | c.x = tanx; 159 | 160 | } else { 161 | // error 162 | } 163 | } 164 | 165 | // iterating over distinct pairs 166 | // source: http://stackoverflow.com/questions/17787410/nested-range-based-for-loops 167 | template 168 | void each_unique_pair(C& container, Op1 fun1) { 169 | for (auto it = container.begin(); it != container.end() - 1; ++it) 170 | for (auto it2 = std::next(it); it2 != container.end(); ++it2) 171 | fun1(*it, *it2, container); 172 | } 173 | 174 | template 175 | void each_unique_pair(C0& container0, C1& container1, Op fun) { 176 | for (auto it = container0.begin(); it != container0.end() - 1; ++it) 177 | for (auto it2 = std::next(it); it2 != container0.end(); ++it2) 178 | fun(*it, *it2, container0, container1); 179 | } 180 | 181 | // keeps map and cartogram data 182 | // input is feeded by using the push function 183 | // the run method invokes the generation of the cartogram 184 | // output is returned by get_map_region 185 | class RecMap{ 186 | recmapvector Map; 187 | recmapvector Cartogram; 188 | mbb_set MBB; 189 | int intersect_count; 190 | bool map_region_intersect_multiset = true; 191 | 192 | int num_regions; 193 | 194 | std::list msg; 195 | std::list warnings; 196 | 197 | public: 198 | RecMap() { 199 | num_regions = 0; 200 | MBB.max_dx = 0; 201 | MBB.max_dy = 0; 202 | intersect_count = 0; 203 | } 204 | 205 | // TODO(cp): Think about a destructor? 206 | void push_region(double x, double y, double dx, double dy, double z, 207 | std::string name) { 208 | map_region R, R1; 209 | 210 | R.x = x; R.y = y; R.dx = dx; R.dy = dy; R.z = z; 211 | R.id = num_regions; 212 | R.area_desired = -1; 213 | R.connected = {}; 214 | R.placed = 1; 215 | R.name = name; 216 | R.dfs_num = -1; 217 | 218 | R1.x = -1; R1.y = -1; R1.dx = dx; R1.dy = dy; R1.z = z; 219 | R1.id = num_regions; 220 | R1.area_desired = -1; 221 | R1.connected = {}; 222 | R1.placed = 0; 223 | R1.name = name; 224 | R1.dfs_num = -1; 225 | R1.topology_error = -1; 226 | R1.relative_position_error = 0.0; 227 | R1.relative_position_neighborhood_error = 0.0; 228 | 229 | Map.push_back(R); 230 | Cartogram.push_back(R1); 231 | num_regions++; 232 | 233 | 234 | //if (num_regions != Map.size()) { 235 | // TODO(cp): call an exception? 236 | //} 237 | } 238 | 239 | void push_pd_edge(int u, int v){ 240 | Map[u].connected.push_back(v); 241 | Map[v].connected.push_back(u); 242 | } 243 | 244 | std::string warnings_pop() { 245 | std::string s = warnings.front(); warnings.pop_front(); 246 | return s; 247 | } 248 | 249 | bool warnings_empty() {return warnings.empty();} 250 | 251 | int get_size() {return num_regions;} 252 | 253 | int get_intersect_count() { return intersect_count; } 254 | void set_map_region_intersect_multiset(bool b) { map_region_intersect_multiset = b; } 255 | 256 | map_region& get_map_region(int i) { return(Cartogram[i]); } 257 | 258 | 259 | void ComputePseudoDual(recmapvector &M) { 260 | each_unique_pair(M, [](map_region &a, map_region &b, 261 | recmapvector &M) { 262 | // add edges tp pseudo dual graph 263 | // iff boxes are connected 264 | if (mbb_check(a, b)) { 265 | M[a.id].connected.push_back(b.id); 266 | M[b.id].connected.push_back(a.id); 267 | } 268 | }); 269 | } 270 | 271 | // taken from the CartoDraw scanline approach date back to yr2000 272 | void ComputeDesiredArea(recmapvector &M, recmapvector &C) { 273 | double sum_z = 0.0; 274 | double sum_area = 0.0; 275 | 276 | std::for_each(M.begin(), M.end(), [&] (map_region &r) {sum_z += r.z;}); 277 | std::for_each(M.begin(), M.end(), 278 | [&] (map_region &r) {sum_area += (4 * r.dx * r.dy);}); 279 | 280 | std::for_each(C.begin(), C.end(), [&] (map_region &r) { 281 | double area_desired = r.z * sum_area / sum_z; 282 | double ratio = r.dy / r.dx; 283 | r.dx = sqrt(area_desired / (4 * ratio)); 284 | r.dy = r.dx * ratio; 285 | }); 286 | } 287 | 288 | 289 | // TODO(cp): Is the original core polygon implementation really usefull? 290 | // the 8x8 checker board suffers but for the x77 map it seems 291 | // to work great 292 | // if yes; implement it here. 293 | int ComputeCoreRegion(recmapvector &M, recmapvector &C) { 294 | int core_region_id = num_regions / 2; 295 | 296 | C[core_region_id].x = M[core_region_id].x; 297 | C[core_region_id].y = M[core_region_id].y; 298 | C[core_region_id].placed++; 299 | C[core_region_id].topology_error = 0; 300 | 301 | mbb_node mn; 302 | mn.key = C[core_region_id].x; mn.id = C[core_region_id].id; 303 | MBB.x.insert(mn); 304 | 305 | mn.key = C[core_region_id].y; mn.id = C[core_region_id].id; 306 | MBB.y.insert(mn); 307 | 308 | MBB.max_dx = C[core_region_id].dx; 309 | MBB.max_dy = C[core_region_id].dy; 310 | 311 | return core_region_id; 312 | } 313 | 314 | // obsolet version of the linear intersection test; keep it for testing 315 | bool map_region_intersect(const recmapvector &C, const map_region &a) { 316 | for (map_region b : C) { 317 | if (a.id != b.id && b.placed > 0) { 318 | intersect_count++; 319 | if (mbb_check(a, b)) { 320 | return true; 321 | }} 322 | } 323 | return false; 324 | } 325 | 326 | // MBB intersection test; doing binary search 327 | bool map_region_intersect_set(recmapvector &C, const mbb_set &S, 328 | const map_region &a) { 329 | double eps = 0.0; 330 | 331 | // 1st: range query on the x-axis 332 | auto lower_x = std::lower_bound(S.x.begin(), S.x.end(), 333 | a.x - a.dx - S.max_dx - eps, 334 | [](const mbb_node& f1, const mbb_node& f2) 335 | { return f1.key < f2.key; }); 336 | 337 | auto upper_x = std::upper_bound(S.x.begin(), S.x.end(), 338 | a.x + a.dx + S.max_dx + eps, 339 | [](const mbb_node& f1, const mbb_node& f2) 340 | { return f1.key < f2.key; }); 341 | 342 | 343 | for (auto it_x = lower_x; it_x != upper_x; ++it_x) { 344 | 345 | intersect_count++; 346 | if ((*it_x).id != a.id && mbb_check(a, C[(*it_x).id])) { 347 | return true; 348 | } 349 | } 350 | 351 | // no intersetions until now; 352 | // 2nd: check the y-axis 353 | auto lower_y = std::lower_bound(S.y.begin(), S.y.end(), 354 | a.y - a.dy - S.max_dy - eps, 355 | [](const mbb_node& f1, const mbb_node& f2) 356 | { return f1.key < f2.key; }); 357 | 358 | auto upper_y = std::upper_bound(S.y.begin(), S.y.end(), 359 | a.y + a.dy + S.max_dy + eps, 360 | [](const mbb_node& f1, const mbb_node& f2) 361 | { return f1.key < f2.key; }); 362 | 363 | for (auto it_y = lower_y; it_y != upper_y; ++it_y) { 364 | intersect_count++; 365 | if ((*it_y).id != a.id && mbb_check(a, C[(*it_y).id])) { 366 | return true; 367 | } 368 | } 369 | 370 | return false; 371 | } 372 | 373 | // place rectangle around predecessor_region_id 374 | bool PlaceRectangle(recmapvector &M, recmapvector &C, int region_id) { 375 | double alpha0, alpha; 376 | mbb_node mn; 377 | 378 | double beta_sign = 1.0; 379 | bool intersect = true; 380 | 381 | // strategy one: try to place it in the neighborhood; 382 | // and only one => allow non feasible solution to be filtered out 383 | // by the metaheuristic 384 | for (double beta = 0.0; beta <= M_PI && C[region_id].placed == 0; 385 | beta += M_PI/180) { 386 | // iterate over all already placed adjacent rectangles 387 | for (const int &adj_region_id : M[region_id].connected) { 388 | if (C[adj_region_id].placed > 0) { 389 | // orginal bearing of two map regions in the input map 390 | alpha0 = get_angle(M[adj_region_id], M[region_id]); 391 | alpha = alpha0 + (beta_sign * beta); 392 | beta_sign *= -1; 393 | 394 | place_rectangle(C[adj_region_id], alpha, C[region_id]); 395 | 396 | if (map_region_intersect_multiset) 397 | intersect = map_region_intersect_set(C, MBB, C[region_id]); 398 | else 399 | intersect = map_region_intersect(C, C[region_id]); 400 | 401 | if (!intersect) { 402 | C[region_id].placed++; 403 | C[region_id].topology_error = 0; // for the moment 404 | 405 | mn.key = C[region_id].x; mn.id = C[region_id].id; 406 | MBB.x.insert(mn); 407 | 408 | mn.key = C[region_id].y; mn.id = C[region_id].id; 409 | MBB.y.insert(mn); 410 | 411 | if (C[region_id].dx > MBB.max_dx) {MBB.max_dx = C[region_id].dx;} 412 | if (C[region_id].dy > MBB.max_dy) {MBB.max_dy = C[region_id].dy;} 413 | 414 | // update dual graph 415 | C[adj_region_id].connected.push_back(region_id); 416 | C[region_id].connected.push_back(adj_region_id); 417 | return true; 418 | } 419 | } 420 | } // END for (int adj_region_id : M[region_id].connected) 421 | } 422 | 423 | // placement failed => make map region as not placed 424 | C[region_id].x = -1; 425 | C[region_id].y = -1; 426 | C[region_id].topology_error = -1; 427 | // communicate this to the user later 428 | warnings.push_back(M[region_id].name 429 | + " could not be placed on the first attempt;"); 430 | return false; 431 | } 432 | 433 | // dfs explore of existing input map M; output cartogram C 434 | void DrawCartogram(recmapvector &M, recmapvector &C, int core_region_id) { 435 | std::list stack; 436 | std::vector visited(num_regions, 0); 437 | std::vector dfs_num(num_regions, 0); 438 | 439 | int dfs_num_counter = 0; 440 | int current_region_id = core_region_id; 441 | stack.push_back(current_region_id); 442 | visited[current_region_id]++; 443 | 444 | while (stack.size() > 0) { 445 | current_region_id = stack.back() ; stack.pop_back(); 446 | dfs_num[current_region_id] = dfs_num_counter++; 447 | C[current_region_id].dfs_num = dfs_num[current_region_id]; 448 | 449 | if (current_region_id != core_region_id) { 450 | if (!PlaceRectangle(M, C, current_region_id)) { 451 | // bad luck - lets place first the other map regions 452 | } 453 | } 454 | 455 | for (const int & adj_region_id : M[current_region_id].connected) { 456 | if (visited[adj_region_id] == 0) { 457 | visited[adj_region_id]++; 458 | stack.push_back(adj_region_id); 459 | } 460 | } 461 | } // while 462 | 463 | std::for_each(C.begin(), C.end(), [&] (map_region &r) { 464 | if (r.placed == 0) { 465 | PlaceRectangle(M, C, r.id); 466 | if (r.placed == 0) { 467 | // yes - 468 | // accept a non feasible solution to save computational resources 469 | // the metaheuristic has to fix that with the fitness function 470 | warnings.push_back(r.name + " was not placed!!"); 471 | } 472 | // 473 | }}); 474 | } 475 | 476 | 477 | void ComputeError(recmapvector &M, recmapvector &C) { 478 | double gammaM, gammaC, delta; 479 | // relative position error 480 | // TODO(cp): make the each_unique_pair construct working to 481 | // save 50% of the hand shakes 482 | for (const auto & a : M) { 483 | for (const auto & b : M) { 484 | gammaM = get_angle(M[a.id], M[b.id]); 485 | gammaC = get_angle(C[a.id], C[b.id]); 486 | 487 | if ((gammaM < 0 && gammaC > 0) || ( gammaM > 0 && gammaC < 0)) 488 | delta = fabs(gammaC + gammaM) / C.size(); 489 | else 490 | delta = fabs(gammaC - gammaM) / C.size(); 491 | 492 | C[a.id].relative_position_error += delta; 493 | } 494 | 495 | // alternative to the relative position error; play with it 496 | for (const auto & idx : a.connected) { 497 | gammaM = get_angle(M[a.id], M[idx]); 498 | gammaC = get_angle(C[a.id], C[idx]); 499 | if ((gammaM < 0 && gammaC > 0) || ( gammaM > 0 && gammaC < 0)) 500 | delta = fabs(gammaC + gammaM) / a.connected.size(); 501 | else 502 | delta = fabs(gammaC - gammaM) / a.connected.size(); 503 | 504 | C[a.id].relative_position_neighborhood_error += delta; 505 | } 506 | 507 | // topology error, 508 | // http://www.cplusplus.com/reference/algorithm/set_symmetric_difference/ 509 | std::vector v(M[a.id].connected.size() + C[a.id].connected.size()); 510 | std::vector::iterator it; 511 | std::sort(M[a.id].connected.begin(), M[a.id].connected.end()); 512 | std::sort(C[a.id].connected.begin(), C[a.id].connected.end()); 513 | 514 | 515 | it = std::set_symmetric_difference(M[a.id].connected.begin(), 516 | M[a.id].connected.end(), 517 | C[a.id].connected.begin(), 518 | C[a.id].connected.end(), 519 | v.begin()); 520 | v.resize(it-v.begin()); 521 | 522 | if (C[a.id].topology_error != -1) 523 | C[a.id].topology_error = (v.size()); 524 | // for debug print all three vectors once 525 | } 526 | } 527 | 528 | void run(bool computePseudoDual = true) { 529 | if (computePseudoDual) ComputePseudoDual(Map); 530 | ComputeDesiredArea(Map, Cartogram); 531 | int core_region_id = ComputeCoreRegion(Map, Cartogram); 532 | msg.push_back("CORE REGION: " + Map[core_region_id].name); 533 | DrawCartogram(Map, Cartogram, core_region_id); 534 | ComputeError(Map, Cartogram); 535 | } // run 536 | 537 | 538 | }; 539 | } // namespace crecmap 540 | #endif // SRC_RECMAP_H_ 541 | -------------------------------------------------------------------------------- /inst/shiny-examples/server.R: -------------------------------------------------------------------------------- 1 | #R 2 | # This is the server logic for a Shiny web application using recmap 3 | # 4 | # https://CRAN.R-project.org/package=recmap 5 | 6 | # use R version >= 4.3 - grDevices::hcl; grDevices::hcl.colors; grDevices::hcl.pals; 7 | # library(colorspace) 8 | 9 | stopifnot(require(GA), 10 | require(maps), 11 | require(recmap)) 12 | 13 | 14 | if (Sys.info()['machine'] == "arm64" && Sys.info()['sysname'] == "Darwin"){ 15 | stopifnot(isFALSE(GA::gaControl()$useRcpp)) 16 | } 17 | 18 | # ----- get U.S. county minimal bounding boxes ------ 19 | .get_county_mbb <- 20 | function(state = 'colorado', 21 | scaleX = 0.5, 22 | scaleY = 0.5) { 23 | 24 | if (require(noncensus)) 25 | data(counties) 26 | else 27 | stop("no package 'noncensus'.") 28 | 29 | # sanity check 30 | if (!state %in% row.names(state.x77)) { 31 | warning("not a valid U.S. state") 32 | return(NULL) 33 | } 34 | MBB <- lapply(map('county', state, plot = FALSE)$names, 35 | function(x) { 36 | r <- map('county', x, plot = FALSE) 37 | dx <- scaleX * (r$range[2] - r$range[1]) 38 | dy <- scaleY * (r$range[4] - r$range[3]) 39 | x <- r$range[1] + dx 40 | y <- r$range[3] + dy 41 | data.frame( 42 | polyname = r$name, 43 | x = x, 44 | y = y, 45 | dx = dx, 46 | dy = dy 47 | ) 48 | }) 49 | MBB <- do.call('rbind', MBB) 50 | MBB <- merge(MBB, county.fips, by = 'polyname') 51 | MBB$fips <- as.integer(MBB$fips) 52 | 53 | P <- data.frame( 54 | fips = paste(counties$state_fips, 55 | counties$county_fips, sep = ''), 56 | z = counties$population, 57 | name = counties$county_name 58 | ) 59 | P$fips <- as.integer(levels(P$fips))[P$fips] 60 | 61 | M <- merge(MBB, P, by = 'fips') 62 | attr(M, 'Map.name') <- paste("U.S.", state) 63 | attr(M, 'Map.stat') <- 'population' 64 | class(M) <- c('recmap', 'data.frame') 65 | M 66 | } 67 | 68 | # ----- shiny server ------- 69 | shinyServer(function(input, output, session) { 70 | output$plot_hoverinfo <- renderText({ 71 | 72 | if (TRUE){ 73 | res <- Cartogram()$Cartogram 74 | x <- input$plot_hover$x 75 | y <- input$plot_hover$y 76 | 77 | query <- 78 | ((res$x - res$dx) < x) & 79 | (x < (res$x + res$dx)) & 80 | ((res$y - res$dy) < y) & (y < (res$y + res$dy)) 81 | rv <- "no object identified." 82 | if (sum(query) == 1) { 83 | rv <- paste(res$name[query]) 84 | } 85 | 86 | message(paste("region name:", rv)) 87 | } 88 | }) 89 | 90 | #---- define colormaps ---- 91 | # some taken from the vignette of https://CRAN.R-project.org/package=colorspace 92 | colormap <- reactive({ 93 | 94 | # heat_hcl <- heat_hcl(12, c = c(80, 30), l = c(30, 90), power = c(1/5, 2)) 95 | 96 | heat_hcl <- c('#8E063B', '#A63945', '#BC584D', '#CF7355', '#DF8B5B', 97 | '#EAA162', '#F2B468', '#F6C56F', '#F6D277', '#F2DD80', 98 | '#EBE48B', '#E2E6BD') 99 | 100 | 101 | # sequential_hcl(12, c = 0, power = 2.2) 102 | # sequential_hcl(12, power = 2.2) 103 | # sequential_hcl(12, c = 0, power = 2.2) 104 | 105 | list( 106 | colorspace_heat_hcl = heat_hcl, 107 | colorspace_rev_heat_hcl = rev(heat_hcl), 108 | colorspace_Set2 = hcl.colors(20, "Set 2"), 109 | colorspace_Set3 = hcl.colors(20, "Set 3"), 110 | colorspace_rev_Set3 = rev(hcl.colors(20, "Set 3")), 111 | heat.colors = heat.colors(12), 112 | rainbow = rainbow(12), 113 | # use DBVIS color maps; 114 | # KEIM, Daniel, 1995. Visual support for query specification and data mining [Dissertation]. 115 | # München: Universität. Aachen : Shaker. ISBN 3-8265-0594-8goes back to 1999 116 | DanKeim = rev(c('#C6CF32', '#88E53B', '#50E258', '#29C67D', '#19999E', 117 | '#2064AF', '#3835AB', '#561493', '#6E086D', '#790D43', 118 | '#741F1E', '#5F3307') 119 | ), 120 | DanKeim_HSV = rev(c('#BECC3D', '#70C337', '#31B93C', '#2BB077', 121 | '#269FA7', '#21589E', '#221C94', '#56188B', 122 | '#82147F', '#791043', '#6F0E0D', '#66380A'))) 123 | }) 124 | 125 | output$colormap <- renderUI({ 126 | selectInput('colormapname', 'colormap name', names(colormap())) 127 | }) 128 | 129 | output$colormapPlot <- renderPlot({ 130 | par(mar = c(0,0,0,0)); 131 | pal(unlist(colormap()[input$colormapname])) 132 | }) 133 | 134 | #---- define output UI ---- 135 | output$methodRadio <- renderUI({ 136 | inputData <- c("checkerboard" = "checkerboard", 137 | "US state" = "USstate") 138 | 139 | if (require('noncensus')){ 140 | inputData <- c("checkerboard" = "checkerboard", 141 | "US county" = "UScounty", 142 | "US state" = "USstate") 143 | } 144 | 145 | 146 | radioButtons("datatype", "Type of data:", 147 | inputData) 148 | }) 149 | 150 | output$II <- renderUI({ 151 | if (input$datatype == 'checkerboard'){ 152 | numericInput("checkerboardSize", "checkerboardSize", 4, min = 2, 153 | max = 16, step = 1) 154 | }else if (input$datatype == 'USstate'){ 155 | list( 156 | selectInput('area', 'area', colnames(state.x77)), 157 | selectInput('color', 'color', colnames(state.x77)), 158 | htmlOutput("colormap") 159 | ) 160 | }else if (input$datatype == 'UScounty'){ 161 | list( 162 | selectInput('state', 'U.S. state', row.names(state.x77), "Louisiana"), 163 | helpText('overlap to compose pseudo dual:'), 164 | sliderInput("scaleX", "scaleX", 0, 1, 0.6), 165 | sliderInput("scaleY", "scaleY", 0, 1, 0.63)) 166 | }}) 167 | 168 | #---- define input map ---- 169 | Map <- reactive({ 170 | progress <- shiny::Progress$new(session = session) 171 | progress$set(message = "get input map") 172 | on.exit(progress$close()) 173 | 174 | res <- NULL 175 | 176 | if (input$datatype == "UScounty" && length(input$state) == 1){ 177 | res <- 178 | .get_county_mbb( 179 | state = input$state, 180 | scaleX = input$scaleX, 181 | scaleY = input$scaleY 182 | ) 183 | res$name <- gsub(" ", "\n", res$name) 184 | res}else if (input$datatype == "checkerboard" && length(input$checkerboardSize) == 1){ 185 | res <- checkerboard(input$checkerboardSize) 186 | }else if (input$datatype == "USstate"){ 187 | usa <- data.frame(x = state.center$x, 188 | y = state.center$y, 189 | # make the rectangles overlapping by correcting lines of longitude distance 190 | dx = sqrt(state.area) / 2 / (0.8 * 60 * cos(state.center$y*pi/180)), 191 | dy = sqrt(state.area) / 2 / (0.8 * 60), 192 | z = sqrt(state.area), 193 | name = state.name) 194 | 195 | usa$z <- state.x77[, input$area] 196 | 197 | res <- usa[!usa$name %in% c("Hawaii", "Alaska"), ] 198 | attr(res, 'Map.name') <- "U.S." 199 | attr(res, 'Map.stat') <- input$area 200 | 201 | class(res) <- c('recmap', class(res)) 202 | } 203 | res 204 | }) 205 | 206 | #---- define fitness function ---- 207 | wfitness <- function(idxOrder, Map, ...) { 208 | Cartogram <- recmap(Map[idxOrder,]) 209 | 210 | if (sum(Cartogram$topology.error == 100) > 0) { 211 | return(0) 212 | } 213 | 214 | 1 / (c(input$objective_weight, 215 | 1 - input$objective_weight) %*% c(S['topology error',] / nrow(Cartogram)^2, 216 | S['relative position error',])) 217 | } 218 | 219 | #---- compute Cartogram ---- 220 | Cartogram <- reactive({ 221 | progress <- shiny::Progress$new(session = session, min = 0, max = 1) 222 | progress$set(message = "recmapGA init") 223 | on.exit(progress$close()) 224 | 225 | options(warn = -1) 226 | 227 | M <- Map() 228 | if (is.null(M)){return(NULL)} 229 | time.elapsed <- rep(proc.time()[3], input$GAmaxiter) 230 | 231 | res <- recmapGA( 232 | M, 233 | maxiter = input$GAmaxiter, 234 | popSize = input$GApopulation * nrow(M), 235 | pmutation = input$GApmutation, 236 | run = input$GArun, 237 | seed = input$seed, 238 | parallel = input$parallel, 239 | monitor = function(object, digits = getOption("digits"), ...) 240 | { 241 | fitness <- na.exclude(object@fitness) 242 | sumryStat <- c(mean(fitness), max(fitness)) 243 | 244 | time.elapsed[object@iter] <- ( proc.time()[3] - time.elapsed[object@iter] ) / object@iter 245 | progress$set( 246 | message = "GA", 247 | detail = paste( 248 | "iteration", 249 | object@iter, "/", input$GAmaxiter, 250 | "fittest = ", 251 | round(sumryStat[2], 5), 252 | "\n elapsed time / generation", round(time.elapsed[object@iter], 2), "in secs" 253 | ), 254 | value = object@iter / input$GAmaxiter 255 | ) 256 | } 257 | ) 258 | res 259 | }) 260 | 261 | #----plot input map ---- 262 | output$mapPlot <- renderPlot({ 263 | message("Plotting map ...") 264 | M <- Map() 265 | if (is.null(M)){return()} 266 | 267 | op <- par(mfrow = c(1, 1), mar = c(0, 0, 0, 0)) 268 | 269 | recmap::plot.recmap(M, col.text = 'darkred') 270 | 271 | x <- input$plot_hover$x 272 | y <- input$plot_hover$y 273 | if(TRUE){ 274 | C <- Cartogram() 275 | if(is.null(C)) {return()} 276 | res <- C$Cartogram 277 | 278 | query <- 279 | ((res$x - res$dx) < x) & 280 | (x < (res$x + res$dx)) & 281 | ((res$y - res$dy) < y) & (y < (res$y + res$dy)) 282 | rv <- "no object identified." 283 | if (sum(query) == 1) { 284 | rv <- paste(res$name[query]) 285 | idx <- which(M$name == rv) 286 | rect(M$x[idx] - M$dx[idx], 287 | M$y[idx] - M$dy[idx] , 288 | M$x[idx] + M$dx[idx], 289 | M$y[idx] + M$dy[idx], 290 | col = rgb(0.8, 0.1, 0.1, 0.3)) 291 | }} 292 | }) 293 | 294 | #----plot output cartogram ---- 295 | output$cartogramPlot <- renderPlot({ 296 | res <- Cartogram() 297 | if (is.null(res)){return(NULL)} 298 | op <- par(mfrow = c(1, 1), mar = c(0, 0, 0, 0)) 299 | 300 | if(input$datatype == "USstate"){ 301 | cm <- unlist(colormap()[input$colormapname]) 302 | 303 | S <- state.x77[which(rownames(state.x77) %in% res$Cartogram$name), input$color] 304 | S <- S[res$GA@solution[1, ]] 305 | S <- round((length(cm) - 1) * (S - min(S)) / (max(S) - min(S))) + 1 306 | plot(res, col=cm[S], col.text = 'black') 307 | legend("topleft", c(paste("Area ~", input$area), 308 | paste("Color ~", input$color)), 309 | box.col = 'white') 310 | 311 | }else{ 312 | plot(res$Cartogram, col.text = 'darkred')} 313 | 314 | }) 315 | 316 | output$gaPlot <- renderPlot({ 317 | plot(Cartogram()$GA) 318 | }) 319 | 320 | output$gaSolution <- DT::renderDataTable({ 321 | t(Cartogram()$GA@solution) 322 | }) 323 | 324 | output$summary <- DT::renderDataTable({ 325 | res <- Cartogram() 326 | t(res$Summary) 327 | }) 328 | 329 | # ------- pdf ------- 330 | output$foo = downloadHandler( 331 | filename = paste("recmap.pdf", sep = ''), 332 | content = function(file) { 333 | pdf(file, 12, 12) 334 | res <- Cartogram() 335 | plot.recmap( 336 | res$Cartogram, 337 | col.text = 'darkred', 338 | sub = paste( 339 | 'U.S. state', 340 | input$state, 341 | '- rectangular cartogram generated by using https://CRAN.R-project.org/package=recmap version', 342 | packageVersion('recmap') 343 | ) 344 | ) 345 | dev.off() 346 | #plotInput() 347 | #dev.copy2pdf(file = file, width=12, height=8, out.type="pdf") 348 | } 349 | ) 350 | 351 | #---- sessionInfo ---- 352 | output$sessionInfo <- renderPrint({ 353 | capture.output(sessionInfo()) 354 | }) 355 | }) 356 | -------------------------------------------------------------------------------- /inst/shiny-examples/ui.R: -------------------------------------------------------------------------------- 1 | #R 2 | # This is the client logic for a Shiny web application using recmap 3 | # 4 | # https://CRAN.R-project.org/package=recmap 5 | 6 | 7 | 8 | shinyUI(fluidPage(# Application title 9 | titlePanel( 10 | paste("https://CRAN.R-project.org/package=recmap", 11 | "version", 12 | packageVersion('recmap') 13 | ) 14 | ), 15 | 16 | # Sidebar with a slider input 17 | sidebarLayout( 18 | sidebarPanel( 19 | htmlOutput("methodRadio"), 20 | br(), 21 | htmlOutput("II"), 22 | hr(), 23 | helpText('Genetic Algorithm (GA):'), 24 | numericInput("seed", "seed", 1), 25 | sliderInput("GApopulation", "population size factor", 1, 10, 1), 26 | numericInput("GAmaxiter", "maxiter", 10), 27 | helpText('the maximum number of iterations to run before the GA search is halted.'), 28 | hr(), 29 | numericInput("GArun", "run", 10), 30 | helpText('the number of consecutive generations without any improvement in the best fitness value before the GA is stopped.'), 31 | hr(), 32 | sliderInput("GApmutation", "probability of mutation in a parent chromosome", 0, 1, 0.2), 33 | #sliderInput("objective_weight", "topology ~ relative position", 0, 1, 0.5), 34 | 35 | checkboxInput("parallel", "parallel - An optional argument which allows to specify if the Genetic Algorithm should be run sequentially or in parallel.", FALSE), 36 | hr(), 37 | downloadButton('foo') 38 | ), 39 | 40 | mainPanel( 41 | tabsetPanel( 42 | tabPanel("recmap", 43 | list( 44 | helpText( 45 | 'overlapping rectangles define the topology of the pseudo dual graph.' 46 | ), 47 | plotOutput("mapPlot"), 48 | tableOutput("plot_hoverinfo"), 49 | p('please wait some seconds until the cartogram is computed.'), 50 | plotOutput( 51 | "cartogramPlot", 52 | hover = hoverOpts( 53 | id = "plot_hover", 54 | delayType = "throttle", 55 | delay = 500 56 | ) 57 | ))), 58 | tabPanel("GA", 59 | list( 60 | plotOutput("gaPlot"), 61 | DT::dataTableOutput("gaSolution") 62 | ) 63 | ), 64 | tabPanel("Summary", 65 | list( 66 | DT::dataTableOutput("summary") 67 | ) 68 | ), 69 | tabPanel("Session Info", verbatimTextOutput("sessionInfo")) 70 | ), 71 | 72 | p( 73 | 'compute your own cartogram with', 74 | a('https://CRAN.R-project.org/package=recmap', 75 | href = 'https://CRAN.R-project.org/package=recmap'), 76 | '.' 77 | ) 78 | ) 79 | ))) 80 | -------------------------------------------------------------------------------- /man/as.SpatialPolygonsDataFrame.recmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{as.SpatialPolygonsDataFrame.recmap} 4 | \alias{as.SpatialPolygonsDataFrame.recmap} 5 | \alias{as.SpatialPolygonsDataFrame} 6 | \title{Convert a recmap Object to SpatialPolygonsDataFrame Object.} 7 | \usage{ 8 | \method{as.SpatialPolygonsDataFrame}{recmap}(x, df = NULL, ...) 9 | } 10 | \arguments{ 11 | \item{x}{a \code{\link{recmap}} object.} 12 | 13 | \item{df}{a \code{data.frame} object. default is NULL.} 14 | 15 | \item{\dots}{\dots} 16 | } 17 | \description{ 18 | The method generates a SpatialPolygons object of a as input given 19 | \code{\link{recmap}} object. Both \code{data.frame}s are merged by the index order. 20 | } 21 | \examples{ 22 | SpDf <- as.SpatialPolygonsDataFrame(recmap(checkerboard(8))) 23 | summary(SpDf) 24 | spplot(SpDf) 25 | 26 | } 27 | -------------------------------------------------------------------------------- /man/as.recmap.SpatialPolygonsDataFrame.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{as.recmap.SpatialPolygonsDataFrame} 4 | \alias{as.recmap.SpatialPolygonsDataFrame} 5 | \alias{as.recmap} 6 | \title{Convert a SpatialPolygonsDataFrame Object to recmap Object} 7 | \usage{ 8 | \method{as.recmap}{SpatialPolygonsDataFrame}(X) 9 | } 10 | \arguments{ 11 | \item{X}{\code{\link{SpatialPolygonsDataFrame}} object.} 12 | } 13 | \value{ 14 | returns a \code{\link{recmap}} object. 15 | } 16 | \description{ 17 | The method generates a recmap class out of a \code{\link{SpatialPolygonsDataFrame}} object. 18 | } 19 | \examples{ 20 | SpDf <- as.SpatialPolygonsDataFrame(recmap(checkerboard(8))) 21 | summary(SpDf) 22 | spplot(SpDf) 23 | summary(as.recmap(SpDf)) 24 | 25 | } 26 | \references{ 27 | Roger S. Bivand, Edzer Pebesma, Virgilio Gomez-Rubio, 2013. 28 | Applied spatial data analysis with R, Second edition. Springer, NY. 29 | } 30 | -------------------------------------------------------------------------------- /man/checkerboard.Rd: -------------------------------------------------------------------------------- 1 | \name{checkerboard} 2 | \alias{checkerboard} 3 | 4 | \title{ 5 | Create a Checkboard 6 | } 7 | \description{ 8 | 9 | This function generates a \code{\link{recmap}} object. 10 | } 11 | \usage{ 12 | checkerboard(n = 8, ratio = 4) 13 | } 14 | 15 | \arguments{ 16 | \item{n}{defines the size of the map. default is 8 which will generate a map 17 | having 64 regions.} 18 | 19 | \item{ratio}{defines the ratio of the statistical value. As default, the 20 | black regions have a value which is four times higher.} 21 | } 22 | 23 | \value{ 24 | returns a checkerboard as \code{\link{recmap}} object. 25 | } 26 | 27 | \author{ 28 | Christian Panse 29 | } 30 | 31 | \seealso{ 32 | 33 | \itemize{ 34 | \item \code{\link{recmap}}. 35 | } 36 | } 37 | 38 | \examples{ 39 | 40 | checkerboard8x8 <- checkerboard(8) 41 | 42 | plot(checkerboard8x8, 43 | col=c('white','white','white','black')[checkerboard8x8$z]) 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /man/dot-draw_recmap_us_state_ev.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{.draw_recmap_us_state_ev} 4 | \alias{.draw_recmap_us_state_ev} 5 | \title{this function reproduces the original election cartogram from 2004 using 6 | the cartogram output from the 2003 implementation.} 7 | \usage{ 8 | .draw_recmap_us_state_ev(plot = TRUE) 9 | } 10 | \arguments{ 11 | \item{plot}{default is TRUE} 12 | } 13 | \value{ 14 | the plot 15 | } 16 | \description{ 17 | this function reproduces the original election cartogram from 2004 using 18 | the cartogram output from the 2003 implementation. 19 | } 20 | -------------------------------------------------------------------------------- /man/dot-get_7triangles.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{.get_7triangles} 4 | \alias{.get_7triangles} 5 | \title{construct polygon mesh displayed in Figure 4a in} 6 | \usage{ 7 | .get_7triangles(A = 1) 8 | } 9 | \arguments{ 10 | \item{A}{defines the area of a region in the center} 11 | } 12 | \value{ 13 | a \link{SpatialPolygons} object 14 | } 15 | \description{ 16 | construct polygon mesh displayed in Figure 4a in 17 | } 18 | \examples{ 19 | triangle.map <- recmap:::.get_7triangles() 20 | z <- c(rep(4, 4), rep(1, 3)) 21 | cols <- c(rep('white', 4), rep('grey',3)) 22 | 23 | op <- par(mfrow=c(1,2), mar=c(0, 0, 0, 0)) 24 | plot(triangle.map, col=cols) 25 | 26 | \dontrun{ 27 | # requires libfft.so installed in linux 28 | if (require(getcartr) & require(Rcartogram)){ 29 | cartogram <- quick.carto(triangle.map, z, res=64) 30 | plot(cartogram, col=cols) 31 | } 32 | } 33 | } 34 | \references{ 35 | \doi{10.1109/TVCG.2004.1260761} 36 | } 37 | -------------------------------------------------------------------------------- /man/is.recmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{is.recmap} 4 | \alias{is.recmap} 5 | \title{Is an Object from a Class recmap?} 6 | \usage{ 7 | is.recmap(object) 8 | } 9 | \arguments{ 10 | \item{object}{any \R object.} 11 | } 12 | \description{ 13 | Is an Object from a Class recmap? 14 | } 15 | -------------------------------------------------------------------------------- /man/jss2711.Rd: -------------------------------------------------------------------------------- 1 | \name{jss2711} 2 | \alias{jss2711} 3 | \alias{SBB} 4 | \alias{Switzerland} 5 | \alias{UK} 6 | \alias{cmp_GA_GRASP} 7 | \alias{mbb_check} 8 | \docType{data} 9 | 10 | \title{ 11 | jss2711 data 12 | } 13 | 14 | \description{ 15 | jss2711 contains the replication materials (input and output) for the 16 | \doi{10.18637/jss.v086.c01} manuscript's 17 | Figures 4, 5, 6, 7, 11, 12, and 13. 18 | } 19 | 20 | \format{ 21 | A set of nested \code{list} of \code{data.frames}. 22 | } 23 | 24 | \source{ 25 | \itemize{ 26 | \item{Figure 4 -- \code{mbb_check} contains a \code{data.frame} with some 27 | \code{recmap} implemention benchmarks. Generated on 28 | \itemize{ 29 | \item {MacBook Pro (15-inch, 2017).} 30 | \item {Processor: 2.9 GHz Intel Core i7} 31 | \item {Memory: 16 GB 2133 MHz LPDDR3} 32 | } 33 | } 34 | 35 | \item{Figure 5 -- \code{cmp_GA_GRASP} contains a \code{list} of results using 36 | a \code{\link[recmap:recmapGA]{GRASP}} and \code{\link[GA:ga]{GA}} metaheuristic. 37 | Generated on a MacBook Pro (Retina, 13-inch, Mid 2014).} 38 | 39 | \item{Figure 11 -- \code{Switzerland}: 40 | \itemize{ 41 | \item {input map rectangles derived from: 42 | Swiss Federal Office of Topography \url{https://www.swisstopo.admin.ch} using Landscape Models / Boundaries GG25, 43 | downloaded 2016-05-01; Perfomed on a Intel(R) Xeon(R) CPU E5-2698 v3 @ 2.30GHz/ Debian8} 44 | \item{statistical data: Bundesamt fur Statistik (BFS) \url{https://www.bfs.admin.ch}, 45 | Website Statistik Schweiz, downloaded file \code{je-d-21.03.01.xls} on 2016-05-26.}, 46 | \item{Perfomed on a Intel(R) Xeon(R) CPU E5-2698 v3 @ 2.30GHz/ Debian8.} 47 | }} 48 | 49 | 50 | \item{Figure 12 -- \code{SBB}}: 51 | \itemize{ 52 | \item {Source: \href{https://data.sbb.ch/explore/?sort=explore.download_count&refine.modified=2016}{https://data.sbb.ch/explore} 2016-05-12}. 53 | \item{Perfomed on a Intel(R) Xeon(R) CPU E5-2698 v3 @ 2.30GHz/ Debian 8.} 54 | } 55 | 56 | \item{Figure 13 -- \code{UK}}: 57 | \itemize{ 58 | \item {input map rectangles derived from: \code{https://census.edina.ac.uk/ukborders}; 59 | Contains OS data Crown copyright [and database right] (2016);} 60 | \item {Source of election data: \href{https://www.nisra.gov.uk}{NISRA}} 61 | \item {copyright - Contains National Statistics data Crown copyright and database right 2016 62 | Contains NRS data Crown copyright and database right 2016} 63 | \item {Perfomed on a Intel(R) Xeon(R) CPU E5-2698 v3 @ 2.30GHz/ Debian8} 64 | }} 65 | } 66 | 67 | 68 | \author{ 69 | Christian Panse, 2018 70 | } 71 | 72 | \references{ 73 | Panse C (2018). "Rectangular Statistical Cartograms in R: The recmap 74 | Package." Journal of Statistical Software, Code Snippets, 86(1), 75 | pp. 1-27. \doi{10.18637/jss.v086.c01}. 76 | } 77 | 78 | \examples{ 79 | options(warn = -1) 80 | 81 | ## Figure 4 82 | jss2711_figure4 <- function(nrep = 1, size = 2:10){ 83 | recmap_debug_code <- ' 84 | // [[Rcpp::plugins(cpp11)]] 85 | 86 | #include 87 | #include 88 | #include 89 | 90 | using namespace Rcpp; 91 | 92 | // [[Rcpp::depends(recmap)]] 93 | // [[Rcpp::export]] 94 | int recmap_debug(DataFrame df, 95 | bool map_region_intersect_multiset = true) { 96 | // access the columns 97 | NumericVector x = df["x"]; 98 | NumericVector y = df["y"]; 99 | NumericVector dx = df["dx"]; 100 | NumericVector dy = df["dy"]; 101 | 102 | 103 | NumericVector z = df["z"]; 104 | CharacterVector name = df["name"]; 105 | 106 | NumericVector cartogram_x(x.size()); 107 | NumericVector cartogram_y(x.size()); 108 | NumericVector cartogram_dx(x.size()); 109 | NumericVector cartogram_dy(x.size()); 110 | 111 | NumericVector dfs_num(x.size()); 112 | NumericVector topology_error(x.size()); 113 | NumericVector relpos_error(x.size()); 114 | NumericVector relpos_nh_error(x.size()); 115 | 116 | crecmap::RecMap X; 117 | X.set_map_region_intersect_multiset(map_region_intersect_multiset); 118 | 119 | for (int i = 0; i < x.size(); i++) { 120 | std::string sname = Rcpp::as(name[i]); 121 | X.push_region(x[i], y[i], dx[i], dy[i], z[i], sname); 122 | } 123 | 124 | X.run(true); 125 | 126 | return(X.get_intersect_count()); 127 | } 128 | ' 129 | 130 | sourceCpp(code = recmap_debug_code, rebuild = TRUE, verbose = TRUE) 131 | 132 | do.call('rbind', lapply(size, function(size){ 133 | set.seed(1); 134 | CB <- checkerboard(size); 135 | 136 | do.call('rbind',lapply(rep(size, nrep), function(n){ 137 | 138 | CB.smp <- CB[sample(nrow(CB), nrow(CB)), ] 139 | start_time <- Sys.time() 140 | ncall.multiset <- recmap_debug(CB.smp, 141 | map_region_intersect_multiset = TRUE) 142 | 143 | end_time <- Sys.time() 144 | 145 | diff_time.multiset <- as.numeric(difftime(end_time, 146 | start_time, units = "secs")) 147 | 148 | 149 | start_time <- Sys.time() 150 | ncall.list <- recmap_debug(CB.smp, 151 | map_region_intersect_multiset = FALSE) 152 | end_time <- Sys.time() 153 | diff_time.list <- as.numeric(difftime(end_time, 154 | start_time, units = "secs")) 155 | 156 | rv <- rbind(data.frame(number = ncall.multiset, 157 | algorithm="multiset", size = nrow(CB), 158 | time_in_secs = diff_time.multiset), 159 | data.frame(number = ncall.list, 160 | algorithm="list", size = nrow(CB), 161 | time_in_secs = diff_time.list)) 162 | 163 | rv$machine <- Sys.info()['machine'] 164 | rv$sysname <- Sys.info()['sysname'] 165 | rv 166 | })) 167 | })) 168 | } 169 | 170 | \dontrun{ 171 | mbb_check <- jss2711_figure4() 172 | } 173 | 174 | data(jss2711) 175 | boxplot(number ~ sqrt(size), 176 | axes=FALSE, 177 | data = mbb_check, 178 | log='y', 179 | cex = 0.75, 180 | subset = algorithm == "list", 181 | col = "red", boxwex = 0.25); 182 | abline(v = sqrt(50), col = 'lightgray', lwd = 3) 183 | 184 | boxplot(number ~ sqrt(size), 185 | data = mbb_check,log='y', 186 | subset = algorithm == "multiset", 187 | cex = 0.75, 188 | ylab = 'number of MBB intersection calls', 189 | xlab = 'number of map regions', 190 | boxwex = 0.25, add = TRUE, axes=FALSE); 191 | axis(2) 192 | axis(1, c(5, sqrt(50), 10, 15, 20), c("5x5", "US", "10x10", "15x15", "20x20")) 193 | box() 194 | 195 | legend("bottomright", c("C++ STL list", "C++ STL multiset"), 196 | col=c('red', 'black'), pch = 16, cex = 1.0) 197 | 198 | 199 | 200 | ## Figure 5 201 | 202 | op <- par(mar=c(0, 0, 0, 0), mfrow=c(1, 3), bg = 'azure') 203 | 204 | plot(cmp_GA_GRASP$GRASP$Map, 205 | border='black', 206 | col=c('white', 'white', 'white', 'black')[cmp_GA_GRASP$GRASP$Map$z]) 207 | 208 | plot(cmp_GA_GRASP$GRASP$Cartogram, 209 | border='black', 210 | col = c('white', 'white', 'white', 'black')[cmp_GA_GRASP$GRASP$Cartogram$z]) 211 | 212 | plot(cmp_GA_GRASP$GA$Cartogram, 213 | border='black', 214 | col = c('white', 'white', 'white', 'black')[cmp_GA_GRASP$GA$Cartogram$z]) 215 | par(op) 216 | 217 | ## Figure 6 - right 218 | 219 | op <- par(mar = c(0, 0, 0, 0), mfrow=c(1, 1), bg = 'azure') 220 | # found by the GA 221 | smp <- cmp_GA_GRASP$GA$GA@solution[1,] 222 | 223 | Cartogram.Checkerboard <- recmap(cmp_GA_GRASP$GA$Map[smp, ]) 224 | idx <- order(Cartogram.Checkerboard$dfs.num) 225 | 226 | plot(Cartogram.Checkerboard, 227 | border='black', 228 | col=c('white', 'white', 'white', 'black')[Cartogram.Checkerboard$z]) 229 | 230 | # draw placement order 231 | lines(Cartogram.Checkerboard$x[idx], 232 | Cartogram.Checkerboard$y[idx], 233 | col = rgb(1,0,0, alpha=0.3), lwd = 4, cex=0.5) 234 | 235 | text(Cartogram.Checkerboard$x[idx], 236 | Cartogram.Checkerboard$y[idx], 237 | 1:length(idx), pos=1, col=rgb(1,0,0, alpha=0.7)) 238 | 239 | points(Cartogram.Checkerboard$x[idx[1]], 240 | Cartogram.Checkerboard$y[idx[1]], lwd = 5, col = 'red') 241 | text(Cartogram.Checkerboard$x[idx[1]], 242 | Cartogram.Checkerboard$y[idx[1]], "start", col = 'red', pos=3) 243 | points(Cartogram.Checkerboard$x[idx[length(idx)]], 244 | Cartogram.Checkerboard$y[idx[length(idx)]], 245 | cex = 1.25, lwd = 2, col = 'red', pch = 5) 246 | par(op) 247 | op <- par(mar = c(4, 4, 1.5, 0.5), mfrow = c(1, 1), bg = 'white') 248 | plot(best ~ elapsedtime, data = cmp_GA_GRASP$cmp, 249 | type = 'n', 250 | ylab = 'best fitness value', 251 | xlab = 'elapsed time [in seconds]') 252 | abline(v=60, col='lightgrey',lwd=2) 253 | lines(cmp_GA_GRASP$cmp[cmp_GA_GRASP$cmp$algorithm == "GRASP", 254 | c('elapsedtime', 'best')], type = 'b', col='red', pch=16) 255 | lines(cmp_GA_GRASP$cmp[cmp_GA_GRASP$cmp$algorithm == "GA", 256 | c('elapsedtime', 'best')], type = 'b', pch=16) 257 | legend("bottomright", 258 | c("Evolutionary based Genetic Algorithm (GA)", 259 | "Greedy Randomized Adaptive Search Procedures (GRASP)"), 260 | col = c('black', 'red'), 261 | pch=16, cex=1.0) 262 | 263 | par(op) 264 | 265 | ## Figure 7 266 | \dontrun{ 267 | 268 | res <- lapply(c(1, 1, 2, 2, 3, 3), function(seed){ 269 | set.seed(seed); 270 | res <- recmapGA(V = checkerboard(4), pmutation = 0.25) 271 | res$seed <- seed 272 | res}) 273 | 274 | op <- par(mfcol=c(2,4), bg='azure', mar=c(5, 5, 0.5, 0.5)) 275 | 276 | x <- recmap(checkerboard(4)) 277 | p <- paste(' = (', paste(1:length(x$z), collapse=", "), ')', sep='') 278 | plot(x, 279 | sub=substitute(paste(Pi['forward'], p), list(p=p)), 280 | col = c('white', 'white', 'white', 'black')[x$z]) 281 | 282 | x <- recmap(checkerboard(4)[rev(1:16),]) 283 | p <- paste(' = (', paste(rev(1:length(x$z)), collapse=", "), ')', sep='') 284 | plot(x, 285 | sub=substitute(paste(Pi[reverse], p), list(p=p)), 286 | col = c('white', 'white', 'white', 'black')[x$z]) 287 | 288 | 289 | rv <- lapply(res, function(x){ 290 | p <- paste(' = (', paste(x$GA@solution[1,], collapse=", "), ')', sep='') 291 | plot(x$Cartogram, 292 | col = c('white', 'white', 'white', 'black')[x$Cartogram$z], 293 | sub=substitute(paste(Pi[seed], perm), list(perm=p, seed=x$seed))) 294 | }) 295 | } 296 | 297 | # sanity check - reproducibility 298 | 299 | identical.recmap <- function(x, y, plot.diff = FALSE){ 300 | target <- x 301 | current <- y 302 | 303 | stopifnot(is.recmap(target)) 304 | stopifnot(is.recmap(current)) 305 | rv <- identical(x$x, y$x) && identical(x$y, y$y) && 306 | identical(x$dx, y$dx) && identical(x$dy, y$dy) 307 | if (plot.diff){ 308 | rvtemp <- lapply(c('x', 'y', 'dx', 'dy'), function(cn){ 309 | plot(sort(abs(target[, cn] - current[, cn])), 310 | ylab = 'absolute error', 311 | main = cn) 312 | abline(h = 0, col = 'grey') 313 | }) 314 | } 315 | 316 | rv 317 | } 318 | 319 | \dontrun{ 320 | op <- par(mfcol = c(4, 4), mar = c(4, 4, 4, 1)); 321 | identical.recmap(res[[1]]$Cartogram, res[[2]]$Cartogram, TRUE) 322 | identical.recmap(res[[3]]$Cartogram, res[[4]]$Cartogram, TRUE) 323 | identical.recmap(res[[5]]$Cartogram, res[[6]]$Cartogram, TRUE) 324 | identical.recmap(res[[1]]$Cartogram, res[[6]]$Cartogram, TRUE) 325 | } 326 | 327 | ## Figure 11 328 | \dontrun{plot(recmap(Switzerland$map[Switzerland$solution,]))} 329 | 330 | op <- par(mfrow=c(1, 1), mar=c(0,0,0,0)); 331 | 332 | C <- Switzerland$Cartogram 333 | 334 | plot(C) 335 | 336 | idx <- rev(order(C$z))[1:50]; 337 | 338 | text(C$x[idx], C$y[idx], C$name[idx], col = 'red', 339 | cex = C$dx[idx] / strwidth(as.character(C$name[idx]))) 340 | 341 | ## Figure 12 342 | 343 | fitness.SBB <- function(idxOrder, Map, ...){ 344 | Cartogram <- recmap(Map[idxOrder, ]) 345 | if (sum(Cartogram$topology.error == 100) > 1){return (0)} 346 | 1 / sum(Cartogram$z / (sqrt(sum(Cartogram$z^2))) * Cartogram$relpos.error) 347 | } 348 | 349 | \dontrun{ 350 | SBB <- recmapGA(V=SBB$Map, 351 | parallel=TRUE, 352 | maxiter=1000, 353 | run=1000, 354 | seed = 1, 355 | keepBest = TRUE, 356 | fitness=fitness.SBB) 357 | } 358 | 359 | SBB.Map <- SBB$Map 360 | 361 | # make input map overlapping 362 | S <- SBB$Map 363 | S <- S[!is.na(S$x),] 364 | S$dx <- 0.1; S$dy <- 0.1; S$z <- S$DTV 365 | S$name <- S$Bahnhof_Haltestelle 366 | 367 | op <- par(mfrow = c(2, 1), mar = c(0, 0, 0, 0)) 368 | plot.recmap(S) 369 | idx <- rev(order(S$z))[1:10] 370 | text(S$x[idx], S$y[idx], S$name[idx], col='red', cex=0.7) 371 | idx <- rev(order(S$z))[11:30] 372 | text(S$x[idx], S$y[idx], S$name[idx], col = 'red', cex = 0.5) 373 | 374 | Cartogram.recomp <- recmap(S) 375 | plot(Cartogram.recomp) 376 | 377 | idx <- rev(order(Cartogram.recomp$z))[1:40] 378 | text(Cartogram.recomp$x[idx],Cartogram.recomp$y[idx], 379 | Cartogram.recomp$name[idx], 380 | col = 'red', 381 | cex = 1.25 * Cartogram.recomp$dx[idx] / strwidth(Cartogram.recomp$name[idx])) 382 | 383 | # sanity check - reproducibility cross plattform 384 | op <- par(mfrow = c(2, 2), mar = c(5, 5, 5, 5)) 385 | identical.recmap(Cartogram.recomp, SBB$Cartogram, TRUE) 386 | 387 | 388 | ## Figure 13 389 | 390 | \dontrun{ 391 | DF <- data.frame(Pct_Leave = UK$Map$Pct_Leave, row.names = UK$Map$name) 392 | spplot(as.SpatialPolygonsDataFrame(UK$Map, DF), 393 | main="Input England/Wales/Scottland") 394 | 395 | UK.recmap <- recmap(UK$Map) 396 | spplot(as.SpatialPolygonsDataFrame(UK.recmap , DF)) 397 | 398 | # sanity check - reproducibility cross plattform 399 | op <- par(mfrow=c(2,2), mar=c(5,5,5,5)) 400 | identical.recmap(UK.recmap, UK$Cartogram, TRUE) 401 | } 402 | 403 | } 404 | \keyword{datasets} 405 | -------------------------------------------------------------------------------- /man/plot.recmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{plot.recmap} 4 | \alias{plot.recmap} 5 | \alias{plot.recmapGA} 6 | \alias{plot.recmapGRASP} 7 | \title{Plot a recmap object.} 8 | \usage{ 9 | \method{plot}{recmap}(x, col = "#00000011", col.text = "grey", border = "darkgreen", ...) 10 | } 11 | \arguments{ 12 | \item{x}{\code{recmap} object - can be input or output of \code{recmap}.} 13 | 14 | \item{col}{a vector of colors.} 15 | 16 | \item{col.text}{a vector of colors.} 17 | 18 | \item{border}{This parameter is passed to the \code{\link{rect}} function. 19 | color for rectangle border(s). The default means par("fg"). 20 | Use border = NA to omit borders. If there are shading lines, border = TRUE 21 | means use the same colour for the border as for the shading lines. 22 | The default value is set to \code{'darkgreen'}.} 23 | 24 | \item{\ldots}{whatsoever} 25 | } 26 | \value{ 27 | graphical output 28 | } 29 | \description{ 30 | plots input and output of the \code{\link{recmap}} function. 31 | The function requires column names (x, y, dx, dy). 32 | } 33 | \examples{ 34 | checkerboard(2) |> recmap() |> plot() 35 | } 36 | -------------------------------------------------------------------------------- /man/recmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{recmap} 4 | \alias{recmap} 5 | \alias{RecMap} 6 | \alias{cartogram} 7 | \alias{all.equal.recmap} 8 | \title{Compute a Rectangular Statistical Cartogram} 9 | \usage{ 10 | recmap(V, E = NULL) 11 | } 12 | \arguments{ 13 | \item{V}{defines the input map regions formatted as \code{\link{data.frame}} 14 | having the column names \code{c('x', 'y', 'dx', 'dy', 'z', 'name')} 15 | as described above. V could also be considered as the nodes of the pseudo dual.} 16 | 17 | \item{E}{defines the edges of the map region's pseudo dual graph. 18 | If \code{E} is not provided, this is the default; the pseudo dual graph is 19 | composed of overlapping rectangles. If used, E must be a 20 | \code{\link{data.frame}} containing two columns named \code{c('u', 'v')} 21 | of type integer referencing the row number of \code{V}.} 22 | } 23 | \value{ 24 | Returns a \code{recmap} S3 object of the transformed map with new coordinates 25 | (x, y, dx, dy) plus additional columns containing information for topology 26 | error, relative position error, and the DFS number. 27 | The error values are thought to be used for fitness function of the 28 | metaheuristic. 29 | } 30 | \description{ 31 | The input consists of a map represented by overlapping rectangles. 32 | The algorithm requires as input for each map region: 33 | \itemize{ 34 | \item{a tuple of (x, y) values corresponding to the 35 | (longitude, latitude) position,} 36 | \item{a tuple of (dx, dy) of expansion along (longitude, latitude),} 37 | \item{and a statistical value z.} 38 | } 39 | The (x, y) coordinates represent the center of the minimal bounding boxes 40 | (MBB), The coordinates of the MBB are derived by adding or subtracting the 41 | (dx, dy) / 2 tuple accordingly. The tuple (dx, dy) also defines the ratio of the 42 | map region. The statistical values define the desired area of each map region. 43 | 44 | The output is a rectangular cartogram where the map regions are: 45 | 46 | \itemize{ 47 | \item{Non-overlapping,} 48 | \item{connected,} 49 | \item{ratio and area of each rectangle correspond to the desired areas,} 50 | \item{rectangles are placed parallel to the axes.} 51 | } 52 | 53 | The construction heuristic places each rectangle in a way that important spatial 54 | constraints, in particular 55 | \itemize{ 56 | \item{the topology of the pseudo dual graph,} 57 | \item{the relative position of MBB centers.} 58 | } 59 | are tried to be preserved. 60 | 61 | The ratios are preserved and the area of each region corresponds to the as 62 | input given statistical value z. 63 | } 64 | \details{ 65 | The basic idea of the current recmap \emph{implementation}: 66 | \enumerate{ 67 | \item{Compute the pseudo dual out of the overlapping map regions.} 68 | \item{Determine the \emph{core region} by \code{index <- int(n / 2)}.} 69 | \item{Place region by region along DFS skeleton of pseudo dual starting 70 | with the \emph{core region}.}} 71 | 72 | Note: if a rectangle can not be placed, accept a non-\emph{feasible solution} 73 | (avoid solutions having a topology error higher than 100) 74 | Solving this constellation can be intensive in the computation, and due to the 75 | assumably low fitness value the candidate cartogram 76 | will be likely rejected by the metaheuristic. 77 | 78 | \emph{Time Complexity:} 79 | The time complexity is \eqn{O(n^2)}, where n is the number of regions. 80 | DFS is visiting each map region only once and therefore has 81 | time complexity \eqn{O(n)}. For each placement, a constant number of 82 | MBB intersection are called (max 360). MBB check is implemented using 83 | \code{std::set}, \code{insert}, \code{upper_bound}, \code{upper_bound} 84 | costs are \eqn{O(\log(n))}{O(log(n))}. 85 | However, the worst case for a range query is \eqn{O(n)}, if and only if dx or dy 86 | cover the whole x or y range. Q.E.D. 87 | 88 | \emph{Performance:} 89 | In praxis, computing on a 2.4 GHz Intel Core i7 machine (using only one core), using the 90 | 50 state U.S. map example, recmap can compute approximately 100 cartograms in one second. 91 | The number of MBB calls were 92 | (Min., Median, Mean, Max) = (1448, 2534, 3174, 17740), using in each run 93 | a different index order using the (\code{\link{sample}}) method. 94 | 95 | \emph{Geodetic datum:} the \code{recmap} algorithm is not transforming the 96 | geodetic datum, e.g., WGS84 or Swissgrid. 97 | } 98 | \examples{ 99 | map <- checkerboard(2) 100 | cartogram <- recmap(map) 101 | 102 | map 103 | cartogram 104 | 105 | op <- par(mfrow = c(1, 2)) 106 | plot(map) 107 | plot(cartogram) 108 | 109 | ## US example 110 | usa <- data.frame(x = state.center$x, 111 | y = state.center$y, 112 | # make the rectangles overlapping by correcting 113 | # lines of longitude distance. 114 | dx = sqrt(state.area) / 2 115 | / (0.8 * 60 * cos(state.center$y * pi / 180)), 116 | dy = sqrt(state.area) / 2 / (0.8 * 60), 117 | z = sqrt(state.area), 118 | name = state.name) 119 | 120 | usa$z <- state.x77[, 'Population'] 121 | US.Map <- usa[match(usa$name, 122 | c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 123 | 124 | plot.recmap(US.Map) 125 | US.Map |> recmap() |> plot() 126 | par(op) 127 | 128 | # define a fitness function 129 | recmap.fitness <- function(idxOrder, Map, ...){ 130 | Cartogram <- recmap(Map[idxOrder, ]) 131 | # a map region could not be placed; 132 | # accept only feasible solutions! 133 | if (sum(Cartogram$topology.error == 100) > 0){return (0)} 134 | 1 / sum(Cartogram$z / (sqrt(sum(Cartogram$z^2))) 135 | * Cartogram$relpos.error) 136 | } 137 | 138 | } 139 | \author{ 140 | Christian Panse, 2016 141 | } 142 | -------------------------------------------------------------------------------- /man/recmapGA.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{recmapGA} 4 | \alias{recmapGA} 5 | \title{Genetic Algorithm Wrapper Function for recmap} 6 | \usage{ 7 | recmapGA( 8 | V, 9 | fitness = .recmap.fitness, 10 | pmutation = 0.25, 11 | popSize = 10 * nrow(Map), 12 | maxiter = 10, 13 | run = maxiter, 14 | monitor = if (interactive()) { 15 | gaMonitor 16 | } else FALSE, 17 | parallel = FALSE, 18 | ... 19 | ) 20 | } 21 | \arguments{ 22 | \item{V}{defines the input map regions formatted as \code{\link{data.frame}} 23 | having the column names \code{c('x', 'y', 'dx', 'dy', 'z', 'name')} 24 | as described above. V could also be considered as the nodes of the pseudo dual.} 25 | 26 | \item{fitness}{the fitness function, any allowable R function which takes as input an individual \code{string} representing a potential solution, and returns a numerical value describing its ``fitness''.} 27 | 28 | \item{pmutation}{the probability of mutation in a parent chromosome. Usually mutation occurs with a small probability, and by default is set to 0.1.} 29 | 30 | \item{popSize}{the population size.} 31 | 32 | \item{maxiter}{the maximum number of iterations to run before the GA search is halted.} 33 | 34 | \item{run}{the number of consecutive generations without any improvement in the best fitness value before the GA is stopped.} 35 | 36 | \item{monitor}{a logical or an R function which takes as input the current state of the \code{ga-class} object and show the evolution of the search. By default, for interactive sessions the function \code{\link[GA]{gaMonitor}} prints the average and best fitness values at each iteration. If set to \code{plot} these information are plotted on a graphical device. Other functions can be written by the user and supplied as argument. In non interactive sessions, by default \code{monitor = FALSE} so any output is suppressed.} 37 | 38 | \item{parallel}{ 39 | An optional argument which allows to specify if the Genetic Algorithm should be run sequentially or in parallel. 40 | 41 | For a single machine with multiple cores, possible values are: 42 | \itemize{ 43 | \item a logical value specifying if parallel computing should be used (\code{TRUE}) or not (\code{FALSE}, default) for evaluating the fitness function; 44 | \item a numerical value which gives the number of cores to employ. By default, this is obtained from the function \code{\link[parallel]{detectCores}}; 45 | \item a character string specifying the type of parallelisation to use. This depends on system OS: on Windows OS only \code{"snow"} type functionality is available, while on Unix/Linux/Mac OSX both \code{"snow"} and \code{"multicore"} (default) functionalities are available. 46 | } 47 | In all the cases described above, at the end of the search the cluster is automatically stopped by shutting down the workers. 48 | 49 | If a cluster of multiple machines is available, evaluation of the fitness function can be executed in parallel using all, or a subset of, the cores available to the machines belonging to the cluster. However, this option requires more work from the user, who needs to set up and register a parallel back end. 50 | In this case the cluster must be explicitly stopped with \code{\link[parallel]{stopCluster}}. 51 | } 52 | 53 | \item{...}{additional arguments to be passed to the fitness function. This allows to write fitness functions that keep some variables fixed during the search.} 54 | } 55 | \value{ 56 | returns a list of the input \code{Map}, the solution of the \code{\link[GA]{ga}} 57 | function, and a \code{\link{recmap}} object containing the cartogram. 58 | } 59 | \description{ 60 | higher-level function for \code{\link{recmap}} using a Genetic Algorithm as 61 | metaheuristic. 62 | } 63 | \examples{ 64 | ## The default fitnes function is currently defined as 65 | function(idxOrder, Map, ...){ 66 | 67 | Cartogram <- recmap(Map[idxOrder, ]) 68 | # a map region could not be placed; 69 | # accept only feasible solutions! 70 | 71 | if (sum(Cartogram$topology.error == 100) > 0){return (0)} 72 | 73 | 1 / sum(Cartogram$relpos.error) 74 | } 75 | 76 | 77 | ## use Genetic Algorithms (GA >=3.0.0) as metaheuristic 78 | set.seed(1) 79 | 80 | ## https://github.com/luca-scr/GA/issues/52 81 | if (Sys.info()['machine'] == "arm64") GA::gaControl(useRcpp = FALSE) 82 | res <- recmapGA(V = checkerboard(4), pmutation = 0.25) 83 | 84 | op <- par(mfrow = c(1, 3)) 85 | plot(res$Map, main = "Input Map") 86 | plot(res$GA, main="Genetic Algorithm") 87 | plot(res$Cartogram, main = "Output Cartogram") 88 | 89 | 90 | ## US example 91 | getUS_map <- function(){ 92 | usa <- data.frame(x = state.center$x, 93 | y = state.center$y, 94 | # make the rectangles overlapping by correcting 95 | # lines of longitude distance. 96 | dx = sqrt(state.area) / 2 97 | / (0.8 * 60 * cos(state.center$y * pi / 180)), 98 | dy = sqrt(state.area) / 2 / (0.8 * 60), 99 | z = sqrt(state.area), 100 | name = state.name) 101 | 102 | usa$z <- state.x77[, 'Population'] 103 | US.Map <- usa[match(usa$name, 104 | c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 105 | 106 | class(US.Map) <- c('recmap', 'data.frame') 107 | US.Map 108 | } 109 | 110 | \dontrun{ 111 | # takes 34.268 seconds on CRAN 112 | res <- recmapGA(V = getUS_map(), maxiter = 5) 113 | op <- par(ask = TRUE) 114 | plot(res) 115 | par(op) 116 | summary(res) 117 | } 118 | } 119 | \references{ 120 | Luca Scrucca (2013). GA: A Package for Genetic Algorithms in R. 121 | Journal of Statistical Software, 53(4), 1-37. 122 | \doi{10.18637/jss.v053.i04}. 123 | } 124 | -------------------------------------------------------------------------------- /man/recmapGRASP.Rd: -------------------------------------------------------------------------------- 1 | \name{recmapGRASP} 2 | \alias{recmapGRASP} 3 | 4 | \title{ 5 | Greedy Randomized Adaptive Search Procedure Wrapper Function for recmap 6 | } 7 | \description{ 8 | Implements a metaheuristic for \code{\link{recmap}} based on GRASP. 9 | } 10 | \usage{ 11 | recmapGRASP(Map, fitness = .recmap.fitness, n.samples = nrow(Map) * 2, 12 | fitness.cutoff = 1.7, iteration.max = 10) 13 | } 14 | 15 | \arguments{ 16 | \item{Map}{ 17 | defines the input map regions formatted as \code{\link{data.frame}} 18 | having the column names \code{c('x', 'y', 'dx', 'dy', 'z', 'name')} 19 | as described above. 20 | } 21 | \item{fitness}{ 22 | a fitness function \code{function(idxOrder, Map, ...)} returning a number 23 | which as to be maximized. 24 | } 25 | 26 | \item{n.samples}{ 27 | number of samples. 28 | } 29 | \item{fitness.cutoff}{ 30 | cut-off value. 31 | } 32 | \item{iteration.max}{ 33 | maximal number of iteration. 34 | } 35 | } 36 | 37 | \value{ 38 | returns a list of the input \code{Map}, the best solution of GRASP, 39 | and a \code{\link{recmap}} object containing the cartogram. 40 | } 41 | 42 | \references{ 43 | Feo TA, Resende MGC (1995). 44 | "Greedy Randomized Adaptive Search Procedures." 45 | Journal of Global Optimization, 6(2), 109-133. ISSN 1573-2916. 46 | \doi{10.1007/BF01096763}. 47 | } 48 | \author{ 49 | Christian Panse 50 | } 51 | 52 | \seealso{ 53 | \code{\link{recmapGA}} and \code{\link{recmap}} 54 | } 55 | 56 | \examples{ 57 | 58 | ## US example 59 | getUS_map <- function(){ 60 | usa <- data.frame(x = state.center$x, 61 | y = state.center$y, 62 | # make the rectangles overlapping by correcting 63 | # lines of longitude distance. 64 | dx = sqrt(state.area) / 2 65 | / (0.8 * 60 * cos(state.center$y * pi / 180)), 66 | dy = sqrt(state.area) / 2 / (0.8 * 60), 67 | z = sqrt(state.area), 68 | name = state.name) 69 | 70 | usa$z <- state.x77[, 'Population'] 71 | US.Map <- usa[match(usa$name, 72 | c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 73 | 74 | class(US.Map) <- c('recmap', 'data.frame') 75 | US.Map 76 | } 77 | 78 | \dontrun{ 79 | res <- recmapGRASP(getUS_map()) 80 | plot(res$Map, main = "Input Map") 81 | plot(res$Cartogram, main = "Output Cartogram") 82 | } 83 | 84 | } 85 | 86 | -------------------------------------------------------------------------------- /man/summary.recmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/recmap.R 3 | \name{summary.recmap} 4 | \alias{summary.recmap} 5 | \alias{summary.recmapGA} 6 | \title{Summary for recmap object} 7 | \usage{ 8 | \method{summary}{recmap}(object, ...) 9 | } 10 | \arguments{ 11 | \item{object}{an object for which a summary is desired.} 12 | 13 | \item{...}{additional arguments affecting the summary produced.} 14 | } 15 | \value{ 16 | returns a \code{data.frame} containing summary information, e.g., 17 | objective functions or number of map regions. 18 | } 19 | \description{ 20 | Summary method for S3 class \code{\link{recmap}}. 21 | The area error is computed as described in the CartoDraw paper. 22 | } 23 | \examples{ 24 | summary(checkerboard(4)); 25 | summary(recmap(checkerboard(4))) 26 | } 27 | \references{ 28 | \doi{10.1109/TVCG.2004.1260761} 29 | } 30 | -------------------------------------------------------------------------------- /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 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // get_angle 14 | double get_angle(double x0, double y0, double x1, double y1); 15 | RcppExport SEXP _recmap_get_angle(SEXP x0SEXP, SEXP y0SEXP, SEXP x1SEXP, SEXP y1SEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< double >::type x0(x0SEXP); 20 | Rcpp::traits::input_parameter< double >::type y0(y0SEXP); 21 | Rcpp::traits::input_parameter< double >::type x1(x1SEXP); 22 | Rcpp::traits::input_parameter< double >::type y1(y1SEXP); 23 | rcpp_result_gen = Rcpp::wrap(get_angle(x0, y0, x1, y1)); 24 | return rcpp_result_gen; 25 | END_RCPP 26 | } 27 | // place_rectangle 28 | DataFrame place_rectangle(double x0, double y0, double dx0, double dy0, double dx1, double dy1, double alpha); 29 | RcppExport SEXP _recmap_place_rectangle(SEXP x0SEXP, SEXP y0SEXP, SEXP dx0SEXP, SEXP dy0SEXP, SEXP dx1SEXP, SEXP dy1SEXP, SEXP alphaSEXP) { 30 | BEGIN_RCPP 31 | Rcpp::RObject rcpp_result_gen; 32 | Rcpp::RNGScope rcpp_rngScope_gen; 33 | Rcpp::traits::input_parameter< double >::type x0(x0SEXP); 34 | Rcpp::traits::input_parameter< double >::type y0(y0SEXP); 35 | Rcpp::traits::input_parameter< double >::type dx0(dx0SEXP); 36 | Rcpp::traits::input_parameter< double >::type dy0(dy0SEXP); 37 | Rcpp::traits::input_parameter< double >::type dx1(dx1SEXP); 38 | Rcpp::traits::input_parameter< double >::type dy1(dy1SEXP); 39 | Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP); 40 | rcpp_result_gen = Rcpp::wrap(place_rectangle(x0, y0, dx0, dy0, dx1, dy1, alpha)); 41 | return rcpp_result_gen; 42 | END_RCPP 43 | } 44 | // recmap 45 | DataFrame recmap(DataFrame V, Rcpp::Nullable E); 46 | RcppExport SEXP _recmap_recmap(SEXP VSEXP, SEXP ESEXP) { 47 | BEGIN_RCPP 48 | Rcpp::RObject rcpp_result_gen; 49 | Rcpp::RNGScope rcpp_rngScope_gen; 50 | Rcpp::traits::input_parameter< DataFrame >::type V(VSEXP); 51 | Rcpp::traits::input_parameter< Rcpp::Nullable >::type E(ESEXP); 52 | rcpp_result_gen = Rcpp::wrap(recmap(V, E)); 53 | return rcpp_result_gen; 54 | END_RCPP 55 | } 56 | 57 | static const R_CallMethodDef CallEntries[] = { 58 | {"_recmap_get_angle", (DL_FUNC) &_recmap_get_angle, 4}, 59 | {"_recmap_place_rectangle", (DL_FUNC) &_recmap_place_rectangle, 7}, 60 | {"_recmap_recmap", (DL_FUNC) &_recmap_recmap, 2}, 61 | {NULL, NULL, 0} 62 | }; 63 | 64 | RcppExport void R_init_recmap(DllInfo *dll) { 65 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 66 | R_useDynamicSymbols(dll, FALSE); 67 | } 68 | -------------------------------------------------------------------------------- /src/Recmap.cpp: -------------------------------------------------------------------------------- 1 | // Copyright 2016 2 | // 3 | // This file is part of the recmap package on CRAN. 4 | // https://CRAN.R-project.org/package=recmap 5 | // 6 | // recmap is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // recmap is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with recmap. If not, see . 18 | 19 | 20 | // Author: Christian Panse 21 | // 2016-04-19/20/21/22 ACCU2016 Bristol, UK 22 | // see also: https://arxiv.org/abs/1606.00464 23 | 24 | #define STRICT_R_HEADERS 25 | #include 26 | #include 27 | 28 | #include "../inst/include/recmap.cpp" 29 | 30 | using namespace Rcpp; 31 | //' @import Rcpp 32 | // [[Rcpp::export]] 33 | double get_angle(double x0, double y0, double x1, double y1) { 34 | crecmap::map_region a, b; 35 | a.x = x0; a.y = y0; 36 | b.x = x1; b.y = y1; 37 | 38 | return (crecmap::get_angle(a, b)); 39 | } 40 | 41 | // [[Rcpp::export]] 42 | DataFrame place_rectangle(double x0, double y0, double dx0, double dy0, 43 | double dx1, double dy1, double alpha) { 44 | crecmap::map_region a, b, c; 45 | 46 | a.x = x0; a.y = y0; a.dx = dx0; a.dy = dy0; 47 | c.dx = dx1; c.dy = dy1; 48 | 49 | crecmap::place_rectangle(a, alpha, c); 50 | return DataFrame::create(_["x"]= c.x, _["y"]= c.y, _["dx"]= dx1, 51 | _["dy"]= dy1); 52 | } 53 | 54 | 55 | //' Compute a Rectangular Statistical Cartogram 56 | //' 57 | //' @description 58 | //' The input consists of a map represented by overlapping rectangles. 59 | //' The algorithm requires as input for each map region: 60 | //' * a tuple of (x, y) values corresponding to the 61 | //' (longitude, latitude) position, 62 | //' * a tuple of (dx, dy) of expansion along (longitude, latitude), 63 | //' * and a statistical value z. 64 | //' 65 | //' The (x, y) coordinates represent the center of the minimal bounding boxes 66 | //' (MBB), The coordinates of the MBB are derived by adding or subtracting the 67 | //' (dx, dy) / 2 tuple accordingly. The tuple (dx, dy) also defines the ratio of the 68 | //' map region. The statistical values define the desired area of each map region. 69 | //' 70 | //' The output is a rectangular cartogram where the map regions are: 71 | //' 72 | //' * Non-overlapping, 73 | //' * connected, 74 | //' * ratio and area of each rectangle correspond to the desired areas, 75 | //' * rectangles are placed parallel to the axes. 76 | //' 77 | //' The construction heuristic places each rectangle in a way that important spatial 78 | //' constraints, in particular 79 | //' * the topology of the pseudo dual graph, 80 | //' * the relative position of MBB centers. 81 | //' 82 | //' are tried to be preserved. 83 | //' 84 | //' The ratios are preserved and the area of each region corresponds to the as 85 | //' input given statistical value z. 86 | //' 87 | //' @param V defines the input map regions formatted as \code{\link{data.frame}} 88 | //' having the column names \code{c('x', 'y', 'dx', 'dy', 'z', 'name')} 89 | //' as described above. V could also be considered as the nodes of the pseudo dual. 90 | //' 91 | //' @param E defines the edges of the map region's pseudo dual graph. 92 | //' If \code{E} is not provided, this is the default; the pseudo dual graph is 93 | //' composed of overlapping rectangles. If used, E must be a 94 | //' \code{\link{data.frame}} containing two columns named \code{c('u', 'v')} 95 | //' of type integer referencing the row number of \code{V}. 96 | //' 97 | //' @details The basic idea of the current recmap \emph{implementation}: 98 | //' 1. Compute the pseudo dual out of the overlapping map regions. 99 | //' 2. Determine the \emph{core region} by \code{index <- int(n / 2)}. 100 | //' 3. Place region by region along DFS skeleton of pseudo dual starting 101 | //' with the \emph{core region}. 102 | //' 103 | //' @note if a rectangle can not be placed, accept a non-\emph{feasible solution} 104 | //' (avoid solutions having a topology error higher than 100) 105 | //' Solving this constellation can be intensive in the computation, and due to the 106 | //' assumably low fitness value the candidate cartogram 107 | //' will be likely rejected by the metaheuristic. 108 | //' 109 | //' \emph{Time Complexity:} 110 | //' The time complexity is \eqn{O(n^2)}, where n is the number of regions. 111 | //' DFS is visiting each map region only once and therefore has 112 | //' time complexity \eqn{O(n)}. For each placement, a constant number of 113 | //' MBB intersection are called (max 360). MBB check is implemented using 114 | //' \code{std::set}, \code{insert}, \code{upper_bound}, \code{upper_bound} 115 | //' costs are \eqn{O(\log(n))}{O(log(n))}. 116 | //' However, the worst case for a range query is \eqn{O(n)}, if and only if dx or dy 117 | //' cover the whole x or y range. Q.E.D. 118 | //' 119 | //' \emph{Performance:} 120 | //' In praxis, computing on a 2.4 GHz Intel Core i7 machine (using only one core), using the 121 | //' 50 state U.S. map example, recmap can compute approximately 100 cartograms in one second. 122 | //' The number of MBB calls were 123 | //' (Min., Median, Mean, Max) = (1448, 2534, 3174, 17740), using in each run 124 | //' a different index order using the (\code{\link{sample}}) method. 125 | //' 126 | //' \emph{Geodetic datum:} the \code{recmap} algorithm is not transforming the 127 | //' geodetic datum, e.g., WGS84 or Swissgrid. 128 | //' 129 | //' @return 130 | //' Returns a \code{recmap} S3 object of the transformed map with new coordinates 131 | //' (x, y, dx, dy) plus additional columns containing information for topology 132 | //' error, relative position error, and the DFS number. 133 | //' The error values are thought to be used for fitness function of the 134 | //' metaheuristic. 135 | //' 136 | //' @aliases RecMap cartogram all.equal.recmap 137 | //' 138 | //' @author Christian Panse, 2016 139 | //' @references 140 | //' * \doi{10.18637/jss.v086.c01} 141 | //' * \doi{10.1109/INFVIS.2004.57} 142 | //' 143 | //' @examples 144 | //' map <- checkerboard(2) 145 | //' cartogram <- recmap(map) 146 | //' 147 | //' map 148 | //' cartogram 149 | //' 150 | //' op <- par(mfrow = c(1, 2)) 151 | //' plot(map) 152 | //' plot(cartogram) 153 | //' 154 | //' ## US example 155 | //' usa <- data.frame(x = state.center$x, 156 | //' y = state.center$y, 157 | //' # make the rectangles overlapping by correcting 158 | //' # lines of longitude distance. 159 | //' dx = sqrt(state.area) / 2 160 | //' / (0.8 * 60 * cos(state.center$y * pi / 180)), 161 | //' dy = sqrt(state.area) / 2 / (0.8 * 60), 162 | //' z = sqrt(state.area), 163 | //' name = state.name) 164 | //' 165 | //' usa$z <- state.x77[, 'Population'] 166 | //' US.Map <- usa[match(usa$name, 167 | //' c('Hawaii', 'Alaska'), nomatch = 0) == 0, ] 168 | //' 169 | //' plot.recmap(US.Map) 170 | //' US.Map |> recmap() |> plot() 171 | //' par(op) 172 | //' 173 | //' # define a fitness function 174 | //' recmap.fitness <- function(idxOrder, Map, ...){ 175 | //' Cartogram <- recmap(Map[idxOrder, ]) 176 | //' # a map region could not be placed; 177 | //' # accept only feasible solutions! 178 | //' if (sum(Cartogram$topology.error == 100) > 0){return (0)} 179 | //' 1 / sum(Cartogram$z / (sqrt(sum(Cartogram$z^2))) 180 | //' * Cartogram$relpos.error) 181 | //' } 182 | //' 183 | //' @export 184 | //' @md 185 | // [[Rcpp::export]] 186 | DataFrame recmap(DataFrame V, Rcpp::Nullable E = R_NilValue) { 187 | // access the columns 188 | NumericVector x = V["x"]; 189 | NumericVector y = V["y"]; 190 | NumericVector dx = V["dx"]; 191 | NumericVector dy = V["dy"]; 192 | 193 | 194 | NumericVector z = V["z"]; 195 | CharacterVector name = V["name"]; 196 | 197 | IntegerVector u = IntegerVector(); 198 | IntegerVector v = IntegerVector(); 199 | 200 | if (E.isNotNull()) { 201 | DataFrame pd = DataFrame(E); 202 | 203 | u = pd("u"); 204 | v = pd("v"); 205 | } 206 | 207 | 208 | NumericVector cartogram_x(x.size()); 209 | NumericVector cartogram_y(x.size()); 210 | NumericVector cartogram_dx(x.size()); 211 | NumericVector cartogram_dy(x.size()); 212 | 213 | NumericVector dfs_num(x.size()); 214 | NumericVector topology_error(x.size()); 215 | NumericVector relpos_error(x.size()); 216 | NumericVector relpos_nh_error(x.size()); 217 | // crecmap::crecmap X(Rcpp::as(x)); 218 | crecmap::RecMap X; 219 | 220 | // TODO(cp): setting and gettings are not optimal 221 | // think about operating on the R allocated memory and avoid copying. 222 | for (int i = 0; i < x.size(); i++) { 223 | std::string sname = Rcpp::as(name[i]); 224 | X.push_region(x[i], y[i], dx[i], dy[i], z[i], sname); 225 | } 226 | 227 | if (u.size() > 0 && v.size() >0){ 228 | for (int i = 0; i < u.size(); i++) { 229 | X.push_pd_edge(u[i] - 1, v[i] - 1); 230 | X.push_pd_edge(v[i] - 1, u[i] - 1); 231 | } 232 | X.run(false); 233 | }else{ 234 | X.run(true); 235 | } 236 | 237 | 238 | // Rcpp::Rcout << "Number of mbb intersection test calls = " 239 | // << X.get_intersect_count() << "\n"; 240 | for (int i = 0; i < x.size(); i++) { 241 | crecmap::map_region r = X.get_map_region(i); 242 | 243 | cartogram_x[i] = r.x; 244 | cartogram_y[i] = r.y; 245 | cartogram_dx[i] = r.dx; 246 | cartogram_dy[i] = r.dy; 247 | 248 | dfs_num[i] = r.dfs_num; 249 | topology_error[i] = r.topology_error; 250 | relpos_error[i] = r.relative_position_error; 251 | relpos_nh_error[i] = r.relative_position_neighborhood_error; 252 | } 253 | 254 | 255 | while (!X.warnings_empty()) { warning(X.warnings_pop()); } 256 | 257 | // Rcpp::exception 258 | 259 | // return a new data frame 260 | DataFrame dfout = DataFrame::create(_["x"]= cartogram_x, 261 | _["y"]= cartogram_y, 262 | _["dx"]= cartogram_dx, 263 | _["dy"]= cartogram_dy, 264 | _["z"]= z, 265 | _["name"]= name, 266 | _["dfs.num"] = dfs_num, 267 | _["topology.error"] = topology_error, 268 | _["relpos.error"] = relpos_error, 269 | _["relposnh.error"] = relpos_nh_error); 270 | CharacterVector v2 = {"recmap", "data.frame"}; 271 | dfout.attr("class") = v2; 272 | return (dfout); 273 | } 274 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | 4 | library(testthat) 5 | 6 | suppressPackageStartupMessages(library(recmap)) 7 | 8 | if (Sys.info()['machine'] == "arm64") GA::gaControl(useRcpp = FALSE) 9 | 10 | test_check("recmap") 11 | 12 | -------------------------------------------------------------------------------- /tests/testthat/test-get_angle.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("get_angle") 4 | 5 | test_that("get angle of two map regions", { 6 | 7 | expect_true(recmap:::get_angle(x0=0, y0=0, x1=0, y1=1) / pi == 0) 8 | expect_true(recmap:::get_angle(x0=0, y0=0, x1=0, y1=-1) / pi == 1 ) 9 | expect_true(recmap:::get_angle(x0=0, y0=0, x1=1, y1=-1) / pi == 0.75 ) 10 | expect_true(recmap:::get_angle(x0=0, y0=0, x1=-1, y1=-1) / pi == -0.75 ) 11 | expect_true(recmap:::get_angle(x0=0, y0=0, x1=-1, y1=1) / pi == -0.25 ) 12 | }) 13 | -------------------------------------------------------------------------------- /tests/testthat/test-jss2711.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("jss2711") 4 | 5 | test_that("reproducibility check for recmapGA using a 4x4 checkerboard (Figure 7)", { 6 | #skip_on_os(os='mac') 7 | 8 | seeds <- c(1, 1, 2, 2, 3, 3) 9 | 10 | res <- lapply(seeds, function(seed){ 11 | 12 | set.seed(seed); 13 | 14 | res <- recmapGA(V = checkerboard(4), 15 | pmutation = 0.25, 16 | parallel = FALSE) 17 | res$seed <- seed 18 | res}) 19 | 20 | # extract best solution for each run 21 | solutions <- lapply(res, function(x){x$GA@solution[1,]}) 22 | 23 | # solution must be identical on the same platform 24 | expect_identical(solutions[[1]], solutions[[2]]) 25 | expect_identical(solutions[[3]], solutions[[4]]) 26 | expect_identical(solutions[[5]], solutions[[6]]) 27 | }) 28 | 29 | test_that("cross-platform reproducibility check of Figures 11 (Switzerland))", { 30 | skip_on_cran() 31 | 32 | data(jss2711) 33 | Switzerland.recmap <- recmap(Switzerland$Map) 34 | 35 | expect_equal(Switzerland.recmap[, 'x'], Switzerland$Cartogram[, 'x'], tolerance = 0.001) 36 | expect_equal(Switzerland.recmap[, 'y'], Switzerland$Cartogram[, 'y'], tolerance = 0.001) 37 | expect_equal(Switzerland.recmap[, 'dx'], Switzerland$Cartogram[, 'dx'], tolerance = 0.001) 38 | expect_equal(Switzerland.recmap[, 'dy'], Switzerland$Cartogram[, 'dy'], tolerance = 0.001) 39 | 40 | }) 41 | 42 | test_that("cross-platform reproducibility check of Figures 12 (SBB))", { 43 | 44 | data(jss2711) 45 | SBB.recmap <- recmap(SBB$Map) 46 | 47 | expect_equal(SBB.recmap[, 'x'], SBB$Cartogram[, 'x'], tolerance = 0.001) 48 | expect_equal(SBB.recmap[, 'y'], SBB$Cartogram[, 'y'], tolerance = 0.001) 49 | expect_equal(SBB.recmap[, 'dx'], SBB$Cartogram[, 'dx'], tolerance = 0.001) 50 | expect_equal(SBB.recmap[, 'dy'], SBB$Cartogram[, 'dy'], tolerance = 0.001) 51 | 52 | }) 53 | 54 | test_that("cross-platform reproducibility check of Figures 13 (UK))", { 55 | 56 | 57 | data(jss2711) 58 | 59 | # note: map idx is in best solution order 60 | UK.recmap <- recmap(UK$Map) 61 | 62 | expect_equal(UK.recmap[, 'x'], UK$Cartogram[, 'x'], tolerance = 0.001) 63 | expect_equal(UK.recmap[, 'y'], UK$Cartogram[, 'y'], tolerance = 0.001) 64 | expect_equal(UK.recmap[, 'dx'], UK$Cartogram[, 'dx'], tolerance = 0.001) 65 | expect_equal(UK.recmap[, 'dy'], UK$Cartogram[, 'dy'], tolerance = 0.001) 66 | 67 | }) 68 | -------------------------------------------------------------------------------- /tests/testthat/test-recmap.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("recmap") 4 | 5 | test_that("input 2x2 checker board", { 6 | 7 | 8 | input.map <- data.frame(x = c(1, 1, 2, 2), 9 | y = c(1, 2, 1, 2), 10 | dx = rep(0.5, 4), 11 | dy = rep(0.5, 4), 12 | z = c(4, 1, 1, 4), 13 | name = c('a1', 'a2', 'b1', 'b2')) 14 | 15 | output.recmap <- recmap(input.map) 16 | 17 | expect_true(sum(abs(c(0.7250889, 1.0413167, 2.0000000, 2.0000000) - output.recmap$x)) < 1E-5) 18 | expect_true(sum(abs(c(0.6837722, 1.9586833, 1.0000000, 1.9586833) - output.recmap$y)) < 1E-5) 19 | expect_true(sum(abs(output.recmap$dx * 4 * output.recmap$dy - c(1.6, 0.4, 0.4, 1.6))) < 1E-6) 20 | expect_true(sum(c("x", "y", "dx", "dy", "name") %in% names(output.recmap)) == 5) 21 | }) 22 | -------------------------------------------------------------------------------- /tests/testthat/test-recmapGRASP.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("recmap Greedy Random Adaptive Search") 4 | 5 | test_that("input 4x4 checker board", { 6 | 7 | set.seed(1) 8 | rv <- recmapGRASP(checkerboard(4)) 9 | 10 | expect_s3_class(rv, "recmapGRASP") 11 | 12 | # solution <- c(7, 14, 3, 5, 8, 13, 10, 9, 16, 12, 4, 15, 11, 2, 6, 1) 13 | # expect_equal(rv$GRASP$solution, solution) 14 | }) 15 | -------------------------------------------------------------------------------- /tests/testthat/test-sp.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("sp") 4 | 5 | test_that("convert a SpatialPolygonsDataFrame object to a recmap object and back", { 6 | 7 | 8 | X <- checkerboard(8) 9 | XX <- as.recmap(X.sp <- as.SpatialPolygonsDataFrame(X)) 10 | 11 | expect_is(X, 'recmap') 12 | expect_is(X.sp, 'SpatialPolygonsDataFrame') 13 | expect_is(XX, 'recmap') 14 | 15 | expect_true(all.equal(X, XX)) 16 | }) 17 | -------------------------------------------------------------------------------- /tests/testthat/test-topoloy_error.R: -------------------------------------------------------------------------------- 1 | #R 2 | 3 | context("topology fitness") 4 | 5 | test_that("input 2x2 checker board for topoloy error test", { 6 | 7 | 8 | input.map <- data.frame(x = c(1, 1, 2, 2), 9 | y = c(1, 2, 1, 2), 10 | dx = rep(0.5, 4), 11 | dy = rep(0.5, 4), 12 | z = c(4, 1, 1, 4), 13 | name = c('a1', 'a2', 'b1', 'b2')) 14 | 15 | output.recmap <- recmap(input.map) 16 | 17 | # a1 loast a2 and b1 => d_T = 2 18 | # a2 lost a1 and b1 => d_T = 2 19 | # b1 lost a1 and a2 => d_T = 2 20 | # b2 is connected to all map regions => d_T = 0 21 | expect_true(sum(output.recmap$topology.error == c(2,2,2,0)) == 4) 22 | }) 23 | -------------------------------------------------------------------------------- /vignettes/graphics/rectangular_statistical_cartogram_construction_animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cpanse/recmap/92cfe7d254792b411d4f270f83a076761893a6d7/vignettes/graphics/rectangular_statistical_cartogram_construction_animation.gif -------------------------------------------------------------------------------- /vignettes/ieee.csl: -------------------------------------------------------------------------------- 1 | 2 | 340 | -------------------------------------------------------------------------------- /vignettes/jss2711.bib: -------------------------------------------------------------------------------- 1 | @Article{Finkel1974, 2 | author = {R. A. Finkel and J. L. Bentley}, 3 | title = {Quad Trees a Data Structure for Retrieval on 4 | Composite Keys}, 5 | journal = {Acta Informatica}, 6 | year = 1974, 7 | volume = 4, 8 | number = 1, 9 | pages = {1--9}, 10 | doi = {10.1007/bf00288933}, 11 | } 12 | 13 | @Article{pmid15136719, 14 | author = {M. T. Gastner and M. E. Newman}, 15 | title = {{{D}iffusion-Based Method for Producing 16 | Density-Equalizing Maps}}, 17 | journal = {Proceedings of the National Academy of Sciences of 18 | the United States of America}, 19 | year = 2004, 20 | volume = 101, 21 | number = 20, 22 | pages = {7499--7504}, 23 | doi = {10.1073/pnas.0400280101}, 24 | } 25 | 26 | @Manual{Rcartogram, 27 | title = {\pkg{Rcartogram}: Interface to Mark Newman's 28 | Cartogram Software}, 29 | author = {Duncan Temple Lang}, 30 | note = {\proglang{R} package version 0.2-2}, 31 | year = 2016, 32 | url = {https://github.com/omegahat/Rcartogram}, 33 | } 34 | 35 | @Manual{getcartr, 36 | title = {\pkg{getcartr}: Front End for \pkg{Rcartogram} 37 | Package}, 38 | author = {Chris Brunsdon and Martin Charlton}, 39 | year = 2014, 40 | note = {\proglang{R} package version 1.01}, 41 | url = {https://github.com/chrisbrunsdon/getcartr}, 42 | } 43 | 44 | @Article{colorspace, 45 | title = {Escaping {RGB}land: Selecting Colors for Statistical 46 | Graphics}, 47 | author = {Achim Zeileis and Kurt Hornik and Paul Murrell}, 48 | journal = {Computational Statistics \& Data Analysis}, 49 | year = 2009, 50 | volume = 53, 51 | number = 9, 52 | pages = {3259--3270}, 53 | doi = {10.1016/j.csda.2008.11.033}, 54 | } 55 | 56 | @Manual{mapproj, 57 | title = {\pkg{mapproj}: Map Projections}, 58 | author = {Doug McIlroy and Ray Brownrigg and Thomas P Minka 59 | and Roger Bivand}, 60 | year = 2015, 61 | note = {\proglang{R} package version 1.2-4}, 62 | url = {https://CRAN.R-project.org/package=mapproj}, 63 | } 64 | 65 | @Book{sp2013, 66 | author = {Roger S. Bivand and Edzer Pebesma and Virgilio 67 | G{\' o}mez-Rubio}, 68 | title = {Applied Spatial Data Analysis with \proglang{R}}, 69 | edition = {2nd}, 70 | year = 2013, 71 | publisher = {Springer-Verlag}, 72 | doi = {10.1007/978-1-4614-7618-4}, 73 | } 74 | 75 | @Manual{rbenchmark, 76 | title = {\pkg{rbenchmark}: Benchmarking Routine for 77 | \proglang{R}}, 78 | author = {Wacek Kusnierczyk}, 79 | year = 2012, 80 | note = {\proglang{R} package version 1.0.0}, 81 | url = {https://CRAN.R-project.org/package=rbenchmark}, 82 | } 83 | 84 | @Manual{noncensus, 85 | title = {\pkg{noncensus}: U.S. Census Regional and 86 | Demographic Data}, 87 | author = {John A. Ramey}, 88 | year = 2014, 89 | note = {\proglang{R} package version 0.1}, 90 | url = {https://CRAN.R-project.org/package=noncensus}, 91 | } 92 | 93 | @Manual{maps, 94 | title = {{\pkg{maps}: Draw Geographical Maps}}, 95 | author = {Richard A. Becker and Allan R. Wilks and Ray 96 | Brownrigg and Thomas P Minka and Alex Deckmyn}, 97 | year = 2016, 98 | note = {\proglang{R} package version 3.1.0}, 99 | url = {https://CRAN.R-project.org/package=maps}, 100 | } 101 | 102 | @Manual{shapefiles, 103 | title = {\pkg{shapefiles}: Read and Write ESRI Shapefiles}, 104 | author = {Ben Stabler}, 105 | year = 2013, 106 | note = {\proglang{R} package version 0.7}, 107 | url = {https://CRAN.R-project.org/package=shapefiles}, 108 | } 109 | 110 | @Book{Rcpp, 111 | title = {Seamless \proglang{R} and \proglang{C++} Integration 112 | with \pkg{Rcpp}}, 113 | author = {Dirk Eddelbuettel}, 114 | publisher = {Springer-Verlag}, 115 | address = {New York}, 116 | year = 2013, 117 | } 118 | 119 | @Manual{shiny, 120 | title = {\pkg{shiny}: Web Application Framework for 121 | \proglang{R}}, 122 | author = {Winston Chang and Joe Cheng and JJ Allaire and Yihui 123 | Xie and Jonathan McPherson}, 124 | year = 2016, 125 | note = {\proglang{R} package version 0.13.2}, 126 | url = {https://CRAN.R-project.org/package=shiny}, 127 | } 128 | 129 | @Article{GA, 130 | title = {\pkg{GA}: A Package for Genetic Algorithms in 131 | \proglang{R}}, 132 | author = {Luca Scrucca}, 133 | journal = {Journal of Statistical Software}, 134 | year = 2013, 135 | volume = 53, 136 | number = 4, 137 | pages = {1--37}, 138 | doi = {10.18637/jss.v053.i04}, 139 | } 140 | 141 | @Book{circle, 142 | author = {Danny Dorling}, 143 | title = {Area Cartograms: Their Use and Creation}, 144 | publisher = {Department of Geography, University of Bristol, 145 | England}, 146 | year = 1996, 147 | edition = {1st}, 148 | } 149 | 150 | @Article{GRASP, 151 | author = {Thomas A. Feo and Mauricio G. C. Resende}, 152 | title = {Greedy Randomized Adaptive Search Procedures}, 153 | journal = {Journal of Global Optimization}, 154 | year = 1995, 155 | volume = 6, 156 | number = 2, 157 | pages = {109--133}, 158 | doi = {10.1007/bf01096763}, 159 | } 160 | 161 | @Article{cartodraw, 162 | author = {Daniel A. Keim and Stephen C. North and Christian 163 | Panse}, 164 | title = {{CartoDraw: A Fast Algorithm for Generating 165 | Contiguous Cartograms}}, 166 | journal = {IEEE Transactions on Visualization and Computer Graphics}, 167 | volume = 10, 168 | number = 1, 169 | pages = {95--110}, 170 | year = 2004, 171 | doi = {10.1109/tvcg.2004.1260761}, 172 | } 173 | 174 | @Article{4015426, 175 | author = {Christian Panse and Mike Sips and Daniel A. Keim and Stephen C. North}, 176 | title = {{Visualization of Geo-spatial Point Sets via Global Shape Transformation and Local Pixel Placement}}, 177 | journal = {IEEE Transactions on Visualization and Computer Graphics}, 178 | volume = 12, 179 | number = 5, 180 | pages = {749--756}, 181 | year = 2006, 182 | doi = {10.1109/TVCG.2006.198}, 183 | } 184 | 185 | @InProceedings{recmap, 186 | author = {Roland Heilmann and Daniel A. Keim and Christian 187 | Panse and Mike Sips}, 188 | title = {{RecMap: Rectangular Map Approximations}}, 189 | booktitle = {{IEEE} {Symposium on Information Visualization}}, 190 | pages = {33--40}, 191 | year = 2004, 192 | doi = {10.1109/infvis.2004.57}, 193 | } 194 | 195 | @Article{ErwinRaisz, 196 | author = {Erwin Raisz}, 197 | title = {{The Rectangular Statistical Cartogram}}, 198 | journal = {{Geographical Review}}, 199 | volume = 24, 200 | number = 2, 201 | pages = {292--296 }, 202 | year = 1934, 203 | doi = {10.2307/208794}, 204 | } 205 | 206 | @InProceedings{Speckmann2004, 207 | author = {Marc J. {van Kreveld} and Bettina Speckmann}, 208 | title = {On Rectangular Cartograms}, 209 | booktitle = {Algorithms -- ESA 2004. ESA 2004}, 210 | series = {Lecture Notes in Computer Science}, 211 | volume = 3221, 212 | pages = {724--735}, 213 | year = 2004, 214 | editor = {Susanne Albers and Tomasz Radzik}, 215 | doi = {10.1007/978-3-540-30140-0_64}, 216 | } 217 | 218 | @Article{Speckmann2007, 219 | author = {Marc J. {van Kreveld} and Bettina Speckmann}, 220 | title = {On Rectangular Cartograms}, 221 | journal = {Computational Geometry}, 222 | volume = 37, 223 | number = 3, 224 | pages = {175--187}, 225 | year = 2007, 226 | doi = {10.1016/j.comgeo.2006.06.002}, 227 | } 228 | 229 | @InProceedings{Speckmann2012, 230 | author = {Kevin Buchin and Bettina Speckmann and Sander 231 | Verdonschot}, 232 | title = {Evolution Strategies for Optimizing Rectangular 233 | Cartograms}, 234 | editor = {Ningchuan Xiao and Mei{-}Po Kwan and Michael 235 | F. Goodchild and Shashi Shekhar}, 236 | booktitle = {Geographic Information Science. GIScience 2012}, 237 | series = {Lecture Notes in Computer Science}, 238 | volume = 7478, 239 | pages = {29--42}, 240 | year = 2012, 241 | doi = {10.1007/978-3-642-33024-7_3}, 242 | } 243 | 244 | @Article{Waldo, 245 | author = {Waldo Tobler}, 246 | title = {Thirty Five Years of Computer Cartograms}, 247 | journal = {The Annals of the Association of American Geographers}, 248 | volume = 94, 249 | number = 1, 250 | publisher = {Blackwell Publishing}, 251 | doi = {10.1111/j.1467-8306.2004.09401004.x}, 252 | pages = {58--73}, 253 | year = 2004, 254 | } 255 | 256 | @Article{TheStateoftheArtInCartograms, 257 | author = {Sabrina Nusrat and Stephen Kobourov}, 258 | title = {The State of the Art in Cartograms}, 259 | journal = {Computer Graphics Forum}, 260 | volume = 35, 261 | number = 3, 262 | year = 2016, 263 | pages = {619--642}, 264 | doi = {10.1111/cgf.12932}, 265 | } 266 | 267 | @Article{Buchin:2016, 268 | author = {Kevin Buchin and David Eppstein and Maarten L{\" 269 | o}ffler and Martin N{\" o}llenburg and Rodrigo 270 | Silveira}, 271 | title = {{Adjacency-Preserving Spatial Treemaps}}, 272 | journal = {Computational Geometry}, 273 | volume = 7, 274 | number = 1, 275 | year = 2016, 276 | pages = {100--122}, 277 | doi = {10.20382/jocg.v7i1a6}, 278 | } 279 | 280 | @Book{snyder1997flattening, 281 | title = {Flattening the Earth: Two Thousand Years of Map 282 | Projections}, 283 | author = {J. P. Snyder}, 284 | lccn = 92036750, 285 | year = 1997, 286 | publisher = {University of Chicago Press}, 287 | } 288 | 289 | @Manual{recmap-pkg, 290 | title = {\pkg{recmap}: Compute the Rectangular Statistical 291 | Cartogram}, 292 | author = {Christian Panse}, 293 | year = 2017, 294 | note = {\proglang{R} package version 0.5.24}, 295 | url = {https://CRAN.R-project.org/package=recmap}, 296 | } 297 | 298 | @Manual{R, 299 | title = {\proglang{R}: A Language and Environment for 300 | Statistical Computing}, 301 | author = {{\proglang{R} Core Team}}, 302 | organization = {\proglang{R} Foundation for Statistical Computing}, 303 | address = {Vienna, Austria}, 304 | year = 2017, 305 | url = {https://www.R-project.org/}, 306 | } 307 | 308 | @Article{sp1, 309 | title = {Classes and Methods for Spatial Data in 310 | \proglang{R}}, 311 | author = {E. J. Pebesma and R. S. Bivand}, 312 | year = 2005, 313 | journal = {\proglang{R} News}, 314 | number = 2, 315 | url = {https://CRAN.R-project.org/doc/Rnews/}, 316 | volume = 5, 317 | pages = {9--13}, 318 | } 319 | 320 | -------------------------------------------------------------------------------- /vignettes/recmap.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Draw your own Rectangular Statistical Cartogram with **recmap**" 3 | author: "Christian Panse" 4 | date: "`r Sys.Date()`" 5 | bibliography: 6 | - recmap.bib 7 | csl: ieee.csl 8 | output: 9 | tufte::tufte_html: default 10 | tufte::tufte_handout: 11 | toc: true 12 | citation_package: natbib 13 | latex_engine: xelatex 14 | vignette: > 15 | %\VignetteIndexEntry{Draw your own Rectangular Statistical Cartogram with recmap} 16 | %\VignetteEngine{knitr::rmarkdown} 17 | %\VignetteEncoding{UTF-8} 18 | --- 19 | 20 | # Introduction 21 | 22 | This package contains a C++ implementation of the RecMap algorithm 23 | [[@recmap]](http://dx.doi.org/10.1109/INFVIS.2004.57), [@2016arXiv160600464P] to draw maps according to 24 | given statistical values. These so-called cartograms or value-by-area-maps may 25 | be used to visualize any geospatial-related data, e.g., political, economic or 26 | public health data. 27 | The input consists of a map represented by overlapping rectangles. 28 | This map is defined by the following parameters for each map region: 29 | 30 | - a tuple of (x, y) values corresponding to the (longitude, latitude) position, 31 | - a tuple of (dx, dy) of expansion along (longitude, latitude), 32 | - and a statistical value z. 33 | 34 | The (x, y) coordinates represent the center of the minimal bounding boxes (MBB), 35 | The coordinates of the MBB are derived by adding or subtracting the (dx, dy) 36 | tuple accordingly. The tuple (dx, dy) also defines the ratio of the map region. 37 | The statistical values define the desired area of each map region. 38 | 39 | The output is a rectangular cartogram where the map regions are: 40 | 41 | - Non-overlapping, 42 | - connected, 43 | - ratio and area of each rectangle correspond to the desired areas, 44 | - rectangles are placed parallel to the axes. 45 | 46 | The construction heuristic places the rectangles in a way that important 47 | spatial constraints, in particular 48 | 49 | - the topology of the pseudo dual graph, 50 | - the relative position of MBB centers. 51 | 52 | are tried to be preserved. 53 | 54 | The ratios are preserved, and the area of each region corresponds to 55 | the as input given statistical value z. 56 | 57 | The graphic below depicts a typical example of a rectangular cartogram drawing. 58 | 59 | ```{r eval = TRUE, echo = FALSE} 60 | options(prompt = "R> ", 61 | continue = "+ ", 62 | width = 70, 63 | useFancyQuotes = FALSE, 64 | warn = -1) 65 | ``` 66 | 67 | ```{r fig.width=7, fig.height=3.5, fig.retina=2, fig.align='left', fig.cap="Rectangular Cartogram of the U.S. election 2004; The area corresponds to the number of electors (color indicates the party red: democrats / blue: Republican; the color intensity ~ outcome of the vote.). The graphic was computed by using the original implementation of the construction heuristic RecMap MP2 introduced in [@recmap].", echo=FALSE, warning=FALSE, comment="ccc", error=FALSE, message=FALSE} 68 | 69 | library(recmap) 70 | op <- par(mar = c(0,0,0,0), bg = NA) 71 | recmap:::.draw_recmap_us_state_ev() 72 | par(op) 73 | # detach("package:recmap", unload=TRUE) 74 | ``` 75 | 76 | # The Usage 77 | 78 | attach the package 79 | ```{r eval=TRUE, echo=TRUE, message=TRUE} 80 | library(recmap) 81 | ``` 82 | 83 | look into for documentation 84 | ```{r eval=FALSE} 85 | help(package="recmap") 86 | ``` 87 | 88 | ## Input - using the U.S. `state` Facts and Figures Dataset 89 | 90 | ```{r} 91 | usa <- data.frame(x = state.center$x, 92 | y = state.center$y, 93 | # make the rectangles overlapping by correcting lines of longitude distance 94 | dx = sqrt(state.area) / 2 / (0.8 * 60 * cos(state.center$y*pi/180)), 95 | dy = sqrt(state.area) / 2 / (0.8 * 60) , 96 | z = sqrt(state.area), 97 | name = state.name) 98 | ``` 99 | 100 | ## Compute Pseudo Dual Graph (PD) 101 | 102 | The rectangles have to overlap to compute the dual graph. This enables to 103 | generate valid input having only the (x, y) coordinates of the map region. 104 | 105 | ```{r fig.width=7, fig.height=3} 106 | library(recmap) 107 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 108 | plot.recmap(M <- usa[!usa$name %in% c("Hawaii", "Alaska"), ], 109 | col.text = 'black', lwd=2) 110 | ``` 111 | 112 | ## Apply a Metaheuristic 113 | 114 | The index order of the input map 115 | has an impact to the resulting cartogram. This algorithmic property is caused due to 116 | the computation of the dual graph. In [@recmap] a genetic algorithm was applied 117 | as metaheuristic. 118 | Due to the limited computing resources on the CRAN 119 | check systems, we do not use all the potential of the metaheuristic. 120 | 121 | 122 | Study the examples of the reference manual `?recmapGA` on 123 | how the [GA](https://cran.r-project.org/package=GA) package can be used. 124 | 125 | 126 | ## Objective Functions 127 | 128 | The **topology error** is an indicator of the deviation of 129 | the neighborhood relationships. 130 | The error is computed by counting the differences 131 | between dual graphs or adjacency graphs of map and cartogram 132 | 133 | The **relative positions error** 134 | measures the angle difference between all region centers. 135 | 136 | 137 | ## Output 138 | 139 | The output is a `data.frame` object. 140 | 141 | ```{r} 142 | Cartogram <- recmap(Map <- usa[!usa$name %in% c("Hawaii", "Alaska"), ]) 143 | head(Cartogram) 144 | ``` 145 | 146 | # Application 147 | 148 | ## Rectangular Map Approximation 149 | 150 | ```{r fig.width=8, fig.height=4.5, fig.align='left', fig.cap="Rectangular Map Approximation - rectangle area correspond to state area." } 151 | 152 | smp <- c(29, 22, 30, 3, 17, 8, 9, 41, 18, 15, 38, 35, 21, 23, 19, 6, 31, 32, 20, 153 | 28, 48, 4, 13, 14, 42, 37, 5, 16, 36 , 43, 25, 33, 12, 7, 39, 44, 2, 47, 154 | 45, 46, 24, 10, 1,11 ,40 ,26 ,27 ,34) 155 | 156 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 157 | plot(Cartogram.Area <- recmap(M[smp, ]), 158 | col.text = 'black', lwd = 2) 159 | ``` 160 | 161 | ```{r} 162 | summary.recmap(M) 163 | summary(Cartogram.Area) 164 | ``` 165 | 166 | ## `state.x77[, 'Population']` 167 | 168 | ```{r fig.width=8, fig.height=4, fig.align='left', fig.cap="Area ~ population estimate as of July 1, 1975;", warning=FALSE} 169 | 170 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 171 | usa$z <- state.x77[, 'Population'] 172 | M <- usa[!usa$name %in% c("Hawaii", "Alaska"), ] 173 | plot(Cartogram.Population <- recmap(M[order(M$x), ]), 174 | col.text = 'black', lwd = 2) 175 | 176 | ``` 177 | 178 | ```{r fig.width=8, fig.height=4, fig.align='left', fig.cap="Area ~ population estimate as of July 1, 1975; a better index order has been chosen to minimize the relative position error."} 179 | # index order 180 | 181 | smp <- c(20,47,4,40,9,6,32,33,3,10,34,22,2,28,15,12,39,7,42,45,19,13,43,30,24, 182 | 25,11,17,37,41,26,29,21,35,8,36,14,16,31,48,46,38,23,18,1,5,44,27) 183 | 184 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 185 | plot(Cartogram.Population <- recmap(M[smp,]), col.text = 'black', lwd = 2) 186 | ``` 187 | 188 | ## `state.x77[, 'Income']` 189 | 190 | ```{r fig.width=8, fig.height=4, fig.align='left', fig.cap="Area ~ capita income (1974);"} 191 | usa$z <- state.x77[, 'Income'] 192 | M <- usa[!usa$name %in% c("Hawaii", "Alaska"), ] 193 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 194 | plot(Cartogram.Income <- recmap(M[order(M$x),]), 195 | col.text = 'black', lwd = 2) 196 | ``` 197 | 198 | ## `state.x77[, 'Frost']` 199 | 200 | ```{r recmapGA, fig.width=8, fig.height=4, fig.align='left', warnings = FALSE, fig.cap="Area ~ mean number of days with minimum temperature below freezing (1931–1960) in capital or large city;", error = TRUE } 201 | usa$z <- state.x77[, 'Frost'] 202 | M <- usa[!usa$name %in% c("Hawaii", "Alaska"), ] 203 | op <- par(mfrow = c(1 ,1), mar = c(0, 0, 0, 0), bg = NA) 204 | gaControl("useRcpp" = FALSE) 205 | Frost <- recmapGA(M, seed = 1) 206 | plot(Frost$Cartogram, 207 | col.text = 'black', lwd = 2) 208 | ``` 209 | 210 | ```{r Frost, error=TRUE} 211 | summary(Frost) 212 | ``` 213 | 214 | More interactive examples using `state.x77` data are available by 215 | running the code snippet below. 216 | ```{r eval=FALSE} 217 | # Requires to install the suggested packages 218 | # install.packages(c('colorspace', 'maps', 'noncensus', 'shiny')) 219 | 220 | library(shiny) 221 | 222 | recmap_shiny <- system.file("shiny-examples", package = "recmap") 223 | shiny::runApp(recmap_shiny, display.mode = "normal") 224 | ``` 225 | 226 | ## Synthetic input maps - checkerboard 227 | 228 | Checkerboards provide examples of sets of map regions which 229 | do not have ideal cartogram solutions according to Definition 1 [@cartodraw]. 230 | 231 | 232 | ```{r fig.width=7, fig.height=2.5, fig.align='center', fig.retina=2, fig.cap="checkerboard fun - input, area of black regions have to be four times as big as white regions (left); solution found by a greedy random algorithm (middle); solution found by genetic algorithm (right)", fig.align='left'} 233 | op <- par(mar = c(0, 0, 0, 0), mfrow = c(1, 3), bg = NA) 234 | 235 | plot(checkerboard8x8 <- checkerboard(8), 236 | col=c('white','white','white','black')[checkerboard8x8$z]) 237 | 238 | # found by a greedy randomized search 239 | index.greedy <- c(8, 56, 18, 5, 13, 57, 3, 37, 62, 58, 7, 16, 40, 59, 17, 34, 240 | 29, 41, 46, 27, 54, 43, 2, 21, 38, 52, 31, 20, 28, 48, 1, 22, 241 | 55, 11, 25, 19, 50, 10, 24, 53, 47, 30, 45, 44, 32, 35, 51, 242 | 15, 64, 12, 14, 39, 26, 6, 42, 33, 4, 36, 63, 49, 60, 61, 9, 243 | 23) 244 | 245 | plot(Cartogram.checkerboard8x8.greedy <- recmap(checkerboard8x8[index.greedy,]), 246 | col = c('white','white','white','black')[Cartogram.checkerboard8x8.greedy$z]) 247 | 248 | # found by a genetic algorithm 249 | index.ga <- c(52, 10, 27, 63, 7, 20, 32, 18, 47, 28, 6, 55, 11, 61, 38, 50, 5, 250 | 21, 36, 34, 2, 22, 3, 1, 29, 57, 43, 4, 51, 58, 31, 49, 44, 25, 251 | 59, 33, 17, 40, 8, 41, 26, 37, 19, 56, 45, 35, 62, 53, 24, 64, 252 | 30, 15, 39, 12, 60, 48, 16, 23, 46, 42, 13, 54, 14, 9) 253 | 254 | plot(Cartogram.checkerboard8x8.ga <- recmap(checkerboard8x8[index.ga,]), 255 | col = c('white','white','white','black')[Cartogram.checkerboard8x8.ga$z]) 256 | 257 | ``` 258 | 259 | # History 260 | 261 | The work on RecMap was initiated by understanding the limits of contiguous 262 | cartogram drawing [@cartodraw] and after studying the visualizations 263 | drawn by Erwin Raisz [@ErwinRaisz]. 264 | The purpose of the first implementation [@recmap] was a feasibility 265 | check on how computer-generated rectangular cartograms with zero area error 266 | could look like. 267 | The `recmap` R package on CRAN provides a rectangular cartogram algorithm to be used by any 268 | R user. Now, it is easy to generate input (e.g., no complex polygon mesh), 269 | the code is maintainable (less than 500 lines of `C++-11` code), and the algorithm is made robust 270 | to the price of not having all features implemented (simplified local placement; 271 | no *empty space error*; no MP1 variant). 272 | Recent research publications on rectangular cartogram drawing include 273 | [@Speckmann2004], [@Speckmann2007], [@Speckmann2012], [@Buchin:2016]. 274 | However, according to a recent publication [@TheStateoftheArtInCartograms], 275 | `recmap` remains the only rectangular cartogram algorithm that 'maintains zero 276 | cartographic error'. 277 | The interested reader can find more details on the package usage and its implementation 278 | in [@2016arXiv160600464P]. 279 | 280 | # Session Info 281 | 282 | ```{r} 283 | sessionInfo() 284 | ``` 285 | 286 | # References 287 | 288 | -------------------------------------------------------------------------------- /vignettes/recmap.bib: -------------------------------------------------------------------------------- 1 | @Article{Buchin:2016, 2 | author = {Kevin Buchin and David Eppstein and Maarten Löffler and Martin Nöllenburg and Rodrigo Silveira}, 3 | title = {{Adjacency-preserving spatial treemaps}}, 4 | journal = {Computational Geometry}, 5 | volume = {7}, 6 | number = {1}, 7 | year = {2016}, 8 | pages = {100--122}, 9 | archivePrefix = {arXiv}, 10 | eprint = {1105.0398}, 11 | 12 | } 13 | 14 | @Article{2016arXiv160600464P, 15 | title = {{Rectangular Statistical Cartograms in R: The recmap Package}}, 16 | author = {Christian Panse}, 17 | journal = {{Journal of Statistical Software, Code Snippets}}, 18 | year = {2018}, 19 | volume = {86}, 20 | number = {1}, 21 | pages = {1--27}, 22 | doi = {10.18637/jss.v086.c01}, 23 | } 24 | 25 | @article{cartodraw, 26 | author = {Daniel A. Keim and 27 | Stephen C. North and 28 | Christian Panse}, 29 | title = {{CartoDraw: A Fast Algorithm for Generating Contiguous Cartograms}}, 30 | journal = {{IEEE} Trans. Vis. Comput. Graph.}, 31 | volume = {10}, 32 | number = {1}, 33 | pages = {95--110}, 34 | year = {2004}, 35 | url = {http://dx.doi.org/10.1109/TVCG.2004.1260761}, 36 | doi = {10.1109/TVCG.2004.1260761}, 37 | timestamp = {Tue, 08 Mar 2016 09:04:38 +0100}, 38 | biburl = {http://dblp.uni-trier.de/rec/bib/journals/tvcg/KeimNP04}, 39 | bibsource = {dblp computer science bibliography, http://dblp.org} 40 | } 41 | 42 | 43 | @proceedings{DBLP:conf/infovis/2004, 44 | editor = {Matthew O. Ward and 45 | Tamara Munzner}, 46 | title = {10th {IEEE} Symposium on Information Visualization (InfoVis 2004), 47 | 10-12 October 2004, Austin, TX, {USA}}, 48 | publisher = {{IEEE} Computer Society}, 49 | year = {2004}, 50 | url = {http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=9496}, 51 | isbn = {0-7803-8779-1}, 52 | timestamp = {Mon, 01 Dec 2014 19:24:58 +0100}, 53 | biburl = {http://dblp.uni-trier.de/rec/bib/conf/infovis/2004}, 54 | bibsource = {dblp computer science bibliography, http://dblp.org} 55 | } 56 | 57 | @inproceedings{recmap, 58 | author = {Roland Heilmann and 59 | Daniel A. Keim and 60 | Christian Panse and 61 | Mike Sips}, 62 | title = {{RecMap: Rectangular Map Approximations}}, 63 | booktitle = {10th {IEEE} {Symposium on Information Visualization (InfoVis 2004), 64 | 10-12 October 2004, Austin, TX, USA}}, 65 | pages = {33--40}, 66 | year = {2004}, 67 | crossref = {DBLP:conf/infovis/2004}, 68 | url = {http://dx.doi.org/10.1109/INFVIS.2004.57}, 69 | doi = {10.1109/INFVIS.2004.57}, 70 | timestamp = {Mon, 01 Dec 2014 19:24:58 +0100}, 71 | biburl = {http://dblp.uni-trier.de/rec/bib/conf/infovis/HeilmannKPS04}, 72 | bibsource = {dblp computer science bibliography, http://dblp.org} 73 | } 74 | 75 | 76 | @article{ErwinRaisz, 77 | author = {Erwin Raisz}, 78 | title = {{The Rectangular Statistical Cartogram}}, 79 | journal = {{Geographical Review.}}, 80 | volume = {24}, 81 | number = {2}, 82 | pages = {292--296 }, 83 | year = {1934}, 84 | url = {http://www.jstor.org/stable/208794 }, 85 | doi = {10.2307/208794} 86 | } 87 | 88 | 89 | 90 | @inproceedings{Speckmann2004, 91 | author = {Marc J. van Kreveld and 92 | Bettina Speckmann}, 93 | title = {On Rectangular Cartograms}, 94 | booktitle = {Algorithms - {ESA} 2004, 12th Annual European Symposium, Bergen, Norway, 95 | September 14-17, 2004, Proceedings}, 96 | pages = {724--735}, 97 | year = {2004}, 98 | crossref = {DBLP:conf/esa/2004}, 99 | url = {http://dx.doi.org/10.1007/978-3-540-30140-0_64}, 100 | doi = {10.1007/978-3-540-30140-0_64}, 101 | timestamp = {Wed, 10 Aug 2011 17:59:44 +0200}, 102 | biburl = {http://dblp.uni-trier.de/rec/bib/conf/esa/KreveldS04a}, 103 | bibsource = {dblp computer science bibliography, http://dblp.org} 104 | } 105 | 106 | @article{Speckmann2007, 107 | author = {Marc J. van Kreveld and 108 | Bettina Speckmann}, 109 | title = {On rectangular cartograms}, 110 | journal = {Comput. Geom.}, 111 | volume = {37}, 112 | number = {3}, 113 | pages = {175--187}, 114 | year = {2007}, 115 | url = {http://dx.doi.org/10.1016/j.comgeo.2006.06.002}, 116 | doi = {10.1016/j.comgeo.2006.06.002}, 117 | timestamp = {Fri, 21 Sep 2007 14:48:54 +0200}, 118 | biburl = {http://dblp.uni-trier.de/rec/bib/journals/comgeo/KreveldS07}, 119 | bibsource = {dblp computer science bibliography, http://dblp.org} 120 | } 121 | 122 | @inproceedings{Speckmann2012, 123 | author = {Kevin Buchin and 124 | Bettina Speckmann and 125 | Sander Verdonschot}, 126 | title = {Evolution Strategies for Optimizing Rectangular Cartograms}, 127 | booktitle = {Geographic Information Science - 7th International Conference, GIScience 128 | 2012, Columbus, OH, USA, September 18-21, 2012. Proceedings}, 129 | pages = {29--42}, 130 | year = {2012}, 131 | crossref = {DBLP:conf/giscience/2012}, 132 | url = {http://dx.doi.org/10.1007/978-3-642-33024-7_3}, 133 | doi = {10.1007/978-3-642-33024-7_3}, 134 | timestamp = {Thu, 06 Sep 2012 20:42:22 +0200}, 135 | biburl = {http://dblp.uni-trier.de/rec/bib/conf/giscience/BuchinSV12}, 136 | bibsource = {dblp computer science bibliography, http://dblp.org} 137 | } 138 | 139 | @article{CRANrecmap2016, 140 | author = {Christian Panse}, 141 | title = {{Compute the Rectangular Statistical Cartogram in R: The recmap Package}}, 142 | journal = {}, 143 | volume = {}, 144 | number = {}, 145 | pages = {}, 146 | year = {submitted}, 147 | url = {}, 148 | doi = {}, 149 | note = {} 150 | } 151 | 152 | @inproceedings{TheStateoftheArtInCartograms, 153 | author = {Sabrina Nusrat and Stephen Kobourov}, 154 | title = {{The State of the Art in Cartograms}}, 155 | booktitle = {{EuroVis 2016, 18th EG/VGTC Conference on Visualization}, 156 | {6-10 June 2016, Groningen, the Netherlands}}, 157 | year = {2016}, 158 | url = {http://www.cs.arizona.edu/~kobourov/star.pdf} 159 | } 160 | 161 | --------------------------------------------------------------------------------