def calloptionMC(spot,strike,vol,T,Rf,M,alpha):
    '''
    call option using Monte Carlo simulation
    returns option price and lower and upper bounds
    '''
    S = np.zeros(M)
    S = spot * np.exp( (Rf - 0.5*vol**2)*T + vol * math.sqrt(T) * random.randn(M))
    Carray = np.exp(-Rf * T) * np.maximum(S - strike, 0)

    c = np.average(Carray)
    c_std = np.std(Carray) / math.sqrt(M)
    bounds = c + np.array([-1,1]) * stats.norm.ppf(0.5 + alpha/2) * c_std
    return c, bounds
def optionBS(spot,strike, vol, T, Rf):
    '''
    call option using Black Scholes
    '''
    denom = vol * math.sqrt(T)
    d1 = (math.log(spot/strike) + (Rf + 0.5*vol**2)*T) / denom
    d2 = d1 - denom
    
    call = spot * stats.norm.cdf(d1) - strike * math.exp(-Rf * T) * stats.norm.cdf(d2)
    put = strike * math.exp(-Rf * T) * stats.norm.cdf(-d2) - spot * stats.norm.cdf(-d1)
    
    return call, put
def get_feature_vector(trajectory, hf, mf, fa):
    pois = [gps2grid(22.639444, 113.810833),
            gps2grid(22.534167, 114.111667)]  # airport, train station.
    feature = np.zeros(11)
    plate = trajectory[0][0]
    bl = list(map(int, mf[plate].split('|')))
    hl = gps2grid(hl_plates[plate][1], hl_plates[plate][0])
    bt = bt_plates[plate][0] // (60 * 5) + 1
    last_step = []
    for i in range(len(trajectory)):
        step = trajectory[i]

        ind = '|'.join(map(str, step[1:]))

        if ind in fa[plate]:
            fml = fa[plate][ind]
        else:
            fml = 0
        db = math.sqrt((bl[0] - step[1])**2 + (bl[1] - step[2])**2)
        dp = [
            math.sqrt((poi[0] - step[1])**2 + (poi[1] - step[2])**2)
            for poi in pois
        ]
        dh = math.sqrt((hl[0] - step[1])**2 + (hl[1] - step[2])**2)
        dt = step[3] - bt
        try:
            f = deepcopy(hf[ind])[:-1]
        except:
            f = [0, 0, 0, 0]
        f.extend(dp)
        f.extend([fml, db, dh, dt])
        if i > 0 and last_step[1] == step[1] and last_step[2] == step[2]:
            f.append(1)
        else:
            f.append(0)
        fea = np.array(f)
        feature += fea
        last_step = step
    return feature
Example #4
0
def rhombus():
    fig = plot.figure()
    p = int(input("CALC -> Please enter the first diagonal length: "))
    q = int(input("CALC -> Please enter the second diagonal length: "))
    area = (p*q) / 2
    perimeter = 2 * math.sqrt(p**2 + q**2)
    print("CALC -> Area = 1/2 * (diagonal 1) * (diagonal 2) = %.3f" %area)
    print("CALC -> Perimeter = 2 * sqrt((diagonal 1)^2 + (diagonal 2)^2) = %.3f" %perimeter) 
    p1 = (0, p/2)
    p2 = (q/2, p)
    p3 = (q, p/2)
    p4 = (q/2, 0)
    tri = patches.Polygon([p1,p2,p3,p4], closed=True,fill=True)
    sub = fig.add_subplot(111, aspect= 'equal')
    sub.add_patch(tri)
    plot.ylim(0, p + 5)
    plot.xlim(0, q + 5)
    plot.show()
Example #5
0
def triangle():
    print("CALC -> Please enter the base length: ")
    b = int(input("CALC -> ")) 
    print("CALC -> Please enter the height: ")  
    h = int(input("CALC -> ")) 
    
    fig = plot.figure()
    area = (1/2)* b * h
    perimeter = b + h + math.sqrt(h**2 + b**2)
    print("CALC -> Area = 1/2 * base * height = %.3f" %area)
    print("CALC -> Perimeter = base + height + sqrt(base^2 + height^2) = %.3f" %perimeter)
    p1 = (0, h)
    p2 = (0, 0)
    p3 = (b, 0)
    tri = patches.Polygon([p1,p2,p3], closed=True,fill=True)
    sub = fig.add_subplot(111, aspect= 'equal')
    sub.add_patch(tri)
    plot.ylim(0, h + 5)
    plot.xlim(0, b+ 5)
    plot.show()
Example #6
0
def RMSE(test, predicted):
    rmse = math.sqrt(mean_squared_error(test, predicted))
    return rmse
Example #7
0
def grasp_callback(my_grasp):

    ## Planning to a Pose goal
    ## ^^^^^^^^^^^^^^^^^^^^^^^
    ## We can plan a motion for this group to a desired pose for the
    ## end-effector

    pose_target = geometry_msgs.msg.PoseStamped()
    pose_target.header.stamp = my_grasp.markers[0].header.stamp.secs
    pose_target.header.frame_id = "/camera_rgb_optical_frame"
    pose_target.pose.position.x = my_grasp.markers[0].points[1].x
    pose_target.pose.position.y = my_grasp.markers[0].points[1].y
    pose_target.pose.position.z = my_grasp.markers[0].points[1].z

    ## Convert to quaternion

    u = [1, 0, 0]
    norm = linalg.norm([
        my_grasp.markers[0].points[0].x - my_grasp.markers[0].points[1].x,
        my_grasp.markers[0].points[0].y - my_grasp.markers[0].points[1].y,
        my_grasp.markers[0].points[0].z - my_grasp.markers[0].points[1].z
    ])
    v = asarray([
        my_grasp.markers[0].points[0].x - my_grasp.markers[0].points[1].x,
        my_grasp.markers[0].points[0].y - my_grasp.markers[0].points[1].y,
        my_grasp.markers[0].points[0].z - my_grasp.markers[0].points[1].z
    ]) / norm

    if (array_equal(u, v)):
        pose_target.pose.orientation.w = 1
        pose_target.pose.orientation.x = 0
        pose_target.pose.orientation.y = 0
        pose_target.pose.orientation.z = 0
    elif (array_equal(u, negative(v))):
        pose_target.pose.orientation.w = 0
        pose_target.pose.orientation.x = 0
        pose_target.pose.orientation.y = 0
        pose_target.pose.orientation.z = 1
    else:
        half = [u[0] + v[0], u[1] + v[1], u[2] + v[2]]
        pose_target.pose.orientation.w = dot(u, half)
        temp = cross(u, half)
        pose_target.pose.orientation.x = temp[0]
        pose_target.pose.orientation.y = temp[1]
        pose_target.pose.orientation.z = temp[2]
    norm = math.sqrt(
        pose_target.pose.orientation.x * pose_target.pose.orientation.x +
        pose_target.pose.orientation.y * pose_target.pose.orientation.y +
        pose_target.pose.orientation.z * pose_target.pose.orientation.z +
        pose_target.pose.orientation.w * pose_target.pose.orientation.w)
    if norm == 0:
        norm = 1
    pose_target.pose.orientation.x = pose_target.pose.orientation.x / norm
    pose_target.pose.orientation.y = pose_target.pose.orientation.y / norm
    pose_target.pose.orientation.z = pose_target.pose.orientation.z / norm
    pose_target.pose.orientation.w = pose_target.pose.orientation.w / norm

    print "Timestamp: %d." % pose_target.header.stamp
    print "Position X: %f." % pose_target.pose.position.x
    print "Position Y: %f." % pose_target.pose.position.y
    print "Position Z: %f." % pose_target.pose.position.z
    print "Orientation X: %f." % pose_target.pose.orientation.x
    print "Orientation Y: %f." % pose_target.pose.orientation.y
    print "Orientation Z: %f." % pose_target.pose.orientation.z
    print "Orientation W: %f." % pose_target.pose.orientation.w

    ## Broadcast transform
    br = tf.TransformBroadcaster()
    br.sendTransform(
        (pose_target.pose.position.x, pose_target.pose.position.y,
         pose_target.pose.position.z),
        (pose_target.pose.orientation.x, pose_target.pose.orientation.y,
         pose_target.pose.orientation.z, pose_target.pose.orientation.w),
        my_grasp.markers[0].header.stamp, "/grasping_target",
        "/camera_rgb_optical_frame")
    #br.sendTransform((pose_target.pose.position.x, pose_target.pose.position.y, pose_target.pose.position.z), tf.transformations.quaternion_from_euler(my_grasp.grasps[0].axis.x, my_grasp.grasps[0].axis.y, my_grasp.grasps[0].axis.z), my_grasp.header.stamp, "/grasping_target", "/camera_rgb_optical_frame")

    ## Listening to transform
    (trans, rot) = listener.lookupTransform('/world', '/grasping_target',
                                            rospy.Time(0))

    ## Build new pose
    pose_target_trans = geometry_msgs.msg.PoseStamped()
    pose_target_trans.header.frame_id = "/world"
    pose_target_trans.header.stamp = my_grasp.markers[0].header.stamp
    pose_target_trans.pose.position.x = trans[0]
    pose_target_trans.pose.position.y = trans[1]
    pose_target_trans.pose.position.z = trans[2]
    pose_target_trans.pose.orientation.x = rot[0]
    pose_target_trans.pose.orientation.y = rot[1]
    pose_target_trans.pose.orientation.z = rot[2]
    pose_target_trans.pose.orientation.w = rot[3]

    print "NEW POSITION."
    print "Position X: %f." % pose_target_trans.pose.position.x
    print "Position Y: %f." % pose_target_trans.pose.position.y
    print "Position Z: %f." % pose_target_trans.pose.position.z
    print "Orientation X: %f." % pose_target_trans.pose.orientation.x
    print "Orientation Y: %f." % pose_target_trans.pose.orientation.y
    print "Orientation Z: %f." % pose_target_trans.pose.orientation.z
    print "Orientation W: %f." % pose_target_trans.pose.orientation.w

    my_grasp_pub.publish(pose_target_trans)

    group.set_pose_target(pose_target_trans.pose, end_effector_link="my_eef")

    ## Now, we call the planner to compute the plan
    ## and visualize it if successful
    ## Note that we are just planning, not asking move_group
    ## to actually move the robot

    #  group.set_planner_id("RRTstarkConfigDefault")
    #  group.allow_replanning(True)

    ## Planning with collision detection can be slow.  Lets set the planning time
    ## to be sure the planner has enough time to plan around the box.  10 seconds
    ## should be plenty.
    #  group.set_planning_time(5.0)

    plan1 = group.plan()

    ## Moving to a pose goal
    ## ^^^^^^^^^^^^^^^^^^^^^
    ##
    ## Moving to a pose goal is similar to the step above
    ## except we now use the go() function. Note that
    ## the pose goal we had set earlier is still active
    ## and so the robot will try to move to that goal. We will
    ## not use that function in this tutorial since it is
    ## a blocking function and requires a controller to be active
    ## and report success on execution of a trajectory.

    # Uncomment below line when working with a real robot
    #  group.go(wait=True)

    print "============ DONE PLANNING ============"
    sys.exit("DONE PLANNING")
    ## Sleep to give Rviz time to visualize the plan. */
    rospy.sleep(5)
    group.clear_pose_targets()
Example #8
0
    estimates = []
    for i in range(0, ntrials):
        # toy generation
        toys = []
        for it in range(0, nt):
            toys.append(rnd.Poisson(mu0))

        # LH estimate
        result = optimize.fmin(lh_poisson, mu0, args=(toys, ), disp=False)
        estimates.append(result)

    # compute the mean, variance, bias
    means.append(numpy.mean(estimates))
    variances.append(numpy.var(estimates))
    biases.append(numpy.mean(estimates) - mu0)
    dmeans.append(math.sqrt(variances[-1] / ntrials))
    dvariances.append(math.sqrt(2 * variances[-1]**2 / (ntrials - 1)))

# plot results
nx = len(ntoys)
c1 = ROOT.TCanvas("c1", "Mean")
gmean = ROOT.TGraphErrors(nx, array('d', ntoys), array('d', means),
                          array('d', dntoys), array('d', dmeans))
gmean.Draw("ALP")
c1.Draw()
c1.SaveAs("c1.pdf")

c2 = ROOT.TCanvas("c2", "Variance")
gvar = ROOT.TGraphErrors(nx, array('d', ntoys), array('d', variances),
                         array('d', dntoys), array('d', dvariances))
gvar.Draw("ALP")
Example #9
0
 def func(x):
     t = math.log10(self.pipe.epsilon / (3.7 * self.pipe.D) + 2.51 /
                    (max(self.Re) * math.sqrt(x)))
     return 1 / math.sqrt(x) + 2 * t
Example #10
0
 def get_distance(self, x1, y1, x2, y2):
     return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
Example #11
0
def get_distance(p1, p2):
    return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def is_prime(n):
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True
Example #13
0
##############
# PARAMETERS #
##############

mu0=3.5
ntrials=1000



################
# MAIN PROGRAM #
################


# derived constants
xmin=max(0,int(mu0-5.*math.sqrt(mu0)))
xmax=int(mu0+5.*math.sqrt(mu0))
nbins=xmax-xmin

# lists to be used to plot the graphs
ntoys = []
dntoys = []
crbounds = []

# list of methods
means = {}
variances = {}
methods = ["moments","MLE"]

for meth in methods:
    means[meth] = 0
Example #14
0
def protectedSqrt(root):
    return math.sqrt(abs(root))
Example #15
0
def grasp_callback(my_grasp):

    my_pose = geometry_msgs.msg.PoseStamped()
    my_pose.header.stamp = my_grasp.markers[0].header.stamp
    my_pose.header.frame_id = "/xtion_rgb_optical_frame"

    pose_target = geometry_msgs.msg.Pose()
    pose_target.position.x = my_grasp.markers[0].points[0].x
    pose_target.position.y = my_grasp.markers[0].points[0].y
    pose_target.position.z = my_grasp.markers[0].points[0].z

    ## Convert to quaternion

    u = [1, 0, 0]
    norm = linalg.norm([
        my_grasp.markers[i].points[0].x - my_grasp.markers[0].points[1].x,
        my_grasp.markers[0].points[0].y - my_grasp.markers[0].points[1].y,
        my_grasp.markers[0].points[0].z - my_grasp.markers[0].points[1].z
    ])
    v = asarray([
        my_grasp.markers[0].points[0].x - my_grasp.markers[0].points[1].x,
        my_grasp.markers[0].points[0].y - my_grasp.markers[0].points[1].y,
        my_grasp.markers[0].points[0].z - my_grasp.markers[0].points[1].z
    ]) / norm

    if (array_equal(u, v)):
        pose_target.orientation.w = 1
        pose_target.orientation.x = 0
        pose_target.orientation.y = 0
        pose_target.orientation.z = 0
    elif (array_equal(u, negative(v))):
        pose_target.orientation.w = 0
        pose_target.orientation.x = 0
        pose_target.orientation.y = 0
        pose_target.orientation.z = 1
    else:
        half = [u[0] + v[0], u[1] + v[1], u[2] + v[2]]
        pose_target.orientation.w = dot(u, half)
        temp = cross(u, half)
        pose_target.orientation.x = temp[0]
        pose_target.orientation.y = temp[1]
        pose_target.orientation.z = temp[2]
    norm = math.sqrt(pose_target.orientation.x * pose_target.orientation.x +
                     pose_target.orientation.y * pose_target.orientation.y +
                     pose_target.orientation.z * pose_target.orientation.z +
                     pose_target.orientation.w * pose_target.orientation.w)

    if norm == 0:
        norm = 1

    my_pose.pose.orientation.x = pose_target.orientation.x / norm
    my_pose.pose.orientation.y = pose_target.orientation.y / norm
    my_pose_.pose.orientation.z = pose_target.orientation.z / norm
    my_pose.pose.orientation.w = pose_target.orientation.w / norm

    pose_target_trans = geometry_msgs.msg.PoseStamped()
    pose_target_trans.header.stamp = pose_target.header.stamp
    pose_target_trans.header.frame_id = "/map"
    now = rospy.Time.now()
    listener.waitForTransform("/map", "/xtion_rgb_optical_frame", now,
                              rospy.Duration(1.0))
    pose_target_trans = listener.transformPose("/map", pose_target)

    my_grasp_pub.publish(pose_target_trans)