54
Team 8363 1 Summary: Geographic Profiling of Serial Criminals Introduction – The purpose of this study is to model the location of a serial criminal’s home based on the location of the crimes. A serial criminal is defined as someone who has committed two or more crimes of a similar nature. Although extensive techniques have been used to attempt to profile these criminals, not all criminals will fit a defined mold. These psychological variations make prediction difficult, but not impossible. The ultimate goal is to provide law enforcement with a probabilistic model that can identify the most likely location of a serial criminal’s home base and predict the most likely location of the next crime. Model Approach – There are many existing models for geographic profiling which rely heavily on center of mass techniques and concepts of angulations and relative distances. Our model will attempt to combine the concepts of center of mass along with a maximum likelihood estimator based on a quasi-normal distribution that we have developed. Our model will look at each location on a grid as a potential home base of a criminal and calculate the probability that the criminal resides there based on the locations of the crimes. After checking all possible locations for the home base on the grid, which encompasses all of the existing crimes, we will provide the most likely locations for the home base and a prediction of the next crime.

bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Embed Size (px)

Citation preview

Page 1: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 1

Summary: Geographic Profiling of Serial Criminals

Introduction – The purpose of this study is to model the location of a serial criminal’s home based on the location of the crimes. A serial criminal is defined as someone who has committed two or more crimes of a similar nature. Although extensive techniques have been used to attempt to profile these criminals, not all criminals will fit a defined mold. These psychological variations make prediction difficult, but not impossible. The ultimate goal is to provide law enforcement with a probabilistic model that can identify the most likely location of a serial criminal’s home base and predict the most likely location of the next crime.

Model Approach – There are many existing models for geographic profiling which rely heavily on center of mass techniques and concepts of angulations and relative distances. Our model will attempt to combine the concepts of center of mass along with a maximum likelihood estimator based on a quasi-normal distribution that we have developed. Our model will look at each location on a grid as a potential home base of a criminal and calculate the probability that the criminal resides there based on the locations of the crimes. After checking all possible locations for the home base on the grid, which encompasses all of the existing crimes, we will provide the most likely locations for the home base and a prediction of the next crime.

Strengths and Weaknesses of the Model – The model currently does not account for the chronology of crimes. Perhaps a heavier weight could be applied toward earlier offenses, since attack domains are presumed to increase in size over time (Canter et al.). A more comprehensive study using additional data sets from different types of serial criminals would also be beneficial for validating this model.

The model is strong in that it is adaptive; for each serial criminal, it generates a unique distribution that takes into account distance and frequency of attack. The model is also strong in that it makes no assumption about a criminal’s intension, which is often unpredictable.

Page 2: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 2

Table of Contents

Geographical Profiling of Serial Criminals......................................................................2 Introduction.............................................................................................................2 Previous Models.......................................................................................................3 Developing Predictors..............................................................................................4

Description of Computer Simulation..............................................................................8 Predictions of Known Serial Criminals............................................................................8

Peter Sutcliffe...........................................................................................................10 Frederick Harlan Coe................................................................................................10 Elmo Rivadeneira......................................................................................................11 David Berkowitz .......................................................................................................12 Results ......................................................................................................................13 Further Development ...............................................................................................14

Executive Summary........................................................................................................15 Works Cited....................................................................................................................17 Appendices: Derivations and Calculations.....................................................................18

Appendix A – Calculating a Revolved Quasi-Normal Density....................................18 Appendix B – Source Code.......................................................................................19

Page 3: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 3

Geographical Profiling of Serial Criminals:

Introduction:

A serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses are often common in other crimes, (e.g. burglary, arson, drunk driving, larceny, etc.) we will restrict ourselves to these offenses. The purpose of this study was to formulate a mathematical model that predicts future offenses of serial criminals as well as where a serial criminal’s base of operation is located. The authors use suppositions from other models to compose an enhanced model.

Predicting where serial criminals are is not an easy task; attempts have been made to profile offenders, but useful generalizations of serial criminals may not be possible (Beasley II). Furthermore, the Federal Bureau of Investigation recognizes that most offenders have families, are employed, and usually do not draw suspicion to members of their community (Morton and Hilts). Sometimes offenders stop for a period of time, which may be for several years. Also, causality varies from case to case, and the factors that contribute to the development of serial criminals are not yet fully understood.

Although serial criminals are evasive, certain patterns in their offenses have been observed. In particular, the FBI notes that most serial killers have “very defined geographic areas of operation” (Morton and Hilts). Such a location may include a residence, workplace, or some other refuge that a criminal routinely returns to. A study on 129 American and 29 British serial killers revealed the following trends (Lundrigan and Canter):

Criminal domains are around their home base and relate to familiar travel distances Each offender has a characteristic attack domain Serial criminals operate in locations similar to their home bases The size of a criminal’s domain increases over time

While these remarks relate to serial killers, it has been shown that serial rapists and serial burglars exhibit a similar pattern (Goodwill and Alison).

Previous Models:

One technique in finding a serial killer is to plot all of the body discovery sites as points in a Cartesian coordinate system. Then, one can calculate the center of mass as an estimate of the perpetrator’s location.

Another technique has been called the “Circle Hypothesis.” This involves choosing the distance between the two body disposal sites which are farthest apart and interpreting

Page 4: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 4

this distance as the diameter of a circle. In Australia, the United States, and Japan, it was discovered that most of the time, serial arsonists, rapists, and burglars were located within this circle (Canter et al.).

The Circle Hypothesis technique has been adapted to include probabilistic exponential decay; as the distance from the offender’s home base increases, the probability of an attack decreases (Canter et al.).

A study done on attack patterns illustrates three additional techniques for observing attack patterns (Goodwill and Alison):

Spatial Dispersion: This is a measure of how concentrated attacks are around an offender’s home.

Sequential Angulation: This is a measure of the geometric angle between two offenses with respect to the offender’s home base.

Relative Distances: This is a measure of how often the offender travels equal distances between each offense with respect to the offender’s home base.

While developing our model, we focused on the concepts of spatial dispersion and relative distances to create a distribution for the location of the crimes. Knowing that a serial criminal will often travel comparable distances to commit offenses, and that they are likely to travel in a certain pattern around their home base, we have developed a quasi-normal distribution to encompass the locations of the crime.

Developing Predictors:

The first proposed predictor is to find the center of mass. Suppose each murder site can be interpreted as a weight on a Cartesian coordinate plane. Then, a collection of n crime scenes can be represent as a set, S={(x1 , y1 ) , (x2 , y2 ) ,…, (xn , yn )}. A weighted average of

the x and y values within S gives the weighted average: center of mass=( 1n∑i=1n

x i ,1n∑i=1

n

y i).An improved attempt at a predictor might be to find the point at which the next murder

would have the minimal impact on the center of mass. Suppose a criminal is interested in attacking where he/she has not yet attacked. With this in mind, a circle is generated around the proposed home base. The radius of this circle is the average distance the perpetrator travels to commit an offense. We wish to choose the point(s) on this circle such that the distance between the point(s) and the nearest offense is maximized. This is our second predictor.

A more robust attempt at a predictor is to assume that a “buffer zone” exists near the offender’s home base. In this zone, an offender will not commit a crime for fear of being recognized by colleagues, family members, etc. Disposing of a body too close to a home base might also not allow an offender to have a viable escape after committing a crime. This hypothesis implies that outside the buffer zone, the probability of the occurrence of an attack will steadily increase, and eventually decrease again when the distance to dispose of

Page 5: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Home Base

Buffer Zone

Danger Zone

Caution Zone

Safe Zone

Team 8363 5

a body becomes too far away from the offender’s home base to be plausible. This idea has been suggested by multiple experts (Whittington-Egan; Canter et al.). A diagram of this idea follows:

Figure 1. Attack schema of a serial criminal

We propose that a probability density function can be superimposed over a region to encompass these phenomena. This scenario lends itself to using a revolved normal distribution radiating out from the center. To construct this, consider the following algorithm:

1) Let f have a normal distribution:

Page 6: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 6

2 2 4 6

0 .2

0 .4

0 .6

0 .8

Figure 2. A normal distribution with a mean of 2 and a standard deviation of 1

2) Truncate f at x=0 and rescale the function so that it maintains the property of being a density function. Call this new function g:

2 2 4 6

0 .2

0 .4

0 .6

0 .8

Figure 3. A truncated and scaled normal distribution

f

x

f (x)

x

g(x )

Page 7: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 7

3) Rotate g about the y-axis to generate a solid region and scale it such that the volume is equal to 1:

Figure 4. A rotated and scaled truncated normal distribution

4) Take a cross-section of the solid region to obtain a new function, h.

1 2 3 4 5 6

0.005

0.010

0.015

0.020

0.025

0.030

Figure 5. A cross-section of the distribution of Figure 4

A more rigorous explanation as to how these functions can be obtained is given in Appendix A. The above example used a normal distribution with a mean of 2 and a standard deviation of 1 for illustrative purposes. In general, the mean and standard deviation are

estimated by x=

∑i=1

n

x i

n and

s2=∑i=1

n

(x i−x )2

n−1, where x i is the distance between body disposal

site i and the offender’s home base.

This model assigns low probabilities to an area near an offender’s home base as well as the areas purported to be too far away. The maximum probability is distributed evenly in

x

h(x )

Page 8: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 8

a circle with a radius of the sample mean of the distances between body disposal sites and the home base.

Thus, a third predictor is generated by this model; consider the offender’s location at the maximum likelihood area. The next attack will occur with maximal probability at any location on the circle with a radius of the offender’s average attack distance.

This model is advantageous because of its adaptivity; if a serial criminal commits offenses far from his/her home base, the variance of the distribution will change, causing the probability of the next location to become more variable. This adjustment makes sense, as the offender has made his/herself less predictable by extending his/her target range. Likewise, if reported crime locations are more condensed, the distribution will change accordingly to reflect a more concentrated attack area. This study focused primarily on serial killers, but it is known that other serial offenders such as rapists and burglars have similar attack patterns. One study determined that burglars tend to strike more concentrated areas than rapists and murders (Goodwill and Alison).

Description of Computer Simulation

A computer simulation was constructed around the aforementioned ideas. Each crime area was divided into a grid. Each cell on the grid was traversed and analyzed as follows:

1) The offender’s home base was hypothetically placed on the location.2) The sample mean and standard deviation of the distances from the home to the

crime scenes were calculated.3) A revolved quasi-normal distribution was constructed about the location.4) The probabilities that each crime occurred conditional on the home base were

calculated and added up.

After each probability was found, the cell that produced the maximum probability was located and designated the maximum likelihood estimator. Each probability was then mapped to a gradient, where the highest probable results were red and lowest probable results were black. For illustrative purposes, the circle described by the Circle Hypothesis was also computed, where the diameter of the circle is determined by the two most distant offenses. The center of mass was also computed. The radii of the circles about the center of mass and maximum likelihood estimator represent the average distance from the center to the crime scenes. Finally, these results were overlaid on a Google map, containing all crime scene locations.

The code for these simulations may be found in Appendix B.

Predictions of Known Serial Criminals

In order to test the accuracy of our model, we have gathered several data sets concerning past serial criminals. As data on the exact locations of the crimes was not

Page 9: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 9

readily available, some of the locations we are using are approximations. Most of these approximations should be within a few blocks of the actual crime scene. Our model will attempt to find the home bases of Peter Sutcliffe and David Berkowitz, who are convicted serial killers. The model will also attempt to find the home bases of Elmo Rivadeneira and Frederick Harlan Coe, who are convicted serial rapists.

The images produced are colored according to the following legend:

Figure 6. Legend describing simulation outputs

Danger Zone:

The Danger Zone indicates the location where the offender is most likely to attack next.

Center of Mass:

The Center of Mass applies a weighing technique to all crime scene locations, weighing each of them equally.

Circle Hypothesis:

The circle hypothesis constructs a circle where the diameter is defined by the distance between the two most distant points.

Crime Scene:

These points indicate where the crime scene was reported.

Likelihood of Residence:

The more red the zone, the more likely it is that the offender lives in the region.

Legend:Danger ZoneCenter of MassCircle HypothesisUnlikely

Residence Likely Residence

Crime Scene

Page 10: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 10

Peter Sutcliffe:

Dubbed the Yorkshire Ripper, Peter Sutcliffe killed 13 women in England from 1975 to 1980. Below is a map of the crime scene locations attributed to him, which is superimposed by our predictors.

Figure 7. Peter Sutcliffe model output

Frederick Harlan Coe (Kevin Coe):

Better known as “The South Hill Rapist,” Kevin Coe was convicted on 4 of 6 counts of first degree rape in 1981. It was suspected that he committed over 40 obscene crimes in the South Hill are of Spokane Washington. Unfortunately, we could not find an exact location of where he was apprehended. So we will use our model to make a prediction of where he was most likely operating from (either a home base or work base) based on the 6 known locations of his rape victims.

Page 11: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 11

Figure 8. Kevin Coe model output

Elmo Rivadeneira:

Elmo Rivadeneira is a serial rapist who frequently attacked in the New York and New Jersey area. He has been convicted of several rapes with more alleged. We have taken 6 confirmed attacks of his for use in our model.

Page 12: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 12

Figure 9. Elmo Rivadeneira model output

David Berkowitz:

Berkowitz, most commonly referred to as the “Son of Sam,” was an American serial killer who struck New York City from July 1976 to August 1977. Berkowitz’s attacks were seemingly random. He showed few patterns in his murders, and the crimes were unprovoked and in random locations throughout New York City. Through the course of 8 shootings, Berkowitz killed 6 people and injured 7 others. For our model, we will use these 8 shooting locations to attempt to find the location where Berkowitz was apprehended; which is presumably close to his home.

Page 13: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 13

Figure 10. David Berkowitz model output

Results:

The Danger Zone appears to be a good predictor for future crime locations, but the maximum likelihood estimate appears to be a poor estimator of the perpetrator’s home base. As the crime scene locations become more linear, the maximum likelihood estimate becomes farther away with a larger Danger Zone radius. Likewise, as crime scene locations become more circular, the maximum likelihood estimate becomes closer with a smaller Danger Zone radius. This occurs because of the nature of the distribution that the authors chose; however, in theory, any distribution could be used and the same technique applied for potentially more viable results.

It appears that crimes, as well as the perpetrator’s home base, tend to fall within the Danger Zone. Thus, a recommendation to police officers would be to increase patrols around the Danger Zone. In the case of Peter Sutcliffe, the patrols would only need to increase around the Danger Zone where the crime scenes are occurring due to the linearity issued discussed above.

Page 14: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 14

Further Development:

It has been suggested that serial criminals tend to increase their attack domains over time (Lundrigan and Canter). If this is true, weighing the first offenses more may be justifiable. Although the present model has this capability, the authors were unable to find a weighing distribution that would prove reasonable. Thus, as it stands, the model does not take into account the chronology of the crimes.

The model also does not account for the terrain of the location. It is the responsibility of the analyst to recognize that a serial criminal will most likely not be located in a lake, river, mountain, etc. However, in a typical cityscape where most area is passable and accessible, the model is not inhibited.

Finally, the authors recommend testing this model on additional data sets to better determine its efficacy. These data sets would include serial rapists and burglars in addition to murderers.

Page 15: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 15

Executive Summary

Purpose: The Purpose of this model is to identify the most probable location of a serial criminal’s home, based on the location of their crimes. In an attempt to help law enforcement catch these serial offenders, we would like to refine their search area to the most likely home base locations based on three criteria: the center of mass of the crimes, the circle hypothesis, and a maximum likelihood estimator based on a quasi-normal distribution.

Methodology: In order to begin developing our model, we first needed to research the most common patterns of serial criminals. Multiple pieces of research suggested that most serial offenders chose not to commit crimes too close to their home bases. With this in mind, we decided to create a buffer zone around the home base in which the criminal was less likely to offend. Then, assuming the distance in which a criminal is willing to commit a crime resembles a normal distribution, we created a quasi-normal distribution to find the likelihood that crimes occurred where they did given a possible location for the assailant’s home base. Essentially, this distribution is a probabilistic model that reflects the likelihood that an offender will not attack too close to a home base but also not too far away.

Model Development: To determine the location of a serial criminal’s home, we have used three distinct methods. Our first method is a simple center of mass. This simply averages the locations of each crime to find the weighted center of the crimes. This method is highly rudimentary but comparing our results to the center will be important. The second method that we used in our geographic profiling model has been called the circle hypothesis. This technique finds the two points that are furthest apart and draws a circle around them. Research also supports that most of the time, offenders are found to be within this circle. This will also serve as a good overlay for our complete model. Lastly, the third method that we will implement is the method of maximum likelihood based on a quasi-normal distribution. The idea behind our quasi-normal likelihood estimator is that the serial criminal will be less likely to commit crimes around their home and more likely to commit a crime at a certain distance, which we have deemed the mean of the distribution. Together, these three models will make individual predictions of a criminal’s home location. By looking at all three, we will be able to get a better prediction and a fuller understanding of where the criminal is likely to commit future crimes.

Model Results: We obtained data on serial criminals with known crime site locations and capture locations. We discovered that our model consistently made good predictions about crime scene locations. Around these locations, our model produces a “danger zone” that identifies where an intruder is likely to strike next. It was also found that a criminal’s location frequently tended to be near the danger zone. The predicted home base of the offender was not accurately predicted, however. Therefore, we recommend that police increase patrols around the danger zone, with increased probability of encountering the offender or another attack.

Page 16: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 16

Model Strengths: The major strength of our model is the combination of the three methods. Looking at each point, and the area of the triangle formed by the three points, we should get a good approximation of the assailant’s home. The third and most important method of our model is the maximum likelihood estimator based on the quasi-normal distribution we developed. This method is one of the strengths of our model as it encompasses many of the readily accepted views on serial criminals. It takes into account the buffer zone around the home, and a mean distance for crimes to take place. Moreover, our model searches an entire grid to assess the most likely home location of the criminal. Unlike existing models out there, our model checks areas outside the circle hypothesis.

Model Weaknesses: One of the main weaknesses of our model is its inability to make distinctions between viable locations. Namely, our model does not distinguish between a possible home location and an impossible one such as the top of a mountain or the bottom of a lake. However, this situation could easily be remedied by inputting coordinates for impossible home locations into the program and having zero probabilities be assigned to that part of the grid. Another seemingly big weakness of our model is for criminals such as Jeffrey Dahmer and John Gacy who primarily kill at their homes. Our model requires data about crime scene locations, and for serial criminals who commit them at home, our model will not be able to find them, as there is no data to input. Lastly, our team was not able to gather sufficient data to produce meaningful conclusions on whether our model accurately predicts the criminal’s home location. Collecting data on crime locations and an assailant’s home turned out to be very difficult. However, with the resources of a police department, this would not pose a problem in using our model.

Model Improvements: The possible improvements to our model are apparent. First, we can take into account impossible home locations for the criminal. By accounting for bodies of water, landmarks, and even highly unlikely crime locations such as inside schools, malls or police stations, our model’s predictions could be greatly improved. Likewise, our computer simulation can easily be improved my allowing for more distributions that are case-specific to the criminal. For instance, if police discover additional tips that indicate a trend of an offender, we would be able to make mathematical adjustments that better reflect the scenario.

Model Output Sample:

Page 17: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 17

Works Cited:

Beasley II, James O. "Serial Murder in America: Case Studies of Seven Offenders." Behavioral Sciences and the Law 22. (2004): 395-414. Web. 19 Feb 2010. [Source 4]

Canter, David V., Laurence J. Alison, Emily Alison, and Natalia Wentink. "The Organized/Disorganized Typology of Serial Murder." Psychology, Public Policy, and Law 10.3 (2004): 293-320. Web. 19 Feb 2010. [Source 6]

Canter, David, Toby Coffey, Malcolm Huntley, and Christopher Missen. "Predicting Serial Killers' Home Base Using a Decision Support System." 16.4 (2000): 457-478. Web. 19 Feb 2010. [Source 1]

Goodwill, Alasdair M., and Laurence J. Alison. "Sequential Angulation, Spatial Dispersion, and Consistency of Distance Attack Patterns From Home in Serial Murder, Rape, and Burglary." Psychology, Crime & Law 2.11 (2005): 161-176. Web. 19 Feb 2010. [Source 5]

Lundrigan, Samantha, and David Canter. "Spatial Patterns of Serial Murder: An Analysis of Disposal Site Location Choice." Behavioral Sciences and the Law. 19. (2001): 595-610. Web. 19 Feb 2010. [Source 3]

Morton, Robert J., and Mark A. Hilts. "Federal Bureau of Investigation - Serial Murder - Multi-Disciplinary Perspectives for Investigators." Serial Murder - Multi-Disciplinary Perspectives for Investigators. 2005. Federal Bureau of Investigaion, Web. 19 Feb 2010. <http://www.fbi.gov/publications/serial_murder.htm>. [Source 2]

Stewart, James. Calculus. 5th ed. Belmont: Brooks/Cole, 2003. Print. [Calc Book for shell method]

Whittington-Egan, Richard. "The Serial Killer Phenomenon." Serial Killer Phenomenon 290.1690 (2008): 323-330. Web. 20 Feb 2010.

Page 18: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 18

Appendices: Derivations and Calculations

Appendix A – Calculating a Revolved Quasi-Normal Density:

Suppose that x=

∑i=1

n

x i

n and

s2=∑i=1

n

(x i−x )2

n−1 are computable and known. Also assume that x>0.

(In our examples, this is a safe assumption because all of the x i values represent distances).

Now, define f ( x ; x , s )= 1√2π s

e−( x−x )2/ (2 s2 ), so that f N (x , s). We wish to truncate this

function at x=0. Let g ( x; x , s )=c1 ∙ f ( x ;x , s ), where c1=1/∫0

f ( x ; x , s )dx and 0<x<∞. This

scales g in such a way that g is a density function. Now, we wish to rotate g about the y-axis. If we do so, we obtain a volume. In order for the solid of rotation to represent a density function, we require the volume to be identically 1.

The volume can be calculated using the method of cylindrical shells (Stewart 394):

V=∫a

b

2 πxg ( x )dx

We must scale the volume by a constant c2, such that it is equal to 1:

1c2∙∫0

2 πxg ( x )dx=1

⟹c2=∫0

2πxg ( x )dx

Define h ( x )=g (x)c2

. h(x ) is not itself a density function, but it is a cross-section of a solid such

that when the solid is revolved from x=0 to positive infinity around the y-axis, the area under the surface is 1. Namely, h is a function that is a cross-section of a bivariate density function. Normally, bivariate density functions are evaluated by using double integrals, but since the joint density function is difficult to obtain, we construct the joint density function as above and choose the appropriate h to radially measure the probability that an attack occurs at the body disposal location conditional on the offender’s house being at the center of the distribution.

Page 19: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 19

Appendix B – Source Code

/********************************************************************** * main.cpp ********************************************************************** * 2010 Mathemtical Contest in Modeling: * * Geographic Profiling of Serial Criminals * * Authors: Matt Holst * Aaron Potvien * Brian Christner * * Use: Reads in data from a text file (see example for format) * and outputs a png imgage file with the specified width, * height, and name represting a heat map and other * predictors of the possible locations of the "home base" * of a serial ciminal based on crime locations * * Run the program with the following format: * * <executable name> <"input.txt"> <width> <height> <"output.png"> * * Example Input File: * * location 107 56 * location 126 96 * location 453 332 * location 383 402 * //location 33 189 * * In the above example, the first four lines will be input as * pixel-mapped locations into the simulation (murder sites * will show up at the (x,y) pixel locations. The fifth line * will be ignored as a comment. Any pixel location that would * be located outside the specified width and height will also * be ignored. * * NOTE: This program uses the libpng-dev package to be install in order * to output the png image. This cann be installed on more linux * systems with: * * sudo apt-get install libpng-dev * * This program uses the Gauss Legendre Quadrature code for Numerical * Integration written by Pavel Holoborodko and distributed under * GNU Public License. His code can be found at his website at: * * http://www.holoborodko.com/pavel/?page_id=679 * **********************************************************************/

#include "map.h"#include "cell.h"#include "cellData.h"#include "math.h"#include "PNGImage.h"#include <iostream>#include <string>#include <fstream>#include <sstream>#include "gauss_legendre.h"#include "gauss_legendre.c"

Page 20: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 20

using namespace std;

const double Pi = 3.1415926535;

int main(int argc, char* argv[]){// Function Declarationsvoid drawImage(Map::Map world, Cell::Cell center,

int width, int height, string fileName);

// Vairable Declarationschar* inputFileName;

int width;int height;char* outputImageFile;

// Read Command Line Argumentsif (argc != 5){

// We have an incorrect argument count, print out usagecout << argc << " parameters specified, correct usage: ";cout << "<executableName> <inputFile.txt> ";cout << "<width> <height> ";cout << "<outputImageName.png>" << endl;return 0;

}else{

// We have the correct argument count, assume correct order. inputFileName = argv[1];stringstream wstream(argv[2]);wstream >> width;stringstream hstream(argv[3]);hstream >> height;outputImageFile = argv[4];

}

// Open the input fileifstream inputFile(inputFileName);

// Count the number of kill locationsstring line;int totalKills = 0;while(!inputFile.eof()){

getline(inputFile, line);if (line.find("location") != string::npos &&

line.find("//") == string::npos)totalKills++;

}

// Create the Map based on width, height and number of locationsMap::Map world(width,height,totalKills);

// Reset the file to read from the beginninginputFile.clear();inputFile.seekg(0);

// Read loactions from the fileint x_temp,y_temp;int count = 0;while(!inputFile.eof()){

getline(inputFile, line);if (line.find("location") != string::npos &&

line.find("//") == string::npos){stringstream ss(stringstream::in|stringstream::out);// Skip the word "location" since we know this line is oness << line.substr(9,string::npos);ss >> x_temp;ss >> y_temp;

Page 21: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 21

if (x_temp <= width && y_temp <= height){world.addCell(x_temp,y_temp,1);// Print location informationcout << "added location to (" << x_temp << ", " ;cout << y_temp << ")\n";count++;

}else{

// Locations off the grid, print messagecout << "location (" << x_temp << ", " << y_temp;cout << ") is off the grid and was not added!\n";

}}//end if

}//end while

// Calculate a weighted center of mass and print itCell::Cell center = world.center();cout << "Center: (" << center.getX()<< ", "<<center.getY() << ")\n";

// Draw the image!drawImage(world, center, width, height, outputImageFile);

return 0;

}//end main

// Draw Image// Input: world, center, width, height, output file name// Output: a PNG image representing our model graphically.void drawImage(Map::Map world, Cell::Cell center,

int w, int h, string fileName){// Function Declarationsdouble f(double x, void* data);double g(double x, void* data);double v(double x, void* data);

// Initialize the PNGWritercs5721::PNGImage pngimage;

// Generate some image datafloat *imageData = new float[ w * h * 3 ]; // Pixel color info

// Declare Variablesint minMax_x, minMax_y; // Minmax locationdouble minMax = 0; // Minmax value

// Epsilon/Tolerance Levelsdouble eps = 5; // For drawing

locationsdouble epsBand = 10; // For ring calculationsdouble epsMinMax = 10; // For minmax drawingdouble bufferDist = 50; // Buffer around house

//Calculate standard deviationcout << "STDDEV: " << world.getStdDev() << "\n";

// Declare variables for keeping track of h(x) and max locationdouble max_h = 0;int max_h_x = 0;int max_h_y = 0;

// First Pass, compute max values and locationfor (int r=0; r<h; r++){

for (int c=0; c<w; c++){// For each pixel...CellData::CellData* test;test = new CellData::CellData(Cell::Cell(c,r,1), world);

Page 22: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 22

void* data = reinterpret_cast<void*>(test);double stdDev = world.getStdDev(c,r);double h_val = 0;

// For each location...for (int i = 0; i < world.getTotalLocations(); i++){

double x_dist = world.getDistance(c,r,i);double avgDist = world.averageDist(c,r);test->setX(x_dist);if (stdDev != 0){

double f_val = gauss_legendre(20, f, data, 0, avgDist+150*stdDev);

//if quadrature returns a value > 1, set it to 1if (f_val > 1)

f_val = 1;

test->setF(f_val);double c2 = gauss_legendre(20, v,

data, 0, avgDist+150*stdDev);double gofx = g(x_dist,data)/c2;if (gofx > 1){

cout << "h-value larger than!";cout << " skipping this value...\n";

}else

h_val += gofx;}//end if

}//end for

// Update max h-value and locationif (h_val > max_h){

max_h = h_val;max_h_x = c;max_h_y = r;cout << "NEW maxX: " << max_h_x << " maxY: " << max_h_y;cout << " h_val:" << h_val << "\n";

}//end if}//end for

}//end for// END FIRST PASS

// Use the max values found in the first pass to create the max CellCell::Cell hcenter(max_h_x, max_h_y, 1);world.setHCenter(hcenter);

cout << "H-Valued Center: (" << (world.getHCenter()).getX();cout << ", " << (world.getHCenter()).getY() << ")\n";cout << "MAX H: "<< max_h << "\n";

//Second Pass, generate color data for the png imagefor (int r=0; r<h; r++){

for (int c=0; c<w; c++){int idx = (r * w * 3) + c * 3;// For each pixel...

CellData::CellData* test;test = new CellData::CellData(Cell::Cell(c,r,1), world);void* data = reinterpret_cast<void*>(test);double stdDev = world.getStdDev(c,r);double h_val = 0;

// For each location...for (int i = 0; i < world.getTotalLocations(); i++){

//double x = world.getDistance(c,r,i);double x_dist = world.getDistance(c,r,i);double avgDist = world.averageDist(c,r);

Page 23: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 23

test->setX(x_dist);if (stdDev != 0){

double f_val = gauss_legendre(20, f, data, 0, avgDist+150*stdDev);

//if quadrature returns a value > 1, set it to 1if (f_val > 1)

f_val = 1;test->setF(f_val);

double c2 = gauss_legendre(20, v, data, 0, avgDist+150*stdDev);

double gofx = g(x_dist,data)/c2;if (gofx > 1){

cout << "h-value larger than!";cout << " skipping this value...\n";

}else

h_val += gofx;}//end if

}//end for

//Generate Color DataCell::Cell CTCenter = world.getCircleTheoryCenter();

if (world.checkCell(c,r,eps)){// Color pixel blue for locationimageData[idx + 0] = 0.0; imageData[idx + 1] = 0.0; imageData[idx + 2] = 1.0;

}else if (world.checkCenter(c,r,eps)){

// Color pixel white for center of massimageData[idx + 0] = 1.0; imageData[idx + 1] = 1.0; imageData[idx + 2] = 1.0;

}else if (world.getDistance(c,r,center.getX(),center.getY())

> world.averageDist(center.getX(),center.getY()) && world.getDistance(c,r,center.getX(),center.getY()) < world.averageDist(center.getX(),center.getY()) + epsBand){

double minDist = world.minDist(c,r);if (minDist > minMax){

minMax = minDist;minMax_x = c;minMax_y = r;

}// Color pixel white for center of mass ringimageData[idx + 0] = 1.0; imageData[idx + 1] = 1.0; imageData[idx + 2] = 1.0;

}else if (world.checkHCenter(c,r,eps)){

// Color the pixel orange for h-valued centerimageData[idx + 0] = 1; imageData[idx + 1] = 0.4; imageData[idx + 2] = 0;

}else if(world.getDistance(c,r,hcenter.getX(),hcenter.getY())

> world.averageDist(hcenter.getX(),hcenter.getY()) && world.getDistance(c,r,hcenter.getX(),hcenter.getY())

< world.averageDist(hcenter.getX(),hcenter.getY()) + epsBand){

// Color the pixel orange for h-valued ringimageData[idx + 0] = 1.0; imageData[idx + 1] = 0.4;

Page 24: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 24

imageData[idx + 2] = 0.0;}else if (world.checkCTCenter(c,r,eps)){

// Color the pixel yellow for circle-theory centerimageData[idx + 0] = 1.0; imageData[idx + 1] = 0.8; imageData[idx + 2] = 0.0;

}else if (world.getDistance(c,r,

CTCenter.getX(),CTCenter.getY()) > (world.getMaxDist()/2) -1

&& world.getDistance(c,r,

CTCenter.getX(),CTCenter.getY()) < (world.getMaxDist()/2) +1){

// Color the pixel yellow for circle-theory ring imageData[idx + 0] = 1.0; imageData[idx + 1] = 0.8; imageData[idx + 2] = 0;

}else if (world.getDistance(c,r,center.getX(),center.getY())

> world.averageDist(center.getX(),center.getY())&& world.getDistance(c,r,center.getX(),center.getY())

< world.averageDist(center.getX(),center.getY()) + epsBand){

double minDistance = world.minDist(c,r);if (minDistance > minMax -epsMinMax &&

minDistance < minMax +epsMinMax){

// Color the pixel green for minMax locationimageData[idx + 0] = 0.0; imageData[idx + 1] = 1.0; imageData[idx + 2] = 0.0;

}if (minDistance == minMax)

cout << "Next Location: ("<< c << ", "<< r << ")\n";}

else{double color = h_val/max_h;// Otherwise color the pixel according the gradient // defined by the h-valued probabilitiesimageData[idx + 0] = color; imageData[idx + 1] = 0; imageData[idx + 2] = 0;

}//end else}//end for

}//end for

// Output the final imagepngimage.writeFileData(fileName, w, h, imageData);

}//end drawImagege

// Read MCM Contest 2010 Submission for more information about thesedouble f(double x, void* data){

// Read in data for computing f(x)CellData::CellData * cellData =

reinterpret_cast<CellData::CellData*>(data);Cell::Cell cell = cellData->getCell();Map::Map world = cellData->getWorld();int x_c = cell.getX();int y_c = cell.getY();double s = world.getStdDev(x_c,y_c);double x_mean = world.averageDist(x_c,y_c);

// Standard Normal Distribution

Page 25: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 25

double result;result = (1/(sqrt(2*Pi)*s))*exp((-(x-x_mean)*(x-x_mean))/(2*s*s));return result;

}

double g(double x, void*data){CellData::CellData * cellData =

reinterpret_cast<CellData::CellData*>(data);double c1 = 1/(cellData->getF());return c1*f(x,data);

}double v(double x, void* data){

return 2*Pi*x*g(x, data);}/********************************************************************** * map.h *********************************************************************/

#ifndef __MAP_H__#define __MAP_H__ 1

#include "cell.h"

class Map{

public:// ConstructorMap(int m, int n, int numLocations);Map();

// Accessor Methodsint getM();int getN();int getTotalLocations();Cell::Cell getCell(int index);Cell::Cell getHCenter();

// Mutator Methodsvoid setHCenter(Cell::Cell hcenter);

// Member Methods

// Adds cell to the map at (x,y) with the given weightvoid addCell(int x, int y, double weight);

// Returns true if (x,y) is within eps of a cell/murder locationbool checkCell(int x, int y, double eps);

// Returns true if (x,y) is within eps of the center of massbool checkCenter(int x, int y, double eps);

// Returns true if (x,y) is within eps of the h-valued centerbool checkHCenter(int x, int y, double eps);

// Returns true if (x,y) is within eps of the Circle Theory centerbool checkCTCenter(int x, int y, double eps);

// Returns the weighted center of massCell::Cell center();

// Returns the center given by the Circle TheoryCell::Cell getCircleTheoryCenter();

// Returns the average distance to a murder locations from (x,y)double averageDist(int x, int y);

// Returns the minimum distance to a murder location from (x,y)

Page 26: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 26

double minDist(int x, int y);

// Returns the maximum distance from any murder site to anotherdouble getMaxDist();

//double getValue(int x, int y);

// Returns the distance from (x1,y1) to (x2,y2)double getDistance(int x1, int y1, int x2, int y2);

// Returns the distance from cell1 to cell2double getDistance(Cell::Cell cell1, Cell::Cell cell2);

// Returns the distance from (x,y) to locations at index double getDistance(int x, int y, int index);

// Returns the StdDev of distance from the center to muder locationsdouble getStdDev();

// Returns hte StdDev of distance from (x,y) to murder locationsdouble getStdDev(int x, int y);

private:// Member Variablesint m_m; // widthint m_n; // HeightCell::Cell *m_locations; // Murder locationsint m_totalLocations; // Number of total locationsCell::Cell m_hcenter;

};//end Map

#endif // __MAP_H_

Page 27: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 27

/********************************************************************** * map.cpp *********************************************************************/

#include "map.h"#include "math.h"#include <iostream>

// ConstructorsMap::Map(int m, int n, int maxLocations){

m_m = m;m_n = n;m_locations = new Cell::Cell[maxLocations];m_totalLocations = 0;

}

Map::Map(){m_m = 0;m_n = 0;m_totalLocations = 0;

}

// Accessor Methodsint Map::getM(){ return m_m; }int Map::getN(){ return m_n; }int Map::getTotalLocations(){ return m_totalLocations; }Cell::Cell Map::getCell(int index){

return m_locations[index];}Cell::Cell Map::getHCenter(){ return m_hcenter;}

// Mutator Methodsvoid Map::setHCenter(Cell::Cell hcenter){m_hcenter = hcenter;}// Member Methods

void Map::addCell(int x, int y, double weight){m_locations[m_totalLocations] = Cell::Cell(x, y, weight);m_totalLocations++;

}

bool Map::checkCell(int x, int y, double eps){for(int i = 0; i< m_totalLocations; i++){if (getDistance(x,y,

m_locations[i].getX(),m_locations[i].getY()) <= eps)return true;

}return false;

}

bool Map::checkCenter(int x, int y, double eps){Cell::Cell center = Map::center();if (getDistance(x,y,center.getX(),center.getY()) <= eps)

return true;else

return false;}

bool Map::checkHCenter(int x, int y, double eps){if (getDistance(x,y,m_hcenter.getX(),m_hcenter.getY()) <= eps)

return true;else

return false;}

bool Map::checkCTCenter(int x, int y, double eps){Cell::Cell CTCenter = Map::getCircleTheoryCenter();if (getDistance(x,y,CTCenter.getX(),CTCenter.getY()) <= eps)

return true;else

return false;}

Page 28: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 28

Cell::Cell Map::center(){double xTotal = 0;double yTotal = 0;double totalWeight = 0;for(int i = 0; i < m_totalLocations; i++){

xTotal += (m_locations[i].getX() * m_locations[i].getWeight());yTotal += (m_locations[i].getY() * m_locations[i].getWeight());totalWeight += m_locations[i].getWeight();

}return Cell::Cell(xTotal/totalWeight, yTotal/totalWeight);

}

Cell::Cell Map::getCircleTheoryCenter(){Cell::Cell point1;Cell::Cell point2;double maxDistance = 0;for(int i = 0; i < m_totalLocations; i++){

for (int j = i; j < m_totalLocations; j++){Cell::Cell a = m_locations[i];Cell::Cell b = m_locations[j];double distance = Map::getDistance(a,b);if (distance > maxDistance){

maxDistance = distance;point1 = a;point2 = b;

}//end if}//end forCell::Cell circleTheoryCenter((point1.getX()+point2.getX())/2,

(point1.getY()+point2.getY())/2);

return circleTheoryCenter; }//end for

}

double Map::averageDist(int x, int y){double total = 0;for(int i = 0; i < m_totalLocations; i++){

total += getDistance(x,y, m_locations[i].getX(),m_locations[i].getY());

}

return total/m_totalLocations;}

double Map::minDist(int x, int y){double min = -1;for(int i = 0; i < m_totalLocations; i++){

int dist = getDistance(x,y, m_locations[i].getX(),m_locations[i].getY());

if (dist < min || min == -1)min = dist;

}return min;

}

double Map::getMaxDist(){double maxDistance = 0;for(int i = 0; i < m_totalLocations; i++){

for (int j = i; j < m_totalLocations; j++){Cell::Cell a = m_locations[i];Cell::Cell b = m_locations[j];double distance = Map::getDistance(a,b);if (distance > maxDistance){

maxDistance = distance;}

}return maxDistance;

}}

Page 29: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 29

double Map::getDistance(int x1, int y1, int x2, int y2){double result = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));return result;

}

double Map::getDistance(Cell::Cell cell1, Cell::Cell cell2){int xdiff = cell2.getX()-cell1.getX();int ydiff = cell2.getY()-cell1.getY();return sqrt((xdiff*xdiff)+(ydiff*ydiff));

}

double Map::getDistance(int x, int y, int i){return getDistance(x, y,

m_locations[i].getX(), m_locations[i].getY());}

double Map::getStdDev(){Cell::Cell center = Map::center();double avg = Map::averageDist(center.getX(), center.getY());double var = 0;for(int i = 0; i < m_totalLocations; i++){

Cell::Cell location = m_locations[i];var += ((Map::getDistance(location,center))-avg)*

((Map::getDistance(location,center))-avg);}return sqrt(var/m_totalLocations);

}

double Map::getStdDev(int x, int y){Cell::Cell house(x,y,1);double avg = Map::averageDist(house.getX(), house.getY());double var = 0;for(int i = 0; i < m_totalLocations; i++){

Cell::Cell location = m_locations[i];var += ((Map::getDistance(location,house))-avg)*

((Map::getDistance(location,house))-avg);}return sqrt(var/(m_totalLocations-1));

}

Page 30: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 30

/********************************************************************** * cell.h *********************************************************************/#ifndef __CELL_H__#define __CELL_H__ 1

class Cell{

public:// ConstructorsCell(double x, double y, double weight);Cell(double x, double y);Cell();

// Accessor Methodsdouble getX();double getY();double getWeight();

// Mutator Methodsvoid setX(int x);void setY(int y);void setWeight(int weight);

private:// Member Variablsdouble m_x;double m_y;double m_weight;

};//end Cell

#endif // __CELL_H_

Page 31: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 31

/********************************************************************** * cell.cpp *********************************************************************/#include "cell.h"

// Constructors

Cell::Cell(double x, double y, double weight){m_x = x;m_y = y;if (weight > 1)

m_weight = 1;else

m_weight = weight;}

Cell::Cell(double x, double y){m_x = x;m_y = y;m_weight = 1;

}

Cell::Cell(){m_x = -1;m_y = -1;m_weight = 1;

}

// Accessor Methodsdouble Cell::getX(){ return m_x; }double Cell::getY(){ return m_y; }double Cell::getWeight() { return m_weight; }

// Mutator Methodsvoid Cell::setX(int x) { m_x = x; }void Cell::setY(int y) { m_y = y; }void Cell::setWeight(int weight) { m_weight = weight; }

Page 32: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 32

/********************************************************************** * cellData.h *********************************************************************/#ifndef __CELLDATA_H__#define __CELLDATA_H__ 1

#include "cell.h"#include "map.h"

class CellData{

public:// ConstructorsCellData(Cell::Cell cell, Map::Map world){

m_cell = cell;m_world = world;m_f = -1;

}

CellData(Cell::Cell cell, Map::Map world, double f) {m_cell = cell;m_world = world;m_f = f;

}

// Accessor MethodsCell::Cell getCell(){return m_cell;}Map::Map getWorld(){return m_world;}double getF(){return m_f;}double getV(){return m_v;}double getX(){return m_x;}

// Mutator Methodsvoid setF(double f){m_f = f;}void setV(double v){m_v = v;}void setX(double x){m_x = x;}

private:// Member VariablsCell::Cell m_cell;Map::Map m_world;double m_f;double m_v;double m_x;

};//end Cell

#endif // __CELLDATA_H_

Page 33: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 33

/********************************************************************** * PNGImage.h *********************************************************************/#ifndef __PNGIMAGE_H__#define __PNGIMAGE_H__ 1

#include <cstdio>#include <string>

#include <setjmp.h> /* for jmpbuf declaration in writepng.h */#include "writepng.h"

namespace cs5721{

class PNGImage { public: PNGImage() {};

bool writeFileData(const std::string& filename, const int width, const int height, const float *data); private: void cleanup(void);

mainprog_info m_png_fileinfo; };

}

#endif // __PNGIMAGE_H__

Page 34: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 34

/********************************************************************** * PNGImage.cpp *********************************************************************/#include <cmath>#include <cstdlib>#include "PNGImage.h"

#define PROGNAME "pbuffer"#define TOO_SMALL 0#define BIG_ENOUGH 1

using namespace cs5721;

bool PNGImage::writeFileData(const std::string& filename, const int width, const int height, const float *data){ int rc, error = 0; ulg rowbytes;

m_png_fileinfo.image_data = NULL; m_png_fileinfo.row_pointers = NULL; m_png_fileinfo.filter = FALSE; m_png_fileinfo.interlaced = FALSE; m_png_fileinfo.have_bg = FALSE; m_png_fileinfo.have_time = FALSE; m_png_fileinfo.have_text = 0; m_png_fileinfo.gamma = 0; m_png_fileinfo.width = width; m_png_fileinfo.height = height; m_png_fileinfo.sample_depth = 8; m_png_fileinfo.modtime = time(0); m_png_fileinfo.infile = NULL;

m_png_fileinfo.pnmtype = 6;

/* check if outname already exists; if not, open */ /* if ((m_png_fileinfo.outfile = fopen(outname, "rb")) != NULL) { fprintf(stderr, " output file exists [%s]\n", outname); fclose(m_png_fileinfo.outfile); } else */ if (!(m_png_fileinfo.outfile = fopen(filename.c_str(), "wb"))) { fprintf(stderr, " can't open output file [%s]\n", filename.c_str()); } /* allocate libpng stuff, initialize transformations, write pre-IDAT data */ if ((rc = writepng_init(&m_png_fileinfo)) != 0) { switch (rc) { case 2:

fprintf(stderr, PROGNAME": libpng initialization problem (longjmp)\n");

break; case 4:

fprintf(stderr, PROGNAME ": insufficient memory\n");break;

case 11:fprintf(stderr, PROGNAME

": internal logic error (unexpected PNM type)\n");break;

default:fprintf(stderr, PROGNAME

": unknown writepng_init() error\n");break;

} exit(rc); }

/* calculate rowbytes on basis of image type; note that this becomes * much more complicated if we choose to support PBM type, ASCII PNM * types, or 16-bit-per-sample binary data [currently not an * official NetPBM type] */

Page 35: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 35

if (m_png_fileinfo.pnmtype == 5) rowbytes = m_png_fileinfo.width; else if (m_png_fileinfo.pnmtype == 6) rowbytes = m_png_fileinfo.width * 3; else /* if (m_png_fileinfo.pnmtype == 8) */ rowbytes = m_png_fileinfo.width * 4;

/* read and write the image, either in its entirety (if writing * interlaced PNG) or row by row (if non-interlaced) */

// fprintf(stderr, "Encoding image data...\n"); // fflush(stderr); if (m_png_fileinfo.interlaced) { long i; ulg bytes; ulg image_bytes = rowbytes * m_png_fileinfo.height; /* overflow? */

m_png_fileinfo.image_data = (uch *)malloc(image_bytes); m_png_fileinfo.row_pointers = (uch **)malloc(m_png_fileinfo.height*sizeof(uch *)); if (m_png_fileinfo.image_data == NULL || m_png_fileinfo.row_pointers == NULL) { fprintf(stderr, PROGNAME ": insufficient memory for image data\n"); writepng_cleanup(&m_png_fileinfo); cleanup(); exit(5); } for (i = 0; i < m_png_fileinfo.height; ++i) m_png_fileinfo.row_pointers[i] = m_png_fileinfo.image_data + i*rowbytes; bytes = fread(m_png_fileinfo.image_data, 1, image_bytes, m_png_fileinfo.infile); if (bytes != image_bytes) { fprintf(stderr, PROGNAME ": expected %lu bytes, got %lu bytes\n",

image_bytes, bytes); fprintf(stderr, " (continuing anyway)\n"); } if (writepng_encode_image(&m_png_fileinfo) != 0) { fprintf(stderr, PROGNAME

": libpng problem (longjmp) while writing image data\n"); writepng_cleanup(&m_png_fileinfo); cleanup(); exit(2); } } else /* not interlaced: write progressively (row by row) */ { long j,x; ulg bytes;

m_png_fileinfo.image_data = (uch *)malloc(rowbytes); if (m_png_fileinfo.image_data == NULL) { fprintf(stderr, PROGNAME ": insufficient memory for row data\n"); writepng_cleanup(&m_png_fileinfo); cleanup(); exit(5); } error = 0; for (j = m_png_fileinfo.height-1; j >= 0L; --j) { long pixelcount; bytes = rowbytes; pixelcount = 0; for (x=0; x<rowbytes; x+=3) {

m_png_fileinfo.image_data[x] = (uch)(floor(data[j*width*3 + pixelcount + 0] * 255));m_png_fileinfo.image_data[x+1] = (uch)(floor(data[j*width*3 + pixelcount + 1] * 255));m_png_fileinfo.image_data[x+2] = (uch)(floor(data[j*width*3 + pixelcount + 2] * 255));pixelcount+=3;/* printf("rowbytes=%ld, x=%ld, color = [%d, %d, %d]\n", rowbytes, x,

m_png_fileinfo.image_data[x+0], m_png_fileinfo.image_data[x+1], m_png_fileinfo.image_data[x+2]); */ }

if (bytes != rowbytes) {fprintf(stderr, PROGNAME

Page 36: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 36

": expected %lu bytes, got %lu bytes (row %ld)\n", rowbytes,bytes, m_png_fileinfo.height-j);

++error;break;

} if (writepng_encode_row(&m_png_fileinfo) != 0) {

fprintf(stderr, PROGNAME": libpng problem (longjmp) while writing row %ld\n",m_png_fileinfo.height-j);

++error;break;

} } if (error) { writepng_cleanup(&m_png_fileinfo); cleanup(); exit(2); } if (writepng_encode_finish(&m_png_fileinfo) != 0) { fprintf(stderr, PROGNAME ": error on final libpng call\n"); writepng_cleanup(&m_png_fileinfo); cleanup(); exit(2); } } /* OK, we're done (successfully): clean up all resources and quit */

// fprintf(stderr, "Done.\n"); // fflush(stderr);

writepng_cleanup(&m_png_fileinfo); return true;}

void PNGImage::cleanup(){ if (m_png_fileinfo.outfile) { fclose(m_png_fileinfo.outfile); m_png_fileinfo.outfile = NULL; }

if (m_png_fileinfo.infile) { fclose(m_png_fileinfo.infile); m_png_fileinfo.infile = NULL; }

if (m_png_fileinfo.image_data) { free(m_png_fileinfo.image_data); m_png_fileinfo.image_data = NULL; }

if (m_png_fileinfo.row_pointers) { free(m_png_fileinfo.row_pointers); m_png_fileinfo.row_pointers = NULL; }}

Page 37: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 37

/*---------------------------------------------------------------------------

wpng - simple PNG-writing program writepng.h

---------------------------------------------------------------------------

Copyright (c) 1998-2000 Greg Roelofs. All rights reserved.

This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment:

This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates.

---------------------------------------------------------------------------*/

#ifndef TRUE# define TRUE 1# define FALSE 0#endif

#ifndef MAX# define MAX(a,b) ((a) > (b)? (a) : (b))# define MIN(a,b) ((a) < (b)? (a) : (b))#endif

#ifdef DEBUG# define Trace(x) {fprintf x ; fflush(stderr); fflush(stdout);}#else# define Trace(x) ;#endif

#define TEXT_TITLE 0x01#define TEXT_AUTHOR 0x02#define TEXT_DESC 0x04#define TEXT_COPY 0x08#define TEXT_EMAIL 0x10#define TEXT_URL 0x20

#define TEXT_TITLE_OFFSET 0#define TEXT_AUTHOR_OFFSET 72#define TEXT_COPY_OFFSET (2*72)#define TEXT_EMAIL_OFFSET (3*72)#define TEXT_URL_OFFSET (4*72)#define TEXT_DESC_OFFSET (5*72)

typedef unsigned char uch;typedef unsigned short ush;typedef unsigned long ulg;

typedef struct _mainprog_info { double gamma; long width; long height; time_t modtime; FILE *infile;

Page 38: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 38

FILE *outfile; void *png_ptr; void *info_ptr; uch *image_data; uch **row_pointers; char *title; char *author; char *desc; char *copyright; char *email; char *url; int filter; /* command-line-filter flag, not PNG row filter! */ int pnmtype; int sample_depth; int interlaced; int have_bg; int have_time; int have_text; jmp_buf jmpbuf; uch bg_red; uch bg_green; uch bg_blue;} mainprog_info;

/* prototypes for public functions in writepng.c */

void writepng_version_info(void);

int writepng_init(mainprog_info *mainprog_ptr);

int writepng_encode_image(mainprog_info *mainprog_ptr);

int writepng_encode_row(mainprog_info *mainprog_ptr);

int writepng_encode_finish(mainprog_info *mainprog_ptr);

void writepng_cleanup(mainprog_info *mainprog_ptr);

Page 39: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 39

/*---------------------------------------------------------------------------

wpng - simple PNG-writing program writepng.c

---------------------------------------------------------------------------

Copyright (c) 1998-2000 Greg Roelofs. All rights reserved.

This software is provided "as is," without warranty of any kind, express or implied. In no event shall the author or contributors be held liable for any damages arising in any way from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

1. Redistributions of source code must retain the above copyright notice, disclaimer, and this list of conditions. 2. Redistributions in binary form must reproduce the above copyright notice, disclaimer, and this list of conditions in the documenta- tion and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgment:

This product includes software developed by Greg Roelofs and contributors for the book, "PNG: The Definitive Guide," published by O'Reilly and Associates.

---------------------------------------------------------------------------*/

#include <stdlib.h> /* for exit() prototype */

#include "png.h" /* libpng header; includes zlib.h and setjmp.h */#include "writepng.h" /* typedefs, common macros, public prototypes */

/* local prototype */

static void writepng_error_handler(png_structp png_ptr, png_const_charp msg);

void writepng_version_info(void){ fprintf(stderr, " Compiled with libpng %s; using libpng %s.\n", PNG_LIBPNG_VER_STRING, png_libpng_ver); fprintf(stderr, " Compiled with zlib %s; using zlib %s.\n", ZLIB_VERSION, zlib_version);}

/* returns 0 for success, 2 for libpng problem, 4 for out of memory, 11 for * unexpected pnmtype; note that outfile might be stdout */

int writepng_init(mainprog_info *mainprog_ptr){ png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; int color_type, interlace_type;

/* could also replace libpng warning-handler (final NULL), but no need: */

png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, writepng_error_handler, NULL); if (!png_ptr) return 4; /* out of memory */

Page 40: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 40

info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); return 4; /* out of memory */ }

/* setjmp() must be called in every function that calls a PNG-writing * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or exit immediately, so here we go: */

if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); return 2; }

/* make sure outfile is (re)opened in BINARY mode */

png_init_io(png_ptr, mainprog_ptr->outfile);

/* set the compression levels--in general, always want to leave filtering * turned on (except for palette images) and allow all of the filters, * which is the default; want 32K zlib window, unless entire image buffer * is 16K or smaller (unknown here)--also the default; usually want max * compression (NOT the default); and remaining compression flags should * be left alone */

png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);/* >> this is default for no filtering; Z_FILTERED is default otherwise: png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY); >> these are all defaults: png_set_compression_mem_level(png_ptr, 8); png_set_compression_window_bits(png_ptr, 15); png_set_compression_method(png_ptr, 8); */

/* set the image parameters appropriately */

if (mainprog_ptr->pnmtype == 5) color_type = PNG_COLOR_TYPE_GRAY; else if (mainprog_ptr->pnmtype == 6) color_type = PNG_COLOR_TYPE_RGB; else if (mainprog_ptr->pnmtype == 8) color_type = PNG_COLOR_TYPE_RGB_ALPHA; else { png_destroy_write_struct(&png_ptr, &info_ptr); return 11; }

interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE;

png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height, mainprog_ptr->sample_depth, color_type, interlace_type, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

if (mainprog_ptr->gamma > 0.0) png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);

if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */ png_color_16 background;

background.red = mainprog_ptr->bg_red; background.green = mainprog_ptr->bg_green; background.blue = mainprog_ptr->bg_blue;

Page 41: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 41

png_set_bKGD(png_ptr, info_ptr, &background); }

if (mainprog_ptr->have_time) { png_time modtime;

png_convert_from_time_t(&modtime, mainprog_ptr->modtime); png_set_tIME(png_ptr, info_ptr, &modtime); }

if (mainprog_ptr->have_text) { png_text text[6]; int num_text = 0;

if (mainprog_ptr->have_text & TEXT_TITLE) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Title"; text[num_text].text = mainprog_ptr->title; ++num_text; } if (mainprog_ptr->have_text & TEXT_AUTHOR) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Author"; text[num_text].text = mainprog_ptr->author; ++num_text; } if (mainprog_ptr->have_text & TEXT_DESC) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Description"; text[num_text].text = mainprog_ptr->desc; ++num_text; } if (mainprog_ptr->have_text & TEXT_COPY) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "Copyright"; text[num_text].text = mainprog_ptr->copyright; ++num_text; } if (mainprog_ptr->have_text & TEXT_EMAIL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "E-mail"; text[num_text].text = mainprog_ptr->email; ++num_text; } if (mainprog_ptr->have_text & TEXT_URL) { text[num_text].compression = PNG_TEXT_COMPRESSION_NONE; text[num_text].key = "URL"; text[num_text].text = mainprog_ptr->url; ++num_text; } png_set_text(png_ptr, info_ptr, text, num_text); }

/* write all chunks up to (but not including) first IDAT */

png_write_info(png_ptr, info_ptr);

/* if we wanted to write any more text info *after* the image data, we * would set up text struct(s) here and call png_set_text() again, with * just the new data; png_set_tIME() could also go here, but it would * have no effect since we already called it above (only one tIME chunk * allowed) */

/* set up the transformations: for now, just pack low-bit-depth pixels * into bytes (one, two or four pixels per byte) */

png_set_packing(png_ptr);/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */

Page 42: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 42

/* make sure we save our pointers for use in writepng_encode_image() */

mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr;

/* OK, that's all we need to do for now; return happy */

return 0;}

/* returns 0 for success, 2 for libpng (longjmp) problem */

int writepng_encode_image(mainprog_info *mainprog_ptr){ png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;

/* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */

if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; }

/* and now we just write the whole image; libpng takes care of interlacing * for us */

png_write_image(png_ptr, mainprog_ptr->row_pointers);

/* since that's it, we also close out the end of the PNG file now--if we * had any text or time info to write after the IDATs, second argument * would be info_ptr, but we optimize slightly by sending NULL pointer: */

png_write_end(png_ptr, NULL);

return 0;}

/* returns 0 if succeeds, 2 if libpng problem */

int writepng_encode_row(mainprog_info *mainprog_ptr) /* NON-interlaced only! */{ png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;

/* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */

if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2;

Page 43: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 43

}

/* image_data points at our one row of image data */

png_write_row(png_ptr, mainprog_ptr->image_data);

return 0;}

/* returns 0 if succeeds, 2 if libpng problem */

int writepng_encode_finish(mainprog_info *mainprog_ptr) /* NON-interlaced! */{ png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;

/* as always, setjmp() must be called in every function that calls a * PNG-writing libpng function */

if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); mainprog_ptr->png_ptr = NULL; mainprog_ptr->info_ptr = NULL; return 2; }

/* close out PNG file; if we had any text or time info to write after * the IDATs, second argument would be info_ptr: */

png_write_end(png_ptr, NULL);

return 0;}

void writepng_cleanup(mainprog_info *mainprog_ptr){ png_structp png_ptr = (png_structp)mainprog_ptr->png_ptr; png_infop info_ptr = (png_infop)mainprog_ptr->info_ptr;

if (png_ptr && info_ptr) png_destroy_write_struct(&png_ptr, &info_ptr);}

static void writepng_error_handler(png_structp png_ptr, png_const_charp msg){ mainprog_info *mainprog_ptr;

/* This function, aside from the extra step of retrieving the "error * pointer" (below) and the fact that it exists within the application * rather than within libpng, is essentially identical to libpng's * default error handler. The second point is critical: since both * setjmp() and longjmp() are called from the same code, they are * guaranteed to have compatible notions of how big a jmp_buf is, * regardless of whether _BSD_SOURCE or anything else has (or has not) * been defined. */

Page 44: bpeckham/export/MCM/2010/MCM Te…  · Web viewA serial criminal is defined as an offender who has committed two or more offenses, including murder and rape. Although repeat offenses

Team 8363 44

fprintf(stderr, "writepng libpng error: %s\n", msg); fflush(stderr);

mainprog_ptr = (mainprog_info*)png_get_error_ptr(png_ptr); if (mainprog_ptr == NULL) { /* we are completely hosed now */ fprintf(stderr, "writepng severe error: jmpbuf not recoverable; terminating.\n"); fflush(stderr); exit(99); }

longjmp(mainprog_ptr->jmpbuf, 1);}