def calculate_with_distance_of_2a(distance, count):
        if count == 0:
            return distance

        b = math.sqrt((1 - math.sqrt(1 - math.pow(distance, 2))) / 2.0)

        return calculate_with_distance_of_2a(b, count - 1)
Example #2
1
 def tdens(self, n, X):
     C = 1.0 + (X * X) / (n * 1.0)
     h = math.lgamma2((n + 1.0) / 2.0) - math.lgamma(n / 2.0)
     h = math.exp(h)
     h = h / math.sqrt(math.pi) / math.sqrt(n)
     Result = h * (C ** (-((n / 2.0) + (1.0 / 2.0))))
     return Result
Example #3
1
def lm_to_radec(ra0, dec0, l, m):
    # This function should be the inverse of radec_to_lmn, but it is
    # not. There is likely an error here.

    sind0 = math.sin(dec0)
    cosd0 = math.cos(dec0)
    dl = l
    dm = m
    d0 = dm * dm * sind0 * sind0 + dl * dl - 2 * dm * cosd0 * sind0
    sind = math.sqrt(abs(sind0 * sind0 - d0))
    cosd = math.sqrt(abs(cosd0 * cosd0 + d0))
    if sind0 > 0:
        sind = abs(sind)
    else:
        sind = -abs(sind)

    dec = math.atan2(sind, cosd)

    if l != 0:
        ra = math.atan2(-dl, (cosd0 - dm * sind0)) + ra0
    else:
        ra = math.atan2((1e-10), (cosd0 - dm * sind0)) + ra0

    # Calculate RA,Dec from l,m and phase center.  Note: As done in
    # Meqtrees, which seems to differ from l, m functions above.  Meqtrees
    # equation may have problems, judging from my difficulty fitting a
    # fringe to L4086 data.  Pandey's equation is now used in radec_to_lmn

    return (ra, dec)
Example #4
1
def uber_three(individual):
    g = 1 + 10 * (len(individual) - 1) + sum(xi ** 2 - 10 * cos(4 * pi * xi) for xi in individual[1:])
    g2 = 1.0 + 9.0 * sum(individual[1:]) / (len(individual) - 1)
    f1 = individual[0]
    f2 = g * (1 - sqrt(f1 / g))
    f3 = g2 * (1 - sqrt(f1 / g2))
    return f1, f2, f3
Example #5
1
 def find_approach(self, msg):
     rospy.loginfo("Finding Approach Point")
     self.pose_in = msg
     self.tf.waitForTransform("pixel_3d_frame", "base_footprint", rospy.Time(0), rospy.Duration(3.0))
     self.tfb.sendTransform(
         (self.pose_in.pose.position.x, self.pose_in.pose.position.y, self.pose_in.pose.position.z),
         (
             self.pose_in.pose.orientation.x,
             self.pose_in.pose.orientation.y,
             self.pose_in.pose.orientation.z,
             self.pose_in.pose.orientation.w,
         ),
         rospy.Time.now(),
         "pixel_3d_frame",
         self.pose_in.header.frame_id,
     )
     self.tf.waitForTransform("pixel_3d_frame", "r_wrist_roll_link", rospy.Time.now(), rospy.Duration(3.0))
     goal = PoseStamped()
     goal.header.frame_id = "pixel_3d_frame"
     goal.header.stamp = rospy.Time.now()
     goal.pose.position.x = 0
     goal.pose.position.y = 0
     goal.pose.position.z = 0.1
     goal.pose.orientation.x = 0
     goal.pose.orientation.y = 0.5 * math.sqrt(2)
     goal.pose.orientation.z = 0
     goal.pose.orientation.w = 0.5 * math.sqrt(2)
     # print "Goal:\r\n %s" %goal
     self.tf.waitForTransform(goal.header.frame_id, "torso_lift_link", rospy.Time.now(), rospy.Duration(3.0))
     appr = self.tf.transformPose("torso_lift_link", goal)
     #    print "Appr: \r\n %s" %appr
     self.wt_log_out.publish(data="Normal Approach with right hand: Trying to move WITH motion planning")
     # self.move_arm_out.publish(appr)
     self.reactive_grasp(appr)
Example #6
1
def lanczos_minmax(F, S=None, **kwargs):
    "Estimate the min/max evals of F using a few iters of Lanczos"
    doS = S is not None
    niter = kwargs.get("niter", 8)
    N = F.shape[0]
    niter = min(N, niter)
    x = zeros(N, "d")
    x[0] = 1
    q = x
    avals = []
    bvals = []
    if doS:
        r = matrixmultiply(S, q)
    else:
        r = q
    beta = sqrt(matrixmultiply(q, r))
    wold = zeros(N, "d")
    for i in xrange(niter):
        w = r / beta
        v = q / beta
        r = matrixmultiply(F, v)
        r = r - wold * beta
        alpha = matrixmultiply(v, r)
        avals.append(alpha)
        r = r - w * alpha
        if doS:
            q = solve(S, r)
        else:
            q = r
        beta = sqrt(matrixmultiply(q, r))
        bvals.append(beta)
        wold = w
    E, V = eigh(tridiagmat(avals, bvals))
    return min(E), max(E)
    def update(self, X, Y):
        if self.iteration > self.maxiter:
            return
        x_shape = X.shape
        y_shape = Y.shape

        if self.W is None:
            self.W = 1 / math.sqrt(self.reg) * np.random.randn(x_shape[1], y_shape[1])

            # Learning Rate
        eta = 1.0 / (self.reg * self.iteration)

        # Evaluation
        z = np.multiply(np.dot(X, self.W), Y)

        # Stochastic Gradient Descent Step
        self.W = (1.0 - eta * self.reg) * self.W - eta / self.k * self.vectorize_dloss(z) * np.multiply(X, Y.T).T

        # Projection Step
        projection = 1.0 / math.sqrt(self.reg) / (np.linalg.norm(self.W))
        if projection < 1.0:
            self.W = projection * self.W

        if self.check:
            # Sanity Check on Loss Function
            if self.iteration % 1000 == 0:
                print "loss", self.loss(self.X, self.Y)

        self.iteration = self.iteration + 1
Example #8
0
def haversineDistanceAndBearing(point_1, point_2):
    # courtesy of http://arduiniana.org/libraries/tinygps/
    lat1 = point_1.lat
    long1 = point_1.lon
    lat2 = point_2.lat
    long2 = point_2.lon
    delta = radians(long1 - long2)
    sdlong = sin(delta)
    cdlong = cos(delta)
    lat1 = radians(lat1)
    lat2 = radians(lat2)
    slat1 = sin(lat1)
    clat1 = cos(lat1)
    slat2 = sin(lat2)
    clat2 = cos(lat2)
    delta = (clat1 * slat2) - (slat1 * clat2 * cdlong)
    x = delta
    y = sdlong * clat2
    delta = sqrt(delta)
    delta += sqrt(clat2 * sdlong)
    delta = sqrt(delta)
    denom = (slat1 * slat2) + (clat1 * clat2 * cdlong)
    delta = atan2(delta, denom)
    distance = delta * 6372.795
    x = 180.0 * (atan2(y, x) / pi)
    bearing = (-x + 360) % 360
    return (distance, bearing)
Example #9
0
def _sym_ortho(a, b):
    """
    Stable implementation of Givens rotation.

    Notes
    -----
    The routine 'SymOrtho' was added for numerical stability. This is
    recommended by S.-C. Choi in [1]_. It removes the unpleasant potential of
    ``1/eps`` in some important places (see, for example text following
    "Compute the next plane rotation Qk" in minres_py).

    References
    ----------
    .. [1] S.-C. Choi, "Iterative Methods for Singular Linear Equations
           and Least-Squares Problems", Dissertation,
           http://www.stanford.edu/group/SOL/dissertations/sou-cheng-choi-thesis.pdf

    """
    if b == 0:
        return np.sign(a), 0, abs(a)
    elif a == 0:
        return 0, np.sign(b), abs(b)
    elif abs(b) > abs(a):
        tau = a / b
        s = np.sign(b) / sqrt(1 + tau * tau)
        c = s * tau
        r = b / s
    else:
        tau = b / a
        c = np.sign(a) / sqrt(1 + tau * tau)
        s = c * tau
        r = a / c
    return c, s, r
Example #10
0
 def TR(self, **kwargs):  # pragma: no cover
     """
     NAME:
        TR
     PURPOSE:
        Calculate the radial period for a power-law rotation curve
     INPUT:
        scipy.integrate.quadrature keywords
     OUTPUT:
        T_R(R,vT,vT)*vc/ro + estimate of the error
     HISTORY:
        2010-12-01 - Written - Bovy (NYU)
     """
     if hasattr(self, "_TR"):
         return self._TR
     (rperi, rap) = self.calcRapRperi(**kwargs)
     if nu.fabs(rap - rperi) / rap < 10.0 ** -4.0:  # Rough limit
         self._TR = 2.0 * m.pi / epifreq(self._pot, self._R)
         return self._TR
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.0)
     EL = self.calcEL(**kwargs)
     E, L = EL
     TR = 0.0
     if Rmean > rperi:
         TR += integrate.quadrature(
             _TRAxiIntegrandSmall, 0.0, m.sqrt(Rmean - rperi), args=(E, L, self._pot, rperi), **kwargs
         )[0]
     if Rmean < rap:
         TR += integrate.quadrature(
             _TRAxiIntegrandLarge, 0.0, m.sqrt(rap - Rmean), args=(E, L, self._pot, rap), **kwargs
         )[0]
     self._TR = 2.0 * TR
     return self._TR
Example #11
0
 def I(self, **kwargs):  # pragma: no cover
     """
     NAME:
        I
     PURPOSE:
        Calculate I, the 'ratio' between the radial and azimutha period
     INPUT:
        +scipy.integrate.quadrature keywords
     OUTPUT:
        I(R,vT,vT) + estimate of the error
     HISTORY:
        2010-12-01 - Written - Bovy (NYU)
     """
     if hasattr(self, "_I"):
         return self._I
     (rperi, rap) = self.calcRapRperi(**kwargs)
     Rmean = m.exp((m.log(rperi) + m.log(rap)) / 2.0)
     if nu.fabs(rap - rperi) / rap < 10.0 ** -4.0:  # Rough limit
         TR = self.TR()[0]
         Tphi = self.Tphi()[0]
         self._I = TR / Tphi * m.pi
         return self._I
     EL = self.calcEL(**kwargs)
     E, L = EL
     I = 0.0
     if Rmean > rperi:
         I += integrate.quadrature(
             _IAxiIntegrandSmall, 0.0, m.sqrt(Rmean - rperi), args=(E, L, self._pot, rperi), **kwargs
         )[0]
     if Rmean < rap:
         I += integrate.quadrature(
             _IAxiIntegrandLarge, 0.0, m.sqrt(rap - Rmean), args=(E, L, self._pot, rap), **kwargs
         )[0]
     self._I = I * self._R * self._vT
     return self._I
Example #12
0
    def calc_dist(self, ps1, ps2=None, arm=0):  # FINISHED, UNTESTED
        if ps2 is None:
            ps2 = self.curr_pose()

        p1 = ps1.pose.position
        p2 = ps2.pose.position
        wrist_dist = math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2 + (p1.z - p2.z) ** 2)

        self.update_frame[arm](ps2)
        ps2.header.stamp = rospy.Time(0)
        np2 = self.tf.transformPose("lh_utility_frame", ps2)
        np2.pose.position.x += 0.21
        self.tf.waitForTransform(np2.header.frame_id, "torso_lift_link", rospy.Time.now(), rospy.Duration(3.0))
        p2 = self.tf.transformPose("torso_lift_link", np2)

        self.update_frame[arm](ps1)
        ps1.header.stamp = rospy.Time(0)
        np1 = self.tf.transformPose("lh_utility_frame", ps1)
        np1.pose.position.x += 0.21
        self.tf.waitForTransform(np1.header.frame_id, "torso_lift_link", rospy.Time.now(), rospy.Duration(3.0))
        p1 = self.tf.transformPose("torso_lift_link", np1)

        p1 = p1.pose.position
        p2 = p2.pose.position
        finger_dist = math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2 + (p1.z - p2.z) ** 2)
        dist = max(wrist_dist, finger_dist)
        print "Calculated Distance: ", dist
        return dist
Example #13
0
def xpos(y1, y2, dxy, rad):
    """
    Given in y1 and y2 are the coordinates of the point y,
    in dxy is the distance between the points x and y,
    and rad is the distance between x and (1, 0).
    The coordinates of the point x are returned in a tuple.
    """
    A = -2 * y1  # coefficient with y1
    B = -2 * y2  # coefficient with y2
    C = y1 ** 2 + y2 ** 2 - dxy ** 2 + rad ** 2  # constant
    fail = True
    if abs(y2) < 1.0e-8:
        x1 = -C / A
        x2sqr = rad ** 2 - x1 ** 2
        x2 = sqrt(x2sqr)
        fail = False
    else:  # eliminate x2
        (alpha, beta) = (-C / B, -A / B)
        (a, b, c) = (1 + beta ** 2, 2 * alpha * beta, alpha ** 2 - rad ** 2)
        b4ac = b ** 2 - 4 * a * c
        disc = sqrt(b4ac)
        x1m = (-b - disc) / (2 * a)
        x2m = alpha + beta * x1m
        x1p = (-b + disc) / (2 * a)
        x2p = alpha + beta * x1p
    return ((x1m, x2m), (x1p, x2p))
Example #14
0
def coupler(x, y, xr, yr):
    """
    In x and y are the coordinates of the solution design.
    In xr and yr are the distances to the coupler point.
    Computes the intersection between two circles, centered
    at x and y, with respective radii in xr and yr.
    """
    A = -2 * x[0] + 2 * y[0]
    B = -2 * x[1] + 2 * y[1]
    C = x[0] ** 2 + x[1] ** 2 - xr ** 2 - y[0] ** 2 - y[1] ** 2 + yr ** 2
    fail = True
    if A + 1.0 != 1.0:  # eliminate z1
        (alpha, beta) = (-C / A, -B / A)
        a = beta ** 2 + 1
        b = 2 * alpha * beta - 2 * x[1] - 2 * x[0] * beta
        c = alpha ** 2 + x[0] ** 2 + x[1] ** 2 - xr ** 2 - 2 * x[0] * alpha
        if b ** 2 - 4 * a * c >= 0:
            fail = False
            disc = sqrt(b ** 2 - 4 * a * c)
            z2 = (-b + disc) / (2 * a)
            z1 = alpha + beta * z2
    if fail:
        (alpha, beta) = (-C / B, -A / B)
        a = beta ** 2 + 1
        b = 2 * alpha * beta - 2 * y[1] - 2 * y[0] * beta
        c = alpha ** 2 + y[0] ** 2 + y[1] ** 2 - yr ** 2 - 2 * y[0] * alpha
        disc = sqrt(b ** 2 - 4 * a * c)
        z1 = (-b + disc) / (2 * a)
        z2 = alpha + beta * z1
        dxz = sqrt((x[0] - z1) ** 2 + (x[1] - z2) ** 2)
    return (z1, z2)
Example #15
0
    def _calc_BS(self):
        """ Internal function for option valuation.     See ``calc_px()`` for complete documentation.

        :Authors:
            Thawda Aung
        """

        _ = self
        tau = self.px_spec.tau
        N = Util.norm_cdf

        d2 = (math.log(_.ref.S0 / _.K) + ((_.rf_r - _.ref.q - _.ref.vol ** 2 / 2) * _.T)) / (_.ref.vol * math.sqrt(_.T))
        d1 = d2 + _.ref.vol * math.sqrt(_.T)

        d2n = (math.log(_.ref.S0 / _.K) + (_.rf_r - _.ref.q) * _.T - _.ref.vol ** 2 * tau / 2) / (
            _.ref.vol * math.sqrt(tau)
        )
        d1n = d2n + _.ref.vol * math.sqrt(tau)

        px = (
            _.ref.S0 * math.exp(-_.ref.q * _.T) * N(d1)
            - _.K * math.exp(-_.rf_r * _.T) * N(d2)
            + _.K * math.exp(-_.rf_r * _.T) * N(-d2n)
            - _.ref.S0 * math.exp(-_.ref.q * _.T) * N(-d1n)
        )
        self.px_spec.add(px=px, d1=d1, d2=d2)

        return self
def getFinalPolarVectorFromVector(m1, v1, m2, v2):
    v1x, v1y = v1[0], v1[1]
    v2x, v2y = v2[0], v2[1]
    vec = get2DCollisionVector(m1, v1x, v1y, m2, v2x, v2y)
    result1 = 0
    result2 = 0
    if vec[0][0] >= 0:
        result1 = (
            math.degrees(math.atan(vec[0][1] / vec[0][0])) % 360,
            math.sqrt((vec[0][0] * vec[0][0]) + (vec[0][1] * vec[0][1])),
        )
    else:
        result1 = (
            180 + math.degrees(math.atan(vec[0][1] / vec[0][0])),
            math.sqrt((vec[0][0] * vec[0][0]) + (vec[0][1] * vec[0][1])),
        )

    if vec[1][0] >= 0:
        result2 = (
            math.degrees(math.atan(vec[1][1] / vec[1][0])) % 360,
            math.sqrt((vec[1][0] * vec[1][0]) + (vec[1][1] * vec[1][1])),
        )
    else:
        result2 = (
            180 + math.degrees(math.atan(vec[1][1] / vec[1][0])),
            math.sqrt((vec[1][0] * vec[1][0]) + (vec[1][1] * vec[1][1])),
        )
    return result1, result2
 def _GetLengthHelper(cls, fnList, ti, tf, tol):
     xi = SplineGenerator.EvalCubic(ti, fnList[0])
     yi = SplineGenerator.EvalCubic(ti, fnList[1])
     xf = SplineGenerator.EvalCubic(tf, fnList[0])
     yf = SplineGenerator.EvalCubic(tf, fnList[1])
     tm = (ti + tf) / float(2)
     xm = SplineGenerator.EvalCubic(tm, fnList[0])
     ym = SplineGenerator.EvalCubic(tm, fnList[1])
     side3 = math.sqrt((xf - xi) * (xf - xi) + (yf - yi) * (yf - yi))
     side1 = math.sqrt((xm - xi) * (xm - xi) + (ym - yi) * (ym - yi))
     side2 = math.sqrt((xf - xm) * (xf - xm) + (yf - ym) * (yf - ym))
     try:
         if (math.fabs(((side1 + side2) / float(side3)) - 1)) <= tol:
             return math.fabs(side1 + side2)
         else:
             return (SplineGenerator._GetLengthHelper(fnList, ti, tm, tol)) + (
                 SplineGenerator._GetLengthHelper(fnList, tm, tf, tol)
             )
     except:
         if (math.fabs(((side1 + side2) / float(side3)) - 1)) <= tol:
             return math.fabs(side1 + side2)
         else:
             return (SplineGenerator._GetLengthHelper(fnList, ti, tm, tol)) + (
                 SplineGenerator._GetLengthHelper(fnList, tm, tf, tol)
             )
    def predict(self, feed_events):
        vec = [0] * self._size
        te = len(feed_events) * 1.0
        weighted_events = [
            (e, math.exp(self._decay * (i - te + 1) / te)) for i, e in enumerate(feed_events) if e in self._model.vocab
        ]
        for e, d in weighted_events:
            vec = [x * d + y for x, y in zip(self._model[e].tolist(), vec)]

        mag = math.sqrt(sum([x ** 2 for x in vec]))
        sim = []
        for e in self._pat_vec:
            sim.append(sum([(x * y) for x, y in zip(e, vec)]) / (mag * math.sqrt(sum([x ** 2 for x in e]))))

        avg_sim = sum(sim) / len(sim)
        predictions = {}
        for d in self._diags:
            probability = 0
            norm = 0
            # norm = 0
            for i, pat_sim in enumerate(sim):
                if d in self._pat_diag[i]:
                    probability += max(0, pat_sim - avg_sim)
                norm += max(0, pat_sim - avg_sim)

            predictions[d] = probability * 1.0 / norm

        return predictions
Example #19
0
def tchi_2(DELTA_0, DELTA_G, ei):
    global x0, xa, x1, x2, wa_mm, ha_mm, wa, ha, pslit
    global dslat, radius, rho, tjit, mod_type, s, thetam, mod_type
    global imod, sx, sy, sz, isam, gam, ia, ix, idet, dd, tbin, titledata
    VEL = 437.392 * math.sqrt(ei)
    tausqr = (((DELTA_0 + DELTA_G * math.sqrt(ei)) / 1.96) / VEL) ** 2
    return tausqr
Example #20
0
def welch_test(a1, a2, delta_mu=0, alternative="two.sided", c=0.95):
    n1 = len(a1)
    n2 = len(a2)
    x1_bar = a1.mean()
    x2_bar = a2.mean()
    var1 = a1.var(ddof=1)
    var2 = a2.var(ddof=1)

    test_t = ((x1_bar - x2_bar) - delta_mu) / sqrt((var1 / n1) + (var2 / n2))

    df = ((var1 / n1) + (var2 / n2)) ** 2 / ((var1 ** 2 / (n1 ** 2 * (n1 - 1))) + (var2 ** 2 / (n2 ** 2 * (n2 - 1))))

    if alternative == "less":
        p = stats.t.cdf(test_t, df)
    elif alternative == "greater":
        p = stats.t.sf(test_t, df)
    elif alternative == "two.sided":
        p = 2 * stats.t.sf(abs(test_t), df)
    else:
        assert False, "Unexpected alternative: " + alternative

    interval_t = stats.t.interval(c, df)[1]
    abs_err = interval_t * sqrt((var1 / n1) + (var2 / n2))
    lower_lim = (x1_bar - x2_bar) - abs_err
    upper_lim = (x1_bar - x2_bar) + abs_err

    return (test_t, df, p, lower_lim, upper_lim)
Example #21
0
 def rate(self, rating, series):
     # Step 2. For each player, convert the rating and RD's onto the
     #         Glicko-2 scale.
     rating = self.scale_down(rating)
     # Step 3. Compute the quantity v. This is the estimated variance of the
     #         team's/player's rating based only on game outcomes.
     # Step 4. Compute the quantity difference, the estimated improvement in
     #         rating by comparing the pre-period rating to the performance
     #         rating based only on game outcomes.
     d_square_inv = 0
     variance_inv = 0
     difference = 0
     for actual_score, other_rating in series:
         other_rating = self.scale_down(other_rating)
         impact = self.reduce_impact(other_rating)
         expected_score = self.expect_score(rating, other_rating, impact)
         variance_inv += impact ** 2 * expected_score * (1 - expected_score)
         difference += impact * (actual_score - expected_score)
         d_square_inv += expected_score * (1 - expected_score) * (Q ** 2) * (impact ** 2)
     difference /= variance_inv
     variance = 1.0 / variance_inv
     denom = rating.sigma ** -2 + d_square_inv
     mu = rating.mu + Q / denom * (difference / variance_inv)
     sigma = math.sqrt(1 / denom)
     # Step 5. Determine the new value, Sigma', ot the volatility. This
     #         computation requires iteration.
     volatility = self.determine_volatility(rating, difference, variance)
     # Step 6. Update the rating deviation to the new pre-rating period
     #         value, Phi*.
     sigma_star = math.sqrt(sigma ** 2 + volatility ** 2)
     # Step 7. Update the rating and RD to the new values, Mu' and Phi'.
     sigma = 1 / math.sqrt(1 / sigma_star ** 2 + 1 / variance)
     mu = rating.mu + sigma ** 2 * (difference / variance)
     # Step 8. Convert ratings and RD's back to original scale.
     return self.scale_up(self.create_rating(mu, sigma, volatility))
Example #22
0
def main():
    L = []

    N = []

    N.append(math.sqrt(2) / 2)
    N.append((math.sqrt(2) / 2) * -1)

    L.append(N)

    N = []

    N.append(math.sqrt(2) / 2)
    N.append(math.sqrt(2) / 2)

    L.append(N)

    tp1.affichage(L)
    N = tp1.transposition(L)
    tp1.affichage(L)
    tp1.affichage(N)

    tp1.affichage(tp1.produit_matrice(N, L))

    print(verifie_orthogonale(L))
def Scelta(x):

    if x == 1:
        print input("Scrivi il calcolo: ")
        Scelta(input("Scegli l'operazione: "))

    elif x == 2:
        print input("Scrivi numero: ") ** input("Scrivi esponente: ")
        Scelta(input("Scegli l'operazione: "))

    elif x == 3:
        print math.sqrt(input("Scrivi numero: "))
        Scelta(input("Scegli l'operazione: "))

    elif x == 4:
        clear()
        print "-" * 60, "\n"
        print "\tGRAZIE PER AVER SCARICATO QUESTA CALCOLATRICE", "\n"
        print "\t" * 2, "Alessandro Alfieri"
        print "-" * 60, "\n"
        exit()

    else:
        clear()
        print "Scelta sbagliata, amico! Fatti meno seghe cosi' vedi meglio i numeri!!! ;)", "\n"
        print "Scegli l'operazione che vuoi fare..."
        print "1:Addizione-Sottrazione-Moltiplicazione-Divisione"
        print "2:Elevazione a potenza"
        print "3:Radice"
        print "4:Esci"
        Scelta(input("Scegli l'operazione: "))
def edge_detect(surface):
    width = surface.get_width()
    height = surface.get_height()

    # surface.fill((0, 0, 0))

    pixArray = pygame.PixelArray(surface)

    values = []

    for i in range(1, height - 1):
        for j in range(1, width - 1):
            a = intToColor(pixArray[j - 1][i - 1])[0]
            b = intToColor(pixArray[j][i - 1])[0]
            c = intToColor(pixArray[j + 1][i - 1])[0]
            d = intToColor(pixArray[j - 1][i])[0]
            e = intToColor(pixArray[j][i + 1])[0]
            f = intToColor(pixArray[j + 1][i - 1])[0]
            g = intToColor(pixArray[j + 1][i])[0]
            h = intToColor(pixArray[j + 1][i + 1])[0]

            E_h = (c + 2 * e + h) - (a + 2 * d + f)
            E_v = (f + 2 * g + h) - (a + 2 * b + c)
            E = int(math.sqrt(E_h ** 2 + E_v ** 2))
            values.append(int(math.sqrt(E_h ** 2 + E_v ** 2)))

    m = max(values)
    for i in range(1, height - 1):
        for j in range(1, width - 1):
            color = (values[(i - 1) * (width - 2) + (j - 1)] * 255) // m
            pixArray[j][i] = (color, color, color)
    return values
Example #25
0
def IK_3DoF(kinematic_chain, x, y, z):
    coxa, femur, tibia = kinematic_chain.kinematic_pairs
    x, y, z = float(x), float(y), float(z)

    # The combined offset along the axes of rotation for the femur and tibia
    d = femur.d + tibia.d
    # There is only one possible coxa angle for any point
    det = x ** 2 + y ** 2 - d ** 2
    if det <= 0:
        return [(0, 0, 0)]
    elif d == y:  # Some weird degenerate case. Couldn't quite figure out why, but this gets around it
        coxa_angle = 2 * atan(y / x)
    else:
        coxa_angle = 2 * atan((x - sqrt(x ** 2 + y ** 2 - d ** 2)) / (d - y))

    # Now move into the coxa's frame using the calculated angle
    nx, ny, nz, _ = kinematic_chain.inv_transform_funcs[0]((x, y, z), coxa_angle).T[0]

    # Now we only care about X and Y. Z should equal d
    target = nx ** 2 + ny ** 2
    range = (femur.r + tibia.r) ** 2
    target_dir = atan2(ny, nx)
    if target > range:  # Too far
        solutions = [(coxa_angle, target_dir, 0)]
    elif target < (femur.r - tibia.r) ** 2:  # Too close
        solutions = [(coxa_angle, 0, 0)]
    else:
        # law of cosines
        theta_a = acos((femur.r ** 2 + tibia.r ** 2 - target) / (2 * femur.r * tibia.r))  # The 'inner tibia angle'
        theta_b = acos((femur.r ** 2 + target - tibia.r ** 2) / (2 * femur.r * sqrt(target)))

        # TODO use servo range limits to select between the two solutions
        solutions = [(coxa_angle, target_dir + theta_b, theta_a - pi), (coxa_angle, target_dir - theta_b, pi - theta_a)]
    return solutions
def PhiMeasurementMatrices(m, d, pointSet, sampleSize, rescaled=False):
    # Returns an array of randomized measurement matrices of size m x pointset length
    n = len(pointSet[0])
    Mons = multiIndices(n, d)
    monValues = np.matrix(evaluateMonomialsAtPoints(Mons, pointSet))  # Rows are monomials, columns are the points
    # Next we produce a random sample for the coefficients
    cov = []
    for mon1 in Mons:
        row = []
        for mon2 in Mons:
            if mon1 == mon2:
                monL = mon1.copy()
                monL.append(d - np.sum(monL))
                row.append(multinomial(d, monL) / pow(2, d))
            else:
                row.append(0)
        cov.append(row)
    mean = np.zeros(len(Mons))
    Results = []
    for _ in range(sampleSize):
        coeffs = np.random.multivariate_normal(mean, cov, m)
        M = (1 / math.sqrt(m)) * np.matrix(coeffs) * monValues
        if rescaled:
            sF = computeScalingFactor(np.transpose(M) * M)
            M = math.sqrt(sF) * M
        Results.append(M)

    return Results
    def update(self, x, p, y):
        """ Update model using x, p, y

            INPUT:
                x: feature, a list of indices
                p: click probability prediction of our model
                y: answer

            MODIFIES:
                self.n: increase by squared gradient
                self.z: weights
        """

        # parameter
        alpha = self.alpha

        # model
        n = self.n
        z = self.z
        w = self.w

        # gradient under logloss
        g = p - y

        # update z and n
        for i in self._indices(x):
            sigma = (sqrt(n[i] + g * g) - sqrt(n[i])) / alpha
            z[i] += g - sigma * w[i]
            n[i] += g * g
Example #28
0
def SeBlock(a, first):  # read Ascii block of Integers
    first += 1
    val = ExtractFloat(a[first])  # Q,AMAX,HWHM
    Q = val[0]
    AMAX = val[1]
    HWHM = val[2]
    first += 1
    val = ExtractFloat(a[first])  # A0
    int0 = [AMAX * val[0]]
    first += 1
    val = ExtractFloat(a[first])  # AI,FWHM first peak
    fw = [2.0 * HWHM * val[1]]
    integer = [AMAX * val[0]]
    first += 1
    val = ExtractFloat(a[first])  # SIG0
    int0.append(val[0])
    first += 1
    val = ExtractFloat(a[first])  # SIG3K
    integer.append(AMAX * math.sqrt(math.fabs(val[0]) + 1.0e-20))
    first += 1
    val = ExtractFloat(a[first])  # SIG1K
    fw.append(2.0 * HWHM * math.sqrt(math.fabs(val[0]) + 1.0e-20))
    first += 1
    be = ExtractFloat(a[first])  # EXPBET
    first += 1
    val = ExtractFloat(a[first])  # SIG2K
    be.append(math.sqrt(math.fabs(val[0]) + 1.0e-20))
    first += 1
    return first, Q, int0, fw, integer, be  # values as list
Example #29
0
    def layout_step(self, correct=False):
        import math

        pad = 0

        if correct:
            for C in self.circles:
                v = Vector(C.ox - C.x, C.oy - C.y)
                v.normalize()
                v.resize(0.5)
                C._move(v.x, v.y)

        for A in self.circles:
            for B in self.circles:
                if A != B:
                    radsq = (A.r + B.r) * (A.r + B.r)
                    d = A.sqdist(B)
                    if radsq + pad > d:
                        # move circles away from each other
                        v = Vector(B.x - A.x, B.y - A.y)
                        v.normalize()
                        m = (math.sqrt(radsq) - math.sqrt(d)) * 0.25
                        v.resize(m)
                        A._move(v.x * -1 * B.weight, v.y * -1 * B.weight)
                        B._move(v.x * A.weight, v.y * A.weight)

        for C in self.circles:
            C.move()
def pearson_correlation(cust_to_items):
    print("generating lookup tables")
    rating_lookup_table, avg_lookup_table = generate_lookup(cust_to_items)
    print("building cor-vectorspace")
    cust_to_correlationvector = {customer: {} for customer in cust_to_items.keys()}
    print("constructs created")
    for customer_i, customer_i_items in tqdm(cust_to_items.items()):
        customer_i_item_set = set(rating_lookup_table[customer_i].keys())
        for customer_j, customer_j_items in cust_to_items.items():
            if (customer_j == customer_i) or (rating_lookup_table[customer_j] is None):
                continue
            numerator = 0
            denominator_i = 0
            denominator_j = 0
            for item in customer_i_item_set.intersection(rating_lookup_table[customer_j].keys()):
                cust_i_item_rating = rating_lookup_table[customer_i][item]
                cust_j_item_rating = rating_lookup_table[customer_j][item]
                cust_i_avg = avg_lookup_table[customer_i]
                cust_j_avg = avg_lookup_table[customer_j]

                numerator += (cust_i_item_rating - cust_i_avg) * (cust_j_item_rating - cust_j_avg)
                denominator_i += (cust_i_item_rating - cust_i_avg) ** 2
                denominator_j += (cust_j_item_rating - cust_j_avg) ** 2
            if numerator == 0:
                cust_to_correlationvector[customer_i][customer_j] = 0
                cust_to_correlationvector[customer_j][customer_i] = 0
                continue
            denominator = sqrt(denominator_i) * sqrt(denominator_j)
            cust_to_correlationvector[customer_i][customer_j] = numerator / denominator if denominator != 0 else 0
            cust_to_correlationvector[customer_j][customer_i] = numerator / denominator if denominator != 0 else 0
        rating_lookup_table[customer_i] = None

    return cust_to_correlationvector