def collect_mode(input_list): """ Collect time execution of mode of each module """ begin_py_mode = clock() py_mode(input_list) end_py_mode = clock() begin_mode = clock() mode(input_list) end_mode = clock() times = format_times(end_py_mode - begin_py_mode, end_mode - begin_mode) save_times(times, logs['mode'])
def sync_check(): # print 'Checking sync...' max_mcnt_difference=4 mcnts=dict() mcnts_list=[] mcnt_tot=0 for f,fpga in enumerate(fpgas): mcnts[f]=dict() try: hdr_index=bram_oob[f]['hdr'].index(1) except: print 'ERR: No headers found in BRAM. Are the F engines properly connected?' exit() pkt_64bit = struct.unpack('>Q',bram_dmp['bram_msb'][f]['data'][(4*hdr_index):(4*hdr_index)+4]+bram_dmp['bram_lsb'][f]['data'][(4*hdr_index):(4*hdr_index)+4])[0] mcnts[f]['mcnt'] =(pkt_64bit&((2**64)-(2**16)))>>16 mcnts_list.append(mcnts[f]['mcnt']) # print '[%s] MCNT: %i'%(servers[f],mcnts[f]['mcnt']) mcnts['mean']=stats.mean(mcnts_list) mcnts['median']=stats.median(mcnts_list) mcnts['mode']=stats.mode(mcnts_list) mcnts['modalmean']=stats.mean(mcnts['mode'][1]) # print 'mean: %i, median: %i, modal mean: %i mode:'%(mcnts['mean'],mcnts['median'],mcnts['modalmean']),mcnts['mode'] for f,fpga in enumerate(fpgas): if mcnts[f]['mcnt']>(mcnts['modalmean']+max_mcnt_difference) or mcnts[f]['mcnt'] < (mcnts['modalmean']-max_mcnt_difference): print '%s OUT OF SYNC!!'%servers[f] mcnts[f]['sync_status']='FAIL with error of %i'%(mcnts[f]['mcnt']-mcnts['modalmean']) else: mcnts[f]['sync_status']='PASS' return mcnts
def calculations(x): from stats import median, mean, mode, MAD, RANGE return { 'median': median(x), 'mean': mean(x), 'mode': mode(x), 'range': RANGE(x), 'MAD': MAD(x) }
def confidence(self, features): votes = [] for c in self._classifiers: v = c.classify(features) votes.append(v) choice_votes = votes.count(mode(votes)) conf = choice_votes / len(votes) return conf
def calculations(x): from stats import median, mean, mode, MAD, RANGE, maximum, minimum return { 'median': median(x), 'mean': mean(x), 'mode': mode(x), 'range': RANGE(x), 'MAD': MAD(x), 'max': maximum(x), 'min': minimum(x) }
def calculations(x): rang = lambda y, z: y - z y = max(x) z = min(x) from stats import median, mode return { 'median': median(x), 'mean': avg(x), 'mode': mode(x), 'range': rang(y, z), 'max': y, 'min': z }
def is_dominated(v, C, delta, error): dims = len(v) num_checks = int(np.log(1 / delta) * 2) num_calls = 0 if num_checks % 2 == 0: num_checks += 1 for c in C: dominated = np.zeros(dims) comp = (v, c) for dim in range(dims): max_i = stats.mode( [oracle_max(comp, dim, error) for _ in range(num_checks)]) num_calls += num_checks dominated[dim] = max_i if np.all(dominated == 1): return True, num_calls return False, num_calls
def max_4(s, dim, delta, error): num_checks = int(2 * len(s) - (1 / 6) / (error) + 1) if num_checks % 2 == 0: num_checks += 1 if len(s) == 0: return None if len(s) == 1: return s[0] else: curr = s[0] for i in range(1, len(s)): comp = (curr, s[i]) temp = stats.mode( [oracle_max(comp, dim, error) for _ in range(num_checks)]) if temp != 0: curr = s[i] return curr
def sync_check(): # print 'Checking sync...' max_mcnt_difference = 4 mcnts = dict() mcnts_list = [] mcnt_tot = 0 for f, fpga in enumerate(fpgas): mcnts[f] = dict() try: hdr_index = bram_oob[f]['hdr'].index(1) except: print 'ERR: No headers found in BRAM. Are the F engines properly connected?' exit() pkt_64bit = struct.unpack( '>Q', bram_dmp['bram_msb'][f]['data'][(4 * hdr_index):(4 * hdr_index) + 4] + bram_dmp['bram_lsb'][f]['data'][(4 * hdr_index):(4 * hdr_index) + 4])[0] mcnts[f]['mcnt'] = (pkt_64bit & ((2**64) - (2**16))) >> 16 mcnts_list.append(mcnts[f]['mcnt']) # print '[%s] MCNT: %i'%(servers[f],mcnts[f]['mcnt']) mcnts['mean'] = stats.mean(mcnts_list) mcnts['median'] = stats.median(mcnts_list) mcnts['mode'] = stats.mode(mcnts_list) mcnts['modalmean'] = stats.mean(mcnts['mode'][1]) # print 'mean: %i, median: %i, modal mean: %i mode:'%(mcnts['mean'],mcnts['median'],mcnts['modalmean']),mcnts['mode'] for f, fpga in enumerate(fpgas): if mcnts[f]['mcnt'] > (mcnts['modalmean'] + max_mcnt_difference) or mcnts[f]['mcnt'] < ( mcnts['modalmean'] - max_mcnt_difference): print '%s OUT OF SYNC!!' % servers[f] mcnts[f]['sync_status'] = 'FAIL with error of %i' % ( mcnts[f]['mcnt'] - mcnts['modalmean']) else: mcnts[f]['sync_status'] = 'PASS' return mcnts
def check_xaui_sync(self,verbose=False): """Checks if all F engines are in sync by examining mcnts at sync of incomming XAUI streams. \n If this test passes, it does not gaurantee that the system is indeed sync'd, merely that the F engines were reset between the same 1PPS pulses. Returns boolean true/false if system is in sync. """ #WORKING OK 2009-07-01 max_mcnt_difference=4 mcnts=dict() mcnts_list=[] mcnt_tot=0 rv=True for f,fpga in enumerate(self.fpgas): for x in range(self.config['n_xaui_ports_per_fpga']): n_xaui=f*self.config['n_xaui_ports_per_fpga']+x mcnts[n_xaui]=dict() mcnts[n_xaui]['mcnt'] =fpga.read_uint('xaui_sync_mcnt%i'%x) mcnts_list.append(mcnts[n_xaui]['mcnt']) # mcnts['mean']=stats.mean(mcnts_list) # mcnts['median']=stats.median(mcnts_list) mcnts['mode']=stats.mode(mcnts_list) if mcnts['mode']==0: raise RuntimeError("Too many XAUI links are receiving no data. Unable to produce a reliable result.") mcnts['modalmean']=stats.mean(mcnts['mode'][1]) # print 'mean: %i, median: %i, modal mean: %i mode:'%(mcnts['mean'],mcnts['median'],mcnts['modalmean']),mcnts['mode'] for f,fpga in enumerate(self.fpgas): for x in range(self.config['n_xaui_ports_per_fpga']): n_xaui=f*self.config['n_xaui_ports_per_fpga']+x if mcnts[n_xaui]['mcnt']>(mcnts['modalmean']+max_mcnt_difference) or mcnts[n_xaui]['mcnt'] < (mcnts['modalmean']-max_mcnt_difference): rv=False if verbose: print 'Sync check failed on %s, port %i with error of %i.'%(self.servers[f],x,mcnts[n_xaui]['mcnt']-mcnts['modalmean']) return rv
def test_mode_unique(self): l = [2, 3, 4, 5, 4, 6] my_value = st.mode(l) self.assertEqual(my_value[0], [4])
#Nama: Rivaldo Marta Dinata #NBI : 1461900135 import numpy import stats speed = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86] x = numpy.mean(speed) print(x) x = numpy.median(speed) print(x) x = stats.mode(speed) print(x)
def testSingleMode(self): # passing only one data point to mode() must return a list with that value self.assertEqual(stats.mode([25.7]), [25.7])
from sklearn import linear_model from sklearn.preprocessing import StandardScaler from sklearn.metrics import r2_score import os filename = 'phys.csv' filepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "\\" + "CsvFiles\\disciplines" + "\\" + filename data = pd.read_csv(filepath, delimiter=';', encoding='utf-8') df = pd.DataFrame(data, columns=['Средний_балл', 'Учебное_заведение', 'Город', 'Число_поступающих']) # print(df) # Mean, Median, and Mode mean = n.mean(df['Средний_балл']) median = n.median(df['Средний_балл']) mode = s.mode(df['Средний_балл']) print("Среднее: ", mean, "\nМедиана: ", median, "\nМода: ", mode, "\n") # Standard Deviation std = n.std(df['Средний_балл']) var = n.var(df['Средний_балл']) print("Стандартное отклонение: ", std, "\nОтклонение: ", var, "\n") # Percentiles per25 = n.percentile(df['Средний_балл'], 25) per75 = n.percentile(df['Средний_балл'], 75) print("25-я процентиль: ", per25, "\n75-я процентиль: ", per75, "\n")
import stats stats = stats.Stats() list1 = [1,3,5,6] list2 = [1,3,4,5] total1 = stats.total(list1) total2 = stats.total(list2) mean1 = stats.mean(list1) mean2 = stats.mean(list2) mode1 = stats.mode(list1) mode2 = stats.mode(list2) median1 = stats.median(list1) median2 = stats.median(list2) variance1 = stats.variance(list1) variance2 = stats.variance(list2) standard_deviation1 = stats.SD(list1) standard_deviation2 = stats.SD(list2) covariance_pop = stats.covariance(list1, list2) covariance_sample = stats.covariance(list1, list2, True) correlation = stats.correlation(list1, list2) skewness_pop1 = stats.skewness(list1) skewness_pop2 = stats.skewness(list2) skewness_sample1 = stats.skewness(list1, True) skewness_sample2 = stats.skewness(list2, True) kurtosis_pop1 = stats.kurtosis(list1) kurtosis_pop2 = stats.kurtosis(list2) kurtosis_sample1 = stats.kurtosis(list1, True) kurtosis_sample2 = stats.kurtosis(list2, True)
def test_mode(): obs = mode([1, 1, 1, 0]) exp = 1 assert_equal(obs, exp)
l = range(1,21) lf = range(1,21) lf[2] = 3.0 a = N.array(l) af = N.array(lf) ll = [l]*5 aa = N.array(ll) print('\nCENTRAL TENDENCY') print('geometricmean:',stats.geometricmean(l), stats.geometricmean(lf), stats.geometricmean(a), stats.geometricmean(af)) print('harmonicmean:',stats.harmonicmean(l), stats.harmonicmean(lf), stats.harmonicmean(a), stats.harmonicmean(af)) print('mean:',stats.mean(l), stats.mean(lf), stats.mean(a), stats.mean(af)) print('median:',stats.median(l),stats.median(lf),stats.median(a),stats.median(af)) print('medianscore:',stats.medianscore(l),stats.medianscore(lf),stats.medianscore(a),stats.medianscore(af)) print('mode:',stats.mode(l),stats.mode(a)) print('\nMOMENTS') print('moment:',stats.moment(l),stats.moment(lf),stats.moment(a),stats.moment(af)) print('variation:',stats.variation(l),stats.variation(a),stats.variation(lf),stats.variation(af)) print('skew:',stats.skew(l),stats.skew(lf),stats.skew(a),stats.skew(af)) print('kurtosis:',stats.kurtosis(l),stats.kurtosis(lf),stats.kurtosis(a),stats.kurtosis(af)) print('mean:',stats.mean(a),stats.mean(af)) print('var:',stats.var(a),stats.var(af)) print('stdev:',stats.stdev(a),stats.stdev(af)) print('sem:',stats.sem(a),stats.sem(af)) print('describe:') print(stats.describe(l)) print(stats.describe(lf)) print(stats.describe(a)) print(stats.describe(af)) print('\nFREQUENCY')
print("vector A = ", A) print("sorted A = ", sorted(A)) mean = st.mean(A) print("A's mean = ", mean) median = st.median(A) print("A's median = ", median) quantile = st.quantile(A, 0.2) print("A's 20% quantile = ", quantile) quantile = st.quantile(A, 0.9) print("A's 90% quantile = ", quantile) mode = st.mode(A) print("A's mode = ", mode) data_range = st.data_range(A) print("A's range = ", data_range) variance = st.variance(A) print("A's variance = ", variance) standard_deviation = st.standard_deviation(A) print("A's standard deviation = ", standard_deviation) interquartile_range = st.interquartile_range(A) print("A's interquartile range of 25% ~ 75% = ", interquartile_range) x = [-2, -1, 0, 1, 2]
finals.sort() return finals[-1][-1] def mostPopularPlayer1(self): allplayers = []
''' statistics_calculator.py Read numbers from a file, calculate and print statistical measures: mean, median, mode, variance, standard deviation ''' from stats import mean, median, mode, variance_sd def read_data(filename): numbers = [] with open(filename) as f: for line in f: numbers.append(float(line)) return numbers if __name__ == '__main__': data = read_data('mydata.txt') m = mean(data) median = median(data) mode = mode(data) variance, sd = variance_sd(data) print('Mean: {0:.5f}'.format(m)) print('Median: {0:.5f}'.format(median)) print('Mode: {0:.5f}'.format(mode)) print('Variance: {0:.5f}'.format(variance)) print('Standard deviation: {0:.5f}'.format(sd))
import numpy as np import stats as sts data = [1, 2, 2, 3] #集中趋势的度量 print('求和:', np.sum(data)) print('个数:', len(data)) print('平均值:', np.mean(data)) print('中位数:', np.median(data)) print('众数:', sts.mode(data)) print('上四分位数', sts.quantile(data, p=0.25)) print('下四分位数', sts.quantile(data, p=0.75)) #离散趋势的度量 print('最大值:', np.max(data)) print('最小值:', np.min(data)) print('极差:', np.max(data) - np.min(data)) print('四分位差', sts.quantile(data, p=0.75) - sts.quantile(data, p=0.25)) print('标准差:', np.std(data)) print('方差:', np.var(data)) print('变异系数:', np.std(data) / np.mean(data)) #偏度与峰度的度量 print('偏度:', sts.skewness(data)) print('峰度:', sts.kurtosis(data)) # 随机生成两个样本 x = np.random.randint(0, 9, 1000) y = np.random.randint(0, 9, 1000) # 计算平均值 mx = x.mean() my = y.mean()
print('方差', df['身高'].var()) print('标准差', df['身高'].std()) print('极差', df['身高'].max() - df['身高'].min()) print('偏度', df['身高'].skew()) print('峰度', df['身高'].kurt()) import numpy as np import stats as sts scores = [1, 2, 2, 2, 5] #集中趋势的度量 print('求和:', np.sum(scores)) print('个数:', len(scores)) print('平均值:', np.mean(scores)) print('中位数:', np.median(scores)) print('众数:', sts.mode(scores)) print('上四分位数', sts.quantile(scores, p=0.25)) print('下四分位数', sts.quantile(scores, p=0.75)) #离散趋势的度量 print('最大值:', np.max(scores)) print('最小值:', np.min(scores)) print('极差:', np.max(scores) - np.min(scores)) print('四分位差', sts.quantile(scores, p=0.75) - sts.quantile(scores, p=0.25)) print('标准差:', np.std(scores)) print('方差:', np.var(scores)) print('离散系数:', np.std(scores) / np.mean(scores)) #偏度与峰度的度量 print('偏度:', sts.skewness(scores)) print('峰度:', sts.kurtosis(scores))
def test_mode_multiple(self): l = [2, 3, 4, 5, 4, 6, 5] my_value = st.mode(l) self.assertEqual(my_value[0], [4, 5])
a = N.array(l) af = N.array(lf) ll = [l] * 5 aa = N.array(ll) print '\nCENTRAL TENDENCY' print 'geometricmean:', stats.geometricmean(l), stats.geometricmean( lf), stats.geometricmean(a), stats.geometricmean(af) print 'harmonicmean:', stats.harmonicmean(l), stats.harmonicmean( lf), stats.harmonicmean(a), stats.harmonicmean(af) print 'mean:', stats.mean(l), stats.mean(lf), stats.mean(a), stats.mean(af) print 'median:', stats.median(l), stats.median(lf), stats.median( a), stats.median(af) print 'medianscore:', stats.medianscore(l), stats.medianscore( lf), stats.medianscore(a), stats.medianscore(af) print 'mode:', stats.mode(l), stats.mode(a) print '\nMOMENTS' print 'moment:', stats.moment(l), stats.moment(lf), stats.moment( a), stats.moment(af) print 'variation:', stats.variation(l), stats.variation(a), stats.variation( lf), stats.variation(af) print 'skew:', stats.skew(l), stats.skew(lf), stats.skew(a), stats.skew(af) print 'kurtosis:', stats.kurtosis(l), stats.kurtosis(lf), stats.kurtosis( a), stats.kurtosis(af) print 'mean:', stats.mean(a), stats.mean(af) print 'var:', stats.var(a), stats.var(af) print 'stdev:', stats.stdev(a), stats.stdev(af) print 'sem:', stats.sem(a), stats.sem(af) print 'describe:' print stats.describe(l)
def classify(self, features): votes = [] for c in self._classifiers: v = c.classify(features) votes.append(v) return mode(votes)
d = map(float, sys.stdin.xreadlines()) else: d = map(long, sys.stdin.xreadlines()) except ValueError, err: sys.stderr.write("Bad datum: %s\n" % str(err)) sys.exit(1) if len(d) == 0: sys.stderr.write("No data given\n") sys.exit(1) d.sort() print " N =", len(d) print " SUM =", stats.sum(d) print " MIN =", min(d) print "1ST-QUARTILE =", stats.firstquartile(d) print " MEDIAN =", stats.median(d) print "3RD-QUARTILE =", stats.thirdquartile(d) print " MAX =", max(d) print " MEAN =", stats.mean(d) if d[0] < 0: print " N50 = NA" else: print " N50 =", stats.n50(d) if options.showMode: modeinfo = stats.mode(d) print " MODE(S) =", ','.join(map(str, modeinfo[0])), "(%d)" % modeinfo[1]
def test_mode(self): self.assertEqual(stats.mode([10]), 10) self.assertEqual(stats.mode([10, 20, 30, 40, 20]), 20)
import numpy as np import stats as sts scares = [ 31, 24, 23, 25, 14, 25, 13, 12, 14, 23, 32, 34, 43, 41, 21, 23, 26, 26, 34, 42, 43, 25, 24, 23, 24, 44, 23, 14, 52, 32, 42, 44, 35, 28, 17, 21, 32, 42, 12, 34 ] print('求和:', np.sum(scares)) print('個數:', len(scares)) print('平均值:', np.mean(scares)) print('中位數:', np.median(scares)) print('眾數:', sts.mode(scares)) print('上四分位數:', sts.quantile(scares, p=0.25)) print('下四分位數:', sts.quantile(scares, p=0.75)) print('最大值:', np.max(scares)) print('最小值:', np.min(scares)) print('極差:', np.std(scares)) print('四分位數:', sts.quantile(scares, p=0.75), sts.quantile(scares, p=0.25)) print('標準差:', np.std(scares)) print('方差', np.var(scares)) print('離散係數', np.std(scares) / np.mean(scares)) print('遍度:', sts.skewness(scares)) print('峰度:', sts.kurtosis(scares))
import numpy as np import stats as sts a = [31, 24, 23, 25, 14, 25, 13, 12, 14, 23, 32, 34, 43, 41, 21, 23, 26, 26, 34, 42, 43, 25, 24, 23, 24, 44, 23, 14, 52,32, 42, 44, 35, 28, 17, 21, 32, 42, 12, 34] scores=np.array(a) print('總合為:',np.sum(scores)) print('筆數為:',len(scores)) print('平均值為:',np.mean(scores)) print('中位數為:',np.median(scores)) print('眾數為:',sts.mode(scores)) print('上四分位數為',sts.quantile(scores,p=0.25)) print('下四分位數為',sts.quantile(scores,p=0.75)) print('最大值:',np.max(scores)) print('最小值:',np.min(scores)) print('全距:',np.ptp(scores)) print('標準差:',np.std(scores)) print('變異數:',np.var(scores)) print('離散係數:',np.std(scores)/np.mean(scores)) print('偏態係數:',sts.skewness(scores)) print('峰態係數:',sts.kurtosis(scores))
obs = mean([0, -200]) exp = -100 assert_equal(obs, exp) obs = mean([0]) exp = 0 assert_equal(obs, exp) def test_floating_mean1(): obs = mean([1, 2]) exp = 1.5 assert_equal(obs, exp) # FIXME Put Median tests here def testMedian() obs= mode(1,1,2) exp = 1 assert_equal(obs, exp) # FIXME Put Mode tests here def test_std1(): obs = std([0.0, 2.0]) exp = 1.0 assert_equal(obs, exp) def test_std2(): obs = std([]) exp = 0.0 assert_equal(obs, exp)
def mode(self, data): print('众数:', sts.mode(data))
def test_mode_none(self): l = [1, 2, 3, 4, 5] my_value = st.mode(l) self.assertEqual(my_value[0], [])
l = range(1,21) lf = range(1,21) lf[2] = 3.0 a = N.array(l) af = N.array(lf) ll = [l]*5 aa = N.array(ll) print '\nCENTRAL TENDENCY' print 'geometricmean:',stats.geometricmean(l), stats.geometricmean(lf), stats.geometricmean(a), stats.geometricmean(af) print 'harmonicmean:',stats.harmonicmean(l), stats.harmonicmean(lf), stats.harmonicmean(a), stats.harmonicmean(af) print 'mean:',stats.mean(l), stats.mean(lf), stats.mean(a), stats.mean(af) print 'median:',stats.median(l),stats.median(lf),stats.median(a),stats.median(af) print 'medianscore:',stats.medianscore(l),stats.medianscore(lf),stats.medianscore(a),stats.medianscore(af) print 'mode:',stats.mode(l),stats.mode(a) print '\nMOMENTS' print 'moment:',stats.moment(l),stats.moment(lf),stats.moment(a),stats.moment(af) print 'variation:',stats.variation(l),stats.variation(a),stats.variation(lf),stats.variation(af) print 'skew:',stats.skew(l),stats.skew(lf),stats.skew(a),stats.skew(af) print 'kurtosis:',stats.kurtosis(l),stats.kurtosis(lf),stats.kurtosis(a),stats.kurtosis(af) print 'tmean:',stats.tmean(a,(5,17)),stats.tmean(af,(5,17)) print 'tvar:',stats.tvar(a,(5,17)),stats.tvar(af,(5,17)) print 'tstdev:',stats.tstdev(a,(5,17)),stats.tstdev(af,(5,17)) print 'tsem:',stats.tsem(a,(5,17)),stats.tsem(af,(5,17)) print 'describe:' print stats.describe(l) print stats.describe(lf) print stats.describe(a) print stats.describe(af)
def check_basic(self): data1 = [3,5,1,10,23,3,2,6,8,6,10,6] vals = stats.mode(data1) assert_almost_equal(vals[0][0],6) assert_almost_equal(vals[1][0],3)
""" statistics_calculator.py Read numbers from a file, calculate and print statistical measures: mean, median, mode, variance, standard deviation """ from stats import mean, median, mode, variance_sd def read_data(filename): numbers = [] with open(filename) as f: for line in f: numbers.append(float(line)) return numbers if __name__ == "__main__": data = read_data("mydata.txt") m = mean(data) median = median(data) mode = mode(data) variance, sd = variance_sd(data) print("Mean: {0:.5f}".format(m)) print("Median: {0:.5f}".format(median)) print("Mode: {0:.5f}".format(mode)) print("Variance: {0:.5f}".format(variance)) print("Standard deviation: {0:.5f}".format(sd))
def _fill_moment_results(self): """ Fills the result arrays used for storing the calculated moments common format: time, mean, mode, var, skewness, kurtosis, 95% confidence lower limit, 95% upper limit """ toprocess = [('stock_tom', self.c_stock, 2), ('stock_woody', self.c_stock, 3), ('stock_non_woody', self.c_stock, 4), ('stock_acid', self.c_stock, 5), ('stock_water', self.c_stock, 6), ('stock_ethanol', self.c_stock, 7), ('stock_non_soluble', self.c_stock, 8), ('stock_humus', self.c_stock, 9), ('change_tom', self.c_change, 2), ('change_woody', self.c_change, 3), ('change_non_woody', self.c_change, 4), ('change_acid', self.c_change, 5), ('change_water', self.c_change, 6), ('change_ethanol', self.c_change, 7), ('change_non_soluble', self.c_change, 8), ('change_humus', self.c_change, 9), ('co2', self.co2_yield, 2)] for (resto, dataarr, dataind) in toprocess: # filter time steps ts = numpy.unique(dataarr[:,1]) # extract data for the timestep for timestep in ts: ind = numpy.where(dataarr[:,1]==timestep) mean = stats.mean(dataarr[ind[0], dataind]) mode_res = stats.mode(dataarr[ind[0], dataind]) mode = mode_res[0] var = stats.var(dataarr[ind[0], dataind]) skew = stats.skew(dataarr[ind[0], dataind]) kurtosis = stats.kurtosis(dataarr[ind[0], dataind]) if var>0.0: sd2 = 2 * math.sqrt(var) else: sd2 = var res = [[timestep, mean, mode[0], var, skew, kurtosis, mean - sd2, mean + sd2]] if resto=='stock_tom': self.md.stock_tom = numpy.append(self.md.stock_tom, res, axis=0) elif resto=='stock_woody': self.md.stock_woody = numpy.append(self.md.stock_woody, res, axis=0) elif resto=='stock_non_woody': self.md.stock_non_woody = numpy.append(\ self.md.stock_non_woody, res, axis=0) elif resto=='stock_acid': self.md.stock_acid = numpy.append(self.md.stock_acid, res, axis=0) elif resto=='stock_water': self.md.stock_water = numpy.append(self.md.stock_water, res, axis=0) elif resto=='stock_ethanol': self.md.stock_ethanol = numpy.append(self.md.stock_ethanol, res, axis=0) elif resto=='stock_non_soluble': self.md.stock_non_soluble= numpy.append( self.md.stock_non_soluble, res, axis=0) elif resto=='stock_humus': self.md.stock_humus = numpy.append(self.md.stock_humus, res, axis=0) elif resto=='change_tom': self.md.change_tom = numpy.append(self.md.change_tom, res, axis=0) elif resto=='change_woody': self.md.change_woody = numpy.append(self.md.change_woody, res, axis=0) elif resto=='change_non_woody': self.md.change_non_woody = numpy.append(\ self.md.change_non_woody, res, axis=0) elif resto=='change_acid': self.md.change_acid = numpy.append(self.md.change_acid, res, axis=0) elif resto=='change_water': self.md.change_water = numpy.append(self.md.change_water, res, axis=0) elif resto=='change_ethanol': self.md.change_ethanol = numpy.append( self.md.change_ethanol, res, axis=0) elif resto=='change_non_soluble': self.md.change_non_soluble=numpy.append( self.md.change_non_soluble, res, axis=0) elif resto=='change_humus': self.md.change_humus = numpy.append(self.md.change_humus, res, axis=0) elif resto=='co2': self.md.co2 = numpy.append(self.md.co2, res, axis=0)
def test_mode(self): self.assertEqual(stats.mode([1, 2, 3, 4, 2]), [2]) self.assertEqual(stats.mode([1, 2]), [1, 2])
def _fill_moment_results(self): """ Fills the result arrays used for storing the calculated moments common format: time, mean, mode, var, skewness, kurtosis, 95% confidence lower limit, 95% upper limit """ toprocess = [('stock_tom', self.c_stock, 2), ('stock_woody', self.c_stock, 3), ('stock_non_woody', self.c_stock, 4), ('stock_acid', self.c_stock, 5), ('stock_water', self.c_stock, 6), ('stock_ethanol', self.c_stock, 7), ('stock_non_soluble', self.c_stock, 8), ('stock_humus', self.c_stock, 9), ('change_tom', self.c_change, 2), ('change_woody', self.c_change, 3), ('change_non_woody', self.c_change, 4), ('change_acid', self.c_change, 5), ('change_water', self.c_change, 6), ('change_ethanol', self.c_change, 7), ('change_non_soluble', self.c_change, 8), ('change_humus', self.c_change, 9), ('co2', self.co2_yield, 2)] for (resto, dataarr, dataind) in toprocess: # filter time steps ts = numpy.unique(dataarr[:, 1]) # extract data for the timestep for timestep in ts: ind = numpy.where(dataarr[:, 1] == timestep) mean = stats.mean(dataarr[ind[0], dataind]) mode_res = stats.mode(dataarr[ind[0], dataind]) mode = mode_res[0] var = stats.var(dataarr[ind[0], dataind]) skew = stats.skew(dataarr[ind[0], dataind]) kurtosis = stats.kurtosis(dataarr[ind[0], dataind]) if var > 0.0: sd2 = 2 * math.sqrt(var) else: sd2 = var res = [[ timestep, mean, mode[0], var, skew, kurtosis, mean - sd2, mean + sd2 ]] if resto == 'stock_tom': self.md.stock_tom = numpy.append(self.md.stock_tom, res, axis=0) elif resto == 'stock_woody': self.md.stock_woody = numpy.append(self.md.stock_woody, res, axis=0) elif resto == 'stock_non_woody': self.md.stock_non_woody = numpy.append(\ self.md.stock_non_woody, res, axis=0) elif resto == 'stock_acid': self.md.stock_acid = numpy.append(self.md.stock_acid, res, axis=0) elif resto == 'stock_water': self.md.stock_water = numpy.append(self.md.stock_water, res, axis=0) elif resto == 'stock_ethanol': self.md.stock_ethanol = numpy.append(self.md.stock_ethanol, res, axis=0) elif resto == 'stock_non_soluble': self.md.stock_non_soluble = numpy.append( self.md.stock_non_soluble, res, axis=0) elif resto == 'stock_humus': self.md.stock_humus = numpy.append(self.md.stock_humus, res, axis=0) elif resto == 'change_tom': self.md.change_tom = numpy.append(self.md.change_tom, res, axis=0) elif resto == 'change_woody': self.md.change_woody = numpy.append(self.md.change_woody, res, axis=0) elif resto == 'change_non_woody': self.md.change_non_woody = numpy.append(\ self.md.change_non_woody, res, axis=0) elif resto == 'change_acid': self.md.change_acid = numpy.append(self.md.change_acid, res, axis=0) elif resto == 'change_water': self.md.change_water = numpy.append(self.md.change_water, res, axis=0) elif resto == 'change_ethanol': self.md.change_ethanol = numpy.append( self.md.change_ethanol, res, axis=0) elif resto == 'change_non_soluble': self.md.change_non_soluble = numpy.append( self.md.change_non_soluble, res, axis=0) elif resto == 'change_humus': self.md.change_humus = numpy.append(self.md.change_humus, res, axis=0) elif resto == 'co2': self.md.co2 = numpy.append(self.md.co2, res, axis=0)