def main(args): # Get current observer location and antenna pointing direction if args.use_config: config = read_config() lat, lon = config['latitude'], config['longitude'] alt, az = config['altitude'], config['azimuth'] if "none" in (lat, lon, alt, az): print('Please check your config file or use command line arguments.') quit() else: lat, lon = args.latitude, args.longitude alt, az = args.altitude, args.azimuth # Get current equatorial and galactic coordinates of antenna RA and Declination Coordinates_class = Coordinates(lat = lat, lon = lon, alt = alt, az = az) ra, dec = Coordinates_class.equatorial() gal_lat, gal_lon = Coordinates_class.galactic() # Receives and writes data Receiver_class = Receiver(frequency = args.frequency, sample_rate = args.sample_rate, ppm = args.ppm, resolution = args.resolution, num_FFT = args.num_FFT) freqs, data, SNR = Receiver_class.receive() # Plots data print('Plotting data...') name = f'ra={ra},dec={dec},SNR={SNR}' Plot_class = Plot() Plot_class.plot(freqs = freqs, data = data, name = name)
def plot_log(file, nodes, edges, arcs={}): res = {} res["nodes"] = nodes.copy() res["segments"] = edges.copy() res["arcs"] = copy.deepcopy(arcs) plot = Plot(res) plot.plot() plot.show()
def autoscale(self): """Autoscale now the Heroku App. This method gonna check the response time through Pingdom API, and adapt the number of dynos according to it. If the measured response time is below the response time low score defined in the HAConf object, the Heroku app will be scaled up. If the measured response time is over the response time high score defined in the HAConf object, the Heroku app will be scaled down. If the measured response time is between the response time low score and the response time high score : - If the tendency of the response times is strongly rising: the Heroku app will be scaled up - If the tendency of the response times is strongly down: the Heroku app will be scaled down """ self._log("----> Start autoscale...") end = datetime.utcnow() end_time = int(time.mktime(end.timetuple())) begin = end - timedelta(minutes = self._conf.getPingdomCheckPeriod()) begin_time = int(time.mktime(begin.timetuple())) self._log("Pingdom period to request: Begin: {0}, End: {1}".format(begin.isoformat(), end.isoformat())) checks = self._pd_wrapper.getChecks(self._conf.getPingdomCheckId(), begin_time, end_time) rep_time_avg = getResponseTimeAvg(checks) self._log("Avg resp time: {0}".format(rep_time_avg)) t = datetime.now() reg_coef = computeLinearRegressionModel(checks) self._log("Linear regression: y' = a * x + b with a = {0}, b = {1}".format(reg_coef[0], reg_coef[1])) if(rep_time_avg < self._conf.getResponseTimeLow()): if(reg_coef[0] < 0): self._removeDyno() settlement = "Revove dyno" else: self._log("===> Do nothing...") settlement = "Do nothing" elif(rep_time_avg >= self._conf.getResponseTimeLow() and rep_time_avg < self._conf.getResponseTimeHigh()): if(reg_coef[0] > self._conf.getResponseTimeTrendHigh()): self._addDyno() settlement = "Add dyno" elif(reg_coef[0] < self._conf.getResponseTimeTrendLow()): self._removeDyno() settlement = "Revove dyno" else: self._log("===> Do nothing...") settlement = "Do nothing" else: if(reg_coef[0] > 0): self._addDyno() settlement = "Add dyno" else: self._log("===> Do nothing...") settlement = "Do nothing" if(self._conf.isPlotting()): Plot.plot(checks, rep_time_avg, reg_coef, self._conf.getResponseTimeLow(), self._conf.getResponseTimeHigh(), settlement, self._conf.getGraphsFolder() + '/' + t.strftime("%d-%m-%Y_%H-%M-%S") + "_out.pdf", "pdf")
def main(args): config = read_config() # Get y-axis limits from config low_y, high_y = config['low_y'], config['high_y'] # Get current observer location and antenna pointing direction if args.use_config: lat, lon = config['latitude'], config['longitude'] alt, az = config['altitude'], config['azimuth'] if "none" in (lat, lon, alt, az): print('Please check your config file or use command line arguments.') quit() else: lat, lon = args.latitude, args.longitude alt, az = args.altitude, args.azimuth # Checks if 360 is divisable with the degree interval and calculates number of collections num_data = 360/args.interval if args.interval != 0 else 0 second_interval = 24*60**2/num_data if num_data > 0 else None if float(num_data).is_integer(): for i in range(int(num_data)+1): current_time = datetime.utcnow() if num_data != 0: end_time = current_time + timedelta(seconds = second_interval) # Get current equatorial and galactic coordinates of antenna RA and Declination Coordinates_class = Coordinates(lat = lat, lon = lon, alt = alt, az = az) ra, dec = Coordinates_class.equatorial() gal_lat, gal_lon = Coordinates_class.galactic() galactic_velocity = Coordinates_class.galactic_velocity(gal_lat, gal_lon) # Receives and writes data Receiver_class = Receiver(sample_rate = args.sample_rate, ppm = args.ppm, resolution = args.resolution, num_FFT = args.num_FFT, num_med = args.num_med) freqs, data = Receiver_class.receive() # Plots data print('Plotting data...') Plot_class = Plot(freqs = freqs, data = data, galactic_velocity = galactic_velocity) Plot_class.plot(ra = ra, dec = dec, low_y = low_y, high_y = high_y) if num_data != 0: time_remaining = end_time - datetime.utcnow() print(f'Waiting for next data collection in {time_remaining.total_seconds()} seconds') time.sleep(time_remaining.total_seconds()) clear_console() else: print('360 must be divisable with the degree interval, eg. 360%\interval=0') quit()
def train(): """ Trains the model using the agent and the game """ # For Plots plot = Plot() plotScores = list() plotMeanScores = list() totalScore = 0 meanScore = 0 highestScore = 0 agent = Agent() game = SnakeGame(ai=True) while True: # Get old/current state stateOld = agent.getState(game) # Get move based on current state finalAction = agent.getAction(stateOld) # Perform the move and get next state reward, done, score = game.playStep(finalAction) stateNew = agent.getState(game) # Train short memory agent.trainShortMemory(stateOld, finalAction, reward, stateNew, done) # Remember (to store in the memory) agent.remember(stateOld, finalAction, reward, stateNew, done) if done: # Train long memory game.reset() agent.games += 1 agent.trainLongMemory() if score > highestScore: highestScore = score agent.model.save() print('Game', agent.games, 'Score', score, 'High Score:', highestScore) plotScores.append(score) totalScore += score meanScore = totalScore / agent.games plotMeanScores.append(meanScore) plot.plot(plotScores, plotMeanScores)
def plot_data(args): root = args["root"] video = args["video"] data = args["data"] min_corner = args["min_corner"] max_corner = args["max_corner"] thr_x, thr_y = args["t"] arrows_plot = args["a"] save_plots = args["s"] show_plots = args["p"] wave = args["w"] is not None arrows_8 = args["a8"] cumulative_displacements = args["cumulative_displacements"] amplitudes_x = np.array(data[:, :, 0]) amplitudes_y = np.array(data[:, :, 1]) phases_x = np.array(data[:, :, 2]) phases_y = np.array(data[:, :, 3]) phases_x[amplitudes_x < thr_x] = float('nan') amplitudes_x[amplitudes_x < thr_x] = float('nan') phases_y[amplitudes_y < thr_y] = float('nan') amplitudes_y[amplitudes_y < thr_y] = float('nan') if arrows_plot: amplitudes = plt.figure() k, scale = args["a"] Plot.plot(video, data[:, :, :2], min_corner, max_corner, 0, k=int(k), scale=1 / scale, color='red') else: amplitudes_x_fig = plt.figure('Amplitudes X') plt.title('Amplitudes X') Plot.scalar_heat_map(video, min_corner, max_corner, 0, amplitudes_x, alpha=0.3) amplitudes_y_fig = plt.figure('Amplitudes Y') plt.title('Amplitudes Y') Plot.scalar_heat_map(video, min_corner, max_corner, 0, amplitudes_y, alpha=0.3) phases_x_fig = plt.figure('Phases X') plt.title('Phases X') Plot.phase_heat_map(video, min_corner, max_corner, 0, phases_x, alpha=0.3) phases_y_fig = plt.figure('Phases Y') plt.title('Phases Y') Plot.phase_heat_map(video, min_corner, max_corner, 0, phases_y, alpha=0.3) if wave: wave_data = args["wave_data"] frequency = args["frequency"] pixel_size = args["pixel_size"] wave_width, wave_height = wave_data.shape[:2] x = np.arange(wave_width) y = np.arange(wave_height) Ax = np.log( np.array( [np.average(wave_data[:, j, 0]) for j in range(wave_height)])) Ay = np.log( np.array( [np.average(wave_data[i, :, 1]) for i in range(wave_width)])) Px = np.unwrap(wave_data[wave_width // 2, :, 2]) Py = np.unwrap(wave_data[:, wave_height // 2, 3]) for (xi, yi, name, dimension) in [(x, Ay, "decay constant x", "1/nm"), (y, Ax, "decay constant y", "1/nm"), (x, Py, "wave speed x", "m/s"), (y, Px, "wave speed y", "m/s")]: plt.figure() plt.plot(xi, yi) a, b = np.polyfit(xi, yi, 1) plt.plot(xi, a * xi + b * np.ones((len(xi)))) if dimension == "m/s": a = 2 * np.pi * frequency / (1e9 * a / pixel_size) else: a = a / pixel_size print(name + ": " + str(abs(a)) + " " + dimension) if save_plots: if arrows_plot: amplitudes.savefig(root + "amplitudes_vector_field.png") else: amplitudes_x_fig.savefig(root + "amplitudes_x" + ".png") amplitudes_y_fig.savefig(root + "amplitudes_y" + ".png") phases_x_fig.savefig(root + "phases_x" + ".png") phases_y_fig.savefig(root + "phases_y" + ".png") if arrows_8: k8, scale8 = arrows_8 displacements = get_displacements_frame_to_frame( cumulative_displacements) for time in range(len(displacements)): optical_flow = plt.figure() Plot.plot(video, displacements[time], min_corner, max_corner, time, k=int(k8), scale=1 / scale8, color="red") optical_flow.savefig(root + "displacements_vector_field_" + str(time) + ".png") plt.close(optical_flow) if show_plots: plt.show()
from Fitbit import Fitbit from Database import Database from Plot import Plot import datetime db = Database() fitbit = Fitbit(db) plot = Plot() while True: date = input("Enter a date (YYYY-MM-DD): ") try: datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: print("Incorrect data format, should be YYYY-MM-DD") continue heartData = fitbit.getHeartIntradayRate(date) if heartData == None: print("No data returned for ", date) continue plot.plot(heartData)
def main(path1, path2, title, xlabel, ylabel): p = Plot(path1, path2, title, xlabel, ylabel) p.plot()