def main(): print( "################### Test #1: Testing Rectangle Class ####################" ) r = Rectangle(10, 10, 10, 10) assert ((r.x, r.y, r.height, r.width) == (10, 10, 10, 10)) r = Rectangle(-1, 1, 1, 1) assert ((r.x, r.y, r.height, r.width) == (0, 1, 1, 1)) r = Rectangle(1, -1, 1, 1) assert ((r.x, r.y, r.height, r.width) == (1, 0, 1, 1)) r = Rectangle(1, 1, -1, 1) assert ((r.x, r.y, r.height, r.width) == (1, 1, 0, 1)) r = Rectangle(1, 1, 1, -1) assert ((r.x, r.y, r.height, r.width) == (1, 1, 1, 0)) print(r) print("Test Complete!") print( "################### Test #2: Test Surface Class ####################" ) s = Surface("myimage.png", 10, 10, 10, 10) assert ((s.rect.x, s.rect.y, s.rect.height, s.rect.width) == (10, 10, 10, 10)) assert ((s.getRect().x, s.getRect().y, s.getRect().height, s.getRect().width) == (10, 10, 10, 10)) assert (s.image == "myimage.png") print("Test Complete!")
def run5(): surface = Surface(np.array([0, 1, 0]), np.array([0, 0, 1]), Surface().get_n_air(), Surface().get_n_water()) list_surface = [surface] # light light_i = Light(np.array([0, 1, 0]), np.array([0, 0, 0])) # run Physical().run_plot(list_surface, light_i, 1, 10)
def run7(): surface1 = Surface(np.array([0, 0, 0]), np.array([0, 0, 1]), Surface().get_n_air(), Surface().get_n_water()) list_surface = [surface1] light_i = Light(np.array([0, 0, 1]), np.array([0.1, 0.1, -1])) Physical().run_plot(list_surface, light_i)
def run8(): surface1 = Surface(np.array([0, 0, 0]), np.array([1, 0, 0])) surface2 = Surface(np.array([0, 0, 0]), np.array([0, 0, 1])) surface3 = Surface(np.array([3, 0, 0]), np.array([1, 0, 0])) list_surface = [surface1, surface2, surface3] light_i = Light(np.array([0, 0, 1]), np.array([1, 0, -1])) Physical().run_plot(list_surface, light_i, 3, 6)
def run1(): # light light_i = Light(np.array([-3, 5, 3]), np.array([1, 0, 0])) # surface surface = Surface(np.array([0, 1, 0]), np.array([0, 0, 1]), Surface().get_n_air(), Surface().get_n_water()) list_surface = [surface] # run Physical().run_plot(list_surface, light_i, 1, 5)
def createPlatforms(self): beats, volumes = self.collectBeats() defaultY = 300 groundHeight = 375 for i in range(len(beats)): if (i == len(beats) - 1): beats[i] += beats[i - 1] + 30 self.goal = Goal(beats[i], 200, 20, self.height * (2 / 3)) elif (i == 0): beats[i] += 500 self.platforms.append(Surface(beats[i], defaultY, 30, 20)) else: platY = defaultY timeDif = beats[i + 1] - beats[i] platWidth = round(timeDif * self.scrollSpeed, 2) platWidth *= 4 # how wide the platform is based on how fast the scrolling is and time difference spikeSize = int(platWidth) beats[i] = round(beats[i - 1] + platWidth) + self.defaultGap * 2 # add descending and ascending platforms # based on the sound level if (volumes[i + 1] > volumes[i]): platY = self.platforms[i - 1].y - 10 elif (volumes[i + 1] < volumes[i]): platY = self.platforms[i - 1].y + 10 if (platY >= groundHeight): # have to move platform up if it goes inside the ground platY = self.platforms[i - 1].y - 50 self.obstacles.append( Spike(beats[i], platY - 35, Spike.image, (spikeSize, spikeHeight))) newX = ( beats[i - 1] + beats[i] ) // 2 # adding jumpPad to make up for height difference newSpikeY = 375 - spikeHeight / 2 self.obstacles.append( Spike(newX, newSpikeY, Spike.image, (spikeSize, spikeHeight))) self.jumps.append( JumpPad(newX, groundHeight - 30 - 15, JumpPad.image, (30, 30))) if (i % 10 == 0): spikeHeight = int(abs(volumes[i]) * 10) if spikeHeight > 50 or spikeHeight < 10: spikeHeight = 30 self.obstacles.append( Spike(beats[i], platY - 35, Spike.image, (spikeSize, spikeHeight))) self.platforms.append(Surface(beats[i], platY, platWidth, 20))
def reflection2(self, surface=Surface(), light_in=Light()): # second way to get reflection # first to get meeting point mp_t0 = self.get_mp_and_t0(surface, light_in) # set the source and time light_r = Light() light_r.set_s(np.array([mp_t0[0], mp_t0[1], mp_t0[2]])) light_r.set_t(np.arange(0, mp_t0[3] + mp_t0[3] / 10, mp_t0[3] / 10)) # get n vector , v_i n = surface.get_n() v_i = light_in.get_v() # get v_i shadow on n vector v_is = np.dot(-v_i, n) / sqrt(np.dot(n, n)) # get sin vector p p = v_is + v_i # get v_r v_r = 2 * p - v_i # set light_r._v light_r.set_v(v_r) return light_r
def get_mp_and_t0(self, surface=Surface(), light=Light()): # mp is meetingpoint , t0 is the meeting time mp_t0 = np.array([0, 0, 0, 0]) # get n,v_i,s n = surface.get_n() v_i = light.get_v() s = light.get_s() # for the case light and surface parallel, n*v' =0, and source is on surface, (s-p)*n'=0 # let the point and time be 100 if np.dot(n, v_i) == 0: t0 = 0 mp_t0 = [0, 0, 0, 0] # source on surface else: if np.dot((s - surface.get_p()), n) == 0: mp_t0 = [s[0], s[1], s[2], 0] else: x, y, z, t0 = symbols('x y z t0') light_in_t0 = light.get_light_in_t0(t0) # get surface eqn for 1 eq1 = surface.get_eqn(x, y, z) # eqn2 for x eq2 = Eq(x, light_in_t0[0]) eq3 = Eq(y, light_in_t0[1]) eq4 = Eq(z, light_in_t0[2]) sol = linsolve([eq1, eq2, eq3, eq4], [x, y, z, t0]) mp_t0 = next(iter(sol)) return mp_t0
def game_start(self, config_data, sprites): # Creates the lander object self.lander = self.setup_lander(config_data) self.surface = Surface( (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT'])) sprites.add(self.lander) sprites.add(self.surface)
def test4(): ''' Normal case, one time reflection and one time transmisson , light in air through the air. data : light source [-1 0 1], light vector [1 0 -1], surface is xoy,n1=1 n2=1 esay to hand calculate light_r.s = [0,0,0] light_r.vector = [1,0,1] light_t.s = [0,0,0] lgiht_t.vector = [1,0,-1] ''' light_i = Light(np.array([-1, 0, 1]), np.array([1, 0, -1])) surface = Surface() list_surface = [surface] phy = Physical() list_tree_surface = phy.lightrun(list_surface, light_i, 1) tree_light = list_tree_surface[0] list_surface = list_tree_surface[1] list_light = tree_light.level_queue(tree_light.root) light_r = list_light[2] light_t = list_light[1] b1 = (light_r.get_s() == np.array([0, 0, 0])).all() b2 = (light_r.get_v() == np.array([1, 0, 1])).all() b3 = (light_t.get_s() == np.array([0, 0, 0])).all() b4 = (light_t.get_v() == np.array([1, 0, -1])).all() assert b1 & b2 & b3 & b4
def __init__(self, point, normal, surface=None): self.point = point self.normal = normal.normalized() self.surface = surface if not surface: self.surface = Surface()
def run_plot(self, list_surface=[Surface()], light_in=Light(), i=1, size=2): # i is the times to t and r, size is the large of surface list_tree_surface = self.lightrun(list_surface, light_in, i) tree_light = list_tree_surface[0] list_surface = list_tree_surface[1] fig = plt.Figure() ax = plt.axes(projection='3d') # get all light to plot list_light = tree_light.level_queue(tree_light.root) # plot light and surface for light in list_light: light.plot(fig, ax) for surface in list_surface: x_p = surface.get_p()[0] y_p = surface.get_p()[1] surface.plot(fig, ax, x=np.arange(-size + x_p, size + x_p, size / 5), y=np.arange(-size + y_p, size + y_p, size / 5)) plt.show()
def __init__(self, center, radius, surface=None): self.center = center # point self.radius = radius # scalar self.surface = surface if not surface: self.surface = Surface()
def __init__(self, width, height): self.width = width self.height = height self.eye_x = self.eye_y = self.eye_z = 0 self.radius = 100 self.phi = 0.0 self.theta = 90.0 self.up_x = 0 self.up_y = 1 self.up_z = 0 self.scale = 1 self.surface = Surface(lambda x, y: 50 * (sin(x * pi / 180) + cos(y * pi / 180))) self.light = Light() self.cube = Cube(10) self.sphere = Sphere(20) self.enable_light_source = True
def transmisson2(self, surface=Surface(), light_in=Light(), n1=1, n2=1.3330): # teacher's way # in parameter will get error, when set n1, n2 to n_air and n_water, so directly use value # return the transmisson light # get n vector , v_i n = surface.get_n() v_i = light_in.get_v() # set n1,n2 must judge the light way with n if np.dot(n, v_i) < 0: n1 = surface.get_n1() n2 = surface.get_n2() else: n2 = surface.get_n1() n1 = surface.get_n2() n = -n # get meeting point and time mp_t0 = self.get_mp_and_t0(surface, light_in) # set the source and time light_t = Light() light_t.set_s(np.array([mp_t0[0], mp_t0[1], mp_t0[2]])) light_t.set_t(np.arange(0, mp_t0[3] + mp_t0[3] / 10, mp_t0[3] / 10)) # sin(theta1),sin(theta2),cos(theta1),cos(theta2) cos1 = np.dot(-v_i, n) / sqrt(np.dot(v_i, v_i) * np.dot(n, n)) sin1 = sqrt(1 - cos1**2) sin2 = n1 * sin1 / n2 cos2 = sqrt(1 - sin2**2) # calculate brust angle sin2_b = 1 sin1_b = n2 * sin2_b / n1 # check special case, n vector is equal with -v_i, directly trans if (np.cross(n, -v_i) == [0, 0, 0]).all(): v_t = v_i else: # check brust case if (n1 >= n2) & (sin1 >= sin1_b): v_t = np.array([0, 0, 0]) # normal case else: v_tx = np.cross(np.cross(n, v_i), n) * n1 / n2 v_ty = -sqrt(np.dot(v_i, v_i) - np.dot(v_tx, v_tx)) * n v_t = v_tx + v_ty light_t.set_v(np.array([v_t[0], v_t[1], v_t[2]])) return light_t
def __init__(self, a, b, c, material=None): self.a = a self.b = b self.c = c self.u = self.b - self.a # direction Vector self.v = self.c - self.a # direction Vector self.surface = material if not material: self.surface = Surface()
def lightrun(self, list_surface=[Surface()], light_in=Light(), i_t=1): # i_t is reflection times and trans times # this function will simulate the ray, and return a tree and list_surface tree_light = Tree() tree_light.add(light_in) # this will be a for command for i_t for i in range(i_t): # calcute for list_surface # get myQueue length q_length = len(tree_light.myQueue) # run over myQueue,to add new light in tree, but we build a new list, queue is dynamic # select light list_light_temp = [] for index in range(q_length): light_temp = tree_light.myQueue[index].elem list_light_temp.append(light_temp) for light_temp in list_light_temp: if light_temp == None: # no light to reflect tree_light.add(None) tree_light.add(None) else: # get p,t,surface list_mpts = self.get_mp_t0_and_surface( list_surface, light_temp) mp_t0 = list_mpts[0] surface_m = list_mpts[1] # judge if surface is None if surface_m == None: # no reflect and transmisson tree_light.add(None) tree_light.add(None) else: # set the current light_in time # find light_temp index in tree, through it's dynamic, bud no influence, cause if light_temp is finish , we dont need that for i in range(len(tree_light.myQueue)): if tree_light.myQueue[i].elem == light_temp: index = i tree_light.myQueue[index].elem.set_t( np.arange(0, mp_t0[3] + mp_t0[3] / 10, mp_t0[3] / 10)) # set the point in surface is meeting point to save the value to plot list_surface_index = list_surface.index(surface_m) # mp = [mp_t0[0], mp_t0[1], mp_t0[2]] # list_surface[list_surface_index].set_p(np.array(mp)) # calcute trans and ref light_t_temp = self.transmisson2(surface_m, light_temp) light_r_temp = self.reflection(surface_m, light_temp) # add to tree tree_light.add(light_t_temp) tree_light.add(light_r_temp) return [tree_light, list_surface]
def test2(): ''' Test when the Light vertically hits the Surface we set the hits time only by 1 and only have 1 surface the light transmision light_t.v will equal with light_i.v ''' surface = Surface(np.array([0, 1, 0]), np.array([0, 0, 1]), Surface().get_n_water(), Surface().get_n_air()) list_surface = [surface] # light light_i = Light(np.array([3, 2, 3]), np.array([0, 0, -1])) phy = Physical() list_tree_surface = phy.lightrun(list_surface, light_i, 1) tree_light = list_tree_surface[0] list_surface = list_tree_surface[1] list_light = tree_light.level_queue(tree_light.root) assert (list_light[0].get_v() == list_light[1].get_v()).all()
def main(): # Теперь в окне не обязательно указывать его название window = Window(1280, 720) # Создаёт холст, позволяющий редактировать его и объекты на нём легче, чем в обычном холсте. surface = Surface(0, 0, 1280, 720) # Создание кнопки button = Button(200, 200, 200, 100) # Создаём и задаём цвет + прозрачность текста text = Text(200, 100, 20) text.set_color((255, 0, 0, 255)) # Окно открыто, пока мы его не закроем по нажатию на крестик или кнопки Escape run = True while run: # Обработка действий пользователя for event in pygame.event.get(): if event.type == pygame.QUIT: # Выход из цикла по нажатию крестика run = False elif event.type == pygame.KEYDOWN: # Выход из цикла по нажатию Escape'а if event.key == pygame.K_ESCAPE: run = False # Заполняем каждый кадр цветом, чтобы заливать предыдущий window.fill((0, 0, 0)) # Говорим на чём рисовать холст surface.draw(window) # Вместо косвенной передачи поверхности через окно (button.draw(window)) # можно передать саму поверхность, что оптимизирует код и делает его читаемым button.draw(surface) # Выводим текст на экран (по умолчанию выведится "text") text.print(window) # Обновляем окно через буффер и выводим на экран window.update() window.close()
def __init__(self, width, height): self.width = width self.height = height self.eye_x = self.eye_y = self.eye_z = 0 self.radius = 100 self.phi = 0.0 self.theta = 90.0 self.up_x = 0 self.up_y = 1 self.up_z = 0 self.scale = 1 self.surface = Surface()
def write_triangulation_files(self): surf_func = Surface() surf_func.write_surface_mol2( self.calpha, self.del_triangle_points.simplices, '%s_non_treatet_delaunay.mol2' % (self.protein.replace(".pdb", ""))) surf_func.write_surface_mol2( self.calpha, self.peeled_list_triangle_points, '%s_peeled_triangle_points.mol2' % (self.protein.replace(".pdb", ""))) surf_func.write_surface_mol2( self.calpha, self.environmental_boundary, '%s_environmental_boundary.mol2' % (self.protein.replace(".pdb", "")))
def test1(): ''' Test 3 speicial case 1. When Light is parallel the surface, the Light don't hit the Surface. 2. When Light source is on the surface. 3. When no Light, it's is equal situation with parallel This 3 cases will judge in Physical.get_mp_and_t0(), it will return t0=0 ''' # the light parallel to surface light_i1 = Light(np.array([-3, 5, 3]), np.array([1, 0, 0])) light_i2 = Light(np.array([0, 1, 0]), np.array([-1.4, 0, -1])) light_i3 = Light(np.array([0, 1, 0]), np.array([0, 0, 0])) surface = Surface(np.array([0, 1, 0]), np.array([0, 0, 1]), Surface().get_n_air(), Surface().get_n_water()) phy = Physical() ms_t0_1 = phy.get_mp_and_t0(surface, light_i1) ms_t0_2 = phy.get_mp_and_t0(surface, light_i2) ms_t0_3 = phy.get_mp_and_t0(surface, light_i3) t1 = ms_t0_1[3] t2 = ms_t0_2[3] t3 = ms_t0_3[3] assert (t1 == 0) & (t2 == 0) & (t3 == 0)
def test3(): ''' Test total internal reflection TIR case when no transmission, it will be no light_t, if the hits times is 1 the light_t.get_v() is [0,0,0] ''' # surface surface = Surface(np.array([0, 1, 0]), np.array([0, 0, 1]), Surface().get_n_water(), Surface().get_n_air()) list_surface = [surface] # light light_i = Light(np.array([3, 2, 3]), np.array([-1.4, 0, -1])) # Physical object phy = Physical() list_tree_surface = phy.lightrun(list_surface, light_i, 1) tree_light = list_tree_surface[0] list_surface = list_tree_surface[1] list_light = tree_light.level_queue(tree_light.root) assert (list_light[1].get_v() == np.array([0, 0, 0])).all()
def the_loop(): print "State Machine Starting" time.sleep(1) my_machine = smach.StateMachine(outcomes=['StopRobot']) with my_machine: smach.StateMachine.add('Initialize_Robot', Initialize_Robot(), transitions={ 'Success': 'SearchForBuoy', 'Failed': 'StopRobot' }) smach.StateMachine.add('SearchForBuoy', SearchForBuoy(), transitions={ 'Success': 'CenterWithBuoy', 'Failed': 'StopRobot' }) smach.StateMachine.add('CenterWithBuoy', CenterWithBuoy(), transitions={ 'Success': 'BumpIntoBuoy', 'Failed': 'StopRobot' }) smach.StateMachine.add('BumpIntoBuoy', BumpIntoBuoy(), transitions={ 'Success': 'SearchForBase', 'Failed': 'StopRobot' }) smach.StateMachine.add('SearchForBase', SearchForBase(), transitions={ 'Success': 'Surface', 'Failed': 'StopRobot' }) smach.StateMachine.add('Surface', Surface(), transitions={ 'Success': 'StopRobot', 'Failed': 'StopRobot' }) sis = smach_ros.IntrospectionServer('server', my_machine, '/Arens_State_Machine') sis.start() outcome = my_machine.execute() rospy.spin() sis.stop()
def make_property(paramters): """ Make an instance of Property """ prop_type = paramters['type'] if prop_type == 'eos': return EOS(paramters) elif prop_type == 'elastic': return Elastic(paramters) elif prop_type == 'vacancy': return Vacancy(paramters) elif prop_type == 'interstitial': return Interstitial(paramters) elif prop_type == 'surface': return Surface(paramters) else: raise RuntimeError(f'unknown property type {prop_type}')
def add_mod_slots(self): x_pos = 20 for slot in range(0, self.item.get_mod_slots()): if len(self.item.get_mod_list()) > slot: mod_rect = Surface([x_pos, self.size[1] - 15], [20, 5], self.item.get_mod_list()[slot].get_color(), 128) else: mod_rect = Surface([x_pos, self.size[1] - 15], [20, 5], (0, 0, 0), 128) mod_rect.set_displacement([x_pos, self.size[1] - 15]) x_pos += 25 self.surfaces.append(mod_rect)
def run9(): surface1 = Surface(np.array([0, 0, 0]), np.array([-1, 0, 0]), Surface().get_n_metal(), Surface().get_n_water()) surface2 = Surface(np.array([3, 0, 0]), np.array([-1, 0, 0]), Surface().get_n_water(), Surface().get_n_metal()) list_surface = [surface1, surface2] light_i = Light(np.array([0, 0, 1]), np.array([1, 0, -1])) # run Physical().run_plot(list_surface, light_i, 5, 30)
def get_mp_t0_and_surface(self, list_surface=[Surface()], light_temp=Light()): # temp list to check min list_mp_t0_temp = [] # get mp_t0 for all surface for surface_temp in list_surface: list_mp_t0_temp.append(self.get_mp_and_t0(surface_temp, light_temp)) # check value , t >0 open a new list list_mp_t0_temp2 = [] for mp_t0_temp in list_mp_t0_temp: if mp_t0_temp[3] > 0: list_mp_t0_temp2.append(mp_t0_temp) # get mp_t0 and the meeting surface # new time list to check list_t = [] for mp_t0_temp2 in list_mp_t0_temp2: list_t.append(mp_t0_temp2[3]) # get min index # if empty if (len(list_t)): # not empty index = list_t.index(min(list_t)) mp_t0 = list_mp_t0_temp2[index] surface_m = list_surface[list_mp_t0_temp.index(mp_t0)] else: # empty # 从这里开始,先考虑平行的情况,如果时间数组为空,说明没有交点(此时没有考虑平行,正在改进),需要返回一个值 mp_t0 = [0, 0, 0, 0] surface_m = None pass # return them on a list list_mpts = [mp_t0, surface_m] return list_mpts
def reflection(self, surface=Surface(), light_in=Light()): # this methond handled reflection mp_t0 = self.get_mp_and_t0(surface, light_in) # set the source and time light_r = Light() light_r.set_s(np.array([mp_t0[0], mp_t0[1], mp_t0[2]])) light_r.set_t(np.arange(0, mp_t0[3] + mp_t0[3] / 10, mp_t0[3] / 10)) # get n vector , v_i n = surface.get_n() v_i = light_in.get_v() # 3 sysmols to solve equation x_r, y_r, z_r = symbols('x_r y_r z_r') # v_r need to solve v_rs = [x_r, y_r, z_r] # 2 equations eq1 = Eq(np.dot(-v_i, n), np.dot(v_rs, n)) eq2 = Eq(np.cross(-v_i + v_rs, n)[0]) eq3 = Eq(np.cross(-v_i + v_rs, n)[1]) eq4 = Eq(np.cross(-v_i + v_rs, n)[2]) # solve equation sol = solve([eq1, eq2, eq3, eq4], v_rs) # change type of sol # sb python will return want ever it like... if type(sol) == dict: v_r = [sol[x_r], sol[y_r], sol[z_r]] else: v_r = next(iter(sol)) light_r.set_v(np.array([v_r[0], v_r[1], v_r[2]])) return light_r
def __init__(self, width, height): Surface.__init__(self, width=width, height=height)
from Surface import Surface from scipy.spatial import distance import sys import multiprocessing as mp n_jobs = int(sys.argv[1]) points_file = sys.argv[2] # '../results/points/points.pkl' surfaces_dir = sys.argv[3] # '../data/faces_scaled_4/' points, faceindexes, borderpoints_no = pickle.load(open(points_file, 'r')) #points = points[:150] no_surfaces = len(points) surfaces_filelist = [ f for f in sorted(os.listdir(surfaces_dir)) if f.endswith('.ply') ] #surfaces_filelist = surfaces_filelist[:150] no_surfaces_2 = len(surfaces_filelist) if no_surfaces != no_surfaces_2: print 'Points and surfaces size different' raise if n_jobs == 1: surfaces = [Surface(surfaces_dir + f) for f in surfaces_filelist] else: pool = mp.Pool(processes=n_jobs, maxtasksperchild=1) surfaces_filelist2 = [surfaces_dir + f for f in surfaces_filelist] surfaces = pool.map(Surface, surfaces_filelist2) pool.close() pool.join()