def open_visualisation(self, event):
     import Visualization
     # dlg = tk.Toplevel(self.master)
     r = tk.Tk()
     dialog = Visualization.Visualization(r)
     dialog.fill_combobox1()
     dialog.run()
示例#2
0
    def __import_fuel_map(self):

        user_settings = UserSettings()
        file_filter = 'Ascii file (*' + AsciiParser.FILE_EXT + ')'
        file, filt = QFileDialog.getOpenFileName(self, 'Open File', user_settings.working_dir, file_filter)

        if file:
            # FIXME: increase SIZE when there are lots of cells in fuel map and ignition

            qApp.setOverrideCursor(Qt.WaitCursor)

            try:
                new_editor = FuelMapViewer(self, file)

            except IndexError:

                qApp.restoreOverrideCursor()
                QMessageBox.information(self, "Invalid file", "A problem occurred while loading the fuel map. Please "
                                                              "verify that the fuel map does not contain non-integer "
                                                              "numbers")
                return

            if self._fl_map_editor:
                self._fl_map_editor.deleteLater()

            self._fl_map_editor = new_editor

            self._fl_map_editor.setEnabled(True)

            self.__setup_fl_map_lgnd()

            # Enable relevant widgets
            self.action_export_fuel_map.setEnabled(True)

            # This means that a DEM has already been loaded,
            # so the user can now convert to FDS file
            if self._ign_pt_editor:
                self.__init_sim_settings()
                self.action_create_environment.setEnabled(True)

                if self._visualization:
                    self._visualization.deleteLater()

                self._visualization = Visualization(self._fl_map_editor.parser(), self._ign_pt_editor.parser(), self)
                self._visualization.setEnabled(True)
                self._visualization.hide()

            # Set current tab to fuel type legend
            self._tab_widget.setCurrentIndex(1)

            self._fm_title_label.setText("Fuel Map Title: " + util.get_filename(file))

            # Tab index might not change, so __tab_changed will never get called
            self._fl_map_editor.show()
            qApp.restoreOverrideCursor()
示例#3
0
    def __import_dem(self):

        user_settings = UserSettings()
        file_filter = 'Ascii file (*' + AsciiParser.FILE_EXT + ')'
        file, filt = QFileDialog.getOpenFileName(self, 'Open File',
                                                 user_settings.working_dir,
                                                 file_filter)

        if file:

            qApp.setOverrideCursor(Qt.WaitCursor)

            if self._ign_pt_editor:
                self._ign_pt_editor.deleteLater()

            self._ign_pt_editor = IgnitionPointViewer(self, file)
            self._ign_pt_editor.setEnabled(True)

            self._setup_ign_pt_map_lgnd()

            # Enable relevant widgets
            self.action_export_dem.setEnabled(True)

            # This means that a fuel map has already been loaded,
            # so the user can now convert to FDS file
            if self._fl_map_editor:
                self.__init_sim_settings()
                self.action_create_environment.setEnabled(True)

                if self._visualization:
                    self._visualization.deleteLater()

                self._visualization = Visualization(
                    self._fl_map_editor.parser(), self._ign_pt_editor.parser(),
                    self)
                self._visualization.setEnabled(True)
                self._visualization.hide()

            # Set current tab to fuel type legend
            self._tab_widget.setCurrentIndex(2)

            self._dem_title_label.setText("DEM Title: " +
                                          util.get_filename(file))

            self._ign_pt_editor.show()
            qApp.restoreOverrideCursor()
示例#4
0
def auto(tiss, data="Female"):
    print('\n')
    segmentation, dico = getDSubstance(data, tiss)
    dicomdir = segmentation.dicomdir
    print('Dicom Dir : ', dicomdir)
    print('Initialize ImageDicom')
    image = segmentation.dicomimage
    if "box" in dico.keys():
        image.cropBoxImages(dico["box"]["dheight"], dico["box"]["drow"],
                            dico["box"]["dcolumn"])
        segmentation.data_dico[segmentation.name]["box"] = dico["box"]
        print("height :", image.height)
    segmentation.pipeline()
    print('Initialize Visualization')
    myMesh = Visualization(segmentation)
    myMesh.pipeline()
    print('Object Created')
    print('----------')
    print('\n')
示例#5
0
from Visualization import *
from defined_maps import *

tile_len = 50
speed = 10
ticks = 10

map, tasks, cars, spawn_points, cars_points, solver = get_scenario1(tile_len, speed)

vis = Visualization(map.to_bitman_objects(), tile_len, cars=cars, ticks=ticks, spawn_points=spawn_points,
                    cars_points=cars_points,
                    solver=solver)

vis.run()
示例#6
0
C.add_road('Lyon', 'Nantes')
C.add_road('Lyon', 'Aix')

C.add_road('Aix', 'Amiens')
C.add_road('Aix', 'Nantes')
C.add_road('Aix', 'Lyon')

C.add_road('Amiens', 'Aix')
C.add_road('Amiens', 'Lille')
C.add_road('Amiens', 'Nantes')

C.add_road('Lille', 'Amiens')
C.add_road('Lille', 'Paris')

C.add_road('Tour', 'Nantes')

C.add_road('Nantes', 'Paris')
C.add_road('Nantes', 'Tour')
C.add_road('Nantes', 'Lyon')
C.add_road('Nantes', 'Aix')
C.add_road('Nantes', 'Amiens')

C.add_road('Paris', 'Lille')
C.add_road('Paris', 'Nantes')

C.initialize()
#print(C)

window = Visualization(C)
window.mainloop()
示例#7
0
def run_visualization(currModel, show_simulation_dynamics = False):
    print "Setting up visualization..."
            
    morphology = currModel.get_reconstruction()

    # Prepare model coordinates for uploading to OpenGL.
    tempIndices = []
    tempVertices = []
    n_index = 0
    tempX = []
    tempY = []
    tempZ = []
    tempCol = []
    
    if not show_simulation_dynamics:
        print '''
        Soma - Red
        Axon - Green
        Dendrites - Blue
        Apical Dendrites - Purple'''
        
    # array of colors to denote individual compartment types
    compartmentColors=[[0.0,0.0,0.0,0.0], # padding for index convenience
                [1.0, 0.0, 0.0, 1.0], #1: soma - red
                [0.0, 1.0, 0.0, 1.0], #2: axon - green
                [0.0, 0.0, 1.0, 1.0], #3: dendrites - blue
                [1.0, 0.0, 1.0, 1.0]] #4: apical dendrites - purple
    color_dim = 4
    
    # used to set up section monitoring for visualization of dynamics
    compartmentNames=['none', # padding for index convenience
    'soma', #1: soma
    'axon', #2: axon
    'dend', #3: dendrites - blue
    'dend'] #4: apical dendrites - purple
    
    sectionIndices=[0,0,0,0,0]
    segmentsPerSection = {}
    sec_name = ''

    # initialize storage arrays for each vertex. 
    index = 0
    n_compartments = len(morphology.compartment_list)
    tempX = [0] * n_compartments
    tempY = [0] * n_compartments
    tempZ = [0] * n_compartments
    tempCol = [0] * n_compartments * color_dim
    
    for n in morphology.compartment_list:
        # add parent coords
        tempX[n['id']] = n['x']
        tempY[n['id']] = -n['y']
        tempZ[n['id']] = n['z']
        
        # add color data for parent
        col_i = 0
        offset = n['id']*color_dim
        for cval in compartmentColors[n['type']]:
            tempCol[offset+col_i] = cval
            col_i += 1
        
        # if at a branch point or an end of a section, set up a vector to monitor that segment's voltage
        type = compartmentNames[n['type']]
        sec_index = sectionIndices[n['type']]
        
        if not (len(morphology.children_of(n)) == 1): #either branch pt or end

            sec_name = type + '[' + str(sec_index) + ']'
            sectionIndices[n['type']] += 1
            
            currModel.monitor_section_voltage(type, sec_index)
            segmentsPerSection[sec_name] = 1
            
        else:
            segmentsPerSection[sec_name] += 1
        
        index += 1
                
        for c in morphology.children_of(n):
            
            # add child coods
            tempX[c['id']] = c['x']
            tempY[c['id']] = -c['y']
            tempZ[c['id']] = c['z']
            
            # add index data:
            # draw from parent to child, for each child
            tempIndices.append(n['id'])
            tempIndices.append(c['id'])
            index += 1

            # add color data for child
            col_i = 0
            offset = c['id']*color_dim
            for cval in compartmentColors[c['type']]:
                tempCol[offset+col_i] = cval
                col_i += 1
                
            segmentsPerSection[sec_name] += 1
        
    # get ranges for scaling
    maxX = max(tempX)
    maxY = max(tempY)
    maxZ = max(tempZ)
    minX = min(tempX)
    minY = min(tempY)
    minZ = min(tempZ)
    xHalfRange = (maxX - minX)/2.0
    yHalfRange = (maxY - minY)/2.0
    zHalfRange = (maxZ - minZ)/2.0
    longestDimLen = max(xHalfRange, yHalfRange, zHalfRange)
    
    # center coords about 0,0,0, with range -1 to 1
    tempX = [((((x-minX)*(2*xHalfRange))/(2*xHalfRange)) - xHalfRange)/longestDimLen for x in tempX]
    tempY = [((((y-minY)*(2*yHalfRange))/(2*yHalfRange)) - yHalfRange)/longestDimLen for y in tempY]
    tempZ = [((((z-minZ)*(2*zHalfRange))/(2*zHalfRange)) - zHalfRange)/longestDimLen for z in tempZ]
    
    # convert everything to a numpy array so OpenGL can use it
    indexData = np.array(tempIndices, dtype='uint16')
    vertexData = np.array([tempX,tempY,tempZ], dtype='float32')
    tempCol  = np.array(tempCol, dtype='float32')
    vertexData = np.append(vertexData.transpose().flatten(), tempCol)    
    #################### /Preparing Model Coords
    
    # Set up the Visualization instance
    n_vertices = len(tempX)
    currVis = Visualization(data=vertexData, indices=indexData, nVert=n_vertices, colorDim=color_dim)
    
    if show_simulation_dynamics:
        currModel.run_test_pulse(amp=0.25, delay=20.0, dur=20.0, tstop=60.0)
        #currModel.plot_output() # uncomment this line to display the somatic potential over time before the visualization begins
        
        sectionOutput = currModel.section_output
        n_segments = n_vertices
        
        # set up looping color change data
        all_voltages = []
        n_pts = len(sectionOutput['t'])
        
        for t in range(n_pts): # for each timepoint...
            for key in sectionOutput.keys(): # for each section...
                if key != 't':
                    for s in range(segmentsPerSection[key]): # for each segment...
                        all_voltages.append(sectionOutput[key][t]) # ...set up color for segment
                    
        all_voltages = np.array(all_voltages, dtype='float32')
        all_voltages -= min(all_voltages)
        all_voltages /= max(all_voltages)
        temp_col = []
        n_pts = 0
        for v in all_voltages:
            temp_col.append(v)
            temp_col.append(0.0)
            temp_col.append(1.0-v)
            temp_col.append(1.0)
            n_pts += 1
        voltage_col = np.array(temp_col, dtype='float32')
    
    
        currVis.change_color_loop(voltage_col, n_colors=n_segments, n_timepoints=n_pts, offset=0, rate=0.10)
    
    currVis.run()
def astar():

    h, w = 10, 10
    threshold = 0.5
    start_point = [5, 3, 0]
    goal_state = [9, 9]
    w1, w2 = 5, 10
    nodes = queue.PriorityQueue()
    init_node = Node(start_point, None, None, 0, None)
    nodes.put((init_node.getCost(), init_node))
    traversed_nodes = []

    obs = Obstacle(0.0)
    viz = Visualization(obs)

    fig, ax = plt.subplots(figsize=(10, 10))
    ax.set(xlim=(0, 10), ylim=(0, 10))
    ax = viz.addObstacles2Map(ax)
    ax.set_aspect("equal")

    goal_reached = False
    node_array = np.array([[[math.inf for k in range(360)]
                            for j in range(int(h / threshold))]
                           for i in range(int(w / threshold))])

    full_path = None
    goal_reached = False
    print('Finding path.........')

    while (not nodes.empty()):
        current_node = nodes.get()[1]
        traversed_nodes.append(current_node)

        if checkGoalReached(current_node, goal_state, 1):
            print('Goal reached')
            print("The cost of path: ", current_node.getCost())
            moves, node_path = current_node.getFullPath()

            visualize(viz, traversed_nodes, node_path)

            goal_reached = True

            fp = open('path_points.csv', 'w')
            fn = open('path_nodes.csv', 'w')
            fv = open('vel_points.csv', 'w')
            writer_p = csv.writer(fp)
            writer_n = csv.writer(fn)
            writer_v = csv.writer(fv)

            for move in moves:
                writer_v.writerow(move)

            for node in node_path:
                xi, yi, _ = node.getState()
                writer_n.writerow([xi, yi])

                points = node.getPathArray()
                if points is not None:
                    for point in points:
                        xn, yn = point
                        row = [xn, yn]
                        writer_p.writerow(row)
                        xi, yi = xn, yn
            fp.close()
            fv.close()
            fn.close()

        else:
            branches = getBranches(current_node, 1, w1, w2, obs)
            for branch_node in branches:
                branch_state = branch_node.getState()
                if checkVisited(branch_node,
                                node_array,
                                goal_state,
                                threshold=0.5):
                    node_array[int(halfRound(branch_state[0]) / threshold),
                               int(halfRound(branch_state[1]) / threshold),
                               branch_state[2]] = branch_node.getCost(
                               ) + computeHeuristicCost(
                                   branch_state, goal_state)
                    nodes.put((branch_node.getCost() +
                               computeHeuristicCost(branch_state, goal_state),
                               branch_node))
        if (goal_reached): break
示例#9
0
#!/usr/bin/env python3
# Final Project - Lichtenberg Figures

import numpy as np
import Configuration
import Visualization
import Pipeline

# Load configuration file.
configuration_info = Configuration.Configuration()

# Create spacing, needed for correct grid scale automatically.
x_points = np.linspace(0, 1, num=configuration_info.grid_resolution_x_points)
y_points = np.linspace(0, 1, num=configuration_info.grid_resolution_y_points)

# Calculate corresponding offset (needed so pixels are not truncated)
x_offset = x_points[1] / 2.0
y_offset = y_points[1] / 2.0

# Create a meshgrid.
xs, ys = np.meshgrid(x_points, y_points)

# Create a pipeline for performing steps and create initial points.
pipeline_process = Pipeline.Pipeline(configuration_info)

# Create animation.
visualizer = Visualization.Visualization(x_offset, y_offset,
                                         configuration_info, pipeline_process)
visualizer.create_animation()
    def populateArgWithCellIndexHandler(self, argIdx=0):
        def cellIndexHandler(event):
            can = self.app.canvas
            if event.widget is can:
                for item in can.find_closest(can.canvasx(event.x),
                                             can.canvasy(event.y)):
                    if item in self.indices:
                        self.app.setArgument(
                            self.app.canvas_itemConfig(item, 'text'), argIdx)

        return cellIndexHandler


if __name__ == '__main__':
    from drawnValue import *
    app = Visualization(title='Table test', canvasBounds=(0, 0, 800, 400))

    app.setArgument = lambda arg, argIndex: print('Set argument', argIndex,
                                                  'to {!r}'.format(arg))

    app.startAnimations()
    table1 = Table(
        app, (100, 50),
        'foo',
        'bar',
        label='Foo bar',
        vertical=True,
        indicesFont=('Courier', -14),
        see=True,
        cellHeight=30,
        cellBorderWidth=4,
if __name__ == '__main__':
    from drawnValue import *
    import random, sys, argparse

    parser = argparse.ArgumentParser(
        description='Test ' + __file__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('label', nargs='*', help='Label(s) to draw.')
    parser.add_argument('-s',
                        '--sleep-time',
                        default=0.01,
                        type=float,
                        help='Sleep time for animation.')
    args = parser.parse_args()

    app = Visualization(title='OutputBox test', canvasBounds=(0, 0, 800, 400))

    app.startAnimations()
    width, height = 140, 25
    outbox1 = OutputBox(
        app, (400 - width // 2 - 5, 190, 400 + width // 2 + 5, 190 + height),
        label='Output Item')
    print('Output box 1: {}', outbox1)
    app.wait(1)
    toAdd = 'Item'
    print('Append {!r} to output box 1'.format(toAdd))
    outbox1.appendText(toAdd)
    app.wait(1)

    dataItems = []
    dy = height // 4
示例#12
0
from Visualization import *

if __name__ == '__main__':
    app = Visualization(title='Font Scaling')
    for size in range(20, 0, -1):
        for x, face in enumerate(('Helvetica', 'Courier')):
            font = (face, -size)
            ds = 4
            y0 = (size + ds) * (size + ds) // 2
            x0 = 50 + x * 300
            app.canvas.create_text(
                x0,
                y0,
                text=str(font),
                anchor=NW,
                font=font,
                fill=app.VALUE_COLOR if x == 0 else app.VARIABLE_COLOR)
            dx = 5
            app.canvas.create_rectangle(x0 - size - dx,
                                        y0,
                                        x0 - dx,
                                        y0 + size,
                                        fill='blue' if x == 0 else 'red',
                                        width=0)

    app.runVisualization()
示例#13
0
import numpy as np
import matplotlib.pyplot as plt
import math
import pandas as pd
import Visualization as vis

VIS = vis.Visualization()
VIS.call_simulation()
示例#14
0
def resetGame(back, front):
    back.resetBoard()
    front.board.replace_board(np.rot90(np.array(back.grid), 3))
    front.board.current_player = random.randint(1, 2)


#Plays move for front and backend
def playMove(player, col):
    backEnd.submitMove(col, player)


if __name__ == "__main__":
    width = 7
    height = 6
    backEnd = Game(width, height)
    frontEnd = Visualization(500, 500)
    frontEnd.board = Board(width, height)
    frontEnd.board.current_player = random.randint(1, 2)

    # Computer == turn 1

    while True:
        #Press Left Arrow Key to exit game
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            exit()

        if frontEnd.board.current_player == 1:
            #Computer makes a move
            time.sleep(.7)
            column_to_place = random.choice(backEnd.getLegalMoves())