def __init__(self): super().__init__() pygame.init() pygame.display.set_caption("ControlGUI(UWU") self.screen_width = 400 self.screen_height = 300 self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height)) self.clock = pygame.time.Clock() self.plot = Plot(self.screen, 400, 300) self.movement = [0 for i in range(6)] self.power = [0 for i in range(6)] self.profile = -1 self.widgets = [] self.widgets.append((ProfilePopup(self.screen_width, self.screen_height), (0, 0))) self.widgets.append((EMPopup(self.screen_width, self.screen_height, 1), (0, 0))) self.widgets.append((EMPopup(self.screen_width, self.screen_height, 2), (0, 0))) self.widgets.append((InvertPopup(self.screen_width, self.screen_height), (0, 0))) self.charts = [] self.charts.append( (Plot(['strafe', 'drive', 'yaw', 'ud', 'tilt', 'zero'], self.screen_width, self.screen_height), (0, 0), 0)) self.charts.append( (Plot(['FL', 'FR', 'BL', 'BR', 'TL', 'TR'], self.screen_width, self.screen_height), (self.screen_width / 2, 0), 1))
def save_all_airfoil_spm_geometry_test(): """ This test saves all airfoil images to the given directory. """ # Write your own path with airfoil data here airfoil_path = r'C:\Users\User\Documents\python\aero\airfoils_data' # Write your own path to save images here (Path must already exists) picture_path = r'C:\Users\User\Documents\python\aero\airfoils_picture' files = listdir(airfoil_path) for i, file in enumerate(files): airfoil = figure.Airfoil(file, airfoil_path) geometry = Geometry(airfoil) # Create grid x0, y0, dx, dy = airfoil.rect grid = figure.Grid(x0, y0, dx + 0.2, dy + 0.5) # Plot plt = Plot(grid) plt.plot_figure(airfoil) plt.plot_source_panel_method(geometry) plt.title(file) plt.save_image('{}\\{}.png'.format(picture_path, file)) plt.close() print(i, file)
def spm_geometry_and_inside_outside_test(): # # Write your own path here # path = r'C:\Users\User\Documents\python\aero\airfoils_data' # # Airfoil name # name = 'ua79sff.txt' # test_fig = figure.Airfoil(name, path) test_fig = figure.Circle(10, num_points=20) # test_fig = figure.Ellipse(10, 5, num_points=50) # test_fig = figure.Square(10, num_points=50) # test_fig = figure.Rectangle(10, 5, num_points=50) # test_fig = figure.Triangle((0, 0), (6, 0), (3, 3)) # test_fig = figure.Triangle((0, 0), (0, 6), (3, 3)) # test_fig = figure.Triangle((0, 0), (6, 3), (3, 4)) # test_fig = figure.Polygon('Polygon', # [(1, 1), (2, 2), (3, 3), # (2, 3), (2, 4), (1, 4), (0, 3)]) # test_fig = figure.Ogive(2, 1, 5) geometry = Geometry(test_fig, 1) x0, y0, dx, dy = test_fig.rect grid = figure.Grid(x0, y0, 1.5 * dx, 1.5 * dy, 20) plt = Plot(grid) plt.plot_figure(test_fig) plt.plot_source_panel_method(geometry) for x in grid.x: for y in grid.y: res = test_fig.is_inside(x, y) if not res: plt.plot_point(x, y, '.y') plt.show()
def set_source(self, source, nodes=None): """ Handles opening a new file. Creates a plot with the given source file. Uses input plugins to convert file to SVG. This disregards all previous settings, thus ui_updates should be called. """ height = self.material.length and self.material.length * UNITS[ self.units] or None p = Plot(width=self.material.width * UNITS[self.units], height=height, color=self.material.color) m = self.material.margin p.set_padding(top=m[0], right=m[1], bottom=m[2], left=m[3]) if type(source) == etree._ElementTree: try: # If certain nodes are selected, only plot them. if nodes: xml = etree.tostring(get_selected_nodes(source, nodes)) else: xml = etree.tostring(source) # Set a job name if none exists if self.name is None: self.name = "*inkscape.svg" # Try to make a plot p.set_graphic(xml) self.plot = p except (IOError, etree.XMLSyntaxError), trace: log.debug(trace) raise Exception( "Failed to create plot. Reason: Failed to import the Inkscape file." )
def PlantResults(): global plantS plantS = simulate(1000) TakeOff(plantS) Climb(plantS, v1=16, desiredCR=1, desiredHeight=100) Climb(plantS, v1=16, desiredCR=3, desiredHeight=200) Cruise(plantS, v1=18, distance=2000) plantS.CalculateE() Plot(plantS, 'x2', 'v1v2', 'energy', 'power', 'speed', 'soc', 'thrust', 'pitch', 'plant', 'iceeff', markers=False, save=True, title=False, direct='simulationPics/plantResults/')
def main(): # Load dataset data = datasets.load_iris() X = normalize(data.data[data.target != 0]) y = data.target[data.target != 0] y[y == 1] = 0 y[y == 2] = 1 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, seed=1) clf = LogisticRegression(gradient_descent=True) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) # Reduce dimension to two using PCA and plot the results Plot().plot_in_2d(X_test, y_pred, title="Logistic Regression", accuracy=accuracy)
def __init__(self, port, baudrate, tag, buffer_len): self.plot = Plot() self.reader = Reader(port, baudrate, len(tag)+buffer_len) self.reader.register_tag_listener(tag, buffer_len, self.process_flydata) self.reader.start()
def evaluate(self): score = self.model.evaluate(self.testset[0], self.testset[1], verbose=0) print('Test Accuracy: ', score[1]) figure = Plot(self.loss_hist) figure.show_loss()
def beam_pattern_cartesian_multi_freq(self, save_fig=False): ''' Plot Array Response including several Frequencies and Azimuth Angle infomation ''' title = '{}_{}'.format('Beampattern_CartersianMultiFreq', self.beam_label) if save_fig: fig_name = self._set_fig_name(title) else: fig_name = None #frequency to plot freq_range = constants.get('freq_range_small') angle_range = np.degrees(constants.get('angle_range')) y_lim_lower = [] plot = Plot() plot.append_axes() for freq in freq_range: response_freq = self.beam_pattern(freq) y_lim_lower.append(np.min(response_freq)) plot.plot_vector(response_freq, angle_range, label='{} kHz'.format(freq / 1000)) y_lim_lower = np.maximum(-70, np.min(y_lim_lower)) plot.set_pipeline(title=title, ylim=(y_lim_lower, 1), xlim=(0, 180), legend='lower right', xlabel='Azimuth Angle[Deg]', ylabel='Beampattern[dB]', fig_name=fig_name)
def test03(): """ Constant Anisotropy """ print('Test 3:') # Mesh mesh = Mesh.newmesh([0, 20, 0, 20], grid_size=(40, 40)) mesh.refine() element = QuadFE(2, 'Q1') system = System(mesh, element) gma = 1 bta = 8 tht = np.pi / 4 v = np.array([np.cos(tht), np.sin(tht)]) H = gma * np.eye(2, 2) + bta * np.outer(v, v) Z = 10 * np.random.normal(size=system.n_dofs()) # Bilinear forms bf = [(1,'u','v'), \ (H[0,0],'ux','vx'), (H[0,1],'uy','vx'),\ (H[1,0],'ux','vy'), (H[1,1],'uy','vy')] A = system.assemble(bilinear_forms=bf, linear_forms=None) M = system.assemble(bilinear_forms=[(1, 'u', 'v')]) m_lumped = np.array(M.sum(axis=1)).squeeze() X = spla.spsolve(A.tocsc(), np.sqrt(m_lumped) * Z) fig, ax = plt.subplots() plot = Plot() ax = plot.contour(ax, fig, X, mesh, element, resolution=(200, 200)) plt.show()
def test02(): """ Spatially varying anisotropy """ print('Test 2:') grid = Grid(box=[0, 20, 0, 20], resolution=(100, 100)) mesh = Mesh(grid=grid) element = QuadFE(2, 'Q1') system = System(mesh, element) alph = 2 kppa = 1 # Symmetric tensor gma T + bta* vv^T gma = 0.1 bta = 25 v2 = lambda x, y: -0.75 * np.cos(np.pi * x / 10) v1 = lambda x, y: 0.25 * np.sin(np.pi * y / 10) h11 = lambda x, y: gma + v1(x, y) * v1(x, y) h12 = lambda x, y: v1(x, y) * v2(x, y) h22 = lambda x, y: v2(x, y) * v2(x, y) X = Gmrf.from_matern_pde(alph, kppa, mesh, element, tau=(h11, h12, h22)) x = X.sample(1).ravel() fig, ax = plt.subplots() plot = Plot() ax = plot.contour(ax, fig, x, mesh, element, resolution=(200, 200)) plt.show()
def add_static_image(self,name,file_path): """ Construct a static image Plot (e.g. a color key for an Orientation Preference map). """ image = Image.open(resolve_path(file_path)) plot = Plot(image,name=name) self._static_plots.append(plot)
def train(self, epochs=500, batch=16): figure = Plot() fix_noise = np.random.normal(0, 5, (batch, 125, 1)) for i in range(epochs): # train discriminator random_index = np.random.randint(0, len(self.Xtrain), size=batch) gt_data = self.Xtrain[random_index] gen_noise = np.random.normal(0, 5, (batch, 125, 1)) fake_data = self.G.predict(gen_noise) x_combined_batch = np.concatenate((gt_data, fake_data)) y_combined_batch = np.concatenate((np.ones( (batch, 1)), np.zeros((batch, 1)))) d_loss = self.D.train_on_batch(x_combined_batch, y_combined_batch) # train generator noise = np.random.normal(0, 5, (batch, 125, 1)) y_gen_label = np.ones((batch, 1)) g_loss = self.G_and_D.train_on_batch(noise, y_gen_label) print( 'epoch: %d, [Discriminator :: d_loss: %f], [ Generator :: loss: %f]' % (i, d_loss, g_loss)) if i % 100 == 0: figure.show_dataset(self.G.predict(fix_noise))
def uncertainty_analysis(self): female, relation, f = self.sensitivity_analysis_detect_intervals( [15, 40, 90]) values = {} for year in range(2001, 2100): values[year] = [] for i in range(1000): self.female_factor_by_year = random.uniform( female['min'], female['max']) self.female_factor['male'] = random.uniform( relation['min'], relation['max']) self.factors_by_year[15] = random.uniform(f[15]['min'], f[15]['max']) self.factors_by_year[40] = random.uniform(f[40]['min'], f[40]['max']) self.factors_by_year[90] = random.uniform(f[90]['min'], f[90]['max']) data = {} self.modeling_by_1(data) for year in range(2001, 2100): s = sum( map(lambda kv: union_count_genders(kv[1]), self.interval_prediction[year].items())) values[year].append(s) plot = Plot(main) plot.set_labels('Анализ неопределенности', 'Год', 'Популяция') plot.draw_uncertainty_analysis(values)
def main(): print("-- XGBoost --") data = datasets.load_iris() X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, seed=2) clf = XGBoost() clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) Plot().plot_in_2d(X_test, y_pred, title="XGBoost", accuracy=accuracy, legend_labels=data.target_names)
def main(): data = CollectData('192.168.1.69', 'AC:75:1D:57:8A:D8') regression = Regression() value = input('Would you like to collect data? [y/n] ') n = 0 while (value == 'y' and n < 6): # collect data foreach distance val = data.collect() # call AddRSSI of regression regression.addRSSI(val) print(regression._RSSIAritmetica) print(regression._RSSIQuadratica) value = input('Would you like to collect data?[y/n] ').strip( '\r').strip('\n') n += 1 # call regression result = regression.linearRegression() print(result) # plot line above point with data gave from regression p1 = Plot('DEVICE', '-log10(distance)', 'RSSI') p1.pointsAndLine(regression.getLog10Distance(), regression.getRSSIAritmetica(), -1, 1, 100, result['arithmeticK'], result['arithmeticA'])
def test_constructor(self): # # Define mesh, element, and dofhandler # mesh = QuadMesh(box=[0, 20, 0, 20], resolution=(20, 20), periodic={0, 1}) dim = mesh.dim() element = QuadFE(dim, 'Q2') dofhandler = DofHandler(mesh, element) dofhandler.distribute_dofs() basis = Basis(dofhandler, 'u') alph = 2 kppa = 1 # Symmetric tensor gma T + bta* vv^T gma = 0.1 bta = 25 p = lambda x: 10/np.pi*(0.75*np.sin(np.pi*x[:,0]/10)+\ 0.25*np.sin(np.pi*x[:,1]/10)) f = Nodal(f=p, basis=basis) fx = f.differentiate((1, 0)) fy = f.differentiate((1, 1)) #plot.contour(f) x = np.linspace(0, 20, 12) X, Y = np.meshgrid(x, x) xy = np.array([X.ravel(), Y.ravel()]).T U = fx.eval(xy).reshape(X.shape) V = fy.eval(xy).reshape(X.shape) v1 = lambda x: -0.25 * np.cos(np.pi * x[:, 1] / 10) v2 = lambda x: 0.75 * np.cos(np.pi * x[:, 0] / 10) U = v1(xy).reshape(X.shape) V = v2(xy).reshape(X.shape) #plt.quiver(X,Y, U, V) #plt.show() h11 = Explicit(lambda x: gma + bta * v1(x) * v1(x), dim=2) h12 = Explicit(lambda x: bta * v1(x) * v2(x), dim=2) h22 = Explicit(lambda x: gma + bta * v2(x) * v2(x), dim=2) tau = (h11, h12, h22) #tau = (Constant(2), Constant(1), Constant(1)) # # Define default elliptic field # u = EllipticField(dofhandler, kappa=1, tau=tau, gamma=2) Q = u.precision() v = Nodal(data=u.sample(mode='precision', decomposition='chol'), basis=basis) plot = Plot(20) plot.contour(v)
def __init__(self, main): super(Plugin, self).__init__("Stack Of Tasks plugin", main) self.setObjectName("Stack Of Tasks plugin") self.main = main self.graph = Graph(self) self.plot = Plot(self) self.tabWidget = QtGui.QTabWidget(self) self.setWidget(self.tabWidget) self.tabWidget.addTab(self.graph.view, "SoT graph") self.tabWidget.addTab(self.plot, "Plot") toolBar = QtGui.QToolBar("SoT buttons") toolBar.addAction(QtGui.QIcon.fromTheme("view-refresh"), "Create entire graph", self.graph.createAllGraph) toolBar.addSeparator() toolBar.addAction(QtGui.QIcon.fromTheme("zoom-fit-best"), "Zoom fit best", self.plot.zoomFitBest) toolBar.addAction(QtGui.QIcon.fromTheme("media-playback-stop"), "Stop fetching data", self.stopAnimation) toolBar.addSeparator() toolBar.addAction(QtGui.QIcon.fromTheme("window-new"), "Create viewer", self.createRobotView) toolBar.addSeparator() toolBar.addAction(QtGui.QIcon.fromTheme("view-filter"), "Set entity filter by name", self.entityFilterByName) main.addToolBar(toolBar) self.displaySignals = [] self.hookRegistered = False self.displaySignalValuesStarted = False
def beam_pattern_heatmap(self, save_fig=False): ''' Plot heatmap of Array Response including all Frequency and Azimuth Angle infomation ''' title = '{}_{}'.format('Beampattern_Heatmap', self.beam_label) if save_fig: fig_name = self._set_fig_name(title) else: fig_name = None freq = np.linspace(8000, 1, num=800, endpoint=True) response_matrix = np.zeros( (len(freq), len(constants.get('angle_range')))) for index, f in enumerate(freq): response_matrix[index:] = self.beam_pattern(f) #plot xticks = np.arange(0, len(constants.get('angle_range')), 60) yticks = np.arange(0, 900, 100) xticklabels = np.arange( 0, len(constants.get('angle_range')), 60, dtype=int) / 2.0 yticklabels = np.linspace(8, 0, num=9, endpoint=True, dtype=int) plot = Plot() plot.append_axes() plot.plot_heatmap(response_matrix) plot.set_pipeline(title=title, xticks=xticks, yticks=yticks, xticklabels=[int(tick) for tick in xticklabels], yticklabels=yticklabels, xlabel='Azimuth Angle[Deg]', ylabel='Freq[kHz]', fig_name=fig_name)
def set_up_plot(self, settings=None): self.plot = Plot() if settings is not None: for key in settings: self.plot.settings[key] = settings[key] self.settings['plot'] = self.plot.settings n_rows = self.plot.settings['n_rows'] n_cols = self.plot.settings['n_cols'] if n_rows is not None and n_cols is not None: print '\nSetting up {0:d}x{1:d} plot.'.format(n_rows, n_cols) else: e_str = 'Number of {0:s} must be an integer > 0.' n_rows, n_cols = (0, 0) while n_rows < 1 or n_cols < 1: n_rows = utils.get_input_integer( \ '\nNumber of subplot rows?\n> ', error_text=e_str.format('rows'))[0] n_cols = utils.get_input_integer( \ 'Number of subplot columns?\n> ', error_text=e_str.format('columns'))[0] if n_rows < 1 or n_cols < 1: print 'Must have > 0 rows and columns.' self.plot.set_up_plot_grid(n_rows, n_cols) #self.plot.plot_grid.tight_layout(self.plot.figure) self.plot.figure.set_tight_layout(True) plt.show(block=False) print '(If you cannot see the plot, try changing the ' print 'matplotlib backend. Current backend is ' + \ plt.get_backend() + '.)'
def heatmap_beam_pattern(self, save_fig=True): ''' beampattern heatmap only available for frequency domain beamforming case : draw beampatten for heatmap. There will be as many subplots as beamforming numbers. ''' if self._beamforming_cout == 0: raise ValueError( 'No beamforming to analysis! Please append one firstly!') beamforming_dict = self._beamforming_list[0] if beamforming_dict.get('beam_domain') == 'time': raise ValueError( 'Time domain beamforming donnot support heatmap plot!') print('This may take a few seconds. Please wating...') figsize = (10, 5) if self._beamforming_cout == 1 else ( 10, 3 * self._beamforming_cout) plot = Plot(figsize=figsize, subplot_rows=self._beamforming_cout) plot.append_axes_combo() xticks = np.arange(0, len(constants.get('angle_range')), 60) yticks = np.arange(0, 900, 100) xticklabels = np.arange( 0, len(constants.get('angle_range')), 60, dtype=int) / 2.0 yticklabels = np.linspace(8, 0, num=9, endpoint=True, dtype=int) freq_range = np.linspace(8000, 1, num=800, endpoint=True) for beam_index, beam in enumerate(self._beamforming_list): response_matrix = np.zeros( (len(freq_range), len(constants.get('angle_range')))) for freq_index, freq in enumerate(freq_range): response_matrix[freq_index:] = beam[ 'beam_instance'].beam_pattern(freq) plot.plot_heatmap(response_matrix, label_pad=-65, subplot_index=beam_index) plot.set_pipeline(title=beam['beam_instance'].beam_label, xticks=xticks, yticks=yticks, xticklabels=[int(tick) for tick in xticklabels], yticklabels=yticklabels, xlabel='Azimuth Angle[Deg]', ylabel='Freq[kHz]', wait_for_user=False, subplot_index=beam_index) if self._beamforming_cout > 1: plot.suptitle( 'Beampattern Heatmap Compare for Different Beamforming', hspace=0.5) if save_fig: fig_name = self.fig_name('Beampattern_Heatmap') plot.save_figure(fig_name) plot.wait_for_user()
def plotSizes(self): """Generates a plot of the size of a data structure without actually performing the operations themselves. Since the operations in bm_length may alter the data structure size significantly, all operations that are benchmarked will be simulated, and the median data structure size will be used for each plot point.""" # Convenience lambda. op = lambda x: self.operations[x][0] size = 0 plot = Plot() # Do operations until bm_start. for i in range(self.bm_start): size += MixedSIDBenchmarkPlot._simOp(op(i)) # Now plot points until we run out of road. current_benchmark = self.bm_start while current_benchmark < len(self.operations): # Very first thing: establish the next benchmark and the end of the current benchmark, since we'll need # both of these in various places. next_benchmark = min(len(self.operations), current_benchmark + self.bm_interval) end_of_benchmark = min(len(self.operations), current_benchmark + self.bm_length) # We're at a plot point, so gather all the data structure sizes and plot the median value. # We'll do the first by hand, then we can loop through easily. bm_sizes = [ size + MixedSIDBenchmarkPlot._simOp(op(current_benchmark)) ] # Now we'll loop through the rest. # Bounds explained: # start at current_benchmark + 1 because we just did current_benchmark. # End (exclusive of the end) at current_benchmark + bm_length (i.e. the last item being benchmarked), # unless that exceeds the operations list, in which case, terminate after the last operation. for index in range(current_benchmark + 1, end_of_benchmark): bm_sizes.append(bm_sizes[-1] + MixedSIDBenchmarkPlot._simOp(op(index))) index += 1 # Now we'll plot the median value plot.plotPoint(current_benchmark, statistics.median(bm_sizes)) # Having finished the benchmark, we'll simulate operations up to the next benchmark, then loop. # First, a bit of clean-up. size = bm_sizes[-1] # Now, we'll simply loop, adjusting sizes. for index in range(end_of_benchmark, next_benchmark): size += MixedSIDBenchmarkPlot._simOp(op(index)) # Finally, we're at the next benchmark, so update current_benchmark and loop. current_benchmark = next_benchmark return plot
def DropandHover(): global s PP = GetParams()[1] s = simulate(500) initialHeight = 500 s.y0 = [0, initialHeight, 0, 0] s.x2[s.n] = initialHeight s.pitch[s.n] = 90 s.pitchShape = 'const' s.pitchCeiling = 90 # make the aircraft mass lower because the powerplant is not enough to # make the full aircraft hover s.totalMass = 4 weight = s.totalMass * AC['g'] s.TShape = 'sigmoid' s.TFloor = 0 s.TCeiling = weight s.TStart = 0 s.TEnd = 50 s.runtime = 200 s.steps = 200 s.RunInterval() Plot(s, 'thrust', 'pitch', 'x2', 'v2', save=True, title=False, direct='simulationPics/hover/') Fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(s.timeArray[:s.n], s.x2[:s.n], label='Height') ax2.plot(s.timeArray[:s.n], s.v2[:s.n], 'r', label='V2') ax1.yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.set_xlabel('time (seconds)') ax1.set_ylabel('AGL (m)') ax2.set_ylabel('velocity (m/s)') ax2.legend(lines + lines2, labels + labels2, loc=0) plt.tight_layout() plt.savefig('simulationPics/hover/x2v2.png') plt.show()
def __init__(self): self.feature_length = 6 self.label_length = 4 self.cost_plot = Plot([], 'Step', 'Cost') self.accuracy_plot = Plot([], 'Step', 'Accuracy') self.checkpoint = 'data/Checkpoints/turn_based_ai.ckpt' self.X = tf.placeholder(tf.float32, [None, self.feature_length]) self.Y = tf.placeholder(tf.float32, [None, self.label_length]) self.model = Model(self.X, self.Y) self.global_step = 0 self.training_data_x = np.empty((0, self.feature_length)) self.training_data_y = np.empty((0, self.label_length)) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def main(): '''The main Program runs the Data and Plot objects to read and plot the data from the radiosonde.''' dat = Data('dats') pl = Plot(dat) pl.plot()
def __init__(self): self.root = tk.Tk() self.model = Model() self.view = View(self.root, self.model, self) self.popup = Popup(self.model) self.plot = Plot(self.model) self.config = configparser.ConfigParser() self.config.read("config.ini")
def temperaturePlot(cities: hug.types.delimited_list(",")): """Rysuje prognozę temperatury dla danych miast""" client = Client(cities) data = client.fetch() adapter = DataAdapter(data) forecasts = adapter.adapt() citiesPlot = Plot(forecasts).plot() return citiesPlot
def move(self, di, dj): "move the Protagonist and interact with other Items and Characters" temp_i = self._i + di temp_j = self._j + dj self._floor = self._tower.current attempt = self._floor.get_floor(temp_i, temp_j) if attempt and not isinstance(attempt, str): print(attempt.get_value('name')) self._moved = False self._interacted = False self._case = False if isinstance(attempt, Trigger): self._case = attempt.get_value('case') # print(attempt.__dict__) attempt = eval( type(ele_lib.LIB[attempt.get_value('obj')]).__name__ + '(temp_i, temp_j, attempt._obj, self._floor)') if attempt and not isinstance(attempt, str): attempt.interact(self) else: self._moved = True if not self.get_value('magic_defense') and self._floor.num > 40: for (i, j) in [(0, 1), (1, 0), (0, -1), (-1, 0)]: test = self._floor.get_floor(temp_i + i, temp_j + j) if test and not isinstance(test, str): if 'pri_witch' in test.get_value('name'): self.add_value('hp', -100) elif 'pro_witch' in test.get_value('name'): self.add_value('hp', -200) elif 'magic_guard' in test.get_value('name'): oppo_test = self._floor.get_floor( temp_i - i, temp_j - j) if oppo_test and not isinstance(oppo_test, str) \ and 'magic_guard' in oppo_test.get_value('name'): self.set_value('hp', self.get_value('hp') // 2) break if self._moved and 0 <= temp_i < 11 and 0 <= temp_j < 11: self._i, self._j = temp_i, temp_j if self._interacted: self._floor.del_floor(self._i, self._j) if self._case: if self._floor.num == 3: self._floor = self._tower.previous_floor() self.move_to(2, 7) self._hp = 400 self._attack = 10 self._defense = 10 else: Plot(self._floor, self._case, self)
def __init__(self, **kwargs): # Initialize self.Fixed (subset of self.Prognostic which will NOT be time-marched) if 'Fixed' in kwargs: self.Fixed = kwargs.pop('Fixed') else: self.Fixed = [] # Initialize I/O self.Io = IO(self, **kwargs) # Get values from restart file, if available if 'RestartFile' in kwargs: ParamNames = Parameters().value.keys() FieldNames = self.Required kwargs = self.Io.readRestart(FieldNames, ParamNames, kwargs) # Initialize scalar parameters self.Params = Parameters(**kwargs) # Frequency with which compute() will be executed if 'UpdateFreq' in kwargs: self.UpdateFreq = kwargs.pop('UpdateFreq') else: self.UpdateFreq = self.Params['dt'] # Initialize State self.State = State(self, **kwargs) self.Grid = self.State.Grid # Dictionary to hold increments on prognos fields self.Inc = {} # Initialize diagnostics self.compute(ForcedCompute=True) # Create output file self.Io.createOutputFile(self.State, self.Params.value) # Write out initial state if not self.Io.Appending: self.write() # Initialize plotting facilities self.Plot = Plot() # Initialize runtime monitor self.Monitor = Monitor(self, **kwargs) # Notify user of unused input quantities self._checkUnused(kwargs) # Set some redundant attributes (mainly for backward compatibility) self.nlon = self.Grid['nlon'] self.nlat = self.Grid['nlat'] self.nlev = self.Grid['nlev'] try: self.o3 = self.State['o3'] except: pass
def __init__(self): db = dbops plot = Plot() self.report1 = Report1DataGetter(db, plot) self.report2 = Report2DataGetter(db, plot) self.report3 = Report3DataGetter(db, plot) self.report4 = Report4DataGetter(db, plot) self.report5 = Report5DataGetter(db, plot) self.report6 = Report6DataGetter(db, plot)