Example #1
0
def GetSpindownStuff(tc, age, l0, b0, emax0, n0):

    t = np.logspace(0, math.log10(1000.0 * age), 300)
    lumt = []
    emaxt = []
    bt = []
    nt = []
    n = 0
    for i in t:
        l = l0 / math.pow(1.0 + i / tc, 2.0)
        btt = b0 * math.sqrt(l / l0) * (1.0 + 0.5 * math.sin(0.1 * n * 3.14))
        lumtt = l * (1.0 + 0.5 * math.cos(0.1 * n * 3.14))
        emaxtt = emax0 * math.pow(l / l0, 0.25) * (1.0 + 0.5 * math.sin(0.05 * n * 3.14))
        ntt = n0 * math.pow(l / l0, 0.25) * (1.0 + 0.5 * math.cos(0.05 * n * 3.14))

        bt.append([])
        bt[n].append(i)
        bt[n].append(btt)
        lumt.append([])
        lumt[n].append(i)
        lumt[n].append(lumtt)
        emaxt.append([])
        emaxt[n].append(i)
        emaxt[n].append(emaxtt)
        nt.append([])
        nt[n].append(i)
        nt[n].append(ntt)

        n = n + 1
    return lumt, bt, emaxt, nt
Example #2
0
    def triangulateClearKick(self):
        # Assert: Neither far post was seen.
        #         Both near posts were seen.
        #         Use near posts to hack a loc for ourselves.
        bearingDiff = self.nearLeftPostBearing - self.nearRightPostBearing
        leftDist = self.nearRightPostDist
        rightDist = self.nearLeftPostDist
        leftPostY = constants.LANDMARK_BLUE_GOAL_TOP_POST_Y
        rightPostY = constants.LANDMARK_BLUE_GOAL_BOTTOM_POST_Y
        farSideLenth = constants.CROSSBAR_CM_WIDTH

        # Should be generalized into a helper method somewhere.
        y = (math.pow(leftPostY, 2) + math.pow(leftDist, 2) - math.pow(rightPostY, 2) - math.pow(rightDist, 2)) / (
            2 * (leftPostY - rightPostY)
        )
        x = math.sqrt(math.pow(leftDist, 2) - math.pow((y - rightPostY), 2))

        # Use locations to get global heading.
        post = Objects.Location(constants.FIELD_WHITE_LEFT_SIDELINE_X, constants.LANDMARK_BLUE_GOAL_TOP_POST_Y)
        me = Objects.Location(x, y)
        meToPost = me.relativeLocationOf(post)

        myGlobalHeading = meToPost.bearing - self.nearLeftPostBearing
        if myGlobalHeading < -180:
            myGlobalHeading += 360
        elif myGlobalHeading > 180:
            myGlobalHeading -= 360

        return self.chooseClearKick(myGlobalHeading, x, y)
Example #3
0
def create_nodes(emin, emax, enumbins):
    """
	Create nodes (energies in TeV).
	"""
    # Open file
    file = open("nodes.xml", "w")

    # Set node boundaries
    elogmin = math.log10(float(emin))
    elogmax = math.log10(float(emax))
    elogbin = (elogmax - elogmin) / (float(enumbins) - 1.0)

    # Fill arrays
    for i in range(int(enumbins)):

        # Compute energy
        energy = math.pow(10.0, i * elogbin + elogmin)

        # Compute scale (HESS Crab spectrum)
        scale = 3.45e-17 * math.pow(energy, -2.63)

        # Write node
        write_node(file, energy, scale)

        # Debug
        # sys.stdout.write(energy)
        # sys.stdout.write(math.pow(10.0, int(math.log10(scale))-1.0)±"\n")

        # Close file
    file.close()

    # Return
    return
Example #4
0
def MZ2(x):
    x1 = x[0]
    x2 = x[1]
    ret = 0
    ret += sin(x1) * pow(sin(1 * x1 * x1 / pi), 20)
    ret += sin(x2) * pow(sin(2 * x2 * x2 / pi), 20)
    return -ret
Example #5
0
def fill_tree(tree, height, npieces, hashes):
    # 1. Fill bottom of tree with hashes
    startoffset = int(pow(2, height) - 1)
    if DEBUG:
        print >>sys.stderr, time.asctime(), "-", "merkle: bottom of tree starts at", startoffset
    for offset in range(startoffset, startoffset + npieces):
        # print >> sys.stderr,time.asctime(),'-', "merkle: copying",offset
        # print >> sys.stderr,time.asctime(),'-', "merkle: hashes[",offset-startoffset,"]=",str(hashes[offset-startoffset])
        tree[offset] = hashes[offset - startoffset]
    # 2. Note that unused leaves are NOT filled. It may be a good idea to fill
    # them as hashing 0 values may create a security problem. However, the
    # filler values would have to be known to any initial seeder, otherwise it
    # will not be able build the same hash tree as the other initial seeders.
    # Assume anyone should be able to autonomously become a seeder, the filler
    # must be public info. I don't know whether having public info as filler
    # instead of 0s is any safer, cryptographically speaking. Hence, we stick
    # with 0 for the moment

    # 3. Calculate higher level hashes from leaves
    for level in range(height, 0, -1):
        if DEBUG:
            print >>sys.stderr, time.asctime(), "-", "merkle: calculating level", level
        for offset in range(int(pow(2, level) - 1), int(pow(2, level + 1) - 2), 2):
            # print >> sys.stderr,time.asctime(),'-', "merkle: data offset",offset
            [parentstartoffset, parentoffset] = get_parent_offset(offset, level)
            # print >> sys.stderr,time.asctime(),'-', "merkle: parent offset",parentoffset
            data = tree[offset] + tree[offset + 1]
            digester = sha()
            digester.update(data)
            digest = digester.digest()
            tree[parentoffset] = digest
    # for offset in range(0,treesize-1):
    #        print offset,"HASH",str(tree[offset])
    return tree
Example #6
0
def sssFloat(Min, Max):  # linear, Float TODO: bad for values, different in low degrees!!!
    if Min < 0:
        if Max < 0:
            s, ss, Min, Max = sss(-Max, -Min)
            return s, ss, -Max, -Min
        s1, ss1, Min1, Max1 = sss(0, -Min)
        s2, ss2, Min2, Max2 = sss(0, Max)
        return s1 + s2, ss1 * ss2, -Max1, Max2  # Min1 must be == Min2 == 0
    if Min == 0:
        if Max == 0:
            return 0, 0, 0, 0
    dm, dM = list(digitsPower(Min)), list(digitsPower(Max))
    if dM[1] != 0:
        dM[0] = dM[0] + 1  # ceiling => we use only first digit!
        dM[1] = 0
        if dM[0] == 10:
            dM = [1, 0, dM[2] + 1]
    if dM[2] == dm[2]:  # the same degree
        newMin, ss = steps(dm[0])
    else:  # lM - lm == 1 (and more...): something else?
        newMin, ss = 0, 2
    newMax, s = dM[0], 1
    if newMin != 0:
        if newMax % newMin:
            newMax += newMin - (newMax % newMin)
        s = newMax / newMin - 1
        newMin *= pow(10, dm[2])
    else:
        newMax, s = steps(n=dM[0], plus=True)
    newMax *= pow(10, dM[2])
    return s, ss, newMin, newMax
Example #7
0
def convert_to_polar(mag):
    hmag = mag[0]
    vmag = mag[1]
    angle = math.atan2(float(vmag), float(hmag))
    distance = math.sqrt(math.pow(mag[0], 2) + math.pow(mag[1], 2))
    angle = 180 - math.degrees(angle)
    return (angle, distance)
Example #8
0
def convert_pvalue_to_r(scans, threshold):

    import scipy.stats as s
    import math

    """
    Method to calculate correlation threshold from p_value
    
    Parameters
    ----------
    scans : int
        Total number of scans in the data
    threshold : float
        input p_value
    
    Returns
    -------
    rvalue : float
        correlation threshold value 
    """

    # p_value =0.05
    print "p_value -> ", threshold
    x = 1 - threshold / 2
    dof = scans - 2
    # Inverse Survival Function (Inverse of SF)
    tvalue = s.t.isf(x, dof)
    rvalue = math.sqrt(math.pow(tvalue, 2) / (dof + math.pow(tvalue, 2)))

    return rvalue
Example #9
0
    def test_GenerateBinomial(self, no_of_samples=10000, size=25, prob=0.2):
        import rpy, random, pylab

        # generate the list of prob(X<=x)
        cdf_list = []
        for i in range(size + 1):
            mass_prob = rpy.r.choose(size, i) * math.pow(prob, i) * math.pow((1 - prob), size - i)
            if len(cdf_list) == 0:
                cdf_list.append(mass_prob)
            else:
                cumulative_prob = mass_prob + cdf_list[-1]
                cdf_list.append(cumulative_prob)
                # start the sampling
        sample_list = []
        for i in range(no_of_samples):
            u = random.random()
            for j in range(size + 1):
                if cdf_list[j] > u:
                    break
            sample_list.append(j)

        pylab.hist(sample_list, 26)
        pylab.title("binomial generator via inverse")
        pylab.show()

        sample_list = rpy.r.rbinom(no_of_samples, size, prob)
        pylab.hist(sample_list, 26)
        pylab.title("R binomial generator")
        pylab.show()
Example #10
0
 def assign_points(self, points):
     if self.debug:
         print "assign points"
     clusters = dict()
     for point in points:
         dist = []
         if self.debug:
             print "point(%f,%f)" % (point.latit, point.longit)
         # find the best cluster for this node
         for mean in self.means:
             dist.append(
                 math.sqrt(math.pow(point.latit - mean.latit, 2.0) + math.pow(point.longit - mean.longit, 2.0))
             )
         # let's find the smallest mean
         if self.debug:
             print dist
         cnt_ = 0
         index = 0
         min_ = dist[0]
         for d in dist:
             if d < min_:
                 min_ = d
                 index = cnt_
             cnt_ += 1
         if self.debug:
             print "index: %d" % index
         clusters.setdefault(index, []).append(point)
     return clusters
 def get_value(self):
     result = None
     d1 = (
         math.log(self.s / math.pow(self.x, -self.i)) + (self.b + (self.i - 0.5) * math.pow(self.sigma, 2)) * self.t
     ) / (self.sigma * math.sqrt(self.t))
     d2 = d1 - self.i * self.sigma * math.sqrt(self.t)
     if self.flag == "call":
         result = (
             math.pow(self.s, self.i)
             * math.exp(
                 (
                     (self.i - 1) * (self.r + self.i * math.pow(self.sigma, 2) / 2)
                     - self.i * (self.r - self.b) * self.t
                 )
             )
             * N(d1)
         ) - (self.x * math.exp(-self.r * self.t) * N(d2))
     elif self.flag == "put":
         result = (self.x * math.exp(-self.r * self.t) * N(-d2)) - (
             math.pow(self.s, self.i)
             * math.exp(
                 (
                     (self.i - 1) * (self.r + self.i * math.pow(self.sigma, 2) / 2)
                     - self.i * (self.r - self.b) * self.t
                 )
             )
             * N(-d1)
         )
     return result
Example #12
0
 def next_random(self, index, points, clusters):
     # pick next node that has the maximum distance from other nodes
     dist = {}
     for point_1 in points:
         if self.debug:
             print "point_1: %f %f" % (point_1.latit, point_1.longit)
         # compute this node distance from all other points in cluster
         for cluster in clusters.values():
             point_2 = cluster[0]
             if self.debug:
                 print "point_2: %f %f" % (point_2.latit, point_2.longit)
             if point_1 not in dist:
                 dist[point_1] = math.sqrt(
                     math.pow(point_1.latit - point_2.latit, 2.0) + math.pow(point_1.longit - point_2.longit, 2.0)
                 )
             else:
                 dist[point_1] += math.sqrt(
                     math.pow(point_1.latit - point_2.latit, 2.0) + math.pow(point_1.longit - point_2.longit, 2.0)
                 )
     if self.debug:
         for key, value in dist.items():
             print "(%f, %f) ==> %f" % (key.latit, key.longit, value)
     # now let's return the point that has the maximum distance from previous nodes
     count_ = 0
     max_ = 0
     for key, value in dist.items():
         if count_ == 0:
             max_ = value
             max_point = key
             count_ += 1
         else:
             if value > max_:
                 max_ = value
                 max_point = key
     return max_point
Example #13
0
    def TFmdm_onek_mpc_nu(self, kk):
        """
        Given a wavenumber in Mpc^-1, return the transfer function for the
        cosmology held in the global variables.
        Input: kk -- Wavenumber in Mpc^-1
        Output:
            tf_cbnu -- the transfer function for density-weighted
                    CDM + Baryon + Massive Neutrino perturbations.
        """

        qq = kk / self.omhh * (self.theta_cmb) ** 2

        # Compute the scale-dependent growth functions
        y_freestream = (
            17.2
            * self.f_hdm
            * (1 + 0.488 * math.pow(self.f_hdm, -7.0 / 6.0))
            * (self.num_degen_hdm * qq / self.f_hdm) ** 2
        )
        temp1 = math.pow(self.growth_k0, 1.0 - self.p_cb)
        temp2 = np.power(self.growth_k0 / (1 + y_freestream), 0.7)
        growth_cbnu = np.power(np.power(self.f_cb, 0.7 / self.p_cb) + temp2, self.p_cb / 0.7) * temp1

        tf_master = self.TFmdm_master_onek_mpc(kk)

        # Now compute the CDM+HDM+baryon transfer functions
        tf_cbnu = tf_master * growth_cbnu / self.growth_k0
        return tf_cbnu
Example #14
0
    def TFmdm_master_onek_mpc(self, kk):
        """
        Given a wavenumber in Mpc^-1, return the master
        transfer function
        Input: kk -- Wavenumber in Mpc^-1
        Output:
            tf_cb -- the transfer function for density-weighted
                    CDM + Baryon perturbations.
        """

        qq = kk / self.omhh * (self.theta_cmb) ** 2

        # Compute the master function
        gamma_eff = self.omhh * (
            self.alpha_gamma + (1 - self.alpha_gamma) / (1 + (kk * self.sound_horizon_fit * 0.43) ** 4)
        )
        qq_eff = qq * self.omhh / gamma_eff

        tf_sup_L = np.log(2.71828 + 1.84 * self.beta_c * self.alpha_gamma * qq_eff)
        tf_sup_C = 14.4 + 325 / (1 + 60.5 * np.power(qq_eff, 1.11))
        tf_sup = tf_sup_L / (tf_sup_L + tf_sup_C * (qq_eff) ** 2)

        qq_nu = 3.92 * qq * math.sqrt(self.num_degen_hdm / self.f_hdm)
        max_fs_correction = 1 + 1.2 * math.pow(self.f_hdm, 0.64) * math.pow(
            self.num_degen_hdm, 0.3 + 0.6 * self.f_hdm
        ) / (np.power(qq_nu, -1.6) + np.power(qq_nu, 0.8))
        tf_master = tf_sup * max_fs_correction

        return tf_master
Example #15
0
def perf(po):
    for num in range(int(pow(10, po - 1)), int(pow(10, po))):
        summ = 0
        for j in range(0, po):
            summ += pow(int(list(str(num))[j]), po)
        if summ == num:
            print num
Example #16
0
    def point_on_bezier_curve(self, p1, p2, p3, p4, t):

        # Below is the equation for a 4 control point bezier curve:
        #
        #   B(t) = P1 * ( 1 - t )^3 + P2 * 3 * t * ( 1 - t )^2 +
        #          P3 * 3 * t^2 * ( 1 - t ) + P4 * t^3

        # Store the (1 - t) in a variable because it is used frequently
        var1 = 1 - t

        # Store the (1 - t)^3 into a variable to cut down computation
        # and create clean code
        var2 = math.pow(var1, 3)

        # Store the t^3 in a variable to cut down computation and
        # create clean code
        var3 = math.pow(t, 3)

        point = [
            var2 * p1[0] + 3 * t * var1 * var1 * p2[0] + 3 * t * t * var1 * p3[0] + var3 * p4[0],
            var2 * p1[1] + 3 * t * var1 * var1 * p2[1] + 3 * t * t * var1 * p3[1] + var3 * p4[1],
            var2 * p1[2] + 3 * t * var1 * var1 * p2[2] + 3 * t * t * var1 * p3[2] + var3 * p4[2],
        ]

        return point
Example #17
0
    def fly_from_point_to_point(self, from_point, to_point, mass=0):

        if self.charge != 100 and ((100 - self.charge) / self.CHARGE_SPEED) > (self.env.now - self.start_charge):
            self.history.append(
                (
                    (from_point, self.env.now),
                    (
                        from_point,
                        self.env.now + ((100 - self.charge) / self.CHARGE_SPEED) - (self.env.now - self.start_charge),
                    ),
                )
            )
            yield self.env.timeout(((100 - self.charge) / self.CHARGE_SPEED) - (self.env.now - self.start_charge))
        else:
            self.charge = 100
        path = math.sqrt(math.pow((from_point.x - to_point.x), 2) + math.pow((from_point.y - to_point.y), 2))
        # print "Start move {5} from {0}.{1} to {2}.{3} -- {4}|| Charge {6}".format(from_point.x, from_point.y,
        #                                                                           to_point.x, to_point.y,
        #                                                                           self.env.now, self.id, self.charge)
        self.charge -= (path / (self.max_speed / (1 - (mass / self.MAX_MASS)))) * self.DISCHARGE_SPEED * 100
        if (path / (self.max_speed / (1 - (mass / self.MAX_MASS)))) * self.DISCHARGE_SPEED * 100 == 0:
            print "qwe"
        self.history.append(
            (
                (from_point, self.env.now),
                (to_point, self.env.now + path / (self.max_speed / (1 - (mass / self.MAX_MASS)))),
            )
        )
        yield self.env.timeout(path / (self.max_speed / (1 - (mass / self.MAX_MASS))))
Example #18
0
    def growSeedOnPlant(self, maxCarbonForSeed):
        if maxCarbonForSeed > self.motherPlant.massSeedMax:
            maxCarbonForSeed = self.motherPlant.massSeedMax
        if not self.motherPlant.massFixed == -0.0:
            if maxCarbonForSeed > self.motherPlant.massFixed:
                maxCarbonForSeed = self.motherPlant.massFixed
        self.motherPlant.massFixed = self.motherPlant.massFixed - maxCarbonForSeed
        self.massSeed = self.massSeed + maxCarbonForSeed
        # use that value to calculate the radius of the seed
        # convert mass to volume and the get the radius
        i = self.massSeed / self.densitySeed  # this is volume in m^3
        # i=i/(4.0/3.0)
        i = i / 1.3333
        # i=i/(math.pi)
        i = i / 3.14
        # i=math.pow(i, 1.0/3.0)
        i = math.pow(i, 0.3333)
        self.radiusSeed = i

        ###need to move the seed as the plant grows###
        if self.motherPlant.leafIsHemisphere:
            dist = geometry_utils.distBetweenPoints(self.x, self.y, self.motherPlant.x, self.motherPlant.y)
            if dist == self.motherPlant.radiusLeaf:
                deltaY = self.motherPlant.radiusLeaf
            elif dist == 0.0:
                deltaY = 0.0
            else:
                deltaY = self.motherPlant.radiusLeaf - math.sqrt(
                    abs(math.pow(self.motherPlant.radiusLeaf, 2.0) - math.pow(dist, 2.0))
                )
            seedZ = self.motherPlant.heightStem + (self.motherPlant.heightLeafMax / 2.0) - deltaY
        else:
            seedZ = self.motherPlant.heightStem + (self.motherPlant.heightLeafMax / 2.0)
        self.z = seedZ
        self.r = self.radiusSeed
Example #19
0
 def coverage_max(self, dmin, dmax, span):
     range = dmax - dmin
     if span > range:
         half = (span - range) / 2.0
         return 1 - math.pow(half, 2) / math.pow(0.1 * range, 2)
     else:
         return 1
Example #20
0
 def makeSomeSeeds(self):
     # make a seed on yourself if you don't have the max number of seeds
     theNum = float(sum(self.massFixedRecord))
     theDenom = float(len(self.massFixedRecord))
     ###this addresses a rare bug where theDenom==0.0
     if theDenom <= 0:
         avgMassFixed = 0
     else:
         avgMassFixed = theNum / theDenom
     maxKgSeeds = self.reproductionConstant * math.pow(self.massFixed, self.reproductionExponent)
     # print "%i, %f, %f, %f, %f" %(self.age, self.leafAreaDisc, self.heightStem, self.massFixed, maxKgSeeds)
     adjMaxKgSeeds = maxKgSeeds * self.fractionCarbonToSeeds
     if self.massFixed < avgMassFixed:
         theFractDifference = self.massFixed / avgMassFixed
         if theFractDifference < self.fractionSelfishness and self.fractionCarbonToSeeds < 1.0:
             adjMaxKgSeeds = maxKgSeeds * 1.0
             # makeThisManySeeds=int(adjMaxKgSeeds/self.massSeedMax)
             # print "constant: %f     exponent: %f     adjMaxKgSeeds: %f" % (self.seedsPerAreaConstant, self.seedsPerAreaExponent, adjMaxKgSeeds)
     if adjMaxKgSeeds <= 0.0:
         makeThisManySeeds = 0
         self.massSeedMax = 0.0
     else:
         self.massSeedMax = self.seedsPerAreaConstant * math.pow(adjMaxKgSeeds, self.seedsPerAreaExponent)
         makeThisManySeeds = int(adjMaxKgSeeds / self.massSeedMax)
         # print "adjMaxKgSeeds: %f     maxSeedMass: %f     #seeds: %i" % (adjMaxKgSeeds, self.massSeedMax, makeThisManySeeds)
     for i in range(makeThisManySeeds):
         self.makeSeed(self)
Example #21
0
    def scale(self, sobol, config_params, sampling):
        i = 0
        for params in config_params:
            key = params[0]
            param_arr = params[1].split(";")

            setter = getattr(self, "set_" + key)
            getter = getattr(self, "get_" + key)

            if param_arr[0] == "p":
                if sampling == "lin":
                    # linearni uprava
                    min_val = getter() * (1 - float(param_arr[1]))
                    max_val = getter() * (1 + float(param_arr[1]))
                    setter(min_val + sobol[i] * (max_val - min_val))
                elif sampling == "log":
                    # log-puvodni
                    setter(getter() * math.pow(float(param_arr[1]), 2 * sobol[i] - 1))
                i += 1
            else:
                default = getter()
                indexes = param_arr[0].split(",")
                for index in indexes:
                    if sampling == "lin":
                        min_val = default[int(index)] * (1 - float(param_arr[1]))
                        max_val = default[int(index)] * (1 + float(param_arr[1]))
                        default[int(index)] = min_val + sobol[i] * (max_val - min_val)
                    else:
                        default[int(index)] = default[int(index)] * math.pow(float(param_arr[1]), 2 * sobol[i] - 1)
                    i += 1

                setter(default)
Example #22
0
def get_distance(lat1, lon1, lat2, lon2):
    r = 6371000
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlon / 2), 2)
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    return round((r * c) / 1850, 1)
Example #23
0
    def _g(self, RD):
        """ The Glicko2 g(RD) function.

        _g() -> float

        """
        return 1 / math.sqrt(1 + 3 * math.pow(RD, 2) / math.pow(math.pi, 2))
def chi2_to_plots(df_chi2, regularisation_settings, chi2_cut, channel):
    """
    Plot chi2 figures
    """
    # variable = regularisation_settings.variable
    plot_outpath = regularisation_settings.outpath.replace("tables/", "plots/") + "tauscan/"
    make_folder_if_not_exists(plot_outpath)

    fig1 = plt.figure()
    ax1 = fig1.add_subplot(1, 1, 1)
    ax1.set_xlim([pow(10, -6), 1])
    ax1.set_ylim([pow(10, -6), 1])
    for var in df_chi2.columns:
        if var == "tau":
            continue

        plt.loglog(df_chi2["tau"], df_chi2[var], label=variables_latex[var])
    plt.axhline(y=chi2_cut, color="black", linestyle="dashed")
    handles, labels = ax1.get_legend_handles_labels()
    ax1.legend(handles, labels, loc=4)
    ax1.set_xlabel("Regularisation Parameter \ensuremath{\\tau}")
    ax1.set_ylabel("\ensuremath{1-P(\\chi^{2}|NDF)}")

    pltName = os.path.join(plot_outpath, "{channel}_all_tauscan.pdf".format(channel=channel))
    fig1.savefig(pltName)
    print "Written plots to {plot_outpath}{channel}_all_tauscan.pdf".format(plot_outpath=plot_outpath, channel=channel)

    return
Example #25
0
def check_tree_path(root_hash, height, hashlist):
    """
    The hashes should be in the right order in the hashlist, otherwise
    the peer will be kicked. The hashlist parameter is assumed to be
    of the right type, and contain values of the right type as well.
    The exact values should be checked for validity here.
    """
    maxoffset = int(pow(2, height + 1) - 2)
    mystartoffset = int(pow(2, height) - 1)
    i = 0
    a = hashlist[i]
    if a[0] < 0 or a[0] > maxoffset:
        return False
    i += 1
    b = hashlist[i]
    if b[0] < 0 or b[0] > maxoffset:
        return False
    i += 1
    myindex = a[0] - mystartoffset
    sibindex = b[0] - mystartoffset
    for level in range(height, 0, -1):
        if DEBUG:
            print >>sys.stderr, time.asctime(), "-", "merkle: checking level", level
        a = check_fork(a, b, level)
        b = hashlist[i]
        if b[0] < 0 or b[0] > maxoffset:
            return False
        i += 1
    if DEBUG:
        print >>sys.stderr, time.asctime(), "-", "merkle: ROOT HASH", ` str(root_hash) `, "==", ` str(a[1]) `
    if a[1] == root_hash:
        return True
    else:
        return False
Example #26
0
 def distance_between(self, point1, point2):
     c = math.sqrt(
         math.pow((point1[0] - point2[0]), 2)
         + math.pow((point1[1] - point2[1]), 2)
         + math.pow((point1[2] - point2[2]), 2)
     )
     return c
Example #27
0
def largest_power(i, power=2):
    start = 0
    while True:
        if int(math.pow(power, start)) > i:
            return int(math.pow(power, start - 1))
        else:
            start += 1
def gradient(image, mask_type="sobel"):
    indice_mascara = {
        "sobelx": [[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]],
        "sobely": [[1.0, 2.0, 1.0], [0.0, 0.0, 0.0], [-1.0, -2.0, -1.0]],
        "prewittx": [[-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0]],
        "prewitty": [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [-1.0, -1.0, -1.0]],
    }

    pic_copy = (image.copy()).load()
    pic = image.load()
    kernelx = indice_mascara[mask_type + "x"]
    kernely = indice_mascara[mask_type + "y"]
    max_value = 0
    for i in range(image.size[0]):
        for j in range(image.size[1]):

            gx, gy = (0.0, 0.0)
            kernel_len = len(kernelx[0])
            kernel_pos = 0
            for h in range(i - 1, i + 2):
                for l in range(j - 1, j + 2):
                    if h >= 0 and l >= 0 and h < image.size[0] and l < image.size[1]:
                        pixel = pic_copy[h, l]
                        pixel = max(pixel) / len(pixel)
                        gx += pixel * kernelx[int(kernel_pos / 3)][kernel_pos % 3]
                        gy += pixel * kernely[int(kernel_pos / 3)][kernel_pos % 3]
                        kernel_pos += 1

            gradiente = int(math.sqrt(math.pow(gx, 2) + math.pow(gy, 2)))
            pic[i, j] = tuple([gradiente] * 3)
            if gradiente > max_value:
                max_value = gradiente
    return max_value
Example #29
0
def nas_grid(tr_classes, tr_set, val_classes, val_set, cv, pocetnic, zavrsnic, korakc, pocetnig, zavrsnig, korakg, tip):
    dat = open("nas_grid_sinonimi.txt", "a+b")
    maks = 0
    px = svm_problem(tr_classes, tr_set)
    i = pocetnic
    while i <= zavrsnic:
        j = pocetnig
        while j <= zavrsnig:
            c = math.pow(2, i)
            g = math.pow(2, j)
            param = svm_parameter()
            param.kernel_type = tip
            param.C = c
            param.gamma = g
            if cv:
                param.nr_fold = cv
                param.cross_validation = 1
                temp = svm_train(px, param)
                print >> dat, str(i) + " " + str(temp) + " "
            else:
                m = svm_train(px, param)
                temp = svm_predict(val_classes, val_set, m)
            if maks < temp:
                maks = temp
                cmaks = c
                gmaks = g
            j = j + korakg
        i = i + korakc
    print >> dat, " "
    dat.close()
    return [cmaks, gmaks]
Example #30
0
def adjust_cosine(rating1, rating2):
    interact = dict()
    for key in rating1:
        if key in rating2:
            interact[key] = 1
    n = len(interact)
    if n == 0:
        return 0
    ave_x_y = dict()
    for key in interact:
        ave_x_y.setdefault(key, 0)
        ave_x_y[key] = (rating1[key] + rating2[key]) / n

    sum_x2 = sum([pow(rating1[key] - ave_x_y[key], 2) for key in interact])
    sum_y2 = sum([pow(rating2[key] - ave_x_y[key], 2) for key in interact])
    sum_xy = sum([(rating1[key] - ave_x_y[key]) * (rating2[key] - ave_x_y[key]) for key in interact])
    denominator = sqrt(sum_x2) * sqrt(sum_y2)
    if denominator == 0:
        return 0
    else:
        val = sum_xy / denominator
        if val < -1:
            return -1
        elif val > 1:
            return 1
        else:
            return val