/
calculations.py
executable file
·287 lines (252 loc) · 10.9 KB
/
calculations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""
calculations.py
* Copyright (c) 2006-2009, University of Colorado.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Colorado nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF COLORADO ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF COLORADO BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
#forces all division to be floating-point
from __future__ import division
import numpy as np
import scipy.integrate as integrate
import confidence
class ListComparison(object):
def __init__(self,normal_list_matrix):
self.normal_matrix = normal_list_matrix
def within(self, currentlist):
'''
currentlist should be same length as previous
output : normal or not
return applicabilities. How normal is this?
'''
# make each row sum to 1
row_sums = self.normal_matrix.sum(axis=1)
new_matrix = self.normal_matrix / row_sums[:, numpy.newaxis]
currentlist = [a/sum(currentlist) for a in currentlist]
# see if currentlist is within previous ranges at each index
mins = np.min(new_matrix,0)
maxes = np.max(new_matrix,0)
inside_range = 0
for i in xrange(len(currentlist)):
if currentlist[i]<=maxes[i] and currentlist[i]>=mins[i]:
inside_range += 1
probability = inside_range / len(currentlist)
if probability >= .9:
return confidence.Applicability.highlyfor
elif probability >= .8:
return confidence.Applicability.mostlyfor
elif probability >= .7:
return confidence.Applicability.weaklyfor
elif probability >= .6:
return confidence.Applicability.weaklyagainst
elif probability >= .3:
return confidence.Applicability.mostlyagainst
else:
return confidence.Applicability.highlyagainst
class GaussianThreshold(object):
def __init__(self, mean, variation):
self.mean = mean
self.variation = variation
def __lt__(self, value, perc):
# P will be the probability that the Gaussian variable is less than "value"
mu = self.mean
sigma = np.sqrt(self.variation)
pdf = lambda t: 1/(sigma*np.sqrt(2*np.pi))*np.exp((t-mu)**2/(2*sigma**2))
P = .5 + integrate.quad(pdf,mu,float(value))[0]
# determine the "applicability"
strictness = min(abs(perc),abs(1-perc))
if P >= perc:
return confidence.Applicability.highlyfor
elif (perc-P) <= strictness/2:
# almost close enough
return confidence.Applicability.weaklyfor
elif (perc-P) <= strictness:
# not very close
return confidence.applicability.weaklyagainst
else:
# very far off
return confidence.Applicability.highlyagainst
def __le__(self, value, perc):
# P will be the probability that the Gaussian variable is less then "value"
mu = self.mean
sigma = np.sqrt(self.variation)
pdf = lambda t: 1/(sigma*np.sqrt(2*np.pi))*np.exp((t-mu)**2/(2*sigma**2))
P = .5 + integrate.quad(pdf,mu,float(value))[0]
# determine the "applicability"
strictness = min(abs(perc),abs(1-perc))
if P >= perc:
return confidence.Applicability.highlyfor
elif (perc-P) <= strictness/2:
return confidence.Applicability.weaklyfor
elif (perc-P) <= strictness:
return confidence.applicability.weaklyagainst
else:
return confidence.Applicability.highlyagainst
def __gt__(self, value, perc):
# P will be the probability that the Gaussian variable is less then "value"
mu = self.mean
sigma = np.sqrt(self.variation)
pdf = lambda t: 1/(sigma*np.sqrt(2*np.pi))*np.exp((t-mu)**2/(2*sigma**2))
P = .5 - integrate.quad(pdf,mu,float(value))[0]
# determine the "applicability"
strictness = min(abs(perc),abs(1-perc))
if P >= perc:
return confidence.Applicability.highlyfor
elif (perc-P) <= strictness/2:
return confidence.Applicability.weaklyfor
elif (perc-P) <= strictness:
return confidence.applicability.weaklyagainst
else:
return confidence.Applicability.highlyagainst
def __ge__(self, value, perc):
# P will be the probability that the Gaussian variable is less then "value"
mu = self.mean
sigma = np.sqrt(self.variation)
pdf = lambda t: 1/(sigma*np.sqrt(2*np.pi))*np.exp((t-mu)**2/(2*sigma**2))
P = .5 - integrate.quad(pdf,mu,float(value))[0]
# determine the "applicability"
strictness = min(abs(perc),abs(1-perc),.25)
if P >= perc:
return confidence.Applicability.highlyfor
elif (perc-P) <= strictness/2:
# we are almost close enough
return confidence.Applicability.weaklyfor
elif (perc-P) <= strictness:
# we're sort of far away
return confidence.applicability.weaklyagainst
else:
# we're really far away
return confidence.Applicability.highlyagainst
def __eq__(self, value, perc):
pass
def __ne__(self, value, perc):
return Applicability.highlyfor
def synth_gaussian(core, mean, variation):
return GaussianThreshold(mean, variation)
def past_avg_temp(core, *args):
return 'cake'
def get_normal_peak_behavior(core, depths):
'''
returns a peak comparison object
warning: doesn't work right if you're too close to the top
or if the core doesn't have very many samples
or if the given depthlist is very long relative to the whole core
'''
# find peaks 3 times
# give list of dictionaries? to peak comparison object creator
# get current peak dict
# object.within(current_peak_dict)
depthlist, proxylist = depths
alldepths = sorted(core.keys())
length = len(depthlist)
# get the index of the depth halfway up
i = next(x[0] for x in enumerate(alldepths) if x[1] > depthlist[0]/2)
depthlist1 = alldepths[i-length:i]
depthlist2 = alldepths[i:i+length]
depthlist3 = alldepths[i+length:i+2*length]
peaklist1 = count_peaks_per_proxy(core,depthlist1,proxylist)
peaklist2 = count_peaks_per_proxy(core,depthlist2,proxylist)
peaklist3 = count_peaks_per_proxy(core,depthlist3,proxylist)
normalpeakmatrix = np.array([peaklist1,peaklist2,peaklist3])
comparison_object = ListComparison(normalpeakmatrix)
return comparison_object
def count_peaks(core,depthlist,proxy_name,strictness=10):
"""
The peak detection algorithm is originally from https://gist.github.com/endolith/250860
I've modified it a bit ( - Kathleen)
"""
# I don't know if this is the right way to grab the data
datalist = [core[depth][proxy_name] for depth in depthlist]
# detrend the dataseries with low-degree polynomial
degree = min(y,np.round(len(datalist)/10))
p = np.polyfit(depthlist,datalist,degree)
p_evaluated = np.polyval(p,depthlist)
datalist -= p_evaluated
datarange = max(datalist)-min(datalist)
delta = datarange/strictness
numPeaks = 0
mn, mx = Inf, -Inf
lookformax = True
for i in arange(len(datalist)):
this = datlist[i]
if this > mx:
mx = this
if this < mn:
mn = this
if lookformax:
if this < mx-delta:
numPeaks += 1
mn = this
lookformax = False
else:
if this > mn+delta:
mx = this
lookformax = True
return numPeaks
def count_peaks_per_proxy(core, depths):
# call count_peaks for each proxy
depthlist, proxylist = depths
peaklist = [count_peaks(core,depthlist,proxy_name) for proxy_name in proxylist]
return peaklist
def number_of_peaks_is_normal(core, depths):
'''
go back to half the depth
look at 3 other depth intervals, each proxy series in those depth intervals
see if your current interval has 'not enough bumps' in each data series, in comparison to 'normal'
if current number of bumps per series is not normal, return evidence AGAINST
if it IS normal, return evidence FOR
'''
depthlist, proxylist = depths
currentpeaklist = count_peaks_per_proxy(core,depthlist,proxylist)
NormalPeakComparer = get_normal_peak_behavior(core,depthlist,proxylist)
result = NormalPeakComparer.within(currentpeaklist)
return result
def known_depth_proxies(core,depth_interval):
depthlist = sorted(core.keys())
depthlist = [a for a in depthlist if a >= depth_interval[0] and a <= depth_interval[1]]
proxylist = sorted(core[depth[0]].keys())
return depthlist,proxylist
#TODO: make a useful auto-currier thing
def min(core, *args):
return np.min(*args)
def max(core, *args):
return np.max(*args)
def find_angles(core, var1, var2):
points = [(float(sample[var1]), float(sample[var2])) for sample in core if
sample[var1] is not None and sample[var2] is not None]
points.sort()
x, y = map(np.array, zip(*points))
x1 = np.ediff1d(x)
y1 = np.ediff1d(y)
a = x1[:-1] ** 2 + y1[:-1] ** 2
b = x1[1:] ** 2 + y1[1:] ** 2
c = (x[2:] - x[:-2]) ** 2 + (y[2:] - y[:-2]) ** 2
return np.degrees(np.arccos((a + b - c) / np.sqrt(4 * a * b)))
def is_ocean(core, latitude, longitude):
#doing the import here for now so not having pillow doesn't crash anyone :P
#(this is the easiest way to make that so)
from PIL import Image
img = Image.open('../resources/ocean.png')
x = (longitude + 180) / 360 * 6000
y = (latitude + 90) / 180 * 3000
return bool(img.getpixel((x, 3000-y))) # 255 = ocean, 0 = land