Example #1
0
def camberbezier(xc, yc, kc, cle, cte):
    """Calculate camber bezier variable in BP3333 airfoil."""
    bc = 0
    co = cot(r(cle)) + cot(r(cte))
    bcu = (16 + 3 * kc * co + 4 * m.sqrt(16 + 6 * kc * co *
                                         (1 - yc * co))) / (3 * kc * co**2)
    bcl = (16 + 3 * kc * co - 4 * m.sqrt(16 + 6 * kc * co *
                                         (1 - yc * co))) / (3 * kc * co**2)

    cbounds = (bcl, bcu)
    bci_list = []

    for bci in cbounds:
        bci_list.append(round(bci, 4))
        if 0 < bci < yc:
            bc = float(bci)
            xlc2 = xc - m.sqrt((2 / 3) * (bci - yc) / (kc))

            if xlc2 <= 0:
                print(f'xc = {xc}')
                print(f'yc = {yc}')
                print(f'kc = {kc:.4f}')
                print(f'bc = {bci:.4f}')
                print(f'x - sqrt((2/3)(b - y)/k) = {xlc2}')
                raise ValueError(' Invalid Airfoil Shape'
                                 f'x - sqrt((2/3)(b - y)/k) = {xlc2}')

    if bc == 0:
        print(f'xc = {xc}'.format(xc=xc))
        print(f'yc = {yc}'.format(yc=yc))
        print(f'kc = {kc}'.format(kc=round(kc, 4)))
        print(f'bc = {bci}'.format(bci=bci_list))
        raise ValueError(f'No bc found within bounds 0 < bc < {yc: .4f}.')
def resize(frame, height, width):
    if height and width >= 1000:
        return cv.resize(frame, (r(height * 0.5), r(width * 0.5)))
    elif height and width >= 2500:
        return cv.resize(frame, (r(height * 0.7), r(width * 0.7)))
    else:
        return cv.resize(frame, (height, width))
Example #3
0
def resize(frame, height, width):
    '''
    This function will resize the image 
    if the frame is above a certain condition
    '''
    if height and width >= 1000:
        return cv.resize(frame, (r(height * 0.5), r(width * 0.5)))
    elif height and width >= 2500:
        return cv.resize(frame, (r(height * 0.7), r(width * 0.7)))
    else:
        return cv.resize(frame, (height, width))
Example #4
0
 def track(self, d_delta, dpm, continuous=False):
     # tracks the position change
     # d_delta: the change of direction clockwise
     # dpm: the displacement x
     # continuous: handle f() and b() separately
     if continuous:
         pass
     self.d += d_delta
     dx = dpm * sin(r(self.d))
     dy = dpm * cos(r(self.d))
     self.x += dx
     self.y += dy
     return self
Example #5
0
 def test_to_polar_1(self):
     from math import radians as r
     res_list= [ (0, 	1,	r(0.0)),	
                 (1, 	0,	r(90.0)),	
                 (0, 	-1,	r(180.0)),	
                 (-1,	0,	r(270.0)),	
                 (1, 	1,	r(45.0)),	
                 (1, 	-1,	r(135.0)),	
                 (-1,	-1,	r(225.0)),	
                 (-1,	1,	r(315.0)) ]
     for x,y,theta in res_list:
         self.assertEqual(to_polar(x,y)[1], theta)
         
     
     self.assertEqual(to_polar(0,1,units='d')[1] , 0.0)
     self.assertEqual(to_polar(1,0,units='d')[1] , 90.0)
     self.assertEqual(to_polar(0,-1)[1] , r(180.0))
     self.assertEqual(to_polar(-1,0)[1]  , r(270.0))
Example #6
0
 def _discover(self, pos, sonic_dist):
     # this method records a new block
     # if this one is an existed one, return false
     _DELTA_ = 0
     if sonic_dist > 200:
         return False
     robo_pos = pos
     x = robo_pos.x
     y = robo_pos.y
     d = robo_pos.d
     t_x = x + sin(r(d)) * sonic_dist
     t_y = y + cos(r(d)) * sonic_dist
     pos = Position(t_x, t_y)
     if self.overlapped(pos):
         return False
     else:
         self.add(pos)
         return True
Example #7
0
 def testLocators(self):
     from math import pi
     from math import radians as r
     class proj_helper(object):
         def __init__(self):
             pass
         def gcpoints(self,a,b,c,d,n):
             return [ [a,c],[b,d] ]
         
     td = [ ( 'DO20','DO21',0.0,self.epsilon ),
            ( 'DO16','DO15',180.0,self.epsilon) ]
     m = proj_helper()
     for c in td:
         d,a = to_polar(*relative_offset_qth(m,c[0],c[1]))
         self.assertLess((a-r(c[2]))%(2*pi),c[3])
Example #8
0
def totalDistance(velo, angle):
	return velo * cos(r(angle)) * totalTime(velo, angle)
Example #9
0
    def calc_fan_flow(self, iphi=None):
        """Calculate flow angles."""
        if iphi is not None:
            self.phi = iphi
        self.psi = 2 * (1 - self.reaction - self.phi * m.tan(r(self.alpha1)))
        self.u = self.rpm / 60 * 2 * m.pi * self.radius
        self.beta1 = d(m.atan((1 / self.phi) - m.tan(r(self.alpha1))))
        self.beta2 = d(
            m.atan((2 * self.reaction - 1) / self.phi + m.tan(r(self.alpha1))))
        self.betam = d(
            m.atan((m.tan(r(self.beta1)) + m.tan(r(self.beta2))) / 2))
        self.alpha2 = d(m.atan((1 / self.phi) - m.tan(r(self.beta2))))
        self.alpham = d(
            m.atan((m.tan(r(self.alpha1)) + m.tan(r(self.alpha2))) / 2))
        self.cx = self.phi * self.u
        self.w1 = self.cx / m.cos(r(self.beta1))
        self.w2 = self.cx / m.cos(r(self.beta2))
        self.c1 = self.cx / m.cos(r(self.alpha1))
        self.c2 = self.cx / m.cos(r(self.alpha2))
        self.wt1 = self.w1 * m.sin(r(self.beta1))
        self.wt2 = self.w1 * m.sin(r(self.beta2))
        self.ct1 = self.c1 * m.sin(r(self.alpha1))
        self.ct2 = self.c2 * m.sin(r(self.alpha2))

        # Thermodynamics
        self.mach = self.cx / m.sqrt(self.GAMMA * self.R * self.t1)
        self.dt0 = self.psi * (self.u)**2 / self.CP

        self.t01 = self.t1 * (1 + ((self.GAMMA - 1) * self.mach**2) / 2)
        self.p01 = self.p1*(1 + ((self.GAMMA - 1)*self.mach**2)/2)\
            ** (self.GAMMA/(self.GAMMA - 1))
        self.t02 = self.t01 + self.dt0
        self.p02 = self.p01 * (self.t02 / self.t01)**(self.GAMMA /
                                                      (self.GAMMA - 1))
        self.t2 = self.t02 / (1 + ((self.GAMMA - 1) * self.mach**2) / 2)
        self.p2 = self.p02 / ((1 + (
            (self.GAMMA - 1) * self.mach**2) / 2)**(self.GAMMA /
                                                    (self.GAMMA - 1)))

        self.eta_p = ((self.GAMMA - 1)/self.GAMMA)\
            * m.log(self.p2/self.p1)/m.log(self.t2/self.t1)
        self.eta_c = ((self.p02/self.p01)**(self.GAMMA/(self.GAMMA - 1)) - 1)\
            / (self.dt0/self.t01)
        self.pr = (1 + (self.dt0/self.t01))\
            ** (self.GAMMA*self.eta_p/(self.GAMMA-1))
        self.cp = (self.p2 - self.p1) / (self.p01 - self.p1)
        self.work = self.CP * self.dt0
        self.torque = self.work / (self.u / self.radius)
        self.capacity = self.GAMMA/m.sqrt(self.GAMMA - 1)*self.mach\
            * (1 + (self.GAMMA - 1)/2*self.mach**2)\
            ** (-(1/2)*(self.GAMMA + 1)/(self.GAMMA - 1))
Example #10
0
def apexTime(velo, angle):
	return velo * sin(r(angle)) / 32.17 #g = 32.17 f/s
Example #11
0
		self.y = y
		self.z = z


class Line3D():
	def __init__(self, start, end):
		self.start = start
		self.end = end


size = [512, 512]
car_x_position = 5
car_z_position = 15
camera_angle = 0
camera_coords = Point3D(0, 3, -15)
fov = r(60)
zoom_x = 1/np.tan(fov/2)
zoom_y = zoom_x * (size[0] / size[1])
near = 0.1
far = 1000
# Set the height and width of the screen
screen = pygame.display.set_mode(size)


def load_obj(filename):
	vertices = []
	indices = []
	lines = []

	f = open(filename, "r")
	for line in f:
Example #12
0
def create_coord_file(filename: str,
                      plot: bool,
                      xc,
                      yc,
                      kc,
                      bc,
                      xt,
                      yt,
                      kt,
                      bt,
                      cle,
                      cte,
                      wte,
                      rle=0):  # pylint: disable=W0613
    """Generate airfoil coordinate file."""
    bp = {
        'x': {
            'LET': [0, 0, bt, xt],
            'TET': [
                xt, 2 * xt - bt,
                1 + (0 - (1.5 * kt * (xt - bt)**2 + yt)) * ut.cot(r(wte)), 1
            ],
            'LEC': [
                0, bc * ut.cot(r(cle)), xc - ((2 * (bc - yc)) / (3 * kc))**0.5,
                xc
            ],
            'TEC': [
                xc, xc + ((2 * (bc - yc)) / (3 * kc))**0.5,
                1 + (0 - bc) * ut.cot(r(cte)), 1
            ]
        },
        'y': {
            'LET': [0, (1.5 * kt * (xt - bt)**2 + yt), yt, yt],
            'TET': [yt, yt, (1.5 * kt * (xt - bt)**2 + yt), 0],
            'LEC': [0, bc, yc, yc],
            'TEC': [yc, yc, bc, 0]
        }
    }
    c = {'x': [], 'yC': [], 'yT': []}
    dc = {'xC': [], 'xT': [], 'yC': [], 'yT': []}

    # x, y coordinates and slopes for LE and TE of T and C bezier curves
    n_points = 80
    for i in range(0, n_points + 1):
        x = (1 - m.cos(i * m.pi / n_points)) / 2
        c['x'].append(x)
        for j in ['C', 'T']:
            if j == 'C':
                xmax = xc
            elif j == 'T':
                xmax = xt
            if x <= xmax:
                loc = 'LE'
                bp_xi = bp['x'][loc + j]
            elif x > xmax:
                loc = 'TE'
                bp_xi = bp['x'][loc + j]

            u_x = [
                -bp_xi[0] + 3 * bp_xi[1] - 3 * bp_xi[2] + bp_xi[3],
                3 * bp_xi[0] - 6 * bp_xi[1] + 3 * bp_xi[2],
                -3 * bp_xi[0] + 3 * bp_xi[1], bp_xi[0] - x
            ]
            u = [
                root.real for root in np.roots(u_x)
                if root.imag == 0 and 0 <= root <= (1 + 1 / (20 * n_points))
            ]
            u = u[0]
            c['y' + j].append(bp['y'][loc + j][0] * (1 - u)**3 +
                              3 * bp['y'][loc + j][1] * (u) * (1 - u)**2 +
                              3 * bp['y'][loc + j][2] * (u)**2 * (1 - u) +
                              bp['y'][loc + j][3] * (u)**3)
            for k in ['x', 'y']:
                dc[k +
                   j].append(bp[k][loc + j][0] * (-3 * (1 - u)**2) +
                             3 * bp[k][loc + j][1] * (3 * u**2 - 4 * u + 1) +
                             3 * bp[k][loc + j][2] * (-3 * u**2 + 2 * u) +
                             bp[k][loc + j][3] * (3 * u**2))

    theta = []
    xu = []
    yu = []
    xl = []
    yl = []
    lines = []
    for i in range(0, len(c['x'])):  # theta[0] is a divide by 0 error
        theta.append(d(m.atan(dc['yC'][i] / dc['xC'][i])))
        xu.append(c['x'][i] - c['yT'][i] * m.sin(r(theta[i])))
        yu.append(c['yC'][i] + c['yT'][i] * m.cos(r(theta[i])))
        xl.append(c['x'][i] + c['yT'][i] * m.sin(r(theta[i])))
        yl.append(c['yC'][i] - c['yT'][i] * m.cos(r(theta[i])))
        lines.append([(xu[i], yu[i]), (xl[i], yl[i])])

    # Organize coordinates so that xfoil can read them
    xcoord = list(reversed(xu))[:-1] + xl
    ycoord = list(reversed(yu))[:-1] + yl
    # Create airfoil file for xfoil
    os.chdir('Input')
    with open(filename, 'w') as datafile:
        for i, _ in enumerate(xcoord):
            datafile.write(f'     {xcoord[i]:.6f}    {ycoord[i]:.6f}\n')
    os.chdir('..')

    if plot:
        lc = mc.LineCollection(lines)
        _, ax = plt.subplots()
        ax.add_collection(lc)
        plt.scatter(c['x'], c['yC'], color='red', marker='^')
        plt.scatter(c['x'], c['yT'], color='blue', marker='^')
        plt.scatter(xu, yu, color='green')
        plt.scatter(xl, yl, color='green')
        plt.axis('equal')
        plt.show()
Example #13
0
])

# for test:
for i in range(5):
    print([
        random.choice([b for b in range(1, 1001) if b % 5 == 0 and b % 7 == 0])
        for i in range(5)
    ])
#####################################################
'''
Question:
Please write a program to randomly print a integer number between 7 and
15 inclusive.
'''
from random import randint as r
print(r(7, 15))

# for test:
for i in range(5):
    print(r(7, 15))
########################################################3
'''
Question:
Please write a program to compress and decompress the string "hello world!
hello world!hello world!hello world!".
'''

######################################################
'''
Question:
Please write a program to print the running time of execution of "1+1"
Example #14
0
def rotate(angle):
	angle = r(angle)
	return np.matrix([[np.cos(angle), 0, -np.sin(angle), 0],
					  [0, 1, 0, 0],
					  [np.sin(angle), 0, np.cos(angle), 0],
					  [0, 0, 0, 1]])
Example #15
0
def totalTime(velo, angle):
	g = 32.17405 #f/s^2
	return 2 * velo * sin(r(angle)) / g
Example #16
0
def Vy(velo, angle, t):
	g = 32.17405 #f/s^2
	return velo * sin(r(angle)) - g * t
Example #17
0
def apexTime(velo, angle):
	g = 9.8	#m/s^2
	return velo * sin(r(angle)) / g
Example #18
0
def totalTime(velo, angle):
	g = 9.8 #m/s^2
	return 2 * velo * sin(r(angle)) / g
Example #19
0
def y(velo, angle, t):
	g = 9.8 #m/s^2
	return velo * sin(r(angle)) * t - (0.5) * g * t**2
Example #20
0
def Vy(velo, angle, t):
	g = 9.8 #m/s^2
	return velo * sin(r(angle)) - g * t
Example #21
0
        # if the video is too big uncomment the below code
        #frame = resize(frame, height, width)

        #padding the image to avoid the bounding going out of the image
        #and crashes the program
        padding = cv.copyMakeBorder(frame, 50, 50, 50, 50, cv.BORDER_CONSTANT)
        #converting numpy array into image
        image = Image.fromarray(padding)

        #gives the face co-ordinates
        face_coord, _ = mtcnn.detect(image)

        if face_coord is not None:
            for coord in face_coord:
                for x1, y1, x2, y2 in [coord]:
                    x1, y1, x2, y2 = r(x1), r(y1), r(x2), r(y2)

                    #face array
                    face = padding[y1:y2, x1:x2]

                    #Preprocessing
                    preprocess = Preprocessing(img=Image.fromarray(face))
                    #tensor array
                    tensor_img_array = preprocess.preprocessed_arrays()

                    #Predicting
                    prob, label = torch.max(torch.exp(
                        model(tensor_img_array.to(device))),
                                            dim=1)

                    scale = round((y2 - y1) * 35 / 100)
Example #22
0
def apexTime(velo, angle):
	g = 32.17405	#f/s^2
	return velo * sin(r(angle)) / g
Example #23
0
     print("\nresult: " + rslt)
     l_og(opn, n1, n2, rslt)
     n1, n2, rslt = r_eset(n1, n2, rslt)
     continue
 elif opn == "d" or opn == "/":
     n1, n2 = n_umber(n1, n2)
     rslt = str(round((n1 / n2), 3))
     print("\nresult: " + rslt)
     l_og(opn, n1, n2, rslt)
     n1, n2, rslt = r_eset(n1, n2, rslt)
     continue
 elif opn == "r" or opn == "\\":
     print("")
     from math import sqrt as r
     n1 = s_num(n1)
     rslt = str(round(r(n1), 2))
     print("\nSquare root of " + str(n1) + " is: " + rslt)
     l_og(opn, n1, n2, rslt)
     n1, n2, rslt = r_eset(n1, n2, rslt)
     continue
 elif opn == "c" or opn == "0":
     print(
         "\nPress valid nonzero values only, for final result press '0'.\n"
     )
     n1 = s_num(n1)
     l_og(opn, n1, n2, rslt)
     rslt = rslt + n1
     if n1 != 0:
         c2 = 2
         while True:
             n2 = s_num(n2)
Example #24
0
def Vx(velo, angle):
	return velo * cos(r(angle))
Example #25
0
 def __init__(self, num):
     from math import radians as r
     self.num = num
     self.radius = r(num)
Example #26
0
def beziers(xc, yc, kc, xt, yt, kt, cle, cte, rle, blade: str, station: str):
    """Calculate camber and thickness Bezier variables in BP3333 airfoil."""
    bc = 0
    bt = 0

    co = cot(r(cle)) + cot(r(cte))
    bcu = (16 + 3 * kc * co + 4 * m.sqrt(16 + 6 * kc * co *
                                         (1 - yc * co))) / (3 * kc * co**2)
    bcl = (16 + 3 * kc * co - 4 * m.sqrt(16 + 6 * kc * co *
                                         (1 - yc * co))) / (3 * kc * co**2)

    cbounds = (bcl, bcu)
    bci_list = []

    for bci in cbounds:
        bci_list.append(round(bci, 4))
        if 0 < bci < yc:
            bc = float(bci)
            xlc2 = xc - m.sqrt((2 / 3) * (bci - yc) / (kc))

            if xlc2 <= 0:
                print(f'xc = {xc}')
                print(f'yc = {yc}')
                print(f'kc = {kc:.4f}')
                print(f'bc = {bci:.4f}')
                print(f'x - sqrt((2/3)(b - y)/k) = {xlc2}')
                raise ValueError('Invalid Airfoil Shape'
                                 f'x - sqrt((2/3)(b - y)/k) = {xlc2}')

    if bc == 0:
        print(f'xc = {xc}')
        print(f'yc = {yc}')
        print(f'kc = {kc:.4f}')
        print(f'bc = {bci_list}')
        raise ValueError(f'No bc found within bounds 0 < bc < {yc: .4f}.')

    b_poly = ((27 / 4) * kt**2, -27 * kt**2 * xt,
              9 * kt * yt + (81 / 2) * kt**2 * xt**2,
              2 * -rle - 18 * kt * xt * yt - 27 * kt**2 * xt**3,
              3 * yt**2 + 9 * kt * xt**2 * yt + (27 / 4) * kt**2 * xt**4)

    real_troots = [root.real for root in np.roots(b_poly) if root.imag == 0]
    low_b = max(0, xt - m.sqrt((-2 / 3) * (yt / kt)))
    bti_list = []

    for bti in real_troots:
        bti_list.append(round(bti, 4))
        if not real_troots:
            print(f'xt = {xt}')
            print(f'yt = {yt}')
            print(f'kt = {kt:.4f}')
            raise ValueError('Invalid Airfoil Shape.'
                             f'{blade} {station} bt is complex.')

        if low_b < bti < xt:
            bt = float(bti)
            ylt1 = yt + (3 / 2) * kt * (xt - bti)**2

            if ylt1 <= 0:
                print(f'xt = {xt}')
                print(f'yt = {yt}')
                print(f'kt = {kt:.4f}')
                print(f'bt = {bti:.4f}')
                print(f'(y + (3/2)k(x - b)^2) = {ylt1}')
                raise ValueError('Invalid Airfoil Shape'
                                 f'(y + (3/2)k(x - b)^2) = {ylt1:.4f}')

    if bt == 0:
        print(f'xt = {xt}')
        print(f'yt = {yt}')
        print(f'kt = {kt:.4f}')
        print(f'bt = {bti_list}')
        raise ValueError(f'No bt found within bounds {low_b:.4f} < bt < {xt}.')

    return bc, bt
Example #27
0
def Vy(velo, angle, t):
	return velo * sin(r(angle)) - 32.17 * t #g = 32.17 f/s
Example #28
0
    def fill_legs(self):
        # initializes legs and puts them in a dictionary

        # leg mount point is on the top surface of thorax
        self.legs["rf"] = Leg("rf", self, MountDescriptor(m(+182.343), m(-104.843), m(0), r(-045.0)), (101, 102, 103, 19))
        self.legs["rm"] = Leg("rm", self, MountDescriptor(m(0000.000), m(-114.198), m(0), r(-90.00)), (104, 105, 106, 11))
        self.legs["rr"] = Leg("rr", self, MountDescriptor(m(-182.343), m(-084.843), m(0), r(-135.0)), (107, 108, 109, 14))
        self.legs["lf"] = Leg("lf", self, MountDescriptor(m(+182.343), m(+104.843), m(0), r(+045.0)), (116, 117, 118, 13))
        self.legs["lm"] = Leg("lm", self, MountDescriptor(m(0000.000), m(+114.198), m(0), r(+90.00)), (113, 114, 115, 20))
        self.legs["lr"] = Leg("lr", self, MountDescriptor(m(+182.343), m(+084.843), m(0), r(+135.0)), (110, 111, 112, 15))

        self.legs["rf"].rostral_neighbor = self.legs["lf"]
        self.legs["rf"].caudal_neighbor = self.legs["rm"]
        self.legs["rm"].rostral_neighbor = self.legs["rf"]
        self.legs["rm"].caudal_neighbor = self.legs["rr"]
        self.legs["rr"].rostral_neighbor = self.legs["rm"]
        self.legs["rr"].caudal_neighbor = self.legs["lr"]

        self.legs["lf"].rostral_neighbor = self.legs["rf"]
        self.legs["lf"].caudal_neighbor = self.legs["lm"]
        self.legs["lm"].rostral_neighbor = self.legs["lf"]
        self.legs["lm"].caudal_neighbor = self.legs["lr"]
        self.legs["lr"].rostral_neighbor = self.legs["lm"]
        self.legs["lr"].caudal_neighbor = self.legs["rr"]
Example #29
0
    def __init__(self, name, parent, mount_descriptor, servo_ids):
        global COXA_LENGTH, FEMUR_LENGTH, TIBIA_LENGTH, TARSUS_LENGTH
        
        self.name = name
        self.parent = parent
        self.mount_descriptor = mount_descriptor

        self.swing_order = 0  # used to keep track of the order in which legs swing. If two legs are ready to swing, priority is given to the one that has been in stance longer

        self.r_was_increasing = False  # indicates whether restrictedness of this leg was increasing before reaching flat plateau

        self.cs = CoordinateSystem(parent.cs, self.name, mount_descriptor.x, mount_descriptor.y, mount_descriptor.z, 0, 0, mount_descriptor.rotz)

        self.segments = dict()
        self.segments["coxa"] = Segment(name=name + "_coxa", servo_id=servo_ids[0],
                                        min_angle=r(-35), neutral_angle=r(0), max_angle=r(35),
                                        length=COXA_LENGTH, parent=self,
                                        leg=self,
                                        offset_in_parent=m(0), mirrored=(mount_descriptor.x < 0), z_rot=True)

        if self.name == "rf":
            self.segments["coxa"].max_angle = r(10)
        elif self.name == "lf":
            self.segments["coxa"].min_angle = r(-10)
        elif self.name == "rr":
            self.segments["coxa"].min_angle = r(-10)
        elif self.name == "lr":
            self.segments["coxa"].max_angle = r(10)

        self.segments["femur"] = Segment(name=name + "_femur", servo_id=servo_ids[1],
                                         min_angle=r(-45), neutral_angle=r(20), max_angle=r(90), length=FEMUR_LENGTH,
                                         parent=self.segments["coxa"], leg=self,
                                         offset_in_parent=COXA_LENGTH)

        self.segments["tibia"] = Segment(name=name + "_tibia", servo_id=servo_ids[2],
                                         min_angle=r(-115), neutral_angle=r(20), max_angle=r(20), length=TIBIA_LENGTH,
                                         parent=self.segments["femur"], leg=self,
                                         offset_in_parent=FEMUR_LENGTH)

        self.segments["tarsus"] = Segment(name=name + "_tarsus", servo_id=servo_ids[3],
                                          min_angle=r(-90), neutral_angle=r(0), max_angle=r(0), length=TARSUS_LENGTH,
                                          parent=self.segments["tibia"], leg=self,
                                          offset_in_parent=TIBIA_LENGTH)

        self.rostral_neighbor = None  # leg in front
        self.caudal_neighbor = None  # leg behind

        self.in_swing = False  # is this leg in swing

        self.swing_z = 0  # target highest Z of current swing (calculated as Z of lift-off point + DEFAULT_SWING_HEIGHT), all in thorax cs

        self.touched_down = False  # whether the leg actually touches ground

        self.wants_to_swing = False  # previously the leg wanted to swing, but was not allowed to do it

        self.landing = False  # leg is forced to land
        self.raising = False  # leg is in initial phase of swing

        coxa_seg = self.segments["coxa"]
        self.home_angle = (coxa_seg.min_angle + coxa_seg.max_angle) / 2
        self.home_position_leg = Position(self.cs)
        self.home_position_thorax = Position(self.cs.parent)

        self.task_cs = CoordinateSystem(parent.cs, self.name + "_tcs", 0, 0, 0, 0, 0, 0)

        self.swings_inwards = False  # foot swings towards thorax

        self._r_ws_inner = None  # restrictedness by inner edge of foot workspace
        self._r_ws_outer = None  # restrictedness by outer edge of foot workspace

        # stored previous values of restrictedness components
        self._r_coxa_prev = 0
        self._r_femur_prev = 0
        self._r_tibia_prev = 0
        self._r_tarsus_prev = 0
        self._r_stretch_prev = 0
        self._r_contract_prev = 0
        self._r_ws_outer_prev = 0
        self._r_ws_inner_prev = 0

        self._r_prev = 0  # previous total restrictedness

        # back-ups for angles and leg node positions
        self.angles_backup = StoredAngles(0, 0, 0, 0)
        self.nodes_backup = dict()

        self.stored_node_positions = dict()  # already calculated coordinates of leg nodes

        # coxa coordinates in leg cs and thorax cs never change
        self.stored_node_positions["coxa"] = Position(self.cs, 0, 0, 0)
        self.stored_node_positions["coxa-thorax"] = self.cs.parent.to_this(self.stored_node_positions["coxa"])
Example #30
0
def x(velo, angle, t):
	return velo * cos(r(angle)) * t
Example #31
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import radians as r
import math

fig, ax = plt.subplots()
redDot, = plt.plot(0, 0, 'ro')  # Disegno il Punto Materiale

x = float(input("Posizione iniziale sull'asse X: ")
          )  # Chiedo la Posizione Iniziale sull'asse X
y = float(input("Posizione iniziale sull'asse Y: ")
          )  # Chiedo la Posizione Iniziale sull'asse Y
vel = float(input("Velocità iniziale: "))
angolo = float(input("Angolo della velocità: "))
velx = vel * math.cos(r(angolo))  # Chiedo la Velocità Iniziale sull'asse X
vely = vel * math.sin(r(angolo))  # Chiedo la Velocità Iniziale sull'asse Y
accx = 0  # Chiedo l'accelerazione sull'asse X
accy = -9.81
tempo = velx / 9.81 * 2  # Chiedo la durata del moto
# Formula per calcolare posizione finale: S0+V0*T+0.5*A*T*T
posFinX = x + velx * tempo  # Calcolo la posizione finale di X
posFinY = 0
tmax = vely / 9.81
maxY = vely * tmax + 0.5 * accy * tmax * tmax
maxX = velx * tmax * 2
if x >= 0 and y >= 0:  # Adatto la dimensione degli assi a seconda delle posizioni iniziali e finali
    ax = plt.axis([x - 5, posFinX + 5, 0, 50])
elif x < 0 and y >= 0:
    ax = plt.axis([posFinX - 5, x + 5, 0, 50])
elif x >= 0 and y < 0:
Example #32
0
def y(velo, angle, t):
	g = 32.17 #f/s
	return velo * sin(r(angle)) * t - (0.5) * g * t**2