├── .Rbuildignore ├── .gitignore ├── .travis.yml ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── EDM.R └── RcppExports.R ├── README.md ├── data └── Scribe.RData ├── man ├── BreakoutDetection-package.Rd ├── Scribe.RData.Rd └── breakout.Rd └── src ├── RcppExports.cpp ├── edm-multi.cpp ├── edm-per.cpp ├── edmTail.cpp ├── edmx.cpp ├── helper.cpp └── helper.h /.Rbuildignore: -------------------------------------------------------------------------------- 1 | LICENSE 2 | .travis.yml 3 | ^.*\.Rproj$ 4 | ^\.Rproj\.user$ 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | 4 | # Example code in package build process 5 | *-Ex.R 6 | 7 | # R data files from past sessions 8 | .Rdata 9 | 10 | # RStudio files 11 | .Rproj.user/ 12 | .Rproj.user 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Sample .travis.yml for R projects. 2 | # 3 | # See https://github.com/craigcitro/r-travis 4 | # https://github.com/eddelbuettel/r-travis/ 5 | 6 | language: c 7 | 8 | env: 9 | global: 10 | - _R_CHECK_FORCE_SUGGESTS_=FALSE 11 | 12 | before_install: 13 | - curl -OL http://raw.github.com/craigcitro/r-travis/master/scripts/travis-tool.sh 14 | - chmod 755 ./travis-tool.sh 15 | - ./travis-tool.sh bootstrap 16 | 17 | install: 18 | - ./travis-tool.sh install_r Rcpp ggplot2 19 | 20 | script: 21 | - ./travis-tool.sh run_tests 22 | 23 | notifications: 24 | email: 25 | on_success: change 26 | on_failure: change 27 | 28 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: BreakoutDetection 2 | Type: Package 3 | Title: Breakout Detection via Robust E-Statistics 4 | Version: 1.0.1 5 | Date: 2014-10-07 6 | Author: Nicholas A. James and Arun Kejariwal and David S. Matteson 7 | Maintainer: Nicholas A. James 8 | Description: This package performs single and multiple change point analysis of univariate time series. The procedures are designed to be robust to the existence of anomalies within the time series. 9 | License: GPL(>= 2) 10 | Imports: Rcpp (>= 0.11.2), ggplot2 11 | LinkingTo: Rcpp 12 | Packaged: 2014-10-09 22:48:03 UTC; njames 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | useDynLib(BreakoutDetection) 2 | export(breakout) 3 | importFrom(Rcpp, evalCpp) 4 | import(ggplot2) 5 | -------------------------------------------------------------------------------- /R/EDM.R: -------------------------------------------------------------------------------- 1 | breakout = function(Z, min.size = 30, method = 'amoc', ...){ 2 | 3 | #function used to scale observations to the interval [0,1] 4 | f = function(x) (x-min(x))/(max(x)-min(x)) 5 | 6 | if(class(Z)%in%c('numeric','integer') || ncol(Z) == 1) 7 | Zcounts = f(Z) 8 | else if(!('timestamp'%in%names(Z) && 'count'%in%names(Z))) 9 | stop("The supplied data must either be a vector, or a data.frame which has columns named 'timestamp' and 'count'.") 10 | else 11 | Zcounts = f(Z$count) 12 | 13 | #capture additional passed arguments 14 | argList = list(...) 15 | 16 | 17 | #Argument checking 18 | if(min.size < 2) 19 | stop("min.size must be an integer greater than 2.") 20 | if(!(method %in% c('amoc','multi'))) 21 | stop("method must be either 'amoc' or 'multi'.") 22 | 23 | #For single change detection check for necessary arguments 24 | #if they aren't present set default value 25 | if(method == 'amoc'){ 26 | multi = F 27 | val = argList[['alpha']] 28 | if(is.null(val) || val > 2 || val <= 0) 29 | alpha = 2 30 | else 31 | alpha = val 32 | 33 | val = argList[['sig.lvl']] 34 | if(is.null(val) || val <= 0 || val >= 1) 35 | sig.lvl = 0.05 36 | else 37 | sig.lvl = val 38 | 39 | val = argList[['nperm']] 40 | if(is.null(val) || val < 0) 41 | nperm = 0 42 | else 43 | nperm = floor(val) 44 | 45 | val = argList[['exact']] 46 | if(is.null(val) || !is.logical(val)) 47 | exact = T 48 | else 49 | exact = val 50 | } 51 | #For multiple change detection check for the degree argument 52 | #For beta and percent check is performed later 53 | else if(method == 'multi'){ 54 | multi = T 55 | degree = argList[['degree']] 56 | if(!(degree %in% c(0,1,2)) || is.null(degree)) 57 | degree = 1 58 | 59 | beta = argList[['beta']] 60 | percent = argList[['percent']] 61 | } 62 | #Select the correct EDM subroutine to run 63 | if(!multi && exact) 64 | Analysis = EDMX 65 | 66 | else if(!multi && !exact) 67 | Analysis = EDM_tail 68 | 69 | #Check for penalty type (beta or percent) 70 | else if(multi && ( !is.null(beta) || is.null(percent) )){ 71 | if(is.null(beta)) 72 | beta = 0.008 73 | penalty = beta 74 | Analysis = EDM_multi 75 | } 76 | 77 | else if(multi && is.null(beta) && !is.null(percent)){ 78 | penalty = percent 79 | Analysis = EDM_percent 80 | } 81 | 82 | #Perform analysis. Report runnint time and change locations 83 | if(!multi){ 84 | p1 = proc.time() 85 | retList = Analysis(Zcounts, min.size, alpha) 86 | if(nperm == 0){ 87 | p2 = proc.time() 88 | retList$time = as.numeric((p2-p1)[3]) 89 | retList$pval = NA 90 | } 91 | else{ 92 | over = 1 93 | for(i in 1:nperm){ 94 | Zcounts = sample(Zcounts) 95 | stat = Analysis(Zcounts, min.size, alpha) 96 | if(stat$stat >= retList$stat) 97 | over = over + 1 98 | } 99 | p2 = proc.time() 100 | retList$time = as.numeric((p2-p1)[3]) 101 | retList$pval = over/(nperm+1) 102 | if(retList$pval > sig.lvl) 103 | retList$loc = NULL 104 | } 105 | } 106 | 107 | else{ 108 | p1 = proc.time() 109 | retList = Analysis(Zcounts, min.size, penalty, degree) 110 | p2 = proc.time() 111 | retList$time = as.numeric((p2-p1)[3]) 112 | retList$pval = NA 113 | } 114 | 115 | #Check to see if plotting was desired and generate plot if necessary 116 | plotting = argList[['plot']] 117 | title = argList[['title']] 118 | xlab = argList[['xlab']] 119 | ylab = argList[['ylab']] 120 | 121 | if(!is.null(plotting) && plotting == T){ 122 | dateTime = T 123 | if(class(Z)%in%c('numeric','integer') || ncol(Z) == 1){ 124 | dateTime = F 125 | Z = data.frame(timestamp=1:length(Z), count = Z) 126 | } 127 | 128 | count <- x <- y <- xend <- yend <- 0L ## to make R CMD check happy 129 | g = ggplot2::ggplot(Z, ggplot2::aes(x=timestamp, y=count)) + ggplot2::theme_bw() + 130 | ggplot2::theme(panel.grid.minor=ggplot2::element_blank(), panel.grid.major=ggplot2::element_blank()) 131 | 132 | if(is.null(xlab)) 133 | xlab = " " 134 | if(is.null(ylab)) 135 | ylab = " " 136 | if(is.null(title)) 137 | title = " " 138 | 139 | g = g + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) + ggplot2::ggtitle(title) 140 | 141 | g = g + ggplot2::geom_line() 142 | if(!is.null(retList$loc)&& length(retList$loc)>0){ 143 | v = retList$loc 144 | v = c(0,v) 145 | for(j in 2:length(v)){ 146 | M = mean(Z$count[(v[j-1]+1):v[j]]) 147 | df2 = data.frame(Z$timestamp[v[j]], Z$timestamp[v[j]], -Inf, M) 148 | names(df2) = c('x','xend','y','yend') 149 | g = g + ggplot2::geom_segment(data=df2,ggplot2::aes(x=x,y=y,xend=xend,yend=yend,color='2'),linetype=2,size=1.2) 150 | g = g + ggplot2::guides(color=FALSE) 151 | } 152 | } 153 | if(dateTime) 154 | g = g + scale_x_datetime(expand=c(0,0)) + scale_y_continuous(expand=c(0,0)) 155 | else 156 | g = g + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0)) 157 | 158 | retList$plot = g 159 | } 160 | 161 | return(retList) 162 | } 163 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # This file was generated by Rcpp::compileAttributes 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | EDM_multi <- function(Z, min_size = 24L, beta = 0, degree = 0L) { 5 | .Call('BreakoutDetection_EDM_multi', PACKAGE = 'BreakoutDetection', Z, min_size, beta, degree) 6 | } 7 | 8 | EDM_percent <- function(Z, min_size = 24L, percent = 0, degree = 0L) { 9 | .Call('BreakoutDetection_EDM_percent', PACKAGE = 'BreakoutDetection', Z, min_size, percent, degree) 10 | } 11 | 12 | EDM_tail <- function(Z, min_size = 24L, alpha = 2, quant = 0.5) { 13 | .Call('BreakoutDetection_EDM_tail', PACKAGE = 'BreakoutDetection', Z, min_size, alpha, quant) 14 | } 15 | 16 | EDMX <- function(Z, min_size = 24L, alpha = 2) { 17 | .Call('BreakoutDetection_EDMX', PACKAGE = 'BreakoutDetection', Z, min_size, alpha) 18 | } 19 | 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BreakoutDetection R package 2 | 3 | [![Build Status](https://travis-ci.org/twitter/BreakoutDetection.png)](https://travis-ci.org/twitter/BreakoutDetection) 4 | 5 | BreakoutDetection is an open-source R package that makes breakout detection simple and fast. The BreakoutDetection package can be used in wide variety of contexts. For example, detecting breakout in user engagement post an A/B test, detecting [behavioral change](http://wiki.cbr.washington.edu/qerm/index.php/Behavioral_Change_Point_Analysis), or for problems in econometrics, financial engineering, political and social sciences. 6 | 7 | ## How the package works 8 | The underlying algorithm – referred to as E-Divisive with Medians (EDM) – employs energy statistics to detect divergence in mean. Note that EDM can also be used detect change in distribution in a given time series. EDM uses [robust statistical metrics](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470129905.html), viz., median, and estimates the statistical significance of a breakout through a permutation test. 9 | 10 | In addition, EDM is non-parametric. This is important since the distribution of production data seldom (if at all) follows the commonly assumed normal distribution or any other widely accepted model. Our experience has been that time series often contain more than one breakout. To this end, the package can also be used to detect multiple breakouts in a given time series. 11 | 12 | ## How to get started 13 | Install the R package using the following commands on the R console: 14 | ``` 15 | install.packages("devtools") 16 | devtools::install_github("twitter/BreakoutDetection") 17 | library(BreakoutDetection) 18 | ``` 19 | 20 | The function breakout is called to detect one or more statistically significant breakouts in the input time series. The documentation of the function breakout, which can be seen by using the following command, details the input arguments and the output of the function breakout. 21 | 22 | ``` 23 | help(breakout) 24 | ``` 25 | 26 | ## A simple example 27 | To get started, the user is recommended to use the example dataset which comes with the packages. Execute the following commands: 28 | 29 | ``` 30 | data(Scribe) 31 | res = breakout(Scribe, min.size=24, method='multi', beta=.001, degree=1, plot=TRUE) 32 | res$plot 33 | ``` 34 | 35 | From the plot, we observe that the input time series experiences two breakouts and also has quite a few anomalies. The two red vertical lines denote the locations of the breakouts detected by the EDM algorithm. 36 | -------------------------------------------------------------------------------- /data/Scribe.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/twitter/BreakoutDetection/7ae3fc49001f8c3f5f46c0b33c61f90e1e889df6/data/Scribe.RData -------------------------------------------------------------------------------- /man/BreakoutDetection-package.Rd: -------------------------------------------------------------------------------- 1 | \name{BreakoutDetection-package} 2 | \alias{BreakoutDetection-package} 3 | \alias{BreakoutDetection} 4 | \docType{package} 5 | \title{ 6 | Breakout Detector: Energy Divisive with Medians 7 | } 8 | \description{ 9 | This package performs single and multiple change point analysis of univariate time series. 10 | The procedures in this package are designed to be robust to the existence of anomalies/outliers 11 | within the time series. 12 | } 13 | \details{ 14 | \tabular{ll}{ 15 | Package: \tab BreakoutDetection\cr 16 | Type: \tab Package\cr 17 | Version: \tab 1.0.1\cr 18 | Date: \tab 2014-10-07\cr 19 | License: \tab GPL(>= 2)\cr 20 | } 21 | } 22 | \author{ 23 | Nicholas A. James, Arun Kejariwal, David S. Matteson 24 | 25 | Maintainer: Nicholas A. James 26 | } 27 | \references{ 28 | Nicholas A. James, Arun Kejariwal, David S. Matteson, "Leveraging Cloud Data to Mitigate User Experience from 'Breaking Bad': The Twitter Approach, 2014 29 | } 30 | -------------------------------------------------------------------------------- /man/Scribe.RData.Rd: -------------------------------------------------------------------------------- 1 | \name{Scribe} 2 | \alias{Scribe} 3 | \docType{data} 4 | \title{ 5 | %% ~~ data name/kind ... ~~ 6 | Reported system metric 7 | } 8 | \description{ 9 | Reported scribe lookup values 10 | 11 | } 12 | \usage{data(Scribe)} 13 | \format{ 14 | A numeric vector of reported observation values. 15 | } 16 | \examples{ 17 | data(BreakoutDetection/data/ACGH.RData) 18 | } 19 | \keyword{datasets} 20 | 21 | -------------------------------------------------------------------------------- /man/breakout.Rd: -------------------------------------------------------------------------------- 1 | \name{breakout} 2 | \alias{breakout} 3 | \title{ 4 | Breakout Detector: Energy Divisive with Medians 5 | } 6 | \description{ 7 | A technique for robustly, i.e., in the presence of anomalies, detecting single or multiple change points in univariate time series. 8 | } 9 | \usage{ 10 | breakout(Z, min.size = 30, method = 'amoc', ...) 11 | } 12 | 13 | \arguments{ 14 | \item{Z}{ 15 | The input time series. This is either a numeric vector or a data.frame which has 'timestamp' and 'count' components. 16 | } 17 | \item{min.size}{ 18 | The minimum number of observations between change points. 19 | } 20 | \item{method}{ 21 | Method must be one of either 'amoc' (At Most One Change) or 'multi' (Multiple Changes). For 'amoc' at most one change point 22 | location will be returned. 23 | } 24 | \item{...}{ 25 | See the details section for information about additional arguments. 26 | } 27 | } 28 | 29 | \details{ 30 | The additional arguments that can be supplied depend upon whether single ('amoc') or multiple ('multi') change point 31 | analysis is being performed. 32 | 33 | In both cases the following arguments are accepted: 34 | \itemize{ 35 | \item \code{plot:} A flag indicating if a plot of the time series along with the estimated change point, indicated by vertical lines, should also be returned. 36 | \item \code{xlab:} X-axis label if plotting is enabled. 37 | \item \code{ylab:} Y-axis label if plotting is enabled. 38 | \item \code{title:} Plot title if plotting is enabled. 39 | } 40 | 41 | For singe change analysis, the following arguments are accepted: 42 | \itemize{ 43 | \item \code{alpha:} 44 | The alpha parameter used to weight the distance between observations. This is a real number in the interval (0,2]. The default value is \code{alpha=2}. 45 | \item \code{exact:} 46 | This flag is for selecting the use of true medians (\code{TRUE}) or approximate medians (\code{FALSE}) when determining change points. The default value is \code{exact=TRUE}. 47 | \item \code{sig.lvl:} 48 | Once a change point is found its statistical significance is determined through a hypothesis test. \code{sig.lvl} specifies the significance for the hypothesis test. The default value is \code{sig.lvl=0.05}. 49 | \item \code{nperm:} 50 | The number of permutations to perform in order to obtain an approximate p-value. If \code{nperm=0} then then permutation test is not 51 | performed. The default value is \code{nperm=0}. 52 | } 53 | 54 | For multiple change analysis, the following arguments are accepted: 55 | \itemize{ 56 | \item \code{degree:} 57 | The degree of the penalization polynomial. \code{degree} can take the values 0, 1, and 2. The default value is \code{degree=1}. 58 | 59 | \item \code{beta:} 60 | A real numbered constant used to further control the amount of penalization. This is the default form of penalization, if neither (or both) \code{beta} or (and) \code{percent} are supplied this argument will be used. The default value is \code{beta=0.008}. 61 | 62 | \item \code{percent:} 63 | A real numbered constant used to further control the amount of penalization. This value specifies the minimum percent change in the goodness of fit statistic to consider adding an additional change point. A value of 0.25 corresponds to a 25\% increase. \code{percent} doesn't have a default value. 64 | } 65 | 66 | } 67 | 68 | \value{ 69 | The returned value is a list with the following components. 70 | \item{loc}{ 71 | The estimated change point location(s). 72 | } 73 | \item{time}{ 74 | The amount of required processing time, in seconds. 75 | } 76 | \item{pval}{ 77 | The approximate p-value obtained from the permutation test. When \code{nperm=0} or \code{method='multi'}, \code{pval=NA}. 78 | } 79 | \item{plot}{ 80 | A ggplot graphical object if plotting was requested by the user. The supplied image is of the input time series along with 81 | the estimated change point location(s). 82 | } 83 | } 84 | 85 | \references{ 86 | Nicholas A. James, Arun Kejariwal, David S. Matteson, "Leveraging Cloud Data to Mitigate User Experience from 'Breaking Bad': The Twitter Approach, 2014 87 | } 88 | 89 | \examples{ 90 | library(BreakoutDetection) 91 | data(Scribe) 92 | res = breakout(Scribe, min.size=24, method='multi', beta=.001, degree=1, plot=TRUE) 93 | res$plot 94 | } 95 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // This file was generated by Rcpp::compileAttributes 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | // EDM_multi 9 | List EDM_multi(const NumericVector& Z, int min_size = 24, double beta = 0, int degree = 0); 10 | RcppExport SEXP BreakoutDetection_EDM_multi(SEXP ZSEXP, SEXP min_sizeSEXP, SEXP betaSEXP, SEXP degreeSEXP) { 11 | BEGIN_RCPP 12 | SEXP __sexp_result; 13 | { 14 | Rcpp::RNGScope __rngScope; 15 | Rcpp::traits::input_parameter< const NumericVector& >::type Z(ZSEXP ); 16 | Rcpp::traits::input_parameter< int >::type min_size(min_sizeSEXP ); 17 | Rcpp::traits::input_parameter< double >::type beta(betaSEXP ); 18 | Rcpp::traits::input_parameter< int >::type degree(degreeSEXP ); 19 | List __result = EDM_multi(Z, min_size, beta, degree); 20 | PROTECT(__sexp_result = Rcpp::wrap(__result)); 21 | } 22 | UNPROTECT(1); 23 | return __sexp_result; 24 | END_RCPP 25 | } 26 | // EDM_percent 27 | List EDM_percent(const NumericVector& Z, int min_size = 24, double percent = 0, int degree = 0); 28 | RcppExport SEXP BreakoutDetection_EDM_percent(SEXP ZSEXP, SEXP min_sizeSEXP, SEXP percentSEXP, SEXP degreeSEXP) { 29 | BEGIN_RCPP 30 | SEXP __sexp_result; 31 | { 32 | Rcpp::RNGScope __rngScope; 33 | Rcpp::traits::input_parameter< const NumericVector& >::type Z(ZSEXP ); 34 | Rcpp::traits::input_parameter< int >::type min_size(min_sizeSEXP ); 35 | Rcpp::traits::input_parameter< double >::type percent(percentSEXP ); 36 | Rcpp::traits::input_parameter< int >::type degree(degreeSEXP ); 37 | List __result = EDM_percent(Z, min_size, percent, degree); 38 | PROTECT(__sexp_result = Rcpp::wrap(__result)); 39 | } 40 | UNPROTECT(1); 41 | return __sexp_result; 42 | END_RCPP 43 | } 44 | // EDM_tail 45 | List EDM_tail(NumericVector& Z, int min_size = 24, double alpha = 2, double quant = 0.5); 46 | RcppExport SEXP BreakoutDetection_EDM_tail(SEXP ZSEXP, SEXP min_sizeSEXP, SEXP alphaSEXP, SEXP quantSEXP) { 47 | BEGIN_RCPP 48 | SEXP __sexp_result; 49 | { 50 | Rcpp::RNGScope __rngScope; 51 | Rcpp::traits::input_parameter< NumericVector& >::type Z(ZSEXP ); 52 | Rcpp::traits::input_parameter< int >::type min_size(min_sizeSEXP ); 53 | Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP ); 54 | Rcpp::traits::input_parameter< double >::type quant(quantSEXP ); 55 | List __result = EDM_tail(Z, min_size, alpha, quant); 56 | PROTECT(__sexp_result = Rcpp::wrap(__result)); 57 | } 58 | UNPROTECT(1); 59 | return __sexp_result; 60 | END_RCPP 61 | } 62 | // EDMX 63 | List EDMX(const NumericVector& Z, int min_size = 24, double alpha = 2); 64 | RcppExport SEXP BreakoutDetection_EDMX(SEXP ZSEXP, SEXP min_sizeSEXP, SEXP alphaSEXP) { 65 | BEGIN_RCPP 66 | SEXP __sexp_result; 67 | { 68 | Rcpp::RNGScope __rngScope; 69 | Rcpp::traits::input_parameter< const NumericVector& >::type Z(ZSEXP ); 70 | Rcpp::traits::input_parameter< int >::type min_size(min_sizeSEXP ); 71 | Rcpp::traits::input_parameter< double >::type alpha(alphaSEXP ); 72 | List __result = EDMX(Z, min_size, alpha); 73 | PROTECT(__sexp_result = Rcpp::wrap(__result)); 74 | } 75 | UNPROTECT(1); 76 | return __sexp_result; 77 | END_RCPP 78 | } 79 | -------------------------------------------------------------------------------- /src/edm-multi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include"helper.h" 6 | 7 | using namespace Rcpp; 8 | using namespace std; 9 | 10 | //Z: time series 11 | //min_size: minimum segment size 12 | //beta: penalization term for the addition of a change point 13 | 14 | // [[Rcpp::export]] 15 | List EDM_multi(const NumericVector& Z, int min_size=24, double beta=0, int degree=0){ 16 | 17 | //identify which type of penalization to use 18 | double (*G)(double); 19 | switch(degree){ 20 | case 1: G=Linear; 21 | break; 22 | case 2: G=Quadratic; 23 | break; 24 | default: G=Const; 25 | break; 26 | } 27 | 28 | int n = Z.size(); 29 | if(beta < 0)//assume that beta is a positive number 30 | beta = -beta; 31 | vector prev(n+1,0);//store optimal location of previous change point 32 | vector number(n+1,0);//store the number of change points in optimal segmentation 33 | vector F(n+1,-3);//store optimal statistic value 34 | //F[s] is calculated using observations { Z[0], Z[1], ..., Z[s-1] } 35 | 36 | //trees used to store the "upper half" of the considered observations 37 | multiset right_min, left_min; 38 | //trees used to store the "lower half" of the considered observations 39 | multiset > right_max, left_max; 40 | 41 | //Iterate over possible locations for the last change 42 | for(int s=2*min_size; s prev[t-1]){ 62 | for(int i=prev[t-1]; i F[s]){ 76 | number[s] = number[t] + 1; 77 | F[s] = tmp; 78 | prev[s] = t; 79 | } 80 | } 81 | } 82 | 83 | //obtain list of optimal change point estimates 84 | IntegerVector ret; 85 | int at = n; 86 | while(at){ 87 | if(prev[at])//don't insert 0 as a change point estimate 88 | ret.push_back(prev[at]); 89 | at = prev[at]; 90 | } 91 | sort(ret.begin(),ret.end()); 92 | 93 | //return statment used for debugging 94 | //return List::create(_["loc"]=ret, _["F"]=F, _["number"]=number,_["prev"]=prev); 95 | 96 | return List::create(_["loc"]=ret); 97 | } 98 | -------------------------------------------------------------------------------- /src/edm-per.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Penalizes based on percent chagne in the statistic value. 3 | Linear penalty means that each new breakout must result in an at least X% increast 4 | Quadratic penalty means that each new brekaout must result in at least an (X*k)% increase for k breakouts 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include"helper.h" 12 | 13 | using namespace Rcpp; 14 | using namespace std; 15 | 16 | // [[Rcpp::export]] 17 | List EDM_percent(const NumericVector& Z, int min_size=24, double percent=0, int degree=0){ 18 | //Z: time series 19 | //min_size: minimum segment size 20 | //beta: penalization term for the addition of a change point 21 | 22 | //identify which type of penalization to use 23 | double (*G)(double); 24 | switch(degree){ 25 | case 1: G=Linear; 26 | break; 27 | case 2: G=Quadratic; 28 | break; 29 | default: G=Const; 30 | break; 31 | } 32 | 33 | int n = Z.size(); 34 | 35 | vector prev(n+1,0);//store optimal location of previous change point 36 | vector number(n+1,0);//store the number of change points in optimal segmentation 37 | vector F(n+1,0);//store optimal statistic value 38 | //F[s] is calculated using observations { Z[0], Z[1], ..., Z[s-1] } 39 | 40 | //trees used to store the "upper half" of the considered observations 41 | multiset right_min, left_min; 42 | //trees used to store the "lower half" of the considered observations 43 | multiset > right_max, left_max; 44 | 45 | //Iterate over possible locations for the last change 46 | for(int s=2*min_size; s prev[t-1]){ 66 | for(int i=prev[t-1]; i(s-prev[t]),2) ); 77 | double tmp = F[t] + normalize * std::pow(static_cast(left_median - right_median),2); 78 | //Find best location for change point. check % condition later 79 | if(tmp > F[s]){ 80 | number[s] = number[t] + 1; 81 | F[s] = tmp; 82 | prev[s] = t; 83 | } 84 | } 85 | //check to make sure we meet the percent change requirement 86 | if( prev[s]){ 87 | if(F[s] - F[prev[s]] < percent*G(number[prev[s]])*F[prev[s]]){ 88 | number[s] = number[prev[s]]; 89 | F[s] = F[prev[s]]; 90 | prev[s] = prev[prev[s]]; 91 | } 92 | } 93 | } 94 | 95 | //obtain list of optimal change point estimates 96 | IntegerVector ret; 97 | int at = n; 98 | while(at){ 99 | if(prev[at])//don't insert 0 as a change point estimate 100 | ret.push_back(prev[at]); 101 | at = prev[at]; 102 | } 103 | sort(ret.begin(),ret.end()); 104 | 105 | //return statment for debugging 106 | //return List::create(_["loc"]=ret, _["F"]=F, _["number"]=number,_["prev"]=prev); 107 | 108 | return List::create(_["loc"]=ret); 109 | } 110 | -------------------------------------------------------------------------------- /src/edmTail.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This version calculates the between distance using the delta points around the change point estimate. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace Rcpp; 12 | 13 | //Class used to hold all the information about the 14 | //breakout location and the interval trees 15 | struct Information{ 16 | NumericVector A, B, AB; 17 | double best_stat; 18 | int best_loc, best_t2; 19 | int min_size, b; 20 | 21 | Information(int, int); 22 | }; 23 | 24 | Information::Information(int bb, int m){ 25 | A = NumericVector(1<<(bb+1)); 26 | B = NumericVector(1<<(bb+1)); 27 | AB = NumericVector(1<<(bb+1)); 28 | b = bb; 29 | best_stat = best_loc = best_t2 = -3; 30 | min_size = m; 31 | } 32 | 33 | /*void printInformation(Information& info){ 34 | std::cout<<"best_stat: "<= N) 57 | break; 58 | if(x[i] == k){//Exactly k elements in this node's subtree. So can terminate early 59 | //Return a weighted combination of the child node medians 60 | double lWeight = x[j]/(x[j]+x[j+1]); 61 | double rWeight = 1 - lWeight; 62 | double lu, rl; 63 | lu = (u+l)/2; 64 | rl = (u+lu)/2; 65 | return lWeight*(quant*(lu-l)+l) + rWeight*(quant*(u-rl)+rl); 66 | } 67 | else if(x[j] >= k){//More than k elements in node's left child's subtree, move to left child 68 | i = j; 69 | u = (l+u)/2; 70 | } 71 | else if(x[j] < k){//Not enough elements in node's left child's subtree, move to right child 72 | k -= x[j]; 73 | i = j+1; 74 | l = (l+u)/2; 75 | } 76 | } 77 | return quant*(u-l)+l; 78 | } 79 | 80 | IntegerVector AddToTree(int B, NumericVector& x){ 81 | IntegerVector A(1<<(B+1)); 82 | NumericVector::iterator i; 83 | for(i = x.begin(); i < x.end(); ++i){//Iterage over items we wish to add to the tree 84 | int index = GetIndex(B,*i); 85 | while(index){ 86 | ++A[index]; 87 | index /= 2; 88 | } 89 | } 90 | return A; 91 | } 92 | 93 | // [[Rcpp::export]] 94 | List EDM_tail(NumericVector& Z, int min_size=24, double alpha=2, double quant=0.5){ 95 | 96 | int N = Z.size(); 97 | int eps = (int)std::ceil( std::log(N) ); 98 | eps = std::max( eps, 10 ); 99 | 100 | Information info(eps,min_size); 101 | 102 | int tau1 = info.min_size; 103 | int tau2 = tau1 * 2; 104 | 105 | 106 | 107 | //Populate trees and calculate statistic value for starting configuration of 108 | //2 min_size segments 109 | for(int i=0; i info.best_stat){ 169 | info.best_stat = stat; 170 | info.best_loc = tau1; 171 | info.best_t2 = tau2; 172 | } 173 | } 174 | 175 | bool forward_move = false; 176 | //Initial consideration of other possible locations for tau1 177 | while(tau1 < N-min_size){ 178 | //"warm start" to update tree and statistic value for other prefix series 179 | if(forward_move){ 180 | ForwardUpdate(Z, info, tau1, quant, alpha); 181 | } 182 | else{ 183 | BackwardUpdate(Z, info, tau1, quant, alpha); 184 | } 185 | forward_move = !forward_move; 186 | } 187 | 188 | //return statment for debugging 189 | //return List::create(_["loc"]=info.best_loc, _["tail"]=info.best_t2, _["stat"]=info.best_stat); 190 | 191 | return List::create(_["loc"]=info.best_loc, _["stat"]=info.best_stat); 192 | } 193 | 194 | void ForwardUpdate(NumericVector& Z, Information& info, int& tau1, double quant, double alpha){ 195 | 196 | int min_size = info.min_size; 197 | int tau2 = tau1 + min_size; 198 | ++tau1; 199 | int N = Z.size(), index; 200 | //Update A tree 201 | for(int i=tau1-min_size; i info.best_stat){ 287 | info.best_stat = stat; 288 | info.best_loc = tau1; 289 | info.best_t2 = tau2; 290 | } 291 | } 292 | } 293 | 294 | void BackwardUpdate(NumericVector& Z, Information& info, int& tau1, double quant, double alpha){ 295 | 296 | int min_size = info.min_size; 297 | int tau2 = tau1 + min_size; 298 | ++tau1; 299 | int N = Z.size(), index; 300 | //Update A tree 301 | for(int i=tau1-min_size; i=tau1+min_size; --tau2){ 379 | index = GetIndex(info.b,Z[tau2-1]-Z[tau2-2]); 380 | while(index){ 381 | --info.B[index]; 382 | index /= 2; 383 | } 384 | qb = std::pow( GetQuantile(info.B,quant), alpha); 385 | 386 | double stat = 2*qc - qa - qb; 387 | stat *= (double)(tau2-tau1)*tau1/tau2; 388 | 389 | if(stat > info.best_stat){ 390 | info.best_stat = stat; 391 | info.best_loc = tau1; 392 | info.best_t2 = tau2; 393 | } 394 | } 395 | } 396 | -------------------------------------------------------------------------------- /src/edmx.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Robust estimation of 2[mean(X)-mean(Y)]^2 time normalization factor 3 | This is the E-Divisive E-statistic when alpha = 2 4 | Instead of calculating mean(X) we calculate median(X), and similarly for Y 5 | */ 6 | 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace Rcpp; 14 | 15 | void AddToHeaps(std::priority_queue, std::greater >& m, 16 | std::priority_queue& M, double x); 17 | 18 | double getMedian(const std::priority_queue, std::greater >& m, 19 | const std::priority_queue& M); 20 | 21 | double Median(const NumericVector& Z, int a, int b){ 22 | //Calculate the median of the values in { Z[i] : a <= i < b } 23 | std::vector x(Z.begin()+a, Z.begin()+b); 24 | int n = x.size(), h=n/2; 25 | 26 | if( n&1){// n is odd 27 | std::nth_element(x.begin(),x.begin()+h,x.end()); 28 | return x[h]; 29 | } 30 | else{// n is even 31 | double y1,y2; 32 | std::nth_element(x.begin(),x.begin()+h,x.end()); 33 | y1 = x[h]; 34 | std::nth_element(x.begin(),x.begin()+h-1,x.end()); 35 | y2 = x[h-1]; 36 | return (y1+y2)/2; 37 | } 38 | } 39 | 40 | // [[Rcpp::export]] 41 | List EDMX(const NumericVector& Z, int min_size = 24, double alpha=2){ 42 | 43 | alpha = 2; //Not used, just here for uniform funciton signature 44 | 45 | std::priority_queue LeftMax; 46 | std::priority_queue, std::greater > LeftMin; 47 | 48 | double stat = -3, stat_best = -3, t1=0.0, t2; 49 | int tau1, tau2; 50 | int N = Z.size(); 51 | for(int i=0; i RightMax; 57 | std::priority_queue, std::greater > RightMin; 58 | double medL = getMedian(LeftMin, LeftMax); 59 | 60 | //Add first set of elements to the heaps for the right segment 61 | for(NumericVector::const_iterator i=Z.begin()+tau1; i!=Z.begin()+tau1+min_size-1; ++i) 62 | AddToHeaps(RightMin, RightMax, *i); 63 | 64 | for(tau2=tau1+min_size; tau2 stat_best){ 72 | t1 = tau1; 73 | t2 = tau2; 74 | stat_best = stat; 75 | } 76 | } 77 | } 78 | 79 | //return statment for debugging 80 | //return List::create(_["loc"]=t1, _["tail"]=t2, _["stat"]=stat_best); 81 | 82 | return List::create(_["loc"]=t1, _["stat"]=stat_best); 83 | } 84 | 85 | // Use 2 heaps to keep track of the median (can also be adjusted for other quantiles). One heap 86 | // for the "larger" and one heap for the "smaller" observations. Simple to update for streaming 87 | // data ( O(log n) ) and find median ( O(1) ). 88 | 89 | double getMedian(const std::priority_queue, std::greater >& m, 90 | const std::priority_queue& M){ 91 | 92 | if(m.size() > M.size()) // There are an odd number of observations 93 | return m.top(); 94 | else if(M.size() > m.size()) // There are an odd number of observations 95 | return M.top(); 96 | else // There are an even number of obersations 97 | return (m.top()+M.top())/2; 98 | } 99 | 100 | void AddToHeaps(std::priority_queue, std::greater >& m, 101 | std::priority_queue& M, double x){ 102 | 103 | // decide on initial heap to place element into 104 | if(m.empty() || x < m.top()) 105 | M.push(x); 106 | else 107 | m.push(x); 108 | // make sure that heaps are balanced 109 | if(m.size() > M.size() + 1){ 110 | M.push( m.top() ); 111 | m.pop(); 112 | } 113 | else if(M.size() > m.size() + 1){ 114 | m.push( M.top() ); 115 | M.pop(); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/helper.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | 9 | extern double Linear(double x){ return 1;} 10 | extern double Const(double x){ return 0;} 11 | extern double Quadratic(double x){ return 2*x+1;} 12 | 13 | 14 | /* 15 | Use 2 multisets (red-black trees) to keep track of the median. One tree for the larger (m) and 16 | one for the smaller (M) observations. Insertion and deletion in O(log(n)) and find 17 | the median in O(1), additional memory use is O(n). 18 | */ 19 | 20 | //insert x into the appropriate tree 21 | extern void insert_element(multiset& m, multiset >& M, double x){ 22 | 23 | if(m.empty() || x < *(m.begin())) 24 | M.insert(x); 25 | else 26 | m.insert(x); 27 | if(m.size() > M.size() + 1){ 28 | multiset::iterator i; 29 | i = m.begin(); 30 | M.insert(*i); 31 | m.erase(m.begin()); 32 | } 33 | else if(M.size() > m.size() + 1){ 34 | multiset >::iterator i; 35 | i = M.begin(); 36 | m.insert(*i); 37 | M.erase(M.begin()); 38 | } 39 | } 40 | 41 | //given a pair of trees obtain the median 42 | extern double get_median(const multiset& m, const multiset >& M){ 43 | 44 | if(m.size() > M.size()) 45 | return *(m.begin()); 46 | else if(M.size() > m.size()) 47 | return *(M.begin()); 48 | else 49 | return ( *(M.begin()) + *(m.begin()) )/2; 50 | } 51 | 52 | //remove x from the tree, if multiple copies of x exist only remove 1 53 | //since this method is never called by the user directly it is assumed 54 | //that there is at least 1 copy of x 55 | extern void remove_element(multiset& m, multiset >& M, double x){ 56 | 57 | if(x < *(m.begin())){ 58 | multiset >::iterator i = M.find(x); 59 | M.erase(i); 60 | } 61 | else{ 62 | multiset::iterator i = m.find(x); 63 | m.erase(i); 64 | } 65 | if(m.size() > M.size() + 1){ 66 | multiset::iterator i; 67 | i = m.begin(); 68 | M.insert(*i); 69 | m.erase(m.begin()); 70 | } 71 | else if(M.size() > m.size() + 1){ 72 | multiset >::iterator i; 73 | i = M.begin(); 74 | m.insert(*i); 75 | M.erase(M.begin()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/helper.h: -------------------------------------------------------------------------------- 1 | #ifndef my_help_func 2 | #define my_help_func 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace Rcpp; 10 | using namespace std; 11 | 12 | double get_median(const multiset&, const multiset >&); 13 | void insert_element(multiset&, multiset >&, double); 14 | void remove_element(multiset&, multiset >&, double); 15 | 16 | extern double Linear(double x); 17 | extern double Const(double x); 18 | extern double Quadratic(double x); 19 | 20 | #endif 21 | --------------------------------------------------------------------------------