def theo_error_curve(m=80, R=20, s=0, saveimage=False):
    '''It computes the actual error and theoretical error in relative sense
        for a fixed m,s and R'''
    print(f'm:{m}, s:{s} and R:{R}')
    M = m
    f_m = [((-R)**k / (2**(k * s) * factorial(k))) for k in range(0, M + 1)]

    Error = np.zeros(M + 1)

    # theoretical error
    for idx, m in enumerate(np.arange(M + 1)):
        error = (power(R, m + 1) * np.exp(R / (2**s))) / (power(2, s * m) *
                                                          factorial(m + 1))
        Error[idx] = error

    plt.figure(figsize=(12, 9))
    ax = plt.subplot(1, 1, 1)

    ax.plot(np.arange(M + 1),
            np.log10(
                np.abs((np.cumsum(f_m))**(2**s) - np.exp(-R)) / np.exp(-R)),
            '-k',
            lw=4,
            label=fr'Computed error')
    ax.plot(np.arange(M + 1),
            np.log10(Error),
            '--r',
            lw=4,
            label=fr'Theoretical error')
    #plt.plot(range(0,M+1),np.log10(np.absolute((1/np.cumsum(f_m))**(power(2,s))-np.exp(-R))/np.exp(-R)),'-k',lw=3,label = fr'relative error$');

    #plt.axhline(y=np.log10(np.exp(-R)),xmin=0,ls='--',color = 'b',lw=2, label=fr'Order of $\exp({-R})$')
    #plt.axhline(y=np.log10(np.spacing(1)*0.5),xmin=0,ls='--',color = 'b',lw=2, label = r'$\epsilon_{mach}\approx 1\times 10^{-16}$')   #machine precision

    ax.minorticks_on()
    ax.grid(which='minor', linestyle=':', linewidth='0.3', color='black')
    plt.grid(which='major', linestyle='-', linewidth='0.5', color='k')
    start, end = ax.get_xlim()
    ax.xaxis.set_ticks(np.arange(0, end, 10))
    plt.xlabel('Truncation parameter $m$ for $T_m(-R/2^s)^{2^s}$', fontsize=24)
    plt.ylabel(r"$\log_{10}$ Relative Error", fontsize=24)
    #plt.title(fr'Relative Error for Composite Taylor for $s={s}$ at $z={-R}$',fontsize=18)
    plt.legend(loc=1, prop={'size': 25})
    plt.tick_params(labelsize=14)
    plt.tight_layout()

    if saveimage:
        # creates a folder plots to save  graphs in the folder
        path = r'C:\Users\xxxxx\OneDrive - Nexus365\Oxford Masters\Modules\Dissertation\Code\Candidate_no_1040706\plots\theoretical_plots'
        if not os.path.exists(path):
            os.mkdir(path)
            print('Folder `plots/theoretical_plots` is created\n')
        plt.savefig(path + f'/theo_s{s}.pdf', format='pdf', dpi=1200)
    plt.show()
Example #2
0
def rsa(msg):
    pn = 7.0
    qn = 17.0
    nn = pn * qn
    t_of_n = (pn - 1)(qn - 1)
    ee = 17
    dd = 2753
    cc = math.power(msg, ee) % nn
    print cc

    mm = math.power(cc, dd) % nn

    print mm
def _optimalval(s, R):
    '''Calculating the truncation parameter m where we see line flattening'''
    e_mach = 0.5 * np.spacing(1)
    max_m = int(R / 2**s)  #value of m where we have the largesr error
    delta = np.abs(
        np.exp(-R / 2**s) - ((-R / 2**s)**max_m) /
        factorial(max_m)) * e_mach  #as shown in the above equation
    m = 0
    error = R**(m + 1) / (power(2, s * (m + 1)) * factorial(m + 1))
    while error > delta:
        m += 1
        error = R**(m + 1) / (power(2, s * (m + 1)) * factorial(m + 1))
    return m
Example #4
0
def solve_for_lower_right(number, base):
    corner = power(base, 2)
    opposing_corner = power(base - 1, 2) + 1
    middle_corner = corner - ((corner - opposing_corner) / 2)
    if number < middle_corner:
        if number <= opposing_corner + ((middle_corner - opposing_corner) / 2):
            return base - 1 - (number - opposing_corner)
        else:
            return base - 1 - (middle_corner - number)
    else:
        if number <= middle_corner + ((corner - middle_corner) / 2):
            return base - 1 - (number - middle_corner)
        else:
            return base - 1 - (corner - number)
Example #5
0
File: gis.py Project: xvill/pyutil
def Distance(lon1, lat1, lon2, lat2):
    earth_padius = 6378.137  # 地球赤道半径(千米),地球平均半径=6371.004 千米
    PI = 3.14159265358979324
    s = 0
    radlon1 = lon1 * PI / 180.0
    radlon2 = lon2 * PI / 180.0

    s = 2 * math.asin(
        math.sqrt(
            math.power(math.sin((radlon1 - radlon2) / 2), 2) +
            math.cos(radlon1) * math.cos(radlon2) *
            math.power(math.sin(((lat1 - lat2) * PI / 180.0) / 2), 2)))
    s = s * earth_padius
    return round(s * 1000, 2)  # 精确到米
Example #6
0
def solve_for_upper_left(number, base):
    corner = power(base, 2)
    opposing_corner = power(base - 1, 2) + 1
    middle_corner = corner - ((corner - opposing_corner) / 2)
    if number < middle_corner:
        if number < opposing_corner + ceil(
            (middle_corner - opposing_corner) / 2):
            return base - 1 - (number - opposing_corner)
        else:
            return base - (middle_corner - number)
    else:
        if number < middle_corner + ceil((corner - middle_corner) / 2):
            return base - (number - middle_corner)
        else:
            return base - 1 - (corner - number)
Example #7
0
def main():
    number = 325489
    base = ceil(sqrt(number))
    if is_even(power(base, 2)):
        print(int(solve_for_upper_left(number, base)))
    else:
        print(int(solve_for_lower_right(number, base)))
Example #8
0
def calculate_poster(j, data_item, alpha_set, mean_vec, variance_vec):
    # wait to be filled
    upper_probablity = (alpha_set[j] * np.exp(-(1.0 / 2) * np.dot(
        np.dot(data_item - np.array(mean_vec[j]), np.linalg.inv(
            variance_vec[j])), (data_item - np.array(mean_vec[j])).T))) / (
                math.power(2 * math.pi, variance_vec[j].shape[0] / 2) *
                math.sqrt(np.linalg.det(variance_vec[j])))
    lower_probablity = 0
    for i in range(len(alpha_set)):
        lower_probablity += (alpha_set[i] * np.exp(-(1.0 / 2) * np.dot(
            np.dot(data_item - np.array(mean_vec[i]),
                   np.linalg.inv(variance_vec[i])),
            (data_item - np.array(mean_vec[i])).T))) / (
                math.power(2 * math.pi, variance_vec[i].shape[0] / 2) *
                math.sqrt(np.linalg.det(variance_vec[i])))
    return upper_probablity / lower_probablity
Example #9
0
def mv_trans_hot_temp(vol_value):
    """
    tc的mv电压换算成热端温度
    :param vol_value:电压值
    :return dst_data:目标数据
    """
    para_below0_k = [
        0.0000000E+00, 2.5173462E+01, -1.1662878E+00, -1.0833638E+00,
        -8.9773540E-01, -3.7342377E-01, -8.6632643E-02, -1.0450598E-02,
        -5.1920577E-04, 0.0000000E+00
    ]
    para_below500_k = [
        0.000000E+00, 2.508355E+01, 7.860106E-02, -2.503131E-01, 8.315270E-02,
        -1.228034E-02, 9.804036E-04, -4.413030E-05, 1.057734E-06, -1.052755E-08
    ]
    para_above500_k = [
        -1.318058E+02, 4.830222E+01, -1.646031E+00, 5.464731E-02,
        -9.650715E-04, 8.802193E-06, -3.110810E-08, 0.000000E+00, 0.000000E+00,
        0.000000E+00
    ]
    p_para = []
    hot_temp = 0
    if -3.852 <= vol_value < 0:
        p_para = para_below0_k
    elif 0 <= vol_value < 20.644:
        p_para = para_below500_k
    elif 20.644 <= vol_value <= 49.202:
        p_para = para_above500_k
    else:
        return 0x7FFF
    for i in range(0, 10):
        hot_temp += p_para[i] * power(vol_value, i)
    hot_temp = hot_temp * 10
    return hot_temp
Example #10
0
def cold_temp_trans_mv(cold_temp):
    """
    tc的冷端温度转毫伏电压
    :param cold_temp:冷端温度
    :return dst_data:目标数据
    """
    cjcbelow_k = [
        0.000000000000E+00, 0.394501280250E-01, 0.236223735980E-04,
        -0.328589067840E-06, -0.499048287770E-08, -0.675090591730E-10,
        -0.574103274280E-12, -0.310888728940E-14, -0.104516093650E-16,
        -0.198892668780E-19, -0.163226974860E-22
    ]
    cjcabove0_k = [
        -0.176004136860E-01, 0.389212049750E-01, 0.185587700320E-04,
        -0.994575928740E-07, 0.318409457190E-09, -0.560728448890E-12,
        0.560750590590E-15, -0.320207200030E-18, 0.971511471520E-22,
        -0.121047212750E-25
    ]
    para_value_a0 = 0.118597600000E+00
    para_value_a1 = -0.118343200000E-03
    para_value_a2 = 0.126968600000E+03
    if -270 <= cold_temp <= 0:
        return __calc_array_value(cold_temp, cjcbelow_k, 10)
    if 0 < cold_temp <= 1372:
        return __calc_array_value(
            cold_temp, cjcabove0_k, 10) + para_value_a0 * myexp(
                para_value_a1 * power(cold_temp - para_value_a2, 2))
    return 0
Example #11
0
    def color2zs(self,color):
        """Get the range of values (zs) associated with a particular color,
        color.
        """

        i = self.color_range.index(color)
        n = len(self.color_range)
        (xmin,ymin,xmax,ymax) = self.get_world()
        if self.yaxis.scale==LINEAR_SCALE:
            zmin = float(i)/float(n)*(ymax - ymin) + ymin
            zmax = float(i+1)/float(n)*(ymax - ymin) + ymin
        else:
            zmin = ymin*math.power(zmax/zmin,float(i)/float(n))
            zmax = ymin*math.power(zmax/zmin,float(i+1)/float(n))

        return zmin,zmax
Example #12
0
    def color2zs(self, color):
        """Get the range of values (zs) associated with a particular color,
        color.
        """

        i = self.color_range.index(color)
        n = len(self.color_range)
        (xmin, ymin, xmax, ymax) = self.get_world()
        if self.yaxis.scale == LINEAR_SCALE:
            zmin = float(i) / float(n) * (ymax - ymin) + ymin
            zmax = float(i + 1) / float(n) * (ymax - ymin) + ymin
        else:
            zmin = ymin * math.power(zmax / zmin, float(i) / float(n))
            zmax = ymin * math.power(zmax / zmin, float(i + 1) / float(n))

        return zmin, zmax
def getNumberOfIntegers(L,R,K):
    L = int(L)
    R = int(R)
    n = []
    for i in range(L+1,R+1):
        n.append(i)
    a = list(filter(check,n))
    return len(a)%(math.power(10,9)+7)
Example #14
0
def convert_size(size_bytes):
    """convert Btye Value to Pretty Value"""
    if size_bytes == 0:
        return "0B"
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    size_index = int(floor(log(size_bytes, 1024)))
    return "%s%s" % (
        round(size_bytes / power(1024, size_index), 2),
        size_name[size_index],
    )
Example #15
0
def __calc_array_value(base, array, count):
    """
    转换公式计算
    :param vol_value:电压值
    :return dst_data:目标数据
    """
    ret_val = 0
    for i in range(0, count):
        ret_val += array[i] * power(base, i)
    return ret_val
Example #16
0
def returnSubsets(List, Sublist):

    numSublists = int(power(2, len(List)))
    bitArray = [int(digit) for digit in bin(numSublists - 1)[2:]]
    mostSigBit = int(power(2, len(bitArray) - 1))
    msbIndx = len(bitArray) - 1
#iterate from 0b0000000 to 0b1111111
#each task is given a bit, when that bit is 1, add its value to the sum for this subset
#append that as a new subset
    for i in range(1, numSublists):
        Indexes = []
        sum = 0
        j = mostSigBit
        k = msbIndx
        while j != 0:
            if i & j == j:
                sum += List[k][lengthIndx]
                Indexes.append(k)
            j /= 2
            k -= 1
        Sublist.append([sum,Indexes])
Example #17
0
 def great_deluge(self, number=1600, debug=False):
     # init solution generated by some constructive feasable h.
     solution = self.init_solution
     # best_solution = deepcopy( solution )
     # best feasable solution
     best_solution_w_e = deepcopy(solution)
     # best feasable/unfeasable price
     best_price = price = self.count(solution)
     # best only feasable price
     best_price_w_e = price
     # debug statistics
     stats1 = {
         "switch two jobs": 0,
         "switch max and random jobs": 0,
         "switch two workers": 0,
         "rearange 2-5 workers": 0,
         "rearange greedy 2-5 workers": 0,
     }
     if debug:
         print "Begin parameters:"
         print self.count(solution, True)
     # level of decay
     level = (
         best_price * self.START_LEVEL_MULTIPLY_BEST
         + self.AVERAGE_ERRORS * self.PENALTY_LIN
         + power(self.AVERAGE_ERRORS, self.PENALTY_EXP)
     )
     # for number of interations or too low decay
     for i in range(number):
         level = self._decay(level)
         new_price, (new_solution, source) = self.select_step(self.available_steps(solution))
         # if step is acceptable
         if new_price < price + level:
             price = new_price
             solution = new_solution
         # if step is optimal
         if new_price < best_price:
             # if new price doesnt have any error
             if self.count(new_solution, True)[2] == 0:
                 best_price_w_e = min(new_price, best_price_w_e)
                 best_solution_w_e = deepcopy(solution)
             if debug:
                 print self.count(new_solution, True), "  l:", round(level), source
             # best infeasable or feasable solution
             stats1[source] += 1
             best_price = min(new_price, best_price)
             # best_solution = deepcopy( solution )
         # finish condition
         if level <= max(self.PENALTY_LIN, 1):
             if debug:
                 print "level", level
             break
     return self.output_format(best_solution_w_e)
Example #18
0
        def compute_R_and_phi_at(t):
            R = [0., 0., 0., 0., 0.]
            phi = [0., 0., 0., 0., 0.]

            T = floor(30.6001 *
                      (1 + self.month + 12 * floor(1 /
                                                   (self.month + 1.0) + 0.7))
                      ) + floor(365.25 *
                                (self.year - floor(1 /
                                                   (self.month + 1.0) + 0.7))
                                ) + self.day + t / 24 - 723258
            h = 279.82 + 0.98564734 * T
            s = 78.16 + 13.17639673 * T
            p = 349.5 + 0.11140408 * T
            N = 208.1 + 0.05295392 * T
            p1 = 282.6 + 0.000047069 * T
            D = 90

            for j in range(5):
                if j != 3:
                    Xj = 0
                    Yj = 0
                    for i in range(11):
                        Vij = 15 * j * t + Tmgpm.n1[j][i] * s + Tmgpm.n2[j][i] * h + Tmgpm.n3[j][i] * p + \
                            Tmgpm.n4[j][i] * N + Tmgpm.n5[j][i] * p1 + Tmgpm.n6[j][i] * D
                        Xj += self.A[j][i] * cos(radians(Vij - self.G[j][i]))
                        Yj += self.A[j][i] * sin(radians(Vij - self.G[j][i]))

                    R[j] = sqrt(power(Xj, 2) + power(Yj, 2))
                    if R[j] == 0:
                        phi[j] = 90
                    else:
                        phi[j] = degrees(acos(Xj / R[j])) * sign(
                            degrees(asin(Yj / R[j])))

            return R, phi
Example #19
0
 def count(self, solution, parts=False):
     cost = 0
     weight_penalty = copy(self.w_capacity)
     penalty_cost = 0
     for worker_id in solution.keys():
         for job_id in solution[worker_id]:
             cost += self.w_price[worker_id][job_id]
             weight_penalty[worker_id] -= self.w_space[worker_id][job_id]
     for item in weight_penalty:
         if item < 0:
             penalty_cost += self.PENALTY_LIN + power(-1 * item, self.PENALTY_EXP)
     if parts == True:
         return round(cost + penalty_cost), cost, round(penalty_cost)
     else:
         return float(cost + penalty_cost)
Example #20
0
def mean_std(L, denom=0):
    """
    - Takes a list L and returns a tuple of (mean, standard deviation)

    - If denom = 0, std will have a denominator of n. If denom = -1, it will
            have a denominator of n-1
    """
    try:
        L = [float(x) for x in L]
        avg = sum(L) / len(L)
        squared = [power(x - avg, 2) for x in L]
        std = sqrt(sum(squared) / (len(L) + denom))
    except ZeroDivisionError:
        print "NO ENTRIES IN LIST!"
        avg = None
        std = None
    return avg, std
def getResult(entries):
    e = (float(eval(entries[epsilon].get(), evalDic)))
    e *= 8.85 * math.pow(10, -12)
    s = (float(eval(entries[sigma].get(), evalDic)))
    sc = (float(eval(entries[sigmaSubC].get(), evalDic)))
    u = 12.57 * math.pow(10, -7)
    h = (float(eval(entries[height].get(), evalDic)))
    w = (float(eval(entries[width].get(), evalDic)))
    f = (float(eval(entries[freq].get(), evalDic)))
    select = int(selector.get())

    try:
        RS = math.sqrt(math.pi * f * (u / sc))
        if (select == coax):
            R = (RS / (2 * math.pi)) * ((1 / h) + (1 / w))
            L = (u / (2 * math.pi)) * (math.log(h / w))
            G = (2 * math.pi * s) / (math.log(h / w))
            C = (2 * math.pi * e) / (math.log(h / w))
        elif (select == twoWire):
            x = math.log((h / w) + math.sqrt(math.power((h / w), 2) - 1))
            R = (2 * RS) / (math.pi * w)
            L = (u / math.pi) * x
            G = (math.pi * s) / x
            C = (math.pi * e) / x
        elif (select == parPlate):
            R = (2 * RS) / w
            L = (u * h) / w
            G = (s * w) / h
            C = (e * w) / h
        result = "R' : {} \u03A9/m\n".format(R)
        result += "L' : {} H/m\n".format(L)
        result += "G' : {} S/m\n".format(G)
        result += "C' : {} F/m\n".format(C)
        b1.configure(text=result)

    except Exception as e:
        b1.configure(text="Error, input variables please\n" + str(e))
        print(e)
import numpy as np  #import numpy, for arrays
import math  #import math, for power and abs

n = 10  #size of the arrays

matrix = np.zeros((n, n))  #create an array of zeros of size n
for i in range(n):  #loop over i
    for j in range(n):  #loop over j
        matrix[i][j] = math.power(math.abs(i - j), 2)  #compute |i-j|^2

for i in range(n):  #loop over i
    for j in range(n):  #loop over j
        print(str(matrix[i][j]) + " ", end="")  #print matrix element.
    print("")
 def __init__(self, card):
     self.CurrentFanNum = card.BaseFanNum
     self.CurrentAtk = card.BaseAtk
     self.CurrentDef = card.BaseDef
     self.CurrentRep = card.BaseRep
     self.BarNormalization = power(card.Zhi*card.Chuang*card.Fu,1.0/3)
Example #24
0
def distance(point1, point2):  #计算两点距离
    return power(point1.color[0]-point2.color[0],2)\
           +power(point1.color[1]-point2.color[1],2)\
           +power(point1.color[2]-point2.color[2],2)
def main():
    # Input parameters
    args = get_args()
    num_tasks = int(args.tasks) if args and args.tasks else DEFAULT_NUM_TASKS
    num_workers = int(
        args.workers) if args and args.workers else DEFAULT_NUM_WORKERS
    high_quality_configuration = str(
        args.configuration
    ) if args and args.configuration else DEFAULT_HIGH_QUALITY_CONFIGURATION
    iterations = int(args.iterations) if args and args.iterations else 1

    # Create results directory.
    DIR = './results/np_%d' % (num_workers)
    if not os.path.exists(DIR):
        os.makedirs(DIR)
    # Initial configuration, 0.1115 from parameter tuning
    team_likelihood = {}
    team_likelihood[2000] = 0.0255
    team_likelihood[200] = 0.1115
    team_likelihood[50] = 0.2515
    team_likelihood[25] = 0.4215

    # for collecting stats
    stats = {}
    initial_high_quality_percent = []
    for i in range(num_tasks):
        stats[i] = ([], [])

    for i in range(iterations):
        is_first_iteration = True if i < 1 else False
        G = generate_points(num_workers, team_likelihood[num_workers],
                            high_quality_configuration)

        # Get the layout of the graph.
        pos = nx.spring_layout(G, None, None, None, 30, 'weight', 200)

        # Plot the team size
        if is_first_iteration:
            plot_team_info(num_workers, G, DIR)

        if is_first_iteration:
            plot_points(G, pos, 0, DIR)

        # initial stats
        initial_average_state = sum([node.state for node in G]) / num_workers
        initial_high_quality = len(
            [node for node in G if node.state >= HIGH_QUALITY_THRESHOLD])
        initial_high_quality_percent = initial_high_quality_percent + [
            float(initial_high_quality) / num_workers
        ]

        #run the simulation
        for j in range(num_tasks):
            if is_first_iteration:
                plot_frequency = power(10, len(str(j)) - 1)
                if j % plot_frequency == 0:
                    plot_points(G, pos, j, DIR)
            complete_task(G)

            # collect stats
            intermediate_average_state = [
                1.0 * sum([node.state for node in G]) / num_workers
            ]
            intermediate_high_quality = [
                1.0 * len([
                    node for node in G if node.state >= HIGH_QUALITY_THRESHOLD
                ])
            ]
            stats[j] = (stats[j][0] + intermediate_average_state,
                        stats[j][1] + intermediate_high_quality)

    # final stats
    output_sample = 100

    file_name = '%s_employees_%s_training_strategy_%s_tasks' % (
        num_workers, high_quality_configuration, num_tasks)
    with open('./%s_average_state.csv' % file_name, 'w') as csvfile:
        fieldnames = [
            'iteration', 'state', 'num_high_quality', 'high_quality_percent'
        ]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for it, values in stats.items():
            state_list = values[0]
            num_high_quality_list = values[1]
            state = float(sum(state_list) / len(state_list))
            num_high_quality = float(
                sum(num_high_quality_list) / len(num_high_quality_list))
            high_quality_percent = 100.0 * num_high_quality / num_workers

            if it % output_sample == 0:
                writer.writerow({
                    'iteration': it,
                    'state': state,
                    'num_high_quality': num_high_quality,
                    'high_quality_percent': high_quality_percent
                })

    with open('./initial_high_quality_%s.csv' % file_name, 'w') as csvfile:
        fieldnames = ['configuration', 'initial_percent']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        average = sum(initial_high_quality_percent) / len(
            initial_high_quality_percent)
        writer.writerow({
            'configuration': high_quality_configuration,
            'initial_percent': average
        })

    # make the gif, requires imageMagick
    system(
        '/opt/local/bin/convert -delay 50 results/*/random_graph_* -loop 1 ./%s.gif'
        % file_name)
Example #26
0
def euclideanDistance(feature1,feature2):
    '''
    计算两个向量的欧式距离
    '''
    return math.sqrt(sum(math.power(feature1-feature2,2)))   
Example #27
0
def disEclud(vecA, vecB):
    return math.sqrt(sum(math.power(vecA - vecB)))
Example #28
0
 def linear_space(self, log_prob):
     return math.power(e, log_prob)
Example #29
0
 def mag(self, raw_mag):
     self.logger.info(f"Calculating SQM Mag")
     try:
         return 7.93 - 5 * (log10(power(10, (4.316 - (raw_mag / 5))) + 1))
     except Exception as e:
         self.logger.error(e)
Example #30
0
def get_distance(start, end):
    return math.sqrt(
        math.power(start[0] - end[0], 2) + math.power(start[1] - end[1], 2))
Example #31
0
def euclidean_distance(vec1, vec2):
    '''
    calculate euclidean distance
    '''
    return math.sqrt(sum(math.power(vec1 - vec2, 2)))
Example #32
0
def my_power(a, b):
	if not (isNumType(a) and isNumType(b)):
		return 
	else:
		return math.power(a, b)
Example #33
0
def kForce(freq):
    """
    Function to assign to each restraint a force proportional to the underlying
    experimental value.
    """
    return power(fabs(freq), 0.5 )
Example #34
0
	def hypothesisTest(self, seq1, seq2, totalSeq1, totalSeq2):
		if (seq1 == 0 and seq2== 0) or (seq1 == totalSeq1 and seq2 == totalSeq2):
			# if the measured effect size is zero, the probability of observing a table
			# more extreme will be large (not strictly 1.0, but large and this degenerate
			# case is problematic to calculate exactly)
			return 1.0, 1.0
		
		# calculate Wald statistic (standardized difference between proportions) for observed data
		pooledP = float(seq1 + seq2) / (totalSeq1 + totalSeq2)
		stdDev = math.sqrt(pooledP * (1.0 - pooledP) * (1.0/totalSeq1 + 1.0/totalSeq2))
		
		obsDiff = float(seq1) /	totalSeq1 - float(seq2) / totalSeq2
		obsStdDiff =	abs(obsDiff / stdDev)
		
		# determine tables more extreme than the observed data
		extremeTables = []
		for a in xrange(0, totalSeq1+1):
			p1 = float(a) / totalSeq1
			
			for b in xrange(0, totalSeq2+1):				
				if (a == 0 and b == 0) or (a == totalSeq1 and b == totalSeq2):
					# difference in proportions is zero so this is not an extreme table
					# but will cause a division by zero exception
					continue
				
				# calculate Wald statistic for current table
				pooledP = float(a + b) / (totalSeq1 + totalSeq2)
				stdDev = math.sqrt(pooledP * (1.0 - pooledP) * (1.0/totalSeq1 + 1.0/totalSeq2))
		
				p2 = float(b) / totalSeq2
				diff = p1 - p2
				stdDiff = abs(diff / stdDev)
				
				if stdDiff >= obsStdDiff:
					# Barnard recommends adding extreme tables under symmetrical and convexity conditions.
					# The latter will be handled here simply by considering all tables. Symmetry may not 
					# occur unless explicitly enforced. Note, that there is no concrete mathematical argument
					# to enforce symmetry. In fact, Barnard describes his general method for finding extreme tables
					# as "laziness".
					if [a,b] not in extremeTables:
						extremeTables.append([a,b])
						extremeTables.append([totalSeq1 - a, totalSeq2 - b])

		# calculate Barnard's p-value (must find optimal population proportion)
		steps = 100
		dPi = 0.5 / float(steps)
		pi = 0.0
		pValueTwoSided = 0
		for dummy in xrange(0,steps):
			pi += dPi
			
			pValue = 0
			for table in extremeTables:
				c1, c2 = table

				nCr1 = math.exp(self.logChoose(totalSeq1,c1))
				nCr2 = math.exp(self.logChoose(totalSeq2,c2)) 
				
				prob = nCr1 * nCr2 * math.power(pi,c1+c2) * math.power(1.0 - pi,totalSeq1+totalSeq2-c1-c2)
				pValue += prob

			if pValue > pValueTwoSided:				
				pValueTwoSided = pValue
	
		return float('inf'), pValueTwoSided
Example #35
0
 def colourDist(self, c):
     distance = math.sqrt(
         math.pow(c.r - self.r, 2) + math.pow(c.g - self.g, 2) +
         math.power(c.b - self.b, 2) * 1.0)
     return distance
Example #36
0
def k_force(Zscore):
    """
    Function to assign to each restraint a force proportional to the underlying
    experimental value.
    """
    return power(fabs(Zscore), 0.5)
Example #37
0
 def CalucalateCallSocre(self):
     Res = 0
     BombCount = self.GetCardParse().GetBombCount()
     if BombCount > 0:
         Res += BombCount * 8 + math.power(2.0, BombCount - 1) * 6
     return Res