def test_distance(self): atom1 = Atom(1, 'CA', '', 'A', 'ALA', 1, '', x=1., y=2., z=2., occupancy=1., b_factor=0., element=None, mass=None) atom2 = Atom() assert_almost_equals(3.0, atom1.distance(atom2)) assert_almost_equals(3.0, atom2.distance(atom1))
def test_Laminate_sanity6(): '''Check middle d_ is half the total thickness.''' cols = ['t(um)'] for case in cases.values(): for LM in case.LMs: # for LMs in cases.values(): # for LM in LMs: if (LM.nplies%2 != 0) & (LM.p%2 != 0) & (LM.p > 3): print(LM.Geometry) #print(LM.name) print(LM.p) #print(LM.LMFrame) df = LM.LMFrame #t_total = df.groupby('layer')['t(um)'].unique().sum()[0] * 1e-6 #print(t_total) #print(LM.total) #print(type(LM.total)) t_mid = df.loc[df['label'] == 'neut. axis', 'd(m)'] actual = t_mid.iloc[0] expected = LM.total/2 #print(actual) #print(expected) # Regular assert breaks due to float. Using assert_almost_equals''' np.testing.assert_almost_equal(actual, expected) nt.assert_almost_equals(actual, expected)
def test_py_c_equal_rt(self): audio, sampling_rate, onsets = modal.get_audio_file('piano_G2.wav') audio = audio[0:4096] frame_size = 256 hop_size = 256 py_odf = EnergyODF() py_odf.set_frame_size(frame_size) py_odf.set_hop_size(hop_size) c_odf = CEnergyODF() c_odf.set_frame_size(frame_size) c_odf.set_hop_size(hop_size) # if necessary, pad the input signal if len(audio) % hop_size != 0: audio = np.hstack(( audio, np.zeros(hop_size - (len(audio) % hop_size), dtype=np.double) )) # get odf samples audio_pos = 0 while audio_pos <= len(audio) - frame_size: frame = audio[audio_pos:audio_pos + frame_size] py_odf_value = py_odf.process_frame(frame) c_odf_value = c_odf.process_frame(frame) assert_almost_equals(py_odf_value, c_odf_value, places=self.FLOAT_PRECISION) audio_pos += hop_size
def _assert_structure_equals(defn, s1, s2, views, r): assert_equals(s1.ndomains(), s2.ndomains()) assert_equals(s1.nrelations(), s2.nrelations()) for did in xrange(s1.ndomains()): assert_equals(s1.nentities(did), s2.nentities(did)) assert_equals(s1.ngroups(did), s2.ngroups(did)) assert_equals(s1.assignments(did), s2.assignments(did)) assert_equals(set(s1.groups(did)), set(s2.groups(did))) assert_close(s1.get_domain_hp(did), s2.get_domain_hp(did)) assert_almost_equals(s1.score_assignment(did), s2.score_assignment(did)) for rid in xrange(s1.nrelations()): assert_close(s1.get_relation_hp(rid), s2.get_relation_hp(rid)) dids = defn.relations()[rid] groups = [s1.groups(did) for did in dids] for gids in it.product(*groups): ss1 = s1.get_suffstats(rid, gids) ss2 = s2.get_suffstats(rid, gids) if ss1 is None: assert_is_none(ss2) else: assert_close(ss1, ss2) assert_almost_equals(s1.score_likelihood(r), s2.score_likelihood(r)) before = list(s1.assignments(0)) bound = model.bind(s1, 0, views) gid = bound.remove_value(0, r) assert_equals(s1.assignments(0)[0], -1) assert_equals(before, s2.assignments(0)) bound.add_value(gid, 0, r) # restore
def test_varyingDropoutRates(): X = T.fmatrix('X') rng = np.random.RandomState(seed=0) W = _make_shared(np.ones((10,1),dtype=cgml.types.floatX)) b = _make_shared(np.zeros((1,), dtype=cgml.types.floatX)) for dropout in [0.0,0.5,1.0]: layer = Layer(rng=rng, input=X, n_in=10, n_out=1, activation=cgml.activations.linear, W=W, b=b, dropout=dropout, name="dropout") f = theano.function(inputs=[X], outputs=layer.output) X_np = np.ones((1,10),dtype=cgml.types.floatX) values = [] for i in range(10000): y_np = f(X_np) values.append(y_np[0,0]) assert_almost_equals(np.mean(values),(1-dropout)*10,places=1)
def test_wlc_dev_exact_accuracy(): global weights_wlc global WLC_FILE mat = evalClassifier(weights_wlc, WLC_FILE, DEVKEY) actual = scorer.accuracy(mat) expected = 0.4467 assert_almost_equals(expected, actual, places=4, msg="UNEQUAL Expected:%f, Actual:%f" % (expected, actual))
def test_match_nopro_f1_d2_3(): global all_markables f, r, p = coref.eval_on_dataset( coref_rules.make_resolver(coref_rules.exact_match_no_pronouns), all_markables) assert_almost_equals(r, 0.3028, places=4) assert_almost_equals(p, 0.9158, places=4)
def test_mcc_dev_accuracy (): global weights_mcc global MCC_FILE mat = evalClassifier (weights_mcc, MCC_FILE, DEVKEY) actual = scorer.accuracy(mat) expected = 0.3756 assert_almost_equals (expected, actual, places=4, msg="UNEQUAL Expected:%f, Actual:%f" %(expected,actual))
def test_get_beta_multiplevalues(): """Check that multiple values are handled properly""" Svals = [16, 256] Nvals = [64, 4096] betavals = get_beta(Svals, Nvals) assert_almost_equals(betavals[0], 0.101, places=3) assert_almost_equals(betavals[1], 0.0147, places=4)
def check_get_beta(S0, N0, version, beta_known): beta_code = get_beta(S0, N0, version=version) #Determine number of decimal places in known value and round code value equilalently decimal_places_in_beta_known = abs(Decimal(beta_known).as_tuple().exponent) beta_code_rounded = round(beta_code, decimal_places_in_beta_known) assert_almost_equals(beta_code_rounded, float(beta_known), places=6)
def test_分词(self): self.bigrams = count_bigrams(self.dev_x, max_size = 100000) print('bigram size',len(self.bigrams)) self.assertEqual(len(self.bigrams), 6308) train_x, train_y = self.dev_x, self.dev_y # for debug test_x, test_y = self.test_x, self.test_y # init the model segger = Base_Segger(bigrams = self.bigrams) # train the model segger.fit(train_x, train_y, dev_x = test_x, dev_y = test_y, iterations = 3) f1 = segger.evaluator.report(quiet = True) assert_almost_equals(f1, 0.8299, places = 4) # save it and reload it gzip.open('test_model.gz','w').write(pickle.dumps(segger)) segger = pickle.load(gzip.open('test_model.gz')) # use the model and evaluate outside evaluator = CWS_Evaluator() output = segger.predict(test_x) evaluator.eval_all(test_y, output) evaluator.report() f1 = segger.evaluator.report(quiet = True) assert_almost_equals(f1, 0.8299, places = 4)
def test_efforts(self): a = np.linspace(10, 100, 10) t = np.array([0, 25, 50, 75]) efforts, w, M = ns.segmentation._efforts(a, t) assert np.all(efforts == np.array([2, 2, 3])) nt.assert_almost_equals(w, 2.333, places=3) # mean of [2, 2, 3] assert M == 1
def test_harmonic_synthesis_ifft(self): pd = SMSPeakDetection() pd.hop_size = hop_size frames = pd.find_peaks(self.audio) pt = SMSPartialTracking() pt.max_partials = max_partials frames = pt.find_partials(frames) synth = SMSSynthesis() synth.hop_size = hop_size synth.max_partials = max_partials synth.det_synthesis_type = SMSSynthesis.SMS_DET_IFFT synth_audio = synth.synth(frames) assert len(synth_audio) == len(self.audio) sms_audio, sampling_rate = simpl.read_wav( libsms_harmonic_synthesis_ifft_path ) assert len(synth_audio) == len(sms_audio) for i in range(len(synth_audio)): assert_almost_equals(synth_audio[i], sms_audio[i], float_precision)
def test_hmm_weights(): simple_weights = viterbi.get_HMM_weights('tests/hmm_simple.dat') assert_almost_equals(1.0, np.exp(simple_weights[('D', START_TAG, TRANS)]), places=3) assert_almost_equals(1.0, np.exp(simple_weights[('N', 'D', TRANS)]), places=3) assert_almost_equals(1.0, np.exp(simple_weights[('V', 'N', TRANS)]), places=3) assert_almost_equals(1.0, np.exp(simple_weights[('JJ', 'V', TRANS)]), places=3) assert_almost_equals(1.0, np.exp(simple_weights[(END_TAG, 'JJ', TRANS)]), places=3)
def test_indindividual_decision_function(): Add.nargs = 2 Mul.nargs = 2 vars = Model.convert_features(X) for x in vars: x._eval_ts = x._eval_tr.copy() vars = [Variable(k, weight=1) for k in range(len(vars))] for i in range(len(vars)): ind = Individual([vars[i]]) ind.decision_function(X) hy = ind._ind[0].hy.tonparray() [assert_almost_equals(a, b) for a, b in zip(X[:, i], hy)] ind = Individual([Sin(0, weight=1), Add(range(2), np.ones(2)), vars[0], vars[-1]]) ind.decision_function(X) hy = ind._ind[0].hy.tonparray() y = np.sin(X[:, 0] + X[:, -1]) [assert_almost_equals(a, b) for a, b in zip(y, hy)] y = np.sin((X[:, 0] + X[:, 1]) * X[:, 0] + X[:, 2]) ind = Individual([Sin(0, weight=1), Add(range(2), weight=np.ones(2)), Mul(range(2), weight=1), Add(range(2), weight=np.ones(2)), vars[0], vars[1], vars[0], vars[2]]) ind.decision_function(X) # assert v.hy.SSE(v.hy_test) == 0 hy = ind._ind[0].hy.tonparray() [assert_almost_equals(a, b) for a, b in zip(hy, y)]
def test_PVSystem_i_from_v(): module = 'Example_Module' module_parameters = sam_data['cecmod'][module] system = pvsystem.PVSystem(module=module, module_parameters=module_parameters) output = system.i_from_v(20, .1, .5, 40, 6e-7, 7) assert_almost_equals(-299.746389916, output, 5)
def test_reclasso(n=5, m=5, mu0=.5, mu1=.8, thresh=1e-4, verbose=True): """ test the reclasso algorithm using random data """ # sample a problem X = np.random.randn(n+1, m) y = np.random.randn(n+1, 1) # solve both problems using an interior point method theta0 = algo.interior_point(X[:-1, :], y[:-1], mu0) theta1 = algo.interior_point(X, y, mu1) # prepare warm-start solution for the homotopy theta0, nz0, K0, truesol0 = algo.fix_sol(X[:-1, :], y[:-1], mu0, theta0, thresh=thresh) theta1, nz1, K1, truesol1 = algo.fix_sol(X, y, mu1, theta1, thresh=thresh) if not truesol0 or not truesol1: raise NameError, "bad threshold for interior point solution" # solve the problem using reclasso theta_nz, nz, K, nbr1, nbr2 = reclasso(X, y, mu0, mu1, theta0[nz0], nz0, K0, verbose=verbose, showpath=False) theta = np.zeros((m, 1)) theta[nz] = theta_nz # check the result is the same as with the interior point method error = np.sum((theta1 - theta)**2)/np.sum(theta1**2) assert_almost_equals(error, 0)
def test_py_c_equal(self): audio, sampling_rate, onsets = modal.get_audio_file('piano_G2.wav') audio = audio[0:4096] frame_size = 512 hop_size = 512 py_odf = LPSpectralDifferenceODF() py_odf.set_frame_size(frame_size) py_odf.set_hop_size(hop_size) py_odf.set_order(self.order) c_odf = CLPSpectralDifferenceODF() c_odf.set_frame_size(frame_size) c_odf.set_hop_size(hop_size) c_odf.set_order(self.order) # if necessary, pad the input signal if len(audio) % hop_size != 0: audio = np.hstack((audio, np.zeros(hop_size - (len(audio) % hop_size), dtype=np.double))) # get odf samples odf_size = len(audio) / hop_size py_samples = np.zeros(odf_size, dtype=np.double) c_samples = np.zeros(odf_size, dtype=np.double) py_odf.process(audio, py_samples) c_odf.process(audio, c_samples) assert len(py_samples) == len(c_samples) for i in range(len(py_samples)): assert_almost_equals(py_samples[i], c_samples[i], places=self.FLOAT_PRECISION)
def test_adadelta_logreg(): x = T.fvector('x') y = T.fscalar('y') w = _make_shared([1.0,1.0],name='w') b = _make_shared([1.0],name='b') yhat = 1.0 / ( 1.0 + T.exp( - T.dot(x,w) - b ) ) e = y - yhat cost = T.dot(e,e) ad = AdaDelta(cost = cost, params = [w,b]) update = theano.function( inputs = [x,y], outputs = cost, updates = ad.updates ) c = update([2,1],0) assert_almost_equals(c,0.9643510838246173) c_prev = c for i in range(100): c = update([2,1],0) assert_equals(c,c) assert_true(c < c_prev) c_prev = c
def test_nb_likelihood_ratio (): expected = 8.7916 instance = {'good':1,'worst':4,OFFSET:1} pos_likelihood = predict (instance, weights_nb, ALL_LABELS)[1]["POS"] neg_likelihood = predict (instance, weights_nb, ALL_LABELS)[1]["NEG"] actual = neg_likelihood - pos_likelihood assert_almost_equals (expected, actual, places=3, msg="UNEQUAL Expected:%f, Actual:%f" %(expected, actual))
def test_nb_smoothing(): ''' Tests for the following two sentences, with smoothing of 0.5 the D man N runs V man V the D cannons N ''' allwords = ['the', 'man', 'runs', 'the', 'cannons'] wordCountsByTag = Counter({ 'D': Counter({'the': 2}), 'N': Counter({'man': 1, 'cannons': 1}), 'V': Counter({'runs': 1, 'man': 1}) }) classCounts = Counter({'D': 2, 'N': 2, 'V': 2}) # smoothing of 0.5 reserves 1/2 probability mass for unknown weights = naivebayes.learnNBWeights(wordCountsByTag, classCounts, allwords, alpha=0.5) assert_almost_equals(5.0 / 8.0, np.exp(weights[('D', 'the')]), places=3) assert_almost_equals(1.0 / 8.0, np.exp(weights[('N', 'the')])) assert_almost_equals(0.333, np.exp(weights[('N', OFFSET)]), places=3) assert_almost_equals(0.333, np.exp(weights[('V', OFFSET)]), places=3) # offsets unchanged assert_almost_equals(0.333, np.exp(weights[('D', OFFSET)]), places=3)
def test_std10_red_chisq(self): std = 10 np.random.seed(1) self.s.add_gaussian_noise(std) self.s.metadata.set_item("Signal.Noise_properties.variance", std ** 2) self.m.fit(fitter="leastsq", method="ls") nt.assert_almost_equals(self.m.red_chisq.data, 0.79949135)
def test_nb_d3_3(): global x_tr, y_tr, x_dv, y_dv, x_te # public theta_nb = naive_bayes.estimate_nb(x_tr,y_tr,0.1) y_hat,scores = clf_base.predict(x_tr[55],theta_nb,labels) assert_almost_equals(scores['science'],-949.406,places=2)
def test_calculate_phi_psi(self): atoms, residues, chains = parse_complex_from_file(self.golden_data_path + '1PPElig.pdb') protein = Complex(chains, atoms) # psi: angle #0:1@n,ca,c #0:2@n # phi: angle #0:1@c #0:2@n,ca,c phi_angles = [-105.92428251619579, -134.402235889132, -58.32268858533758, -85.62997439535678, -129.666484600813, -77.00076813772478, -142.09891098624075, -82.10672119029674, -163.14606891327375, -109.37900096123484, -138.72905680654182, -59.09699793329797, -60.06774387010816, -74.41030551527874, -99.82766540256617, -92.6495110068149, 54.969041241310705, -104.60151419194615, -67.57074855137641, -123.83574594954692, -85.90313254423194, -87.7781803331676, -66.345484249271, -64.51513795752882, 108.23656098935888, -129.62530277139578, -71.90658189461674, -170.4460918036806] psi_angles = [138.38576328505278, 105.22472788100255, 106.42882930892199, 150.65572151747787, 72.08329638522976, 130.19890858175336, 115.48238807519739, 132.48041144914038, 163.35191386073618, 151.17756189538443, -28.310569696143393, 162.66293554938997, -32.25480696024475, -20.28436719199857, -11.444789534534305, 163.38578466073147, 150.2534549328882, -128.53524744082424, 20.01260634937939, 151.96710290169335, 159.55519588393594, 115.07091589216549, 152.8911959270869, -24.04765297807205, -14.890186424782046, 15.86273088398991, 152.7552784042674, 146.11762131430552] for i in range(1, len(protein.residues)): phi, psi = calculate_phi_psi(protein.residues[i], protein.residues[i - 1]) assert_almost_equals(phi_angles[i - 1], math.degrees(phi)) assert_almost_equals(psi_angles[i - 1], math.degrees(psi))
def test_case2(self): # case2: C = 1.0, phi = 2.0 scw = SCW(2.0, 1.0) assert_equals(scw.psi, 3.0) assert_equals(scw.zeta, 5.0) x = {} Trie.insert(x, ["a", "b", "c"], 1.0) Trie.insert(scw.mu, ["a", "b", "c"], 1.0) margin = scw.calc_margin(x, 1) assert_equals(margin, 1.0) variance = scw.calc_variance(x) assert_equals(variance, 1.0) alpha = scw.calc_alpha(margin, variance) assert_almost_equals(alpha, (math.sqrt(24)-3)/5) beta = scw.calc_beta(margin, variance, alpha) desired = ((2 * (math.sqrt(24) - 3) / 5) / (0.5 * (-2 * (math.sqrt(24) - 3) / 5 + math.sqrt(4 * (33 - 6 * math.sqrt(24)) / 25 + 4)) + 2 * (math.sqrt(24) - 3) / 5)) assert_almost_equals(beta, desired) Trie.insert(x, ["a", "b", "d"], 2.0) scw.update_mu_sigma(x, -1, 0.2, 0.5) assert_equals(Trie.find(scw.mu, ["a", "b", "c"]), 0.8) assert_equals(Trie.find(scw.mu, ["a", "b", "d"]), -0.4) assert_equals(Trie.find(scw.sigma, ["a", "b", "c"]), 0.5) assert_equals(Trie.find(scw.sigma, ["a", "b", "d"]), -1.0)
def test_sapm_celltemp_dict_like(): default = pvsystem.sapm_celltemp(900, 5, 20) assert_almost_equals(43.509, default.ix[0, 'temp_cell'], 3) assert_almost_equals(40.809, default.ix[0, 'temp_module'], 3) model = {'a':-3.47, 'b':-.0594, 'deltaT':3} assert_frame_equal(default, pvsystem.sapm_celltemp(900, 5, 20, model)) model = pd.Series(model) assert_frame_equal(default, pvsystem.sapm_celltemp(900, 5, 20, model))
def test_sum_transactions_set_days(): transactions = [ '2015-11-01: days 0', '2015-11-01: rate 20', '2015-11-10: off', '2015-11-15: days 7', ] assert_almost_equals(trans.sum_transactions(transactions), 7)
def assert_1d_lists_almost_equals(first, second, places=None, msg=None, delta=None): assert_equals(len(first), len(second), msg=msg) for i, j in zip(first, second): assert_almost_equals(i, j, places=places, msg=msg, delta=delta)
def test_std1_red_chisq_in_range(self): std = 1 self.m.set_signal_range(10, 50) np.random.seed(1) self.s.add_gaussian_noise(std) self.s.metadata.set_item("Signal.Noise_properties.variance", std ** 2) self.m.fit(fitter="leastsq", method="ls") nt.assert_almost_equals(self.m.red_chisq.data, 0.86206965)
def test_sum_transactions_easy(): transactions = [ # 9 working days: 11 is Holiday '2015-11-01: days 0', '2015-11-01: rate 20', '2015-11-15: show', ] expected = 8 * (20.0 / 250) assert_almost_equals(trans.sum_transactions(transactions), expected)
def check_solution(solution, expected): assert_almost_equals(solution, expected, places=2)
def test_animation_constraint_3(): """Animation constraint to kinematic parent""" _new(1, 120) a = cmdx.createNode("transform") b = cmdx.createNode("transform", parent=a) a["ty"] = 5.0 b["tx"] = 5.0 scene = commands.create_scene() scene["gravity"] = 0 rb = commands.create_rigid(b, scene) commands.animation_constraint(rb) assert_almost_equals(a.translation(cmdx.sWorld).y, 5.0, 2) assert_almost_equals(b.translation(cmdx.sWorld).y, 5.0, 2) _step(b, 3) assert_almost_equals(a.translation(cmdx.sWorld).y, 5.0, 2) assert_almost_equals(b.translation(cmdx.sWorld).y, 5.0, 2) a["ty"] = 10.0 _step(b, 100) assert_almost_equals(a.translation(cmdx.sWorld).y, 10.0, 2) assert_almost_equals(b.translation(cmdx.sWorld).y, 10.0, 2)
def test_isomorphism(self): """ Test whether two isomorphic graphs can be perfectly matched. Note - the graph used must have no automorphisms - ie. there can only be one correct answer and so its harder to test.""" A = np.array([[ 0, 0, 1, 0, 0, 0, ], [ 0, 0, 0, 1, 0, 0, ], [ 1, 0, 0, 1, 1, 0, ], [ 0, 1, 1, 0, 1, 1, ], [ 0, 0, 1, 1, 0, 1, ], [ 0, 0, 0, 1, 1, 0, ]]) B = A.copy() Gs = [A, B] G_eig_vals, G_eig_vecs = utils.calc_graph_eigenvalues(Gs) T = wks.wks_matching_tensor(G_eig_vals, G_eig_vecs, sigma=1., num_t=1000) for i in range(6): for j in range(6): if i == j: assert_almost_equals(T[0, 1, i, j], 0.) else: assert_true(T[0, 1, i, j] > 0)
def test_earthsun_distance(): times = pd.date_range(datetime.datetime(2003,10,17,13,30,30), periods=1, freq='D') assert_almost_equals(1, solarposition.pyephem_earthsun_distance(times).values[0], 0)
def test_sum_of_squares(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(5.0, coordinates.sum_of_squares())
def test_estimate_preference_UserBasedRecommender(): nhood_strategy = NearestNeighborsStrategy() similarity = UserSimilarity(matrix_model, euclidean_distances) recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_almost_equals( 3.5, recsys.estimate_preference('Marcel Caraciolo', 'Superman Returns')) assert_almost_equals( 2.4533792305691886, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_almost_equals( 3.5, recsys.estimate_preference('Marcel Caraciolo', 'Superman Returns')) assert_almost_equals( 2.8960083169728952, recsys.estimate_preference(user_id='Leopoldo Pires', item_id='You, Me and Dupree', distance=pearson_correlation, nhood_size=4, minimal_similarity=-1.0)) recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_almost_equals( 2.0653946891716108, recsys.estimate_preference(user_id='Leopoldo Pires', item_id='You, Me and Dupree', nhood_size=4)) #With capper = False recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy, False) assert_almost_equals( 2.0653946891716108, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) assert_almost_equals( 2.8960083169728952, recsys.estimate_preference(user_id='Leopoldo Pires', item_id='You, Me and Dupree', distance=pearson_correlation, nhood_size=4, minimal_similarity=-1.0)) recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy, False) assert_almost_equals( 2.0653946891716108, recsys.estimate_preference(user_id='Leopoldo Pires', item_id='You, Me and Dupree', nhood_size=4)) #Non-Preferences assert_array_equal( np.nan, recsys.estimate_preference('Maria Gabriela', 'You, Me and Dupree')) nhood_strategy = NearestNeighborsStrategy() similarity = UserSimilarity(boolean_matrix_model, jaccard_coefficient) recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy) assert_almost_equals( 1.0, recsys.estimate_preference('Marcel Caraciolo', 'Superman Returns')) assert_almost_equals( 1.0, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) assert_almost_equals( 1.0, recsys.estimate_preference(user_id='Leopoldo Pires', item_id='You, Me and Dupree', distance=jaccard_coefficient, nhood_size=3)) #With capper = False recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy, False) assert_almost_equals( 1.0, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) #Non-Preferences assert_array_equal( np.NaN, recsys.estimate_preference('Maria Gabriela', 'You, Me and Dupree'))
def test_recommend_ItemBasedRecommender(): items_strategy = ItemsNeighborhoodStrategy() similarity = ItemSimilarity(matrix_model, euclidean_distances) #Empty Recommendation recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy) assert_array_equal(np.array([]), recsys.recommend('Marcel Caraciolo')) #Semi Recommendation recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy) assert_array_equal(np.array(['Just My Luck', 'You, Me and Dupree']), \ recsys.recommend('Leopoldo Pires')) #Semi Recommendation recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy) assert_array_equal(np.array(['Just My Luck']), \ recsys.recommend('Leopoldo Pires', 1)) #Empty Recommendation recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #Test with params update recsys.recommend(user_id='Maria Gabriela', similarity=similarity) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #with_preference recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy, True, True) assert_equals('Just My Luck', recsys.recommend('Leopoldo Pires')[0][0]) assert_equals('You, Me and Dupree', recsys.recommend('Leopoldo Pires')[1][0]) assert_almost_equals(3.20597, recsys.recommend('Leopoldo Pires')[0][1], 2) assert_almost_equals(3.147178755, recsys.recommend('Leopoldo Pires')[1][1], 2) similarity = ItemSimilarity(boolean_matrix_model, jaccard_coefficient) #Empty Recommendation recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy) assert_array_equal(np.array([]), recsys.recommend('Marcel Caraciolo')) #Semi Recommendation recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy) assert_array_equal(np.array(['You, Me and Dupree', 'Just My Luck']), \ recsys.recommend('Leopoldo Pires')) #Semi Recommendation recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy) assert_array_equal(np.array(['You, Me and Dupree']), \ recsys.recommend('Leopoldo Pires', 1)) #Empty Recommendation recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #Test with params update recsys.recommend(user_id='Maria Gabriela', similarity=similarity) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #with_preference recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy, True, True) assert_equals('You, Me and Dupree', recsys.recommend('Leopoldo Pires')[0][0]) assert_equals('Just My Luck', recsys.recommend('Leopoldo Pires')[1][0]) assert_almost_equals(1.0, recsys.recommend('Leopoldo Pires')[0][1], 2) assert_almost_equals(1.0, recsys.recommend('Leopoldo Pires')[1][1], 2)
def test_sapm_celltemp(): default = pvsystem.sapm_celltemp(900, 5, 20) assert_almost_equals(43.509, default.ix[0, 'temp_cell'], 3) assert_almost_equals(40.809, default.ix[0, 'temp_module'], 3) assert_frame_equal(default, pvsystem.sapm_celltemp(900, 5, 20, [-3.47, -.0594, 3]))
def test_estimate_preference_ItemBasedRecommender(): items_strategy = ItemsNeighborhoodStrategy() similarity = ItemSimilarity(matrix_model, euclidean_distances) recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy) assert_almost_equals( 3.5, recsys.estimate_preference('Marcel Caraciolo', 'Superman Returns')) assert_almost_equals( 3.14717875510, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) #With capper = False recsys = ItemBasedRecommender(matrix_model, similarity, items_strategy, False) assert_almost_equals( 3.14717875510, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) #Non-Preferences assert_array_equal( np.nan, recsys.estimate_preference('Maria Gabriela', 'You, Me and Dupree')) items_strategy = ItemsNeighborhoodStrategy() similarity = ItemSimilarity(boolean_matrix_model, jaccard_coefficient) recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy) assert_almost_equals( 1.0, recsys.estimate_preference('Marcel Caraciolo', 'Superman Returns')) assert_almost_equals( 1.0, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) #With capper = False recsys = ItemBasedRecommender(boolean_matrix_model, similarity, items_strategy, False) assert_almost_equals( 1.0, recsys.estimate_preference('Leopoldo Pires', 'You, Me and Dupree')) #Non-Preferences assert_array_equal( np.NaN, recsys.estimate_preference('Maria Gabriela', 'You, Me and Dupree'))
def test_i_from_v(): output = pvsystem.i_from_v(20, .1, .5, 40, 6e-7, 7) assert_almost_equals(-299.746389916, output, 5)
def test_v_from_i_big(): output = pvsystem.v_from_i(500, 10, 4.06, 0, 6e-10, 1.2) assert_almost_equals(86.320000493521079, output, 5)
def test_create_coordinates_3D(self): coordinates = Coordinates(self.values_3D) assert coordinates.dimension == 3 for i in range(coordinates.dimension): assert_almost_equals(self.values_3D[i], coordinates[i])
def test_extraradiation_ephem_scalar(): assert_almost_equals( 1382, irradiance.extraradiation(300, method='pyephem').values[0], -1)
def test_recommend_UserBasedRecommender(): nhood_strategy = NearestNeighborsStrategy() similarity = UserSimilarity(matrix_model, euclidean_distances) #Empty Recommendation recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_array_equal(np.array([]), recsys.recommend('Marcel Caraciolo')) #Semi Recommendation recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_array_equal(np.array(['Just My Luck', 'You, Me and Dupree']), \ recsys.recommend('Leopoldo Pires')) #Semi Recommendation recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_array_equal(np.array(['Just My Luck']), \ recsys.recommend('Leopoldo Pires', 1)) #Empty Recommendation recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #Test with params update recsys.recommend(user_id='Maria Gabriela', similarity=similarity) assert_array_equal(np.array([]), recsys.recommend('Maria Gabriela')) #with_preference recsys = UserBasedRecommender(matrix_model, similarity, nhood_strategy, True, True) assert_equals('Just My Luck', recsys.recommend_estimate_strategy('Leopoldo Pires')[0][0]) assert_equals('You, Me and Dupree', recsys.recommend_estimate_strategy('Leopoldo Pires')[1][0]) assert_equals('Just My Luck', recsys.recommend('Leopoldo Pires')[0]) assert_equals('You, Me and Dupree', recsys.recommend('Leopoldo Pires')[1]) leo = recsys.recommend_estimate_strategy('Leopoldo Pires') assert_almost_equals(2.456743361464, leo[0][1], 2) assert_almost_equals( 2.453379, recsys.recommend_estimate_strategy('Leopoldo Pires')[1][1], 2) similarity = UserSimilarity(boolean_matrix_model, jaccard_coefficient) #Empty Recommendation recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy) assert_array_equal(np.array([]), recsys.recommend('Marcel Caraciolo')) #Semi Recommendation recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy) assert_array_equal(np.array(['You, Me and Dupree', 'Just My Luck']), \ recsys.recommend_estimate_strategy('Leopoldo Pires')) #Semi Recommendation recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy) assert_array_equal(np.array(['You, Me and Dupree']), \ recsys.recommend_estimate_strategy('Leopoldo Pires', 1)) #Empty Recommendation recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy) assert_array_equal(np.array([]), recsys.recommend_estimate_strategy('Maria Gabriela')) #Test with params update recsys.recommend(user_id='Maria Gabriela', similarity=similarity) assert_array_equal(np.array([]), recsys.recommend_estimate_strategy('Maria Gabriela')) #with_preference recsys = UserBasedRecommender(boolean_matrix_model, similarity, nhood_strategy, True, True) assert_equals('You, Me and Dupree', recsys.recommend_estimate_strategy('Leopoldo Pires')[0][0]) assert_equals('Just My Luck', recsys.recommend_estimate_strategy('Leopoldo Pires')[1][0]) assert_almost_equals( 1.0, recsys.recommend_estimate_strategy('Leopoldo Pires')[0][1], 2) assert_almost_equals( 1.0, recsys.recommend_estimate_strategy('Leopoldo Pires')[1][1], 2)
def test_compare_to_mixture_model(): r = rng() N, D = 4, 5 Y = np.random.uniform(size=(N, D)) > 0.8 Y_rec = np.array([tuple(y) for y in Y], dtype=[('', bool)] * D) mm_view = rec_numpy_dataview(Y_rec) irm_view = relation_numpy_dataview(Y) mm_def = mm_definition(N, [bb] * D) irm_def = irm_definition([N, D], [((0, 1), bb)]) perms = list(permutation_iter(N)) assignment = perms[np.random.randint(0, len(perms))] mm_s = mm_initialize(mm_def, mm_view, r=r, assignment=assignment) irm_s = irm_initialize(irm_def, [irm_view], r=r, domain_assignments=[ assignment, range(D), ]) def assert_suff_stats_equal(): assert set(mm_s.groups()) == set(irm_s.groups(0)) assert irm_s.groups(1) == range(D) groups = mm_s.groups() for g in groups: for i in xrange(D): a = mm_s.get_suffstats(g, i) b = irm_s.get_suffstats(0, [g, i]) if b is None: b = {'heads': 0L, 'tails': 0L} assert a['heads'] == b['heads'] and a['tails'] == b['tails'] assert_suff_stats_equal() assert_almost_equals(mm_s.score_assignment(), irm_s.score_assignment(0), places=3) bound_mm_s = mm_bind(mm_s, mm_view) bound_irm_s = irm_bind(irm_s, 0, [irm_view]) # XXX: doesn't really have to be true, just is true of impl assert not bound_mm_s.empty_groups() assert not bound_irm_s.empty_groups() bound_mm_s.create_group(r) bound_irm_s.create_group(r) gid_a = bound_mm_s.remove_value(0, r) gid_b = bound_irm_s.remove_value(0, r) assert gid_a == gid_b assert_suff_stats_equal() x0, y0 = bound_mm_s.score_value(0, r) x1, y1 = bound_irm_s.score_value(0, r) assert x0 == x1 # XXX: not really a requirement # XXX: should really normalize and then check for a, b in zip(y0, y1): assert_almost_equals(a, b, places=2)
def test_read_gso_parameters(self): parameteres = GSOParameters() assert_almost_equals(0.4, parameteres.rho) assert_almost_equals(0.6, parameteres.gamma) assert_almost_equals(0.08, parameteres.beta) assert_almost_equals(5.0, parameteres.initial_luciferin) assert_almost_equals(0.2, parameteres.initial_vision_range) assert_almost_equals(5.0, parameteres.max_vision_range) assert 5 == parameteres.max_neighbors
def test_distance2_different_coordinates(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates([2.0, 3.0]) assert_almost_equals(2.0, coordinates1.distance2(coordinates2))
def test_read_gso_parameters_with_file(self): parameteres = GSOParameters(self.golden_data_path + 'glowworm.conf') assert_almost_equals(0.1, parameteres.rho) assert_almost_equals(0.2, parameteres.gamma) assert_almost_equals(0.6, parameteres.beta) assert_almost_equals(0.3, parameteres.initial_luciferin) assert_almost_equals(0.4, parameteres.initial_vision_range) assert_almost_equals(0.5, parameteres.max_vision_range) assert 7 == parameteres.max_neighbors
def test_distance2_same_coordinate(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(0.0, coordinates.distance2(coordinates))
def test_norm(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(2.236067977, coordinates.norm())
def test_distance_different_coordinates(self): coordinates1 = Coordinates([0., 0., 0.]) coordinates2 = Coordinates([20., 0., 21.]) assert_almost_equals(29.0, coordinates1.distance(coordinates2))
def test_sum_of_squares(self): assert_almost_equals(332833500.0, sum_of_squares(self.values))
def check_tensor_correctness(pairs): for pair in pairs: for pred, true in zip(pair[0], pair[1]): assert_almost_equals(pred, true, places=4)
def test_float_mean(): assert_almost_equals(mean([.5,.5,1]), .66, 1) # .66, 1-> can choose the degree of precision by changing 1 to 2, 3, 4..
def test_close_interaction(): assert_equals(interaction(1, 2), 1) assert_equals(interaction(0.5, 0.75), 0.25) assert_almost_equals(interaction(1. / 3, 1), 0.67, 2)
def test_extraradiation(): assert_almost_equals(1382, irradiance.extraradiation(300), -1)
def test_extraradiation_asce(): assert_almost_equals(1382, irradiance.extraradiation(300, method='asce'), -1)
def test_extraradiation_spencer(): assert_almost_equals(1382, irradiance.extraradiation(300, method='spencer'), -1)
def test_v_from_i(): output = pvsystem.v_from_i(20, .1, .5, 3, 6e-7, 7) assert_almost_equals(7.5049875193450521, output, 5)
def test_calcAccuracy1(self): computingPower = 50 torpAccuracy = 75 jamming = 0 assert_almost_equals(87.5, calcAccuracy(computingPower, torpAccuracy, jamming))