The periodicity of male nocturnal emission (Draft 2)

Richard Baxter*,¤

¤2915/350 William St, Melbourne VIC 3000, Australia * [email protected]

Abstract

Mental health diagnosis has become separated from theoretical models [1]. is a response to (imaginary) stimuli indicative of the environment of evolutionary adaptedness for copulation. Given that culture (including clothing) exists to limit experience of this environment to private, proprietary relations, it is possible that masturbation has become unwittingly normalised in sexually saturated (overstimulated) societies. If so, we would expect nature to exhibit alternate, unconscious systems of sexual regulation. It was first hypothesised (H1) that conscious sexual activity was not an inevitable behaviour for males, in that it could be entirely replaced by nocturnal emission (wet ). It was further hypothesised (H2) that periodicity in nocturnal emission would be exhibited, and based on preliminary data (H2B) that the periodicity observed would match the female menstrual cycle. The preliminary data set comprised a qualitative 1390 day observation and 210 day record of nocturnal emission. The primary data set comprised a 2641 day record featuring a total 471 instances of nocturnal emission. All hypotheses were confirmed. It is concluded that care must be taken to partial out societal changes (constraints) before reframing psychological health.

Author Summary Introduction

Psychological health is presently ill-defined [2] and many clinical classification schemes are atheoretical (e.g. DSM-III+ [1]). While medical health/diagnosis is grounded in biology (societal independent construction of conditions), mental health diagnosis has become separated from theoretical models. Attempts are therefore being made to ground mental health classification in biology (e.g. NIMH). Moreover, psychological health is considered to interact with society. For example, DSM classifications are dependent on an individual operating correctly (flourishing) in their society. This leaves open the possibility however of the society itself being non-conducive to human flourishing, and so mental health construction may become entangled in the failings of an individual society or societies. This is especially the case if research does not adequately span spatio-temporal horizons across culture. Mental health is rarely investigated cross-culturally so as to abstract psychological truths at a species level. First world societies have evolved rapidly over the last century (shift in social norms). Traditional large scale societies (civilisations) which maintain interactions beyond kin or tribe typically exhibit features that mitigate adaptive tendencies in males/females to respond procreatively to stimuli (e.g. clothing, proprietary). WEIRD (western educated industrialised rich democratic) nations have seen a shift however towards the elimination

1 of such norms. Such has been facilitated by the availability of artificial and abortion (the elimination of the natural consequences of sexual dysregulation). Masturbation is a response to (imaginary) stimuli indicative of the environment of evolutionary adaptedness for copulation. Given that culture (including clothing) exists to limit experience of this environment to private, proprietary relations, it is perhaps not coincidental that masturbation has become normalised in sexually saturated (overstimulated) societies. See S1 Appendix for an example of cultural shifts in attitudes towards mental health and sexual morality (compare USA scout handbook 1911 to that of 1967 on male maturation), or likewise, 19th and 20th century accounts in which masturbation was reviled [3, 4]. The construal of mental health has evolved to accommodate an increasingly large variety of sexual practices. It remains to be determined whether such changes in classification are a product of an increasingly adept theoretical understanding of human psychology, or are a byproduct of changes in societal expectations with regards to sexual proprietary. Likewise, it remains to be determined whether conscious sexual activity (intercourse or otherwise) is a necessary behaviour for a maturing/mature human or is a response to the (perceived) environment. Modern psychology regularly posits that it is a normal phenomenon for sexually inactive (null intercourse) males in a civilised society, as opposed to it being a response to (imaginary) stimuli indicative of the onset of natural sexual relations (as encoded within the environment of evolutionary adaptedness). The framing of masturbation as a cognitively ordered or biologically adaptive phenomenon (e.g. [5]) may therefore be incorrect. Such could be a culturally biased deduction based on an expectation for Homo sapiens to function normally in phylogenetically recent and therefore evolutionarily foreign large scale societies—without restrictions on proprietary. If so, we would expect nature to exhibit alternate, unconscious systems of sexual regulation. Nocturnal emission (or wet dreams) are commonly exhibited during male maturation. Historic estimates of their frequency have been measured to be once every two weeks on average [6]. Furthermore, there is circumstantial evidence to suggest that the experience of nocturnal emission is decreasing [6] for maturing males, which aligns with the inverse correlation observed between frequency of pornographic masturbation and nocturnal emission [7] and the increasing prevalence of pornographic consumption amongst youth (approaching 85% consumption) [8]. Some general principles regarding the prevalence of nocturnal emission are evident. Although the consistency of historic accounts is disputed [4], it has been suggested that nocturnal emission is strongly affected by sexual activity, in that its occurrence can be eliminated by the conscious acceptance of a subconscious reaction to real or imagined stimuli (i.e. intercourse or masturbation respectively) [7]. It may also be weakly affected by the environment irrespective of sexual activity (e.g. saturated experience of sexual stimuli), although such a possibility has not been investigated here. Therefore, in order to test the periodicity of nocturnal emission its occurrence was observed across a complete sexually inactive time period (null copulation/masturbation). An experiment was conducted to confirm (H1) that conscious sexual activity was not an inevitable or necessary phenomenon in an adult male. It was further hypothesised (H2) that if nocturnal emission is a natural and psychologically healthy behaviour for regulating sexual drive in human males, then rhythmic periodicity may be exhibited.

Method Preliminary qualitative observations suggested that (in accordance with H1) conscious sexual activity was not inevitable (1390 day complete sexually inactive observation). Likewise, (in accordance with H2) periodicity was observed in a preliminary data set that imprecisely (+/- 5 day accuracy) recorded nocturnal emission events (210 days).

2 Furthermore, it was observed that nocturnal emission appeared to occur on an approximately 30 day cycle, coincidental with the average 28 day (SD:4) female menstrual cycle [9]. The ability of a male cycle (if existent) to coordinate with that of its female group may be adaptive. It was therefore further hypothesised (H2B) that the periodicity observed would match the female menstrual cycle. These findings were retested in a controlled setting across a large time period. The existing primary data set comprises a 2641 day record featuring a total 471 instances of nocturnal emission (wet ) with zero instances of sexual activity/masturbation. In order to maintain this requirement (in a sexually suggestive society), both external and internal stimuli were analysed for their influence on prospective behaviours/desire, and a high degree of exercise (physical discipline) was engaged in. Instances of nocturnal emission were recorded upon wake (or the following day).

Results An average of 5.4 nocturnal emission events were observed per month. According to the first hypothesis (H1), it was found that conscious sexual activity was entirely replaced by subconscious sexual activity (nocturnal emission) for the time period sampled. See Fig. 1 and Fig. 2 for graphs of the recorded instances of wet dreams (WD), either stacked (where repeat events occurred within a 1-3 day time period), or used to create a histogram (with preliminary smoothing applied, enabling capture of repeat events across an approx 1-3 day time period). See S2 Appendix for a record of the primary raw dataset.

stack < 3 days (WD)

7

6

5

0 30 60 90 120 150 180 210 0 0 30 60 90 120 150 180 210 240 270 300 330 360 390 420 450 480 510 540 570 600 630 660 690 720 750 780 810 840 870 900 930 960 990 1020 1050 1080 1110 1140 1170 1200 1230 1260 1290 1320 1350 1380 1410 1440 1470 1500 1530 1560 1590 1620 1650 1680 1710 1740 1770 1800 1830 1860 1890 1920 1950 1980 2010 2040 2070 2100 2130 2160 2190 2220 2250 2280 2310 2340 2370 2400 2430 2460 2490 2520 2550 2580 2610 2640 y

c 4 n e u q e r F

3

2

1

0

Days

Figure 1. Record of all instances of wet dreams (WD) in the preliminary and primary data gathering stages, in stacked format (where repeat events occurred within a 1-3 day time period).

3 Histogram (WD) 7

6

5

4 y c n e u q e r

F 3

2

1

0 0 90 180 0 0 90 180 270 360 450 540 630 720 810 900 990 1080 1170 1260 1350 1440 1530 1620 1710 1800 1890 1980 2070 2160 2250 2340 2430 2520 2610

Days

Figure 2. Record of all instances of wet dreams (WD) in the preliminary and primary data gathering stages, in histogram format (with preliminary smoothing applied, enabling capture of repeat events across an approx 1-3 day time period).

When fitting a model of periodicity to the data, the optimum models indicated approximate 60 and 30 day periodicity respectively (frequency of the wet dream calculated optimum period across all data segmentation sizes and indices). That is, of the periodic models being overlayed with the data (periodicity spikes modelled as gaussian distributions), the models most frequently converged at an optiumum periodicity of 74 (67-78) and 37 (30-43) days. See Fig. 3 below. See S3 Appendix for a record of the software used to calculate the optimum periodicity (and offset) for different data segmentation sizes and indices.

4 90 74

80

70 71 60

y 50 c n

e 37 u

q 40 e r F 30 36 6973 70 136 18 4041 20 21 38 60 140 3233 72 23 3943 535559 129134137 3034 42 5152 6768 7578 130131135138 10 202224 293135 444549505456575861626466 9698 124128132133139 123456781091112131415161719 25262728 464748 6365 767779808182838485868788899091929394959799100101102103104105106107108109110111112113114115116117118119120121122123125126127 0 0 20 40 60 80 100 120 140 Male WD calculated optimum period (days)

Figure 3. Frequency of calculated male WD optimum period (days) across all data segmentation sizes and indices.

Discussion

Both hypotheses were confirmed. It was found (H1) that conscious sexual activity was not an inevitable or necessary phenomenon for an adult male. This concords with 19th and 20th century accounts of masturbation/nocturnal emission [3, 4]. Likewise, it was found (H2) that nocturnal emission exhibited periodicity, similar (. 2σ) in frequency to that of the female (average 28 day) menstrual cycle (H2B). This concords with various 19-20th century anecdotal accounts of nocturnal emission periodicity [10]; "four weeks", "at regular intervals of exactly a month", "every fortnight". Likewise, various 19-20th century anecdotal accounts cite similar rates of nocturnal emission to this sample; "the average frequency is about 3 per month of twenty-eight days" [10], 3-4 per month [3], 3-4 per month [4]. The results must be replicated for a large sample of individuals. It is concluded that in the effort to better construe mental health, theoretical psychology needs to focus harder on partialling out societal changes before reframing psychological health (or presenting traditionally ostracised behaviours as normal).

Acknowledgments

Jerry. is acknowledged for providing preliminary review of this manuscript.

5 Supporting Information S1 Appendix Cultural shifts in mental health and sexual morality

S2 Appendix Primary dataset of wet dream events (raw)

S3 Appendix WD experiment data analysis software program

References

1. Surís A, Holliday R, North CS. The evolution of the classification of psychiatric disorders. Behavioral Sciences. 2016;6(1):5. 2. Hickie IB, Scott J, Hermens DF, Scott EM, Naismith SL, Guastella AJ, et al. Clinical classification in mental health at the cross-roads: which direction next? BMC medicine. 2013;11(1):125.

3. Ellis H. Nocturnal emissions. Am J Psychol. 1904;15:104–107. 4. Burg B. Nocturnal emission and masturbatory frequency relationships: A 19th-century account. Journal of sex research. 1988;24(1):216–220. 5. Robbins CL, Schick V, Reece M, Herbenick D, Sanders SA, Dodge B, et al. Prevalence, frequency, and associations of masturbation with partnered sexual behaviors among US adolescents. Archives of pediatrics & adolescent medicine. 2011;165(12):1087–1093. 6. Matthews BS, Wells JW. A Comparative Study of Nocturnal Emissions. Journal of and Therapy. 1983;9(2):26–31. 7. Yu CKC. consumption and sexual behaviors as correlates of erotic dreams and nocturnal emissions. Dreaming. 2012;22(4):230. 8. Lim MS, Agius PA, Carrotte ER, Vella AM, Hellard ME. Young Australians’ use of pornography and associations with sexual risk behaviours. Australian and New Zealand journal of public health. 2017;41(4):438–443.

9. Chiazze L, Brayer FT, Macisco JJ, Parker MP, Duffy BJ. The length and variability of the human menstrual cycle. Jama. 1968;203(6):377–380. 10. Ellis H. Studies in the Psychology of Sex, Volume 1 The Evolution of , The Phenomena of Sexual Periodicity, Auto-Erotism. tredition; 2012.

6 S1 Appendix - Cultural shifts in attitudes towards mental health and sexual morality Extract from US Boy Scouts Handboook (1911) - "Conservation" In this chapter much has been said of the active measures which a boy should take in order to become strong and well. We should be equally concerned in saving and storing up natural forces we already have. In the body of every boy, who has reached his teens, the Creator of the universe has sown a very important fluid. This fluid is the most wonderful material in all the physical world. Some parts of it find their way into the blood, and through the blood give tone to the muscles, power to the brain, and strength to the nerves. This fluid is the sex fluid. When this fluid appears in a boy’s body, it works a wonderful change in him. His chest deepens, his shoulders broaden, his voice changes, his ideals are changed and enlarged. It gives him the capacity for deep feeling, for rich emotion. Pity the boy, therefore, who has wrong ideas of this important function, because they will lower his ideals of life. These organs actually secrete into the blood material that makes a boy manly, strong, and noble. Any habit which a boy has that causes this fluid to be discharged from the body tends to weaken his strength, to make him less able to resist disease, and often unfortunately fastens upon him habits which later in life he cannot break. Even several years before this fluid appears in the body such habits are harmful to a growing boy. To become strong, therefore, one must be pure in thought and clean in habit. This power which I have spoken of must be conserved, because this sex function is so deep and strong that there will come times when temptation to wrong habits will be very powerful. But remember that to yield means to sacrifice strength and power and manliness. For boys who desire to know more of this subject we would suggest a splendid book by Dr. Winfield S. Hall, entitled, "From Youth into Manhood." Every boy in his teens who wants to know the secret of strength, power, and endurance should read this book.

Extract from US Boy Scouts Handboook (1965) - "From Boy to Man" From Boy to Man. At the age of 13, 14, or 15 (sometimes earlier, sometimes later) you not only grow, but numerous changes take place in your body. Your voice changes. Hair appears on your face, in the armpits, around the sex organ. Your sex organ increases in size. All these changes are caused by the function of the sex glands or testicles. They produce fluids or secretions that have a great effect on your development. At times the glands discharge part of their secretions through the sex organ during . This process is called a nocturnal emission or a "wet dream." It is perfectly natural and healthy and a sign that nature has taken care of the situation in its own manner. There are boys who do not let nature have its own way with them but cause emissions themselves. This may do no physical harm, but may cause them to worry. Any real boy knows that anything that causes him to worry should be avoided or overcome. If anything like this worries you, this is not unusual just about all boys have the same problem. Seek the correct answer to any question which bothers you about your development from boy to man. But be sure to get your information from reliable sources — your parents, your physician, your spiritual adviser.

1 S2 Appendix - Primary dataset of wet dream events (raw)

frequency.txt (number of events per day);

10000000000000000000000000000000030000000000000000001000000100000

0000000000100000000000011001000002000000001030000000010000010000000

0000010000030000300000100100100010000011100010000000001000100000000

0000100000000000000101000000100101010201010000000011000000000010001

0001000000000000000000000000000001000000010110000000001200100010000

1002000000100011000001110000000000011000000010000101111001000110101

0000002000011000000000001000001100100101000101010001000000000010000

1000001000010000000000010000000000000000001000001000000002000010000

0001000110000010000001000000000000010000000000000111000001001100000

0101010000000000001000100010010000000101010000100000130000000100010

0000011001000000011000000001010000201010100011000000000000100000001

0300101000000110100000100000000000001000000101000000000110101000010

0001000000000001000000110201011000100000000000000001100000001000000

1010101100000010000000000010101000000000010010001100000000000000001

0000000000101001000001000010010000000100000100000000310100001100000

1000000000010000200001000001000100010000000000000002011000020000000

1000100000000000100010000000010000000000010010000000010011000000000

0000011000000020000000000011000000000100000000100000001000100011000

0000000000010001100000000000000010000000000200010000010001000000000

0001000000110100200010000000000000000000000100000100000000000001000

0010010010100100000000100011100000000000000001000000000010000003010

0000001000000000000000010100000100100000000000000000110000000003001

1010000100000000100000000000001000011000000000020000000000001000000

0001001000000100020000001000001000000010200110000001000000000010000

1110000210100000001001000000000000001000001020000010000000011000001

0000000000100000000000000000000001000100001000001000000001110000000

0100000000000100000000000010000020000010000000000001000001100100000

0000001021000000010000001000000000000001000000000000000000000000202

1000000000000000000000020000000000000000000100100000000000000120000

1000100010000000000110000001000010001000001000000000011000000000200

0000100000000000000102000000000000000001110001100000010010000000000

0000000000020000000000000103000000001000000000000000000000000000000

0100100000000000000002000010102000000200000000011000000000000000001

0000000001000000000010010000000000000010000000000000000001100100000

0000000000020000000100000000000000001100100011010000000010000000000

0000000001000000000000001000000000000000000000000001000010001000001

0100000001000000100010000000000010001010000000100100200000000100000

0100000000000001000000000000000000000000001000000100000100000000100

0010001000010000010000000001000100001000020000001010010200001000010

000000000000000000000000000010

1 S3 Appendix - WD experiment data analysis software program WDexperimentDataAnalysis.h

/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ ∗ ∗ File Name: WDexperimentDataAnalysis.h ∗ Author: Richard Bruce Baxter − Copyright (c) 2016 ∗ Project: WD Experiment Data Analysis ∗ Project Version: 1a1d 28−August −2016 ∗ Requirements: requires frequency data generated by WDexperiment−x . ods ∗ ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/

#de f i n e WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET //1 a1b #de f i n e WD_OPTIMISE_PARAMETERS_SEGMENTATION //1 a1c //#d e f i n e WD_OPTIMISE_PARAMETERS_VERBOSE_OUTPUT // removed 1 a1c ( e n a b l e s h i s t o g r a m d a t a t o be c o l l e c t e d ) //#d e f i n e WD_DEBUG_USE_PRELIM_DATA

#de f i n e WD_WRITE_FREQUENCY_MODEL #de f i n e WD_WRITE_FREQUENCY_AVERAGED #de f i n e WD_MODEL_GAUSSIAN //else use cosine distribution #de f i n e WD_DATA_FREQUENCY_FILE_NAME " f r e q u e n c y . t x t " #de f i n e WD_DATA_FREQUENCY_PRELIM_FILE_NAME " f r e q u e n c y P r e l i m . t x t " #de f i n e WD_DATA_FREQUENCY_AVERAGED_FILE_NAME " f r e q u e n c y A v e r a g e d . t x t " #de f i n e 1 WD_DATA_FREQUENCY_THEORETICAL_FILE_NAME " f r e q u e n c y T h e o r e t i c a l . t x t " #de f i n e CHAR_NEWLINE ’ \n ’

#include #include #include #include #include #include #include #include

#include #include < l i s t > #include

using namespace s t d ;

i n t main ( ) ; void findOptimumPeriod (); bool getFilesFromFileList(string inputListFileName , vector∗ inputTextFileNameList , i n t ∗ numberOfInputFilesInList ); void writeStringToFile(string fileName , string ∗ s ) ; i n t convertStringToInt(string number); string convertDoubleToString( double number, string format); double absoluteValue( double v a l ) ; #i f d e f WD_MODEL_GAUSSIAN double calculateGaussianPeriodCoverage( i n t p e r i o d , double gaussianStandardDeviationPerPeriod ); double calculateGaussianDistributionAtPoint( i n t i , i n t p e r i o d , double gaussianStandardDeviationPerPeriod ); double calculateGaussianDistribution( double x , double mean , double standardDeviation ); #e l s e double calculateCosinePeriodCoverage( i n t p e r i o d ) ; #e n d i f double calculateCosineDistributionAtPoint( i n t i , i n t p e r i o d ) ; WDexperimentDataAnalysis.cpp

/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ ∗ ∗ File Name: WDexperimentDataAnalysis.cpp ∗ Author: Richard Bruce Baxter − Copyright (c) 2016 ∗ Project: WD Experiment Data Analysis ∗ Project Version: 1a1d 28−August −2016 ∗ Requirements: requires frequency data generated by WDexperiment−x . ods ∗ ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/

#include "WDexperimentDataAnalysis .h"

i n t main ( ) { findOptimumPeriod (); }

void findOptimumPeriod () { //http ://www. cplusplus .com/reference/random/normal_distribution/

#i f d e f WD_DEBUG_USE_PRELIM_DATA s t r i n g f r e q u e n c y F i l e N a m e = WD_DATA_FREQUENCY_PRELIM_FILE_NAME; #e l s e s t r i n g f r e q u e n c y F i l e N a m e = WD_DATA_FREQUENCY_FILE_NAME;

2 #e n d i f vector frequencyListString ; v e c t o r frequencyList; i n t numberOfDays = 0; i f (! getFilesFromFileList(frequencyFileName , &frequencyListString , &numberOfDays)) { cout << "main{}␣error :␣! getFilesFromFileList :␣" << frequencyFileName << endl; } i n t numberOfEvents = 0; f o r (vector::iterator iter=frequencyListString.begin(); iter != frequencyListString.end(); iter++) { string frequencyString = ∗ i t e r ; i n t frequency = convertStringToInt(frequencyString ); frequencyList .push_back(frequency ); numberOfEvents = numberOfEvents + frequency ; }

double averageNumberOfEventsPerDay = double (numberOfEvents)/ double (numberOfDays ); //calculated based on sum of frequency.txt

//convergence optimisation parameters i n t segmentationDefault = 1000; //180: 6 months 365: 12 months //numberOfDays; #i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION i n t segmentationMin = numberOfDays/4/4; //approx 3 months //theoretical ideal segmentation = 6 months (360/2) i n t segmentationMax = numberOfDays; i n t segmentationInterval = 10; i n t segmentationNum = (segmentationMax−segmentationMin)/segmentationInterval ; i n t segmentationOpt = −1; // 48

i n t segmentNum = numberOfDays/segmentationMin ; // 16 i n t averageSegmentSize = (segmentationMax − segmentationMin )/2; //this will be an overestimate i n t segmentationNumApprox = numberOfDays/averageSegmentSize ;

cout << "segmentationMin␣=␣" << segmentationMin << endl ; cout << "segmentationMax␣=␣" << segmentationMax << endl ; cout << "segmentationInterval␣=␣" << segmentationInterval << endl; #e n d i f

i n t segmentOpt = −1;

i n t binDefault = 5; //averaging bin size

double seasonalVariationFractionDefault = 0.0; //seasonal variation

i n t seasonalVariationPeriodDefault = 360; //1 year

i n t seasonalVariationOffsetDefault = 0; //minimal seasonal variation

i n t periodDefault = 30; //theoretical ideal period = 30 days #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET i n t periodMin = 10; i n t periodMax = 160; i n t periodInterval = 1; i n t periodNum = (periodMax−periodMin)/periodInterval ; // 50 i n t p eri od Opt = −1; cout << "periodMin␣=␣" << periodMin << endl; cout << "periodMax␣=␣" << periodMax << endl; cout << "periodInterval␣=␣" << periodInterval << endl; #e n d i f

i n t offsetDefault = periodDefault/2; //centre first period at first data point #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET i n t offsetMin = 0; i n t offsetInterval = 1; 3 i n t offsetNumApprox = periodMax/2; // e . g . 30 i n t o f f s e t O p t = −1; cout << "offsetMin␣=␣" << offsetMin << endl; cout << "offsetInterval␣=␣" << offsetInterval << endl; cout << "offsetNumApprox␣=␣" << offsetNumApprox << endl ; #e n d i f

double gaussianStandardDeviationPerPeriodDefault = 3.0; // 2 . 0 − expect 95% of events to occur each period //consider changing to 1.0 − expect 68% of events to occur each period

double eventsPerDayMinimaFractionDefault = 0.0; //y offset of model distribution (allows for the modelling of a noisy distribution)

i n t segmentationIndex = 0; #d e f i n e SOME_LARGE_NUMBER ( 9 9 9 9 9 9 9 9 9 9 9 . 9 )

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION double f r e q u e n c y D i f f A v e r a g e M i n = SOME_LARGE_NUMBER; #e n d i f

v e c t o r frequencyListTheoretical(numberOfDays);

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION f o r ( i n t segmentation = segmentationMin; segmentation < segmentationMax; segmentation = segmentation+segmentationInterval) { #e l s e i n t segmentation = segmentationDefault ; #e n d i f #i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION v e c t o r segmentFrequencyDiffAverageMinList ; double segmentFrequencyDiffAverageMinAveraged = 0.0; #e n d i f #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET #i f d e f WD_OPTIMISE_PARAMETERS_VERBOSE_OUTPUT cout << "segmentation␣=␣" << segmentation << "␣days" << endl; #e n d i f double segmentPeriodOptAveraged = 0.0; double segmentOffsetOptAveraged = 0.0; #e n d i f

i n t segmentIndex = 0; f o r ( i n t segmentStartDay = 0; segmentStartDay < numberOfDays; segmentStartDay = segmentStartDay + segmentation) { i n t segmentEndDay = segmentStartDay + segmentation ; i f (segmentEndDay > numberOfDays) { segmentEndDay = numberOfDays; } i n t segmentNumberOfDays = segmentEndDay−segmentStartDay ; double s e g m e n t F r e q u e n c y D i f f A v e r a g e M i n = SOME_LARGE_NUMBER; i n t bin = binDefault; v e c t o r frequencyListAveraged(numberOfDays); l i s t frequencyStacked; f o r ( i n t i=0; i= b i n ) { i n t numberOfEventsInBin = 0; f o r ( l i s t ::iterator iter=frequencyStacked.begin(); iter != frequencyStacked.end(); iter++) { numberOfEventsInBin = numberOfEventsInBin + ∗ i t e r ; } 4 double frequencyAveraged = double (numberOfEventsInBin)/ double ( b i n ) ; //cout << "i = " << i << ", numberOfEventsInBin = " << numberOfEventsInBin << endl; //cout << "i = " << i << ", frequencyAveraged = " << frequencyAveraged << endl; frequencyListAveraged [ i −(bin/2)] = frequencyAveraged;

frequencyStacked .pop_front (); } }

#i f d e f WD_WRITE_FREQUENCY_MODEL //vector frequencyListAveragedString ; string frequencyListAveragedString = ""; f o r ( v e c t o r ::iterator iter=frequencyListAveraged.begin(); iter != frequencyListAveraged.end(); iter++) { double frequencyAveraged = ∗ i t e r ; string frequencyAveragedString = convertDoubleToString(frequencyAveraged , "%0.6f"); //frequencyListAveragedString .push_back(frequencyAveragedString ); frequencyListAveragedString = frequencyListAveragedString + frequencyAveragedString + CHAR_NEWLINE; } w r i t e S t r i n g T o F i l e (WD_DATA_FREQUENCY_AVERAGED_FILE_NAME, &f r e q u e n c y L i s t A v e r a g e d S t r i n g ) ; #e n d i f

double seasonalVariationFraction = seasonalVariationFractionDefault ; i n t seasonalVariationPeriod = seasonalVariationPeriodDefault ; i n t seasonalVariationOffset = seasonalVariationOffsetDefault ; #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET i n t periodIndex = 0; f o r ( i n t period = periodMin; period < periodMax; period = period+periodInterval) { i n t offsetIndex = 0; i n t offsetMax = period/2; f o r ( i n t offset = offsetMin; offset < offsetMax; offset = offset+offsetInterval) { #e l s e i n t period = periodDefault; i n t offset = offsetDefault; #e n d i f double gaussianStandardDeviationPerPeriod = gaussianStandardDeviationPerPeriodDefault ; double eventsPerDayMinimaFraction = eventsPerDayMinimaFractionDefault ;

#i f d e f WD_MODEL_GAUSSIAN double modelPeriodCoverage = calculateGaussianPeriodCoverage(period , gaussianStandardDeviationPerPeriod ); #e l s e double modelPeriodCoverage = calculateCosinePeriodCoverage(period ); //will return 0 (as equal negative and positive components of distribution) #e n d i f double eventsPerPeriod = averageNumberOfEventsPerDay ∗ p e r i o d ;

#i f d e f WD_DEBUG cout << "modelPeriodCoverage␣=␣" << modelPeriodCoverage << endl ; #e n d i f

//int startDay = segmentStartDay+offset ; //int endDay = segmentEndDay+offset ; double frequencyDiffAverage = 0.0; double frequencySumOfSquares = 0.0; i n t dayIndex = 0; f o r ( i n t day = segmentStartDay; day < segmentEndDay; day++) { double seasonalVariationForDayModifier = calculateCosineDistributionAtPoint(day+seasonalVariationOffset , seasonalVariationPeriod) ∗ seasonalVariationFraction ; //cout << "seasonalVariationForDayModifier = " << seasonalVariationForDayModifier << endl;

5 i n t i = (dayIndex+offset)%period; //int i = mod(dayIndex+offset , period); #i f d e f WD_MODEL_GAUSSIAN double modelValue = calculateGaussianDistributionAtPoint(i , period , gaussianStandardDeviationPerPeriod ); #e l s e double modelValue = calculateCosineDistributionAtPoint(i , period) + 1.0; //+1.0 to ensure that distribution coverage is always positive; #e n d i f double frequencyTheoretical = ((modelValue/modelPeriodCoverage ∗ eventsPerPeriod) + (eventsPerPeriod ∗ eventsPerDayMinimaFraction))/(1.0 + eventsPerDayMinimaFraction) + seasonalVariationForDayModifier ; //CHECKTHIS #i f d e f WD_DEBUG cout << "eventsPerDayMinimaFraction␣=␣" << eventsPerDayMinimaFraction << endl ; cout << "modelPeriodCoverage␣=␣" << modelPeriodCoverage << endl ; cout << "eventsPerPeriod␣=␣" << eventsPerPeriod << endl; cout << "modelValue␣=␣" << modelValue << endl; cout << "frequencyTheoretical␣=␣" << frequencyTheoretical << endl; #e n d i f frequencyListTheoretical [day] = frequencyTheoretical ; double frequency = frequencyListAveraged[day]; double frequencyDiff = frequency − frequencyTheoretical ; frequencyDiffAverage = frequencyDiffAverage + absoluteValue(frequencyDiff ); frequencySumOfSquares = frequencySumOfSquares + pow(frequencyDiff , 2); dayIndex++; } double frequencyVariance = frequencySumOfSquares/(dayIndex −1); frequencyDiffAverage = frequencyVariance ; //use variance rather than average diff //frequencyDiffAverage = frequencyDiffAverage/dayIndex;

i f (frequencyDiffAverage < segmentFrequencyDiffAverageMin) { segmentFrequencyDiffAverageMin = frequencyDiffAverage ; #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET periodOpt = period; offsetOpt = offset; #e n d i f } #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET offsetIndex++; } periodIndex++; } #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_VERBOSE_OUTPUT cout << "segmentIndex␣=␣" << segmentIndex << endl; #i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET cout << "periodOpt␣=␣" << periodOpt << endl; cout << "offsetOpt␣=␣" << offsetOpt << endl; #e n d i f #e l s e cout << segmentation << "\t" << segmentationIndex << "\t" << periodOpt << endl; #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET segmentPeriodOptAveraged = segmentPeriodOptAveraged + periodOpt ; segmentOffsetOptAveraged = segmentOffsetOptAveraged + offsetOpt ; #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION segmentFrequencyDiffAverageMinList .push_back(segmentFrequencyDiffAverageMin ); segmentFrequencyDiffAverageMinAveraged = segmentFrequencyDiffAverageMinAveraged + segmentFrequencyDiffAverageMin ; #e n d i f

segmentIndex++; 6

}

#i f d e f WD_OPTIMISE_PARAMETERS_PERIOD_AND_OFFSET segmentPeriodOptAveraged = segmentPeriodOptAveraged/segmentIndex ; segmentOffsetOptAveraged = segmentOffsetOptAveraged/segmentIndex ; #i f d e f WD_OPTIMISE_PARAMETERS_VERBOSE_OUTPUT cout << "segmentPeriodOptAveraged␣=␣" << segmentPeriodOptAveraged << endl ; cout << "segmentOffsetOptAveraged␣=␣" << segmentOffsetOptAveraged << endl ; #e n d i f #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION segmentFrequencyDiffAverageMinAveraged = segmentFrequencyDiffAverageMinAveraged/segmentIndex ; i f (segmentFrequencyDiffAverageMinAveraged < frequencyDiffAverageMin) { frequencyDiffAverageMin = segmentFrequencyDiffAverageMinAveraged ; segmentationOpt = segmentationIndex ; } #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION segmentationIndex++; } #e n d i f

#i f d e f WD_OPTIMISE_PARAMETERS_SEGMENTATION cout << "frequencyDiffAverageMin␣=␣" << frequencyDiffAverageMin << endl ; cout << "segmentationOpt␣=␣" << segmentationOpt << endl ; #e n d i f

#i f d e f WD_WRITE_FREQUENCY_MODEL //vector frequencyListTheoreticalString ; string frequencyListTheoreticalString = ""; f o r ( v e c t o r ::iterator iter=frequencyListTheoretical.begin(); iter != frequencyListTheoretical.end(); iter++) { double frequencyTheoretical = ∗ i t e r ; string frequencyTheoreticalString = convertDoubleToString(frequencyTheoretical , "%0.6f"); //frequencyListTheoreticalString .push_back(frequencyTheoreticalString ); frequencyListTheoreticalString = frequencyListTheoreticalString + frequencyTheoreticalString + CHAR_NEWLINE; } w r i t e S t r i n g T o F i l e (WD_DATA_FREQUENCY_THEORETICAL_FILE_NAME, &f r e q u e n c y L i s t T h e o r e t i c a l S t r i n g ) ; #e n d i f }

bool getFilesFromFileList(string inputListFileName , vector∗ inputTextFileNameList , i n t ∗ numberOfInputFilesInList) { bool r e s u l t = true ; ∗ numberOfInputFilesInList = 0; ifstream parseFileObject(inputListFileName.c_str ()); i f (! parseFileObject .rdbuf()−>is_open ()) { //txt file does not exist in current directory. #i f n d e f NLC_USE_LIBRARY_DISABLE_FUNCTIONS_LIST_WARNING cout << "Error:␣input␣list␣file␣does␣not␣exist␣in␣current␣directory :␣" << inputListFileName << endl; #e n d i f r e s u l t = f a l s e ; } e l s e { char currentToken ; i n t fileNameIndex = 0; 7 i n t charCount = 0; string currentFileName = ""; while (parseFileObject . get(currentToken)) { i f ( c u r r e n t T o k e n == CHAR_NEWLINE) { inputTextFileNameList −>push_back(currentFileName ); #i f d e f GIA_MAIN_DEBUG //cout << "currentFileName = " << currentFileName << endl; #e n d i f currentFileName = ""; fileNameIndex++; } e l s e { currentFileName = currentFileName + currentToken; } charCount++; } ∗ numberOfInputFilesInList = fileNameIndex; } #i f d e f GIA_MAIN_DEBUG // c o u t << "∗ numberOfInputFilesInList = " <<∗ numberOfInputFilesInList << endl; #e n d i f return r e s u l t ; }

void writeStringToFile(string fileName , string ∗ s ) { ofstream writeFileObject(fileName.c_str ());

//writeFileObject . write(∗ s ) ; f o r ( i n t i =0; i < s−>size (); i++) { writeFileObject .put(( ∗ s ) [ i ] ) ; }

writeFileObject . close (); }

i n t convertStringToInt(string number) { return atoi(number. c_str ()); }

string convertDoubleToString( double number, string format) { char stringCharStar [100]; sprintf(stringCharStar , format.c_str(), number); return string(stringCharStar ); }

double absoluteValue( double v a l ) { return abs ( v a l ) ; }

#i f d e f WD_MODEL_GAUSSIAN //centre the distribution about the centre of the first period in the segment double calculateGaussianPeriodCoverage( i n t p e r i o d , double gaussianStandardDeviationPerPeriod) { double modelPeriodCoverage = 0.0; 8 f o r ( i n t i=0; i