Exemple #1
0
 def __init__(self, system, Y, Z, frame, tolerance=1e-10, name=None):
     Surface.__init__(self, system, name, tolerance)
     self.Y = Y
     self.Z = Z
     self.frame = frame
     self.sign = -1.0
     self.pegrw = np.array((0, Y, Z, 1))
Exemple #2
0
def main():
    ren = Rendering((200, 300), (1, 0, 0))
    mat_sphere = SurfaceMaterial('orange_wall', (1, 0.7, 0.0), 0.8, (1, 1, 1),
                                 0, 50, 1.0)
    asphere = Surface.from_sphere((
        0,
        0,
        0,
    ), 1, (1, 31), mat_sphere)

    mat_mobius = SurfaceMaterial('pink_metallic', (1, 0.8, 1), 0.1, (1, 1, 1),
                                 0.9, 50, 1.0)
    amobius = Surface.from_mobius(mat_mobius)

    liver = Surface.from_STL_file('liver.stl')

    mat_head = VolumeMaterial('head', [(0, (0, 0, 0)), (1000, (1, 1, 1))],
                              [(0, 0), (500, 0), (4000, 1)])
    head = Volume.from_VTK_file('head.vtk', mat_head)

    ren.renderer.AddVolume(head)
    ren.renderer.AddActor(liver)
    ren.renderer.AddActor(asphere)
    ren.renderer.AddActor(amobius)
    ren.interactor.Initialize()
    ren.interactor.Start()
Exemple #3
0
 def __init__(self, system, frame, Y=0, Z=0, R=1, name=None, tolerance=1e-10, ):
     Surface.__init__(self, system, name, tolerance)
     self.frame = frame
     self.Y = Y
     self.Z = Z
     self.R = R
     self.sign = 1.0
Exemple #4
0
 def __init__(self,
              base=[0, 0, 0],
              focal=200.0,
              seglen=30.0,
              ang=0.006,
              r0=5.5,
              r1=None
              ):
     '''
     Constructor
     
     Parameters:
         base:    the center point of the wide end of the segment
         seglen:  the axial length of the segment
         ang:     angle of the segment side to the axis
         r0:      radius of the wide end of the segment
         r1:      radius of the small end of the segment
     '''
     # instantiate
     Surface.__init__(self)
     self.base = np.array(base, dt)
     self.focal = focal
     self.seglen = seglen
     self.ang = ang
     ''' Vanspeybroeck and Chase Parameters '''
     self.e = cos(4 * ang) * (1 + (tan(4 * ang) * tan(3 * ang)))
     self.d = focal * tan(4 * ang) * tan((4 * ang) - 3 * ang)
     self.updateDims(r0, r1)
Exemple #5
0
    def __init__(self,
                 system,
                 frame1,
                 frame2,
                 dist,
                 invalid='short',
                 name='distance'):
        Surface.__init__(self, system, name)
        self.frame1 = self.system.get_frame(frame1)
        self.frame2 = self.system.get_frame(frame2)
        self.tape_measure = trep.TapeMeasure(system, [frame1, frame2])

        # The invalid keyword controls whether phi < 0 when the distance
        # is less than or greater than the specified distance.
        assert invalid in ['short', 'long'], "Incorrect 'invalid' type"
        if invalid == 'short':
            self.sgn = 1.0
        else:
            self.sgn = -1.0

        if isinstance(dist, str):
            self.config = trep.Config(system=self.system,
                                      name=dist,
                                      kinematic=True)
        else:
            self.config = None
            self.dist = dist

        self.dist = dist
        self.sign = 1.0
Exemple #6
0
    def __init__(self, width, height, channels, brightness=1):
        self.running = False
        self.width = width
        self.height = height
        self.channels = channels
        self.tbuf = TranslatedFrameBuffer()

        self.surface = Surface(width, height, channels, brightness)

        self.jobs = JobRunner()

        weatherFetcher = WeatherFetcher()
        newsApi = NewsApi()

        self.jobs.add(weatherFetcher.do)
        self.jobs.add(newsApi.do)

        self.apps = [
            App(News(newsApi), 0, 0),
            App(Weather(weatherFetcher), 0, 10),
            App(Clock(), 0, 20),
        ]

        self.rotator = Rotator(self.apps, 2 * second, 120 * second)
        self.timer = Timer(self.loop, 60)
Exemple #7
0
def get_velocities(surface: Surface):
    """ Calculates the surface velocity regarding to etching or sputtering."""
    
    if par.ETCHING:
        return par.ETCH_RATE * np.ones_like(surface.x)
    else:
        N = par.DENSITY
        
        # get the normal vectors
        normal = surface.normal()
        normal_x = normal[0]
        normal_y = normal[1]
        theta = np.empty_like(normal_x)
        
        # calculate theta by using the inner product
        theta = np.arccos(np.abs(normal_y))
        # calculate f_beam and f_sput
        y = sputter_yield(theta)
        f_beam = par.BEAM_CURRENT_DENSITY / constants.e
        f_sput = f_beam * y * np.cos(theta)
        
        # convert from cm/s to nm/s
        v_normal = f_sput / N * 1e7
        
        #Calculate redeposition
        if par.REDEP:
            f_redep = surface.viewfactor().dot(f_sput)
            #v_normal = (f_sput - f_redep) / N * 1e7

        return v_normal
Exemple #8
0
    def draw(self, surface, total_surface):
        """
        Calculate the scaling and display to the inputted surface.

        `surface` - The `Surface` being drawn to.
        `total_surface` - The `Surface` being copied from.
        """
        scale = self.getScale()

        # Optimization, no need to do scaling when the scale is 1.
        if scale == 1:
            self._display.update(
                total_surface, Display.translate(total_surface.get_rect(),
                                                 self))
        else:
            # Optimization, caches the `Surface` object so long as the scale isn't changing.
            if scale != self._lastScale:
                self._surfaceCache = Surface((self.w, self.h))
            self._surfaceCache.blit(total_surface, (-self.x, -self.y))

            scaleTo = self.unscaled()
            transform.scale(self._surfaceCache, (scaleTo.w, scaleTo.h),
                            self._displaySurfaceCache)
            self._lastScale = scale

        self._display.draw(surface)
Exemple #9
0
def scorer(pred,label,vxlspacing):
	"""

	:param pred:
	:param label:
	:param voxelspacing:
	:return:
	"""

	volscores = {}

	volscores['dice'] = metric.dc(pred,label)
	volscores['jaccard'] = metric.binary.jc(pred,label)
	volscores['voe'] = 1. - volscores['jaccard']
	volscores['rvd'] = metric.ravd(label,pred)

	if np.count_nonzero(pred) ==0 or np.count_nonzero(label)==0:
		volscores['assd'] = 0
		volscores['msd'] = 0
	else:
		evalsurf = Surface(pred,label,physical_voxel_spacing = vxlspacing,mask_offset = [0.,0.,0.], reference_offset = [0.,0.,0.])
		volscores['assd'] = evalsurf.get_average_symmetric_surface_distance()
	
		volscores['msd'] = metric.hd(label,pred,voxelspacing=vxlspacing)



	logging.info("\tDice " + str(volscores['dice']))
	logging.info("\tJaccard " + str(volscores['jaccard']))
	logging.info("\tVOE " + str(volscores['voe']))
	logging.info("\tRVD " + str(volscores['rvd']))
	logging.info("\tASSD " + str(volscores['assd']))
	logging.info("\tMSD " + str(volscores['msd']))

	return volscores
Exemple #10
0
 def __init__(self, system, Y, Z, frame, tolerance=1e-10, name=None):
     Surface.__init__(self, system, name, tolerance)
     self.Y = Y
     self.Z = Z
     self.frame = frame
     self.sign = -1.0
     self.pegrw = np.array((0,Y,Z,1))
        def update_neighbors_list(tile):

            neighbors = []

            neighbor_left = Surface.get_tile_by_position(
                (tile.x - tile.width, tile.y))
            neighbor_right = Surface.get_tile_by_position(
                (tile.x + tile.width, tile.y))
            neighbor_top = Surface.get_tile_by_position(
                (tile.x, tile.y - tile.height))
            neighbor_botton = Surface.get_tile_by_position(
                (tile.x, tile.y + tile.height))

            if check_neighbor(neighbor_left):
                neighbors.append(neighbor_left)

            if check_neighbor(neighbor_right):
                neighbors.append(neighbor_right)

            if check_neighbor(neighbor_top):
                neighbors.append(neighbor_top)

            if check_neighbor(neighbor_botton):
                neighbors.append(neighbor_botton)

            return neighbors
Exemple #12
0
def simulation(tend, dt):
    """
    starts the simulation, plots and writes the data

    creates a Surface Object and starts the simulation. 
    the correct timestep is calculated with the timestep function 
    from the advance module. 
    Writes all calculated datapoints to a file with the 
    filenname: basic_<tend>_<dt>.srf
    plots the simulation fpr t = 0 and t = tend

    :param tend: endtime of the simulation
    :param dt: timestep of the simulation
    """
    s = Surface()
    time = 0
    filename = f"basic_{tend}_{dt}.srf"
    s.plot(time)

    while time < tend:
        s.write(time, filename)
        advance(s, timestep(dt, time, tend))
        time += timestep(dt, time, tend)

    s.write(time, filename)
    s.plot(time)
    plt.legend()
    plt.show()
Exemple #13
0
class Weapon(Emitter, Inputable):
    def __init__(self, level, **kwargs):
        super().__init__(**kwargs)

        self._level = level
        self._part = None
        self._s = Surface((20, 10))
        self._s.fill((255, 0, 0))

        self._input = Input(inputStream=self.getInputStream())
        self._input.set(pygame.KEYDOWN, self.createNew, pygame.K_f)

    def createNew(self):
        x, y = self._offsetFunc()
        self._part = Particle((self._anchor.x + x, self._anchor.y + y, 20, 10),
                              (10, 0),
                              self._s,
                              self._level,
                              Behaviors.killAt(150, 150),
                              Behaviors.moveAt(self._anchor.getIntDir() * 10, 0),
                              Behaviors.killOnCollision(exceptions=(self._anchor.getId(),)),
                              Behaviors.cleanupCollision(),
                              altname="bullet")
        if x < 0:
            self._part.x -= self._part.w
        self._part.move.setSpeed(x=self._part.move.getTopSpeed(x=True))

    def _emit(self):
        if self._part:
            self._children.append(self._part)
            self._part = None

    def tick(self):
        self._input()
        super().tick()
Exemple #14
0
class Box(Surface):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.button_bar = Surface(parent=self,
                                  position=(0,
                                            self.height - flags.square_size),
                                  size=(flags.bar_size, flags.square_size))
        self.body = Page(self)
        self.buttons = []

        for i in range(flags.bar_squares):
            self.buttons.append(
                Button(parent=self.button_bar,
                       position=(i * flags.square_size, 0)))

    def initialize(self):
        self.body.initialize()

        for button in self.buttons:
            button.print()

        self.button_bar.print()
        self.print()

    def mouse(self, coords, pressed=False):
        for button in self.buttons:
            if button.contains(coords):
                button.mouse(pressed=pressed)
            elif button.is_hovered or button.is_pressed:
                button.clear()
Exemple #15
0
def get_assd(preds_path, labels_path, dicoms_path, result_path, ):
    test_time = time.strftime("%Y.%m.%d.%H.%M.%S", time.localtime())
    result = os.path.join(result_path, "results.txt")
    assd = {}
    all_assd = 0
    # 获取病人姓名
    patients = os.listdir(preds_path)
    for patient in patients:
        # 获取标签集合和预测集合
        pred_path = os.path.join(preds_path, patient)
        label_path = os.path.join(labels_path, patient)
        dicom_path = os.path.join(dicoms_path, patient)
        preds = sorted(glob.glob(os.path.join(pred_path, "*.bmp")))
        labels = sorted(glob.glob(os.path.join(label_path, "*.bmp")))
        # 创建array变量,存储每个病人图片数据
        [width, height] = imageio.imread(preds[0]).shape
        pred_rawData = np.zeros((width, height, len(preds)))
        label_rawData = np.zeros((width, height, len(labels)))
        i = 0
        for pred, label in zip(preds, labels):
            # 读取图片,获取numpy array
            pred_array = imageio.imread(pred)
            label_array = imageio.imread(label)
            # 进行二值化处理
            pred_rawData[:, :, i] = pred_array / 255
            label_rawData[:, :, i] = label_array / 255
            # 循环将每张图片数据进行转换并保存
            i += 1
        # 对array进行数据格式转换
        pred_rawData = pred_rawData.astype(int)
        label_rawData = label_rawData.astype(int)
        # print("*"*30)
        print(dicom_path)
        pixel_info = get_pixel_info(dicom_path)
        print(patient, "_像素间距:", pixel_info)
        # print("*"*30)
        evalsurf = Surface(pred_rawData, label_rawData, physical_voxel_spacing=pixel_info, mask_offset=[0., 0., 0.],
                           reference_offset=[0., 0., 0.])
        assd[patient] = evalsurf.get_average_symmetric_surface_distance()
        per_result = "'%s'_the average symmetric surface distance:%.2f" % (patient, assd[patient])
        print(per_result)
        with open(result, mode='a') as file:
            file.write(test_time)
            file.write("    ")
            file.write(per_result)
            file.write("\n")

    for key in assd.keys():
        all_assd += assd.get(key)

    average_assd = all_assd / len(assd)
    average_result = "AllPatients_the average symmetric surface distance:%.2f" % (average_assd)
    print(average_result)
    with open(result, mode='a') as file:
        file.write(test_time)
        file.write("    ")
        file.write(average_result)
        file.write("\n")
    return  assd
Exemple #16
0
 def __init__(self, system, X, Y, Z, R, frame, tolerance=1e-10, name=None):
     Surface.__init__(self, system, name, tolerance)
     self.X = X
     self.Y = Y
     self.Z = Z
     self.R = R
     self.frame = frame
     self.sign = -1.0
Exemple #17
0
 def __init__(self, system, X, Y, Z, R, frame, tolerance=1e-10, name=None):
     Surface.__init__(self, system, name, tolerance)
     self.X = X
     self.Y = Y
     self.Z = Z
     self.R = R
     self.frame = frame
     self.sign = -1.0
Exemple #18
0
 def __init__(self, system, point, normal, frame, tolerance=1e-10, name=None):
     Surface.__init__(self, system, name, tolerance)
     self.normal = normal
     self.point = point
     self.frame = frame
     self.plane_d = -np.dot(point, normal)
     self.plane_r = np.sqrt(np.dot(normal,normal))
     self.sign = -1.0
def compute_segmentation_scores(prediction_mask, reference_mask,
                                voxel_spacing):
    """
    Calculates metrics scores from numpy arrays and returns an dict.
    Assumes that each object in the input mask has an integer label that
    defines object correspondence between prediction_mask and
    reference_mask.
    :param prediction_mask: numpy.array, int
    :param reference_mask: numpy.array, int
    :param voxel_spacing: list with x,y and z spacing
    :return: dict with dice, jaccard, voe, rvd, assd, rmsd, and msd
    """
    scores = {
        'dice': [],
        'jaccard': [],
        'voe': [],
        'rvd': [],
        'assd': [],
        'rmsd': [],
        'msd': []
    }

    p = (prediction_mask > 0)
    r = (reference_mask > 0)
    if np.any(p) and np.any(r):
        dice = metric.dc(p, r)
        jaccard = dice / (2. - dice)
        scores['dice'].append(dice)
        scores['jaccard'].append(jaccard)
        scores['voe'].append(1. - jaccard)
        scores['rvd'].append(metric.ravd(r, p))
        evalsurf = Surface(p,
                           r,
                           physical_voxel_spacing=voxel_spacing,
                           mask_offset=[0., 0., 0.],
                           reference_offset=[0., 0., 0.])

        assd = evalsurf.get_average_symmetric_surface_distance()
        rmsd = evalsurf.get_root_mean_square_symmetric_surface_distance()
        msd = evalsurf.get_maximum_symmetric_surface_distance()
        scores['assd'].append(assd)
        scores['rmsd'].append(rmsd)
        scores['msd'].append(msd)
    else:
        # There are no objects in the prediction, in the reference, or both
        scores['dice'].append(0)
        scores['jaccard'].append(0)
        scores['voe'].append(1.)
        # Surface distance (and volume difference) metrics between the two
        # masks are meaningless when any one of the masks is empty. Assign
        # maximum penalty. The average score for these metrics, over all
        # objects, will thus also not be finite as it also loses meaning.
        scores['rvd'].append(LARGE)
        scores['assd'].append(LARGE)
        scores['rmsd'].append(LARGE)
        scores['msd'].append(LARGE)

    return scores
Exemple #20
0
def main():

    # Get command-line arguments.
    args = parse_args()

    ## Create renderer and graphics window.
    win_width = 500
    win_height = 500
    renderer, renderer_window = gr.init_graphics(win_width, win_height)

    ## Read in the segmentation surface.
    surface_file_name = args.surface_file
    surface = Surface(gr, renderer_window, renderer)
    surface.read(surface_file_name)
    gr_geom = gr.add_geometry(renderer,
                              surface.geometry,
                              color=[0.8, 0.8, 1.0])
    surface.vtk_actor = gr_geom
    #gr_geom.GetProperty().SetOpacity(0.5)

    ## Create a Centerlines object used to clip the surface.
    centerlines = Centerlines()
    centerlines.graphics = gr
    centerlines.surface = surface
    centerlines.window = renderer_window
    centerlines.renderer = renderer
    centerlines.clip_distance = args.clip_distance
    centerlines.clip_width_scale = args.clip_width_scale
    centerlines.remesh_scale = args.remesh_scale
    centerlines.mesh_scale = args.mesh_scale

    print("---------- Alphanumeric Keys ----------")
    print(
        "a - Compute model automatically for a three vessel surface with flat ends."
    )
    print("c - Compute centerlines.")
    print("m - Create a model from the surface and centerlines.")
    print("q - Quit")
    print("s - Select a centerline source point.")
    print("t - Select a centerline target point.")
    print("u - Undo the selection of a centerline source or target point.")

    ## Create a mouse interactor for selecting centerline points.
    picking_keys = ['s', 't']
    event_table = {
        'a': (surface.create_model_automatically, centerlines),
        'c': (surface.compute_centerlines, surface),
        'm': (centerlines.create_model, surface),
        's': surface.add_centerlines_source_node,
        't': surface.add_centerlines_target_node
    }
    interactor = gr.init_picking(renderer_window, renderer, surface.geometry,
                                 picking_keys, event_table)

    ## Display window.
    interactor.Start()
Exemple #21
0
    def __init__(self, level, **kwargs):
        super().__init__(**kwargs)

        self._level = level
        self._part = None
        self._s = Surface((20, 10))
        self._s.fill((255, 0, 0))

        self._input = Input(inputStream=self.getInputStream())
        self._input.set(pygame.KEYDOWN, self.createNew, pygame.K_f)
Exemple #22
0
 def resize(self, width, height):
     Surface.resize(self, width, height)
     self.surface.resize(width, height)
     try:
         self.surface._display.textbox.resize()
     except (TypeError, AttributeError):     #pyjs-O:TypeError/-S:AttributeError
         pass
     try:
         self.surface._display.textarea.resize()
     except (TypeError, AttributeError):     #pyjs-O:TypeError/-S:AttributeError
         pass
 def convert_image(self, image):
     """
     Return the image as a Surface.
     """
     if env.canvas._isCanvas:
         img = image.getElement()
         surface = Surface((img.width,img.height))
         surface.drawImage(image, 0, 0)
     else:
         surface = Surf(image)
     return surface
 def convert_image(self, image):
     """
     Return the image as a Surface.
     """
     if env.canvas._isCanvas:
         img = image.getElement()
         surface = Surface((img.width, img.height))
         surface.drawImage(image, 0, 0)
     else:
         surface = Surf(image)
     return surface
    def scale(self, surface, size, dest=None):
        """
        Return Surface resized by the given size.
        An optional destination surface can be provided.
        """
        if not dest:
            surf = Surface(size)
        else:
            surf = dest
        surf.drawImage(surface.canvas, 0, 0, surface.get_width(), surface.get_height(), 0, 0, size[0], size[1])    #pyjs0.8 *.canvas
#        surf.drawImage(surface, 0, 0, surface.get_width(), surface.get_height(), 0, 0, size[0], size[1])
        return surf
Exemple #26
0
 def __init__(self,
              system,
              frame,
              name=None,
              tolerance=1e-10,
              dim=2,
              lims=(-3, 3)):
     Surface.__init__(self, system, name, tolerance)
     self.frame = frame
     self.dim = dim
     self.lims = lims
     self.sign = 1.0
Exemple #27
0
def test_miniTopSim():
    '''
    this test is testing the miniTopSim.py script
    the test is checking of the generate srf file has equal values to the srf_save file
    for verfing the test the methode distance() of surface.py is used
    '''
    distance_measure = 0.720801905617422
    simulation(os.path.join(filedir,'etch_dx1.cfg'))
    surface1 = Surface(filename = os.path.join(filedir,'etch_dx1.srf'))
    surface2 = Surface(filename = os.path.join(filedir,'etch_dx0.125.srf_save'))
    distance = surface1.distance(surface2)
    assert distance  < (distance_measure/2)
Exemple #28
0
def test_cosine_vert():
    '''
    this test is testing the miniTopSim.py script
    the test is checking of the generate srf file has equal values to the srf_save file
    for verfing the test the methode distance() of surface.py is used
    '''
    distance_measure = 2.3
    simulation(os.path.join(filedir, 'cosine_vert_1.cfg'))
    surface1 = Surface(filename=os.path.join(filedir, 'cosine_vert_1.srf'))
    surface2 = Surface(
        filename=os.path.join(filedir, 'cosine_vert_05.srf_save'))
    distance = surface1.distance(surface2)
    assert distance < (distance_measure / 2)
Exemple #29
0
 def __init__(self, origin = [-1,-1,0], ax1 = [2,0,0], ax2 = [0,2,0]):
     '''
     Constructor
     
     Parameters:
         ax1:     first edge of parallelogram as a vector
         ax2:     second edge of parallelogram as a vector
         origin:  the origin coordinate for both axes
     '''
     Surface.__init__(self)
     self.origin = np.array(origin,dt)
     self.ax1 = np.array(ax1,dt)
     self.ax2 = np.array(ax2,dt)
Exemple #30
0
 def __init__(self,
              system,
              point,
              normal,
              frame,
              tolerance=1e-10,
              name=None):
     Surface.__init__(self, system, name, tolerance)
     self.normal = normal
     self.point = point
     self.frame = frame
     self.plane_d = -np.dot(point, normal)
     self.plane_r = np.sqrt(np.dot(normal, normal))
     self.sign = -1.0
Exemple #31
0
 def scale(self, surface, size, dest=None):
     """
     Return Surface resized by the given size.
     An optional destination surface can be provided.
     """
     if not dest:
         surf = Surface(size, BufferedImage.TYPE_INT_ARGB)
     else:
         surf = dest
     g2d = surf.createGraphics()
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, 0, 0, size[0], size[1], None)
     g2d.dispose()
     return surf
Exemple #32
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.button_bar = Surface(parent=self,
                                  position=(0,
                                            self.height - flags.square_size),
                                  size=(flags.bar_size, flags.square_size))
        self.body = Page(self)
        self.buttons = []

        for i in range(flags.bar_squares):
            self.buttons.append(
                Button(parent=self.button_bar,
                       position=(i * flags.square_size, 0)))
Exemple #33
0
def home(game_values):
    """
    Home page of the game / GUI
    """
    width, height = rows * blocksize, columns * blocksize
    # icon size constants
    i_width, i_height = width // 4 + (rows // 3), height // 4
    # icon position constants,
    # sg for single, and double,
    # sn for snake
    sg_width = width // 10
    sg_height = height // 4 + height // 10
    sn_width, sn_height = (width // 2 - (width + rows) // 6, i_height // 10)
    # Initializing objects
    images = utils.load_images(os.path.dirname(__file__), i_width, i_height)
    surface = Surface(*game_values, caption="Home Screen", color=BLACK)
    surface.make_screen()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        surface.screen.blit(
            images["single"],
            (sg_width, sg_height),
        )
        surface.screen.blit(
            images["double"],
            (width - (sg_width + i_width), sg_height),
        )
        surface.screen.blit(images["snake"], (sn_width, sn_height))
        # Highlighting an icon
        x, y = pygame.mouse.get_pos()
        if sg_height <= y <= sg_height + i_height:
            # single player
            if sg_width <= x <= sg_width + i_width:
                rect = pygame.Rect((sg_width, sg_height), (i_width, i_height))
                pygame.draw.rect(surface.screen, RED, rect, 3)
                if pygame.mouse.get_pressed()[0]:
                    return 1
            # double player
            elif (width - (sg_width + i_width) <= x <= width -
                  (sg_width + i_width) + i_width):
                rect = pygame.Rect((width - (sg_width + i_width), sg_height),
                                   (i_width, i_height))
                pygame.draw.rect(surface.screen, RED, rect, 3)
                if pygame.mouse.get_pressed()[0]:
                    return 2
        pygame.display.flip()
Exemple #34
0
 def scale(self, surface, size, dest=None):
     """
     Return Surface resized by the given size.
     An optional destination surface can be provided.
     """
     if not dest:
         surf = Surface(size, BufferedImage.TYPE_INT_ARGB)
     else:
         surf = dest
     g2d = surf.createGraphics()
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                          RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, 0, 0, size[0], size[1], None)
     g2d.dispose()
     return surf
Exemple #35
0
 def __init__(
     self,
     system,
     frame,
     Y=0,
     Z=0,
     R=1,
     name=None,
     tolerance=1e-10,
 ):
     Surface.__init__(self, system, name, tolerance)
     self.frame = frame
     self.Y = Y
     self.Z = Z
     self.R = R
     self.sign = 1.0
Exemple #36
0
 def apply(self):
     self._log.debug(u"""Applying values
     filename: '%s',
     subdivisions: '%f',
     bezier factor: '%f'""" % (
         self.surface_filename,
         self.surface_subdivisions,
         self.bezier_factor))
     if self.surface:
         del self.surface
         if self.plane:
             self.plane.removeNode()
             self.plane = None
         if self.mls_surface:
             self.mls_surface.removeNode()
             self.mls_surface = None
         if self.bezier_surface:
             self.bezier_surface.removeNode()
             self.bezier_surface = None
         if self.point_cloud:
             self.point_cloud.removeNode()
             self.point_cloud = None
     self.surface = Surface.from_file(self.surface_filename)
     self._toggle_plane()
     self._toggle_mls_surface()
     self._toggle_bezier_surface()
     self._toggle_point_cloud()
	def create_life(self):

		spot_count = len(Level1.LIFE_SPOT)
		spot_number = randint(0, spot_count - 1)
		life_tile = Surface.get_tile_by_number(Level1.LIFE_SPOT[spot_number])

		Life(life_tile.x, life_tile.y)
Exemple #38
0
def read_model(file_name, edges, vertices, surfaces):
    f = open(file_name)
    surface_id = 0
    for line in f.readlines():
        l = line.rstrip('\n').split(' ')
        flag = l[0]
        if flag == 'v':
            vertices.append((float(l[1]), float(l[2]), float(l[3])))
        elif flag == 'f':
            edges_list = l[1:]  # Edge list in string
            surface_edges = []
            for i in range(len(edges_list)):
                if i == len(edges_list) - 1:
                    edges.append((int(edges_list[i]), int(edges_list[0])))
                    surface_edges.append(
                        (int(edges_list[i]), int(edges_list[0])))
                else:
                    edges.append((int(edges_list[i]), int(edges_list[i + 1])))
                    surface_edges.append(
                        (int(edges_list[i]), int(edges_list[i + 1])))
            surface = Surface(surface_id, surface_edges)
            surfaces.append(surface)
            surface_id = surface_id + 1

    f.close()
Exemple #39
0
    def __init__(   self,
                    camera,
                    scale=1.0,
                    tileSize=128,
                    tilesX=1,
                    tilesZ=1,
                    depth=30.0):
    
        self.depth = depth

        self.tileSize = tileSize
        self.tilesX = tilesX
        self.tilesZ = tilesZ

        self.camera = camera
        self.scale = scale
        
        self.surfaceShader = ShaderProgram.open('shaders/colour_by_height.shader')

        
        # Use the shallow pool ripple surface generator
        self.heightfield = Ripples(self.camera, self.tileSize)
                                           
        # The water surface
        self.surface = Surface( self.surfaceShader,
                                self.camera,
                                texture=None,
                                heightfield=self.heightfield,
                                tileSize=self.tileSize, 
                                tilesX=self.tilesX,
                                tilesZ=self.tilesZ,
                                scale=self.scale, 
                                offset=Vector3(0.0,self.depth,0.0))
Exemple #40
0
def test_erf():
    """
    Test if last surface of .srf file is equal to last surface of .srf_save file

    :var distance_measure:  maximum allowed difference between the two surfaces
    :var distance:          actual difference between the two surfaces
    """

    distance_measure = 1e-5

    simulation(os.path.join(filedir, 'erf.cfg'))
    surface1 = Surface(filename=os.path.join(filedir, 'erf.srf'))
    surface2 = Surface(filename=os.path.join(filedir, 'erf.srf_save'))

    distance = surface1.distance(surface2)
    assert distance < distance_measure
Exemple #41
0
    def __init__(self,
                 size,
                 scale,
                 target=None,
                 boundBox=Object(),
                 maxBounds=None):
        """
        `size` - The size (width and height).
        `scale` - The scale at which to render the view.
        `target` - (Optional) An object that the position of the `Viewport` should follows. If
                   not set, the `Viewport` will not move automatically.
        `boundBox` - (Optional) A sub-view of the `Viewport`, inside which the `target` should
                     always remain. If not set, it will be set to the Viewport's size.
        `maxBounds` - (Optional) A Rectangle inside of which the `Viewport` should always remain.
                      If not set, there will be no max/min bounds on the position of the `Viewport`.
        """
        super().__init__(size=size, scale=scale)

        self._target = target
        self._boundBox = ScaledOffsetObject(rect=boundBox, scale=self.getScale)
        self._maxBounds = maxBounds

        self._display = Display(Surface(size))
        self._displaySurfaceCache = self._display.getImage()
        self._surfaceCache = None

        self._lastScale = None
Exemple #42
0
class Pool():
    '''
    A shallow pool with concentric ripples on its surface
    '''
    def __init__(   self,
                    camera,
                    scale=1.0,
                    tileSize=128,
                    tilesX=1,
                    tilesZ=1,
                    depth=30.0):
    
        self.depth = depth

        self.tileSize = tileSize
        self.tilesX = tilesX
        self.tilesZ = tilesZ

        self.camera = camera
        self.scale = scale
        
        self.surfaceShader = ShaderProgram.open('shaders/colour_by_height.shader')

        
        # Use the shallow pool ripple surface generator
        self.heightfield = Ripples(self.camera, self.tileSize)
                                           
        # The water surface
        self.surface = Surface( self.surfaceShader,
                                self.camera,
                                texture=None,
                                heightfield=self.heightfield,
                                tileSize=self.tileSize, 
                                tilesX=self.tilesX,
                                tilesZ=self.tilesZ,
                                scale=self.scale, 
                                offset=Vector3(0.0,self.depth,0.0))

    def setDepth(self, depth):
        self.surface.setDepth(self.depth)
    def tap(self, tapPosition):
        self.heightfield.tap(tapPosition)

    def draw(self,dt):
        self.surface.draw(dt)        
Exemple #43
0
 def blit_array(self, surface, array):
     """
     Generates image pixels from a JNumeric array.
     Arguments include surface to generate the image, and array of integer colors.
     """
     if not self.initialized:
         self._init()
     w,h = array.shape
     data = Numeric.reshape(array, (1,w*h))[0]
     if not surface.getColorModel().hasAlpha():
         surface.setRGB(0, 0, surface.width, surface.height, data, 0, surface.width)
     else:
         surf = Surface((w,h), BufferedImage.TYPE_INT_RGB)
         surf.setRGB(0, 0, surface.width, surface.height, data, 0, surface.width)
         g2d = surface.createGraphics()
         g2d.drawImage(surf, 0, 0, None)
         g2d.dispose()
     return None
Exemple #44
0
def load(file):
    """Load an image from a file name in a new surface. Type detected from file name.
    Args
        file: The name of the image file.

    Returns:
        A new surface.

    """
    return Surface._from_ptr(check_ptr_err(lib.IMG_Load(file)))
	def create_enemy(self, player):

		spot_count = len(Level1.ENEMY_SPOT)
		spot_number = randint(0, spot_count - 1)
		enemy_tile = Surface.get_tile_by_number(Level1.ENEMY_SPOT[spot_number])

		type_count = len(Enemy.Types)
		type_index = randint(0, type_count - 1)

		Enemy(enemy_tile.x, enemy_tile.y, player, Enemy.Types[type_index])
 def addLayers(self, final_n):
     """Add layers until the number of layers equals final_n."""
     if final_n > settings.max_number_of_layers:
         return
     if final_n >= len(self.layers):
         for i in range(final_n - len(self.layers) + 1):
             layer = Surface.create(self)
             layer.atom_types = self.substrate_atom_types
             layer.hide()
             self.layers.append(layer)
Exemple #47
0
 def __init__(self, size, buffered):
     Surface.__init__(self, size)
     MouseWheelHandler.__init__(self, True)
     if isinstance(buffered, bool):
         self._bufferedimage = buffered
     else:
         self._bufferedimage = True
     try:
         if self.impl.canvasContext:
             self._isCanvas = True
     except:
         self._isCanvas = False
         self._bufferedimage = False
     if self._bufferedimage:
         self.surface = Surface(size)
     else:
         self.surface = self
     self.resize(size[0], size[1])
     self.images = {}
     self.image_list = []
     self.function = None
     self.time_wait = 0
     self.time = Time()
     self.event = pyjsdl.event
     self.addMouseListener(self)
     self.addMouseWheelListener(self)
     self.addKeyboardListener(self)
     self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
     self.modKey = pyjsdl.event.modKey
     self.specialKey = pyjsdl.event.specialKey
     self._rect_list = []
     self._rect_list.append(Rect(0,0,0,0))
     self._rect_len = 1
     self._rect_num = 0
     self._rect_temp = Rect(0,0,0,0)
     _animationFrame = self._initAnimationFrame()
     if _animationFrame:
         self.time_hold_min = 0
     else:
         self.time_hold_min = 1
     self.time_hold = self.time_hold_min
     self.initialized = False
    def __init__(self, system, frame1, frame2, dist, invalid='short'):
        Surface.__init__(self, system, 'Distance')
        self.frame1 = self.system.get_frame(frame1)
        self.frame2 = self.system.get_frame(frame2)
        self.tape_measure = trep.TapeMeasure(system, [frame1, frame2])

        # The invalid keyword controls whether phi < 0 when the distance
        # is less than or greater than the specified distance.
        assert invalid in ['short', 'long'], "Incorrect 'invalid' type"
        if invalid == 'short':
            self.sgn = 1.0
        else:
            self.sgn = -1.0

        if isinstance(dist, str):
            self.config = trep.Config(system=self.system, name=dist, kinematic=True)
        else:
            self.config = None
            self.dist = dist

        self.dist = dist
        self.sign = -self.sgn
		def update_neighbors_list(tile):

			neighbors = []

			neighbor_left = Surface.get_tile_by_position((tile.x - tile.width, tile.y))
			neighbor_right = Surface.get_tile_by_position((tile.x + tile.width, tile.y))
			neighbor_top = Surface.get_tile_by_position((tile.x, tile.y - tile.height))
			neighbor_botton = Surface.get_tile_by_position((tile.x, tile.y + tile.height))

			if check_neighbor(neighbor_left):
				neighbors.append(neighbor_left)

			if check_neighbor(neighbor_right):
				neighbors.append(neighbor_right)

			if check_neighbor(neighbor_top):
				neighbors.append(neighbor_top)

			if check_neighbor(neighbor_botton):
				neighbors.append(neighbor_botton)

			return neighbors
Exemple #50
0
 def rotate(self, surface, angle):
     """
     Return Surface rotated by the given angle.
     """
     theta = angle*self.deg_rad
     width_i = surface.getWidth()
     height_i = surface.getHeight()
     cos_theta = math.fabs( math.cos(theta) )
     sin_theta = math.fabs( math.sin(theta) )
     width_f = int( (width_i*cos_theta)+(height_i*sin_theta) )
     height_f = int( (width_i*sin_theta)+(height_i*cos_theta) )
     surf = Surface((width_f,height_f), BufferedImage.TYPE_INT_ARGB)
     at = AffineTransform()
     at.rotate(-theta, width_f/2, height_f/2)
     g2d = surf.createGraphics()
     ot = g2d.getTransform()
     g2d.setTransform(at)
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
     g2d.drawImage(surface, (width_f-width_i)//2, (height_f-height_i)//2, None)
     g2d.setTransform(ot)
     g2d.dispose()
     return surf
Exemple #51
0
    def __init__(self, x, y, maxTime, numNums=3):
        image, width = const.numbers
        numbers = Files.loadImage(image)
        numbers.set_colorkey(numbers.get_at((0, 0)))

        super().__init__(rect=(x, y, width * numNums, numbers.get_height()), enabled=True)

        self._numbers = []
        self._digits = []
        self._maxTime = maxTime
        self._currentTime = maxTime
        self._blank = Display(Surface((width, self.h)))

        for i in range(width):
            self._numbers.append(Display(numbers.subsurface((i * width, 0, width, self.h))))

        surf = Surface((self.w + 2 * numNums, self.h))
        self._display = Display(surf, self, transparent=True, alpha=200)
        for i in range(numNums):
            self._digits.append(surf.subsurface((i * width + 2 * i, 0, width, self.h)))

        self._lastUpdate = -maxTime
Exemple #52
0
 def __init__(self,
              base = [0,0,0],
              seglen = 30.0,
              ang = 0.006,
              r0 = 5.5,
              r1 = None
              ):
     '''
     Constructor
     
     Parameters:
         base:    the center point of the wide end of the segment
         seglen:  the axial length of the segment
         ang:     angle of the segment side to the axis
         r0:      radius of the wide end of the segment
         r1:      radius of the small end of the segment
     '''
     # instantiate
     Surface.__init__(self)
     self.base = np.array(base,dt)
     self.seglen = seglen
     self.ang = ang
     self.updateDims(r0,r1)
Exemple #53
0
def main(argv):
    
    sim_start_time = clock()
    # check if config is given as parameter
    if len(sys.argv) < 2:
        usage()
        exit()
    
    cfg_file = sys.argv[1]
    srf_file = os.path.splitext(cfg_file)[0] + '.srf'
    
    par.LoadConfig(sys.argv[1])

    init_sputtering()

    dtime = par.TIME_STEP
    dt = dtime
    time = 0
    end_time = par.TOTAL_TIME
    
    surface_start = Surface(par.XMAX, par.XMIN, par.DELTA_X)   

    surface = Surface(par.XMAX, par.XMIN, par.DELTA_X)

    while time < end_time:        
        advance(surface, dt)
        surface.write(srf_file, time, surface.x.size, end_time, dtime)
        time, dt = timestep(dtime, time, end_time)

    surface.write(srf_file, time, surface.x.size, end_time, dtime)  
    
    sim_end_time = clock()
    print("Execution time:" + str(sim_end_time - sim_start_time) + "s")
    
    if par.PLOT_SURFACE:
        surface_start.plot('OF Start', '-+r')
        surface.plot('OF Stop','-+b')
 def __init__(self, parent):
     super(MolecularScene, self).__init__(parent)
     self.surface = Surface.create(self)
     self.surface.atom_types = settings.surface_atom_types[:]
     self.substrate_atom_types = settings.substrate_atom_types[:]
     self.layers = [self.surface]
     self.addLayers(settings.number_of_layers)
     self.current_layer_i = 0
     self.current_layer = self.layers[self.current_layer_i]
     self.peek_layer = None
     self.selection_box = None
     self.drag_border = None
     self.draw_mode = DRAW_ALL
     self.updateSceneRect()
     self.update()
Exemple #55
0
    def update(self):
        self._heartLen = self._parent.getBaseHealth()
        self.w, self.h = 10 * self._heartLen + 2 * ceil(self._heartLen / 2), 16

        surf = Surface((self.w, self.h))
        trans = self._heartFilled[0].get_at((0, 0))
        surf.fill(trans)
        surf.set_colorkey(trans)
        self._display = Display(surface=surf, klass=self)

        for i in range(self._heartLen):
            self._hearts.append(surf.subsurface(Object(rect=(10 * i + 2 * (i // 2), 0, 10, 16)).asRect()))
Exemple #56
0
 def __call__(self, text):
     font_width, font_height = self.surface.size
     offsets = [0]
     baseline = 0
     overline = 0
     x = 0
     for character in text:
         metrics = self.metadata.get(character)
         if metrics is None:
             continue
         if metrics["display"]:
             baseline = max(baseline, metrics["vbearing"])
             overline = max(overline, metrics["height"] - metrics["vbearing"])
         x += metrics['advance']
         offsets.append(x)
     surface = Surface.empty(offsets[-1], baseline + overline)
     x = 0
     for character in text:
         metrics = self.metadata.get(character)
         if metrics is None:
             continue
         if metrics["display"]:
             width = metrics["width"]
             height = metrics["height"]
             uv = metrics["uv"]
             glyph = self.surface.subsurface((
                 (uv["s"] * font_width,
                 uv["t"] * font_height),
                 (width,
                 height)
             ))
             surface(glyph, (
                 (x + metrics["hbearing"],
                 baseline - metrics["vbearing"]),
                 (width,
                 height)
             ))
         x += metrics['advance']
     mathline = self.calculate_mathline(baseline)
     return Label(surface.pys, offsets, baseline, mathline)