Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_lhs(cell, order):
degrees = list(range(3, 8))
if cell == TensorProductCell(triangle, interval):
degrees = list(range(3, 6))
flops = [count_flops(helmholtz(cell, degree))
for degree in degrees]
rates = numpy.diff(numpy.log(flops)) / numpy.diff(numpy.log(degrees))
assert (rates < order).all()
def h(X):
R = get_entries(X, R_cds)
# Move this out...
np.seterr(divide='raise')
np.seterr(invalid='raise')
np.seterr(over='raise')
np.seterr(divide='raise')
np.seterr(invalid='raise')
np.seterr(over='raise')
try:
val = -np.log(np.linalg.det(R)) + np.trace(np.dot(R, B))
except FloatingPointError:
return -np.inf
return val
# grad - log det R = -R^{-1} = -Q (see Boyd and Vandenberge, A4.1)
ncx = 8
ncy = 8
ncz = 8
npad = 4
# hx = [(cs, ncx), (cs, npad, 1.3)]
# hz = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)]
mesh = Mesh.TensorMesh(
[
[(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)],
[(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)],
[(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)]
], 'CCC'
)
active = mesh.vectorCCz < 0.
activeMap = Maps.InjectActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
mapping = Maps.ExpMap(mesh) * Maps.SurjectVertical1D(mesh) * activeMap
prb = getattr(EM.TDEM, 'Problem3D_{}'.format(prbtype))(mesh, sigmaMap=mapping)
rxtimes = np.logspace(-4, -3, 20)
if waveform.upper() == 'RAW':
out = EM.Utils.VTEMFun(prb.times, 0.00595, 0.006, 100)
wavefun = interp1d(prb.times, out)
t0 = 0.006
waveform = EM.TDEM.Src.RawWaveform(offTime=t0, waveFct=wavefun)
prb.timeSteps = [(1e-3, 5), (1e-4, 5), (5e-5, 10), (5e-5, 10), (1e-4, 10)]
rxtimes = t0+rxtimes
else:
waveform = EM.TDEM.Src.StepOffWaveform()
# Test data set
x_test = x[split:]
y_test = y[split:]
cls = SVC().fit(x_train, y_train)
accuracy_train = accuracy_score(y_train, cls.predict(x_train))
accuracy_test = accuracy_score(y_test, cls.predict(x_test))
print('\nTrain Accuracy:{: .2f}%'.format(accuracy_train*100))
print('Test Accuracy:{: .2f}%'.format(accuracy_test*100))
df['Predicted_Signal'] = cls.predict(x)
# Calculate log returns
df['Return'] = np.log(df.close.shift(-1) / df.close)*100
df['Strategy_Return'] = df.Return * df.Predicted_Signal
df.Strategy_Return.iloc[split:].cumsum().plot(figsize=(10,5))
plt.ylabel("Strategy Returns (%)")
plt.show()
print(df)
def manual_ll(D, alpha=1, p=0.5):
"""
Manually compute the log likelihood for a model where edges are formed
with by preferential attachment with alpha with probability p and
uniformly at random with probability 1-p.
"""
# preferential attachment
# transform degree to score
D['score'] = np.exp(alpha * np.log(D.deg + log_smooth))
# compute total utility per case
score_tot = D.groupby('choice_id')['score'].aggregate(np.sum)
# compute probabilities of choices
scores_pa = np.array(D.loc[D.y == 1, 'score']) / np.array(score_tot)
# uniform
scores_uniform = np.array(1.0 / D.groupby('choice_id')['y'].aggregate(len))
# combine stores
scores = p * scores_pa + (1 - p) * scores_uniform
# add tiny smoothing for deg=0 choices
scores += log_smooth
# return sum
return -1 * sum(np.log(scores))
def r2z(r):
"""
Convert from R-space to CC-space
:type r: float
:param r: the critical value in the R space
:returns: the critical value in the CC-space
"""
return np.log((1+r)/(1-r))/2.0
def getErrCorr(self, wave, err_E_BV, rel_wave=None):
"""
Return the error on the correction for a given wavelength, given the error on E(B-V)
Parameters:
- wave wavelength(s)
- err_E_BV error on E(B-V)
- rel_wave reference wavelength for the normalization (optional)
"""
if rel_wave is None:
rel_X = 0.
else:
rel_X = self.X(rel_wave)
return np.log(10) * abs(self.X(wave) - rel_X) * 0.4 * err_E_BV * self.E_BV
d = np.zeros(indices.shape[0], dtype=np.float32)
p1 = c1 / w1
for i in range(indices.shape[0]):
ind2 = indices[i]
if scipy.sparse.issparse(c):
c2 = (c[ind2, statesKeep].toarray()[0] + unmerged[ind2] *
unmerged[statesKeep] / c.shape[0])
else:
c2 = (c[ind2, statesKeep] + unmerged[ind2]*unmerged[statesKeep] /
c.shape[0])
p2 = c2 / w[ind2]
cp = c1 + c2
cp /= (w1 + w[ind2])
d[i] = c1.dot(np.log(p1/cp)) + c2.dot(np.log(p2/cp))
return d
intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.)
intersect_area = intersect_wh[0] * intersect_wh[1]
box_area = box[2] * box[3]
anchor_area = anchor[0] * anchor[1]
iou = intersect_area / (box_area + anchor_area - intersect_area)
if iou > best_iou:
best_iou = iou
best_anchor = k
if best_iou > 0:
detectors_mask[i, j, best_anchor] = 1
adjusted_box = np.array(
[
box[0] - j, box[1] - i,
np.log(box[2] / anchors[best_anchor][0]),
np.log(box[3] / anchors[best_anchor][1]), box_class
],
dtype=np.float32)
matching_true_boxes[i, j, best_anchor] = adjusted_box
return detectors_mask, matching_true_boxes
def fisher(df, win, smooth_p = 0.7, smooth_i = 0.7):
roll_high = max(df.high[-win:])
roll_low = min(df.low[-win:])
price_loc = (df.ix[-1, 'close'] - roll_low)*2.0/(roll_high - roll_low) - 1
df.ix[-1, 'FISHER_P'] = df.ix[-2, 'FISHER_P'] * (1 - smooth_p) + smooth_p * price_loc
fisher_ind = 0.5 * np.log((1 + df.ix[-1, 'FISHER_P'])/(1 - df.ix[-1, 'FISHER_P']))
df.ix[-1, 'FISHER_I'] = df.ix[-2, 'FISHER_I'] * (1 - smooth_i) + smooth_i * fisher_ind