def misidentificationAnalysis(self): """ Preform analysis on misidentifying the synchronization impulse """ self.logger.debug("Entering misidentificationAnalysis") measurement_file = "/Users/lance/Programming/Python/Masters/testdata/2012/08/120806_reflective_63.db" alpha = self.loadAbsorptionCoefficient(measurement_file) print alpha.measurement_settings grapher = Grapher(alpha.measurement_settings) fig = figure(figsize=(7, 5)) mic_impulse_loc = int(alpha.measurement_settings["microphone impulse location"]) gen_impulse_loc = int(alpha.measurement_settings["generator impulse location"]) (gen_start, gen_end) = (gen_impulse_loc - 20, gen_impulse_loc + 20) (mic_start, mic_end) = (mic_impulse_loc - 20, mic_impulse_loc + 100) gen_signal = alpha.generator_signals[0][gen_start:gen_end] mic_signal = alpha.microphone_signals[0][mic_start:mic_end] ax = fig.add_subplot(211) ax.plot(gen_signal) ax.axvline(x=gen_impulse_loc - gen_start, color="black", linestyle="--", lw=1) ax = fig.add_subplot(212) ax.plot(mic_signal) ax.axvline(x=mic_impulse_loc - mic_start, color="black", linestyle="--", lw=1) show() fig = figure(figsize=(7, 5)) ax = fig.add_subplot(111) resp = abs(fft(alpha.microphone_signals[0])) ** 2 t = arange(0, len(alpha.generator_cepstrum) / 44100.0, 1 / 44100.0) ax.plot(t, alpha.generator_cepstrum) ax.plot(t, alpha.microphone_cepstrum) ax.plot(t, alpha.power_cepstrum) show() fig = figure(figsize=(7, 5)) handler = Object() handler.figure = fig handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) show() alpha.measurement_settings["microphone impulse location"] = mic_impulse_loc alpha.measurement_settings["generator impulse location"] = gen_impulse_loc + 3 alpha.determineAlpha() fig = figure(figsize=(7, 5)) ax = fig.add_subplot(111) ax.plot(alpha.generator_cepstrum) ax.plot(alpha.microphone_cepstrum) show() fig = figure(figsize=(7, 5)) handler = Object() handler.figure = fig handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) show()
def __init__(self, measurement_settings, audio_devices): """ Constructor for RapidController, sets up the view, signals and shows the window. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating RapidController") QMainWindow.__init__(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self.alpha = None self.setupUi(self) self._setupWidgets() self._setupSignals() self.showMaximized()
def compare_results(self): """ Function to compare the absorption coefficient using the cepstral technique comparing to the impedance tube. """ self.logger.debug("Entering compare_results") measurement_filename = "../testdata/120519_asphalt_13.db" alpha = self.loadAbsorptionCoefficient(measurement_filename) grapher = Grapher(alpha.measurement_settings) fig = figure() handler = Object() handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) a = [ 0.032116172, 0.034017778, 0.032430265, 0.02675464, 0.192021209, 0.415370952, 0.372468791, 0.691662969, 0.54285943, 0.338953418, 0.284023669, 0.355485023, 0.475263874, 0.282777409, 0.595041322 ] f = [ 100, 125, 160, 200, 250, 300, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000 ] handler.axes.plot(f, a, "x") show()
def __init__(self, measurement_settings, audio_devices): """ Constructor to for the Frequency Response view. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating FrequencyResponseController") QMainWindow.__init__(self) self.setupUi(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self._populateWidgets() self._loadSettings() self._setupSignals() self._updateWidgets() self.showMaximized()
def showFilterTests(self): """" plot the absorption coefficient of the various tests done with different filter orders """ self.logger.debug("Entering showFilterTests") hpf_order_tests = [1, 3, 4, 5] hpf_cutoff_tests = [100, 150, 200, 500, 1000] fig = figure() for order_index, hpf_order in enumerate(hpf_order_tests): for cutoff_index, hpf_cutoff in enumerate(hpf_cutoff_tests): measurement_filename = "../test data/120323_hpf_%s_%s.db" % ( hpf_order, hpf_cutoff) alpha = self.loadAbsorptionCoefficient(measurement_filename) grapher = Grapher(alpha.measurement_settings) handler = Object() handler.axes = fig.add_subplot( len(hpf_order_tests), len(hpf_cutoff_tests), order_index * len(hpf_cutoff_tests) + cutoff_index) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) plot(alpha.alpha) title("%s Hz order %s" % (hpf_cutoff, hpf_order)) show()
def main(): filename = "allocatorTest/report1.i" parser = Parser.Parser(filename) parse_result = parser.parse_file() renamer = Renamer.Renamer(parser) renamer.rename_sr_2_live_range() grapher = Grapher(renamer) grapher.print_Graph()
def loudspeakerFrequencyResponse(self): """ Creates graphs for the frequency response curves for the Phillips AD3714 loudspeaker driver. """ self.logger.debug("Entering loudspeakerFrequencyResponse") def plot_frequency_response(frequency_response, name): # Plot frequency response fig = figure(figsize=(2 * 3.375, 3.375)) handler = Object() handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphFrequencyResponse(frequency_response, handler) handler.axes.set_xticklabels([ "", "", "", 31.5, "", "", 63, "", "", 125, "", "", 250, "", "", 500, "", "", "1K", "", "", "2K", "", "", "4K", "", "", "8K", "", "" ]) fig.subplots_adjust(bottom=0.15, top=0.98, right=0.98, left=0.1) savefig("Analysis/Images/%s_frequency_response.eps" % (name, )) def plot_impulse_response(impulse_response, name): # Plot the impulse response fig = figure(figsize=(2 * 3.375, 3.375)) handler = Object() handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphImpulseResponse(impulse_response, handler) fig.subplots_adjust(bottom=0.15, top=0.98, right=0.98, left=0.1) savefig("Analysis/Images/%s_impulse_response.eps" % (name)) name = "120602_loudspeaker_3" measurement_filename = "../testdata/%s.fdb" % (name) freq = self.loadFrequencyResponse(measurement_filename) grapher = Grapher(freq.measurement_settings) plot_frequency_response(freq.frequency_response, name) plot_impulse_response(freq.impulse_response, name) return # Base case, no modifications for i in range(1, 13): name = "120514_loudspeaker_%s" % (i) measurement_filename = "../testdata/%s.fdb" % (name) freq = self.loadFrequencyResponse(measurement_filename) grapher = Grapher(freq.measurement_settings) plot_frequency_response(freq.frequency_response, name) plot_impulse_response(freq.impulse_response, name)
def create_graph(intervals, chosen_banks, graph_all_results=False, save_graph=False, graph_filename=""): bankname = get_chosen_bank(chosen_banks) data = load_data(bankname) if graph_all_results: grapher = Grapher(data=data, save_graph=save_graph, graph_filename=graph_filename, bankname=bankname) grapher.create_graph() else: grapher = Grapher(data=data, intervals=intervals, save_graph=save_graph, graph_filename=graph_filename, bankname=bankname) grapher.create_graph()
def graphOneSeries(self, configFiles, xVar, yVar, outputName): grapher = Grapher() fig, axes = grapher.simple2D(configFiles, "config", xVar, "state", yVar) grapher.setAxisLabels(axes, xVar, yVar) figurePath = os.path.join(self.path, outputName) grapher.saveFigure(fig, figurePath) return fig, axes
def grapher(self): print "results length : %s",(len(self.searcher.generator.results), ) grapher = Grapher() newg = nx.Graph() for path in self.searcher.useful_paths: print '%s - %s' % (self.uuid,path) newg.add_path(path) grapher.paths.append(path) grapher.graph = newg #writer = nx.readwrite.graphml.GraphMLWriter(encoding='utf-8') #writer.add_graph_element(grapher.graph) #output = StringIO.StringIO() #writer.dump(self.request) from networkx.readwrite import d3_js # mikedewar = nx.read_graphml('mikedewar_rec.graphml') mikedewar = newg # We need to relabel nodes as Twitter name if we want to show the names in the plot #def gen_label(node): # label = "" # label = "%s::%s::%s::%d" %(node.path_index,node.publication_date.absdate,node.id,node.hasMatchingAuthorsName(self.searcher.core_authors())) # print label # return label #label_dict = dict(map(lambda i : (mikedewar.nodes()[i], gen_label(mikedewar.nodes()[i])), xrange(mikedewar.number_of_nodes()))) #mikedewar_d3 = nx.relabel_nodes(mikedewar, label_dict) # Export #d3_js.export_d3_js(mikedewar_d3, files_dir="mikedewar", graphname="mikedewar", group=None) graph_json = d3_js.d3_json(mikedewar, group=None, searcher=self.searcher) import json #self.request.write(json.dumps(graph_json, indent=2)) params = self.params params['network_graph'] = json.dumps(graph_json, indent=2) self.updateDatabase(params)
def main(): filename = "report/report01.i" parser = Parser.Parser(filename) parse_result = parser.parse_file() renamer = Renamer.Renamer(parser) renamer.rename_sr_2_live_range() grapher = Grapher.Grapher(renamer) grapher.graph_builder() grapher.print_graph()
def change(): if isinstance(self.cinema, Grapher): self.cinema = InsideButtFrame(self.master, bg="pink") self.cinema.grid(row=1, column=2, rowspan=3, columnspan=2, sticky="nsew") self.master.update() elif isinstance(self.cinema, InsideButtFrame): self.cinema = Grapher(self.master) self.cinema.draw_it() self.cinema.grid(row=1, column=2, rowspan=3, columnspan=2, sticky="nsew") self.master.update() else: print("Unknown instance")
def showFilterTests(self): """" plot the absorption coefficient of the various tests done with different filter orders """ self.logger.debug("Entering showFilterTests") hpf_order_tests = [1, 3, 4, 5] hpf_cutoff_tests = [100, 150, 200, 500, 1000] fig = figure() for order_index, hpf_order in enumerate(hpf_order_tests): for cutoff_index, hpf_cutoff in enumerate(hpf_cutoff_tests): measurement_filename = "../test data/120323_hpf_%s_%s.db" % (hpf_order, hpf_cutoff) alpha = self.loadAbsorptionCoefficient(measurement_filename) grapher = Grapher(alpha.measurement_settings) handler = Object() handler.axes = fig.add_subplot(len(hpf_order_tests), len(hpf_cutoff_tests), order_index * len(hpf_cutoff_tests) + cutoff_index) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) plot(alpha.alpha) title("%s Hz order %s" % (hpf_cutoff, hpf_order)) show()
def compare_results(self): """ Function to compare the absorption coefficient using the cepstral technique comparing to the impedance tube. """ self.logger.debug("Entering compare_results") measurement_filename = "../testdata/120519_asphalt_13.db" alpha = self.loadAbsorptionCoefficient(measurement_filename) grapher = Grapher(alpha.measurement_settings) fig = figure() handler = Object() handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) a = [0.032116172, 0.034017778, 0.032430265, 0.02675464, 0.192021209, 0.415370952, 0.372468791, 0.691662969, 0.54285943, 0.338953418, 0.284023669, 0.355485023, 0.475263874, 0.282777409, 0.595041322] f = [100, 125, 160, 200, 250, 300, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000] handler.axes.plot(f, a, "x") show()
def __init__(self, market='BTCUSDT'): self.api_key = os.getenv("binance_api_key") self.api_secret = os.getenv("binance_api_secret") self.client = Client(self.api_key, self.api_secret) logger.info("Starting Binance Trading Engine.") self.market = market self.__process_initial_book_state() logger.info("Book state initialized.") self.trader = TestTrader() #self.trader = Playbook.OGTrader_BTC() self.event_buffer = queue.Queue() self.event_thread = threading.Thread(target=self.event_loop) self.socketManager = BinanceSocketManager(self.client, user_timeout=60) self.book_diff = self.socketManager.start_depth_socket( market, self.on_depth_message) self.trade_stream = self.socketManager.start_trade_socket( market, self.on_trade_message) self.PRINT_BOOK = True self.grapher = Grapher() self.graphing = False self.tradingOn = True self.alive = True
def searchPlayer(playerName): '''Used to search for a single player from the command line''' # Create the player object player = Player(playerName) # Use try block to catch misspelled names here try: Scraper.makeDataDirectory( Scraper.directory) # Create the temporary data directory Player.getDefenseRankings( Scraper.directory ) # Static function that gets all of the defenses and there rankings player.getData(Scraper.directory) # Get the players data player.printPlayer() # Prints the players stats to the terminal Scraper.deleteDataDirectory( Scraper.directory) # Delete the temporary data dictionary # Use a Grapher to show the graphs for the player being searched Grapher.graphSinglePlayer(player, Player.defenseRankings) except Exception as e: print(e)
def graphSeriesDict(self, seriesDict, seriesLabel, xVar, yVar, outputName, legend_title=None): grapher = Grapher() fig, axes = grapher.plotSeriesDict(seriesDict, seriesLabel, "config", xVar, "state", yVar, legend_title=legend_title) grapher.setAxisLabels(axes, xVar, yVar) figurePath = os.path.join(self.path, outputName) grapher.saveFigure(fig, figurePath) return fig, axes
CT_rate = int(input("Average CT imaging time in minutes (1-60): ")) CT_enabled = True else: num_CTs = 1 CT_rate = 15 CT_enabled = False duration = int(input("Simulation duration in hours (1-72): ")) duration = duration * 60 for j in range(50): if j == 0: myED = ED(1, num_docs, doc_front_rate, doc_end_rate, patient_rate, department_size, waiting_size, admit_rate, labs_enabled, lab_rate, CT_enabled, num_CTs, CT_rate, True) else: myED = ED(1, num_docs, doc_front_rate, doc_end_rate, patient_rate, department_size, waiting_size, admit_rate, labs_enabled, lab_rate, CT_enabled, num_CTs, CT_rate, False) for i in range(duration): myED.update() TotalStats.add_dataframe(myED.output_stats()) TotalStats.merge_dataframes() TotalStats.stats_total_to_file() mygraph = Grapher() mygraph.basic_graphs()
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys, os from Grapher import Grapher if len(sys.argv) < 2: print "usage: python test_Grapher.py path" sys.exit(1) path = sys.argv[1] configNames = ["test_grapher0", "test_grapher1", "test_grapher2"] fullConfigPaths = [os.path.join(path, config) for config in configNames] grapher = Grapher(fullConfigPaths) outputs = grapher.readOutputs() for dataSet in outputs: print( dataSet.getLatestVar("config", "x") + " : " + dataSet.getLatestVar("test_section", "y")) fig, axes = grapher.simple2D("config", "x", "test_section", "y") grapher.setAxisLabels(axes, "x", "y") figurePath = os.path.join(path, "testFig") grapher.saveFigure(fig, figurePath)
density = .93 # -----> Defining the simulation parameters # so in order, these represent (sigma, epsilon, alpha, r_a, a_g, sig_g, r_g) param_list = [(1, 1, .11268, 1.1051, .96, 1.00547, .05153) ] #parameters after being reduced, used for RL unreduced_param_list = (340, 5.298, 758789.8) #epsilon, sigma, mass #110.2586974 box_params = (110.26, 173.27, 110.26) #size of the box, (x,y,z) command_list = [(100, 4000), (0, 100, 531250) ] #1000000 #how to run the simulations themselves g = Grapher("convolution") #added in order to repeat a simulation multiple times for i in range(1): for p in param_list: sim = SimulatorRL(box_params, density, temperature, 1, Vector(-.0166, 0, 0), p, command_list) fn = "attempt3D_1" #filename sim.update_fn(fn) sim.run() file = fn + ".xyz" #add the pressure sensors ps = PressureSensorRL((50.1182, 60.1418, 76.6113, 96.6586), 2, p[2:],
process_tree.binder_time) print(" ------ Freq events in %s seconds" % process_tree.freq_time) except Exception, e: print("Error processing event {}: {}".format(error_event, e)) return try: start_time = time.time() sys.stdout.write("Finishing process tree") optimizations_found = process_tree.finish_tree( self.filename, governor, subdir) print(" --- COMPLETED in {} seconds".format(time.time() - start_time)) print( "Found {} B2L realloc, {} DVFS, {} Intra-cluster realloc, {} DVFS after realloc" .format(optimizations_found[0], optimizations_found[1], optimizations_found[2], optimizations_found[3])) except Exception, e: print("Error finishing tree: %s" % e) return if draw: sys.stdout.write("Drawing graph") start_time = time.time() draw_graph = Grapher(process_tree, subdir) draw_graph.draw_graph() print(" --- COMPLETED in %s seconds" % (time.time() - start_time)) print("** Processing finished in %s seconds **" % (time.time() - process_start_time))
def generate_graph(self, fn): g = Grapher(self.areas, self.pressures, "component") g.graph("Attempt", fn)
class RapidController(QMainWindow, Ui_RapidAlphaWindow): # pyqtSignals startMeasurement = pyqtSignal() saveGraph = pyqtSignal("QString") exportData = pyqtSignal("QString") loadMeasurement = pyqtSignal("QString") saveMeasurement = pyqtSignal("QString") showPreferences = pyqtSignal() savePreferences = pyqtSignal("QString") loadPreferences = pyqtSignal("QString") exit = pyqtSignal() def __init__(self, measurement_settings, audio_devices): """ Constructor for RapidController, sets up the view, signals and shows the window. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating RapidController") QMainWindow.__init__(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self.alpha = None self.setupUi(self) self._setupWidgets() self._setupSignals() self.showMaximized() def update(self): """ Updates the graph showing the absorption coefficient of the material measured. """ self.logger.debug("Entering update") self.grapher.graphAbsorption(self.alpha.alpha, self.AlphaPlot) self.grapher.graphCepstrum( self.alpha.microphone_cepstrum, self.alpha.generator_cepstrum, self.alpha.power_cepstrum, self.alpha.impulse_response, self.alpha.window, float(self.alpha.measurement_settings["window start"]), self.CepstrumPlot) def _setupWidgets(self): """ Setup the widgets to show the user. The graph is formatted with no data. """ self.logger.debug("Entering _setupWidgets") self.grapher.graphAbsorption([], self.AlphaPlot) self.grapher.graphCepstrum([], [], [], [], [], 0, self.CepstrumPlot) # Add Volume slider to toolbar self.gainSlider = QSlider(Qt.Horizontal) self.gainSlider.setMaximumWidth(100) self.gainSlider.setMaximum(0) self.gainSlider.setMinimum(-1000) self.gainSpin = QDoubleSpinBox() self.gainSpin.setMaximum(0) self.gainSpin.setMinimum(-10) self.gainSpin.setSingleStep(0.01) self.toolBar.addSeparator() self.toolBar.addWidget(QSpacerItem(0, 0).widget()) self.toolBar.addWidget(QLabel("Gain: ")) self.toolBar.addWidget(self.gainSlider) self.toolBar.addWidget(self.gainSpin) self.toolBar.addWidget(QLabel(" dB")) self.updateWidgets() def updateWidgets(self): """ Set the values for widgets on the screen. """ gain = 20 * log10(float(self.measurement_settings["gain"])) self.gainSlider.setValue(gain) self.gainSpin.setValue(gain) def _updateMeasurementSettings(self): """ Update the Measurement Settings dictionary. For the Rapid View, the only settings that change are the input and output devices. """ self.logger.debug("Entering _updateMeasurementSettings") selected_index = self.InputDeviceList.currentIndex() input_device = self.InputDeviceList.itemData(selected_index).toInt() self.measurement_settings["input device"] = input_device[0] selected_index = self.OutputDeviceList.currentIndex() output_device = self.OutputDeviceList.itemData(selected_index).toInt() self.measurement_settings["output device"] = output_device[0] def _setupSignals(self): """ Connects the various button signals to the class signals. """ self.logger.debug("Entering _setupSignals") save_func = self._showSaveDialog self.actionSave.triggered.connect(lambda: save_func("measurement")) self.actionExport_Data.triggered.connect(lambda: save_func("csv")) self.actionExport_Graph.triggered.connect(lambda: save_func("graph")) self.actionSave_Preferences.triggered.connect( lambda: save_func("preferences")) load_func = self._showOpenDialog self.actionLoad_Preferences.triggered.connect( lambda: load_func("preferences")) self.actionLoad_Measurement.triggered.connect( lambda: load_func("measurement")) self.actionExit.triggered.connect(self.exit) self.actionStart_Measurement.triggered.connect(self.startMeasurement) self.actionPreferences.triggered.connect(self.showPreferences) self.gainSlider.valueChanged.connect(self._updateWidgets) self.gainSpin.valueChanged.connect(self._updateWidgets) def _updateWidgets(self): """ Keeps widgets synchronized with the measurement settings, and each other """ self.logger.debug("Entering _updateWidgets") # Keep the gain in sync gain = float(self.measurement_settings["gain"]) gain_db = 20 * log10(gain) self.logger.debug("sender: %s" % (self.sender())) if self.sender() == self.gainSlider: self.logger.debug("Slider: %s" % (self.gainSlider.value())) self.gainSpin.setValue((self.gainSlider.value() / 100.0)) elif self.sender() == self.gainSpin: self.gainSlider.setValue(self.gainSpin.value() * 100.0) gain = 10**(self.gainSpin.value() / 20.0) self.measurement_settings["gain"] = gain def _showOpenDialog(self, file_type): """ Shows the open dialog to get the filename to load the required data. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showOpenDialog") if file_type == "measurement": caption = "Select Measurement File to Load" filter = "AlphaDb (*.adb)" signal = self.loadMeasurement elif file_type == "preferences": caption = "Select Preferences File to Load" filter = "Preferences (*.pdb)" signal = self.loadPreferences else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getOpenFileName(self, caption, dir, filter) # filename is a tuple (filename, selected filter) when file is selected # else a blank string if dialog closed if filename != "": signal.emit(filename) def _showSaveDialog(self, file_type): """ Shows the save dialog to get the filename to save the required data to. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showSaveDialog") if file_type == "graph": caption = "Select file to save the graph" supported_file_types = self.AlphaPlot.figure.canvas.get_supported_filetypes_grouped( ) # Get available output formats filter = [] for key, value in supported_file_types.items(): filter.append("%s (*.%s)" % (key, " *.".join(value))) filter = ";;".join(filter) signal = self.saveGraph elif file_type == "csv": caption = "Select file to export data to" filter = "CSV (*.csv)" signal = self.exportData elif file_type == "measurement": caption = "Enter file name of measurement" filter = "AlphaDb (*.adb)" signal = self.saveMeasurement elif file_type == "preferences": caption = "Enter file name of preferences" filter = "Preferences (*.pdb)" signal = self.savePreferences else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getSaveFileName(self, caption, dir, filter) if filename != "": signal.emit(filename)
#!/bin/python import sys from Parser import Parser from Grapher import Grapher from Flows import Flows import networkx as nx if __name__ == "__main__": p = Parser(sys.argv[1]) net = p.xml_to_json() g = Grapher(net) graph = g.json_to_graph() print 'Enter a flow between two hosts (e.g., h1, h2)' i = 1 for n in graph.nodes(data=True): if n[1].get('type') == 'host': print str(i) + '. ' + n[0] i = i + 1 flows = [] flow = 'default' while flow != '': flow = raw_input('Flow: ') if flow != '': flows.append(flow.split(',')) # perhaps we should sanitize the list here?
from TrafficMonitor import TrafficMonitor import networkx as nx if __name__ == "__main__": # start parser with command line arg p = Parser(sys.argv[1]) # this is the topology in json net = p.xml_to_json() # list of emulated flows emuflows = p.emuflows() # translate to networkx graph = Grapher(net) g = graph.json_to_graph() d = Downscaler(emuflows, g) pipes = d.get_pipes() for p in pipes: print p print '\n' st = SymbioTopo(net, pipes) st.getNodes() for e in emuflows:
def __init__(self, master=None, y=10, x="sample string"): print('initing MainApp') self.master = master self.y = y self.x = x """ Creating Menu """ self.menu = tk.Menu(self.master) self.master.config(menu=self.menu) self.master.geometry("{}x{}+0+0".format(WIDTH, HEIGHT)) self.menu.add_command(label="Import") self.checkvar = tk.IntVar() self.menu.add_checkbutton(label="Check", command=lambda: print(self.checkvar.get()), variable=self.checkvar, onvalue=1, offvalue=0, indicatoron=False) self.menu.add_radiobutton(label="Radio") self.filemenu = tk.Menu(self.menu, tearoff=0, takefocus=0) self.filemenu.add_command(label="Open") self.filemenu.add_command(label="Edit") self.filemenu.add_command(label="Exit", command=self.master.quit) self.menu.add_cascade(label="Cascade", menu=self.filemenu) """ Creating Frame Layout """ self.leftFrame = tk.Frame(self.master, bg="black") self.leftFrame.grid(rowspan=4, sticky="nsew") self.leftFrame.rowconfigure(0, weight=1) self.leftFrame.columnconfigure(0, weight=1) """ Inserting Widgets""" def change(): if isinstance(self.cinema, Grapher): self.cinema = InsideButtFrame(self.master, bg="pink") self.cinema.grid(row=1, column=2, rowspan=3, columnspan=2, sticky="nsew") self.master.update() elif isinstance(self.cinema, InsideButtFrame): self.cinema = Grapher(self.master) self.cinema.draw_it() self.cinema.grid(row=1, column=2, rowspan=3, columnspan=2, sticky="nsew") self.master.update() else: print("Unknown instance") self.butt1 = tk.Button(self.leftFrame, text="Deep Shit", bg="darkgrey", relief="groove", bd=1, font=("Verdana", 8)) self.butt2 = tk.Button(self.leftFrame, text="CHNG", bg="darkgrey", relief="groove", bd=1, font=("Verdana", 8)) self.butt3 = ttk.Button(self.leftFrame, text="CHANGE", command=change) self.butt4 = tk.Button(self.leftFrame, text="Deep Stuff") self.butt1.pack(fill="x") self.butt2.pack(fill="x") self.butt3.pack(fill="x") self.butt4.pack(fill="x") """ STATIV """ self.ins_but = InsideButtFrame(self.master, bg="lightgreen") self.ins_but.grid(row=1, column=1, rowspan=3, sticky="nsew") """ CINEMA """ # self.cinema =tk.Label(self.master, text = "Don Carlos", bg = "darkgrey") # self.cinema.grid(row = 1, column = 2, rowspan = 3, columnspan = 2, sticky = "nsew") self.cinema = Grapher(self.master, bg="green") self.cinema.draw_it(x="random test shit") self.cinema.grid(row=1, column=2, rowspan=3, columnspan=2, sticky="nsew") self.master.rowconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) self.master.rowconfigure(2, weight=1) self.master.rowconfigure(3, weight=1) self.master.columnconfigure(0, weight=1) self.master.columnconfigure(1, weight=4) self.master.columnconfigure(2, weight=4) self.master.columnconfigure(3, weight=4) """ Creating layout"""
def misidentificationAnalysis(self): """ Preform analysis on misidentifying the synchronization impulse """ self.logger.debug("Entering misidentificationAnalysis") measurement_file = "/Users/lance/Programming/Python/Masters/testdata/2012/08/120806_reflective_63.db" alpha = self.loadAbsorptionCoefficient(measurement_file) print alpha.measurement_settings grapher = Grapher(alpha.measurement_settings) fig = figure(figsize=(7, 5)) mic_impulse_loc = int( alpha.measurement_settings["microphone impulse location"]) gen_impulse_loc = int( alpha.measurement_settings["generator impulse location"]) (gen_start, gen_end) = (gen_impulse_loc - 20, gen_impulse_loc + 20) (mic_start, mic_end) = (mic_impulse_loc - 20, mic_impulse_loc + 100) gen_signal = alpha.generator_signals[0][gen_start:gen_end] mic_signal = alpha.microphone_signals[0][mic_start:mic_end] ax = fig.add_subplot(211) ax.plot(gen_signal) ax.axvline(x=gen_impulse_loc - gen_start, color="black", linestyle="--", lw=1) ax = fig.add_subplot(212) ax.plot(mic_signal) ax.axvline(x=mic_impulse_loc - mic_start, color="black", linestyle="--", lw=1) show() fig = figure(figsize=(7, 5)) ax = fig.add_subplot(111) resp = abs(fft(alpha.microphone_signals[0]))**2 t = arange(0, len(alpha.generator_cepstrum) / 44100.0, 1 / 44100.0) ax.plot(t, alpha.generator_cepstrum) ax.plot(t, alpha.microphone_cepstrum) ax.plot(t, alpha.power_cepstrum) show() fig = figure(figsize=(7, 5)) handler = Object() handler.figure = fig handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) show() alpha.measurement_settings[ "microphone impulse location"] = mic_impulse_loc alpha.measurement_settings[ "generator impulse location"] = gen_impulse_loc + 3 alpha.determineAlpha() fig = figure(figsize=(7, 5)) ax = fig.add_subplot(111) ax.plot(alpha.generator_cepstrum) ax.plot(alpha.microphone_cepstrum) show() fig = figure(figsize=(7, 5)) handler = Object() handler.figure = fig handler.axes = fig.add_subplot(111) handler.draw = draw grapher.graphAbsorption(alpha.alpha, handler) show()
class BinanceTradeEngine: def __init__(self, market='BTCUSDT'): self.api_key = os.getenv("binance_api_key") self.api_secret = os.getenv("binance_api_secret") self.client = Client(self.api_key, self.api_secret) logger.info("Starting Binance Trading Engine.") self.market = market self.__process_initial_book_state() logger.info("Book state initialized.") self.trader = TestTrader() #self.trader = Playbook.OGTrader_BTC() self.event_buffer = queue.Queue() self.event_thread = threading.Thread(target=self.event_loop) self.socketManager = BinanceSocketManager(self.client, user_timeout=60) self.book_diff = self.socketManager.start_depth_socket( market, self.on_depth_message) self.trade_stream = self.socketManager.start_trade_socket( market, self.on_trade_message) self.PRINT_BOOK = True self.grapher = Grapher() self.graphing = False self.tradingOn = True self.alive = True def start(self): self.socketManager.start() logger.info("Socket Manager started.") self.event_thread.start() logger.info("Event thread started.") def stop(self): self.socketManager.close() logger.info("Socket Manager closed.") self.alive = False self.event_thread.join() logger.info("Event thread killed.") def __process_initial_book_state(self): self.market_state = MarketState(self.market) book = self.client.get_order_book(symbol=self.market) # print(book, type(book)) self.order_book = self.market_state.order_book for bid in book['bids']: self.order_book.add_modify_delete(Order(float(bid[0]), float(bid[1])), side='b') for ask in book['asks']: self.order_book.add_modify_delete(Order(float(ask[0]), float(ask[1])), side='a') print(self.order_book) def event_loop(self): global done while self.alive: if not self.event_buffer.empty(): (event_type, msg) = self.event_buffer.get() if event_type == EventType.DEPTH: self.depthUpdateHandler(msg) elif event_type == EventType.TRADE: self.tradeUpdateHandler(msg) def on_depth_message(self, msg): self.event_buffer.put((EventType.DEPTH, msg)) def on_trade_message(self, msg): self.event_buffer.put((EventType.TRADE, msg)) def depthUpdateHandler(self, msg): try: self.order_book.binance_incremental_book_update_handler(msg) self.market_state.binance_incremental_depth_update_handler(msg) print(self.trader) if self.PRINT_BOOK: print(self.market_state) if self.tradingOn: self.trader.on_depth_update(self.market_state) except Exception as e: print("Exception caught in depth update") print(e) print(e.args) print("LAST TRADE: " + str(self.market_state.last_trade)) print() print(self.market_state) logger.critical("Exception caught in depth update") logger.critical(msg=e) logger.critical(msg="LAST TRADE: " + str(self.market_state.last_trade)) logger.critical(msg=self.market_state) self.socketManager.close() traceback.print_exc() done = False def tradeUpdateHandler(self, msg): try: self.market_state.binance_incremental_trade_update_handler(msg) if self.graphing: self.grapher.update_graph(float(msg['p']), msg['m']) if self.tradingOn: self.trader.on_trade_update(self.market_state) #self.done = True print(self.trader) if self.PRINT_BOOK: print(self.market_state) except Exception as e: print("Exception caught in trade update") print(e) print(e.args) print("LAST TRADE: " + str(self.market_state.last_trade)) print() print(self.market_state) logger.critical("Exception caught in trade update") logger.critical(msg=e) logger.critical(msg="LAST TRADE: " + str(self.market_state.last_trade)) logger.critical(msg=self.market_state) self.socketManager.close() traceback.print_exc()
'boards/board-2-2.txt', 'boards/board-2-3.txt', 'boards/board-2-4.txt'] Astar = Solver('Astar', lambda s,t: abs(t[0]-s[0])+abs(t[1]-s[1]), Heap, Queue) Dijkstra = Solver('Dijkstra',lambda s,t: 0, Heap, Queue) BFS = Solver('BFS', lambda s,t: 0, Queue, Queue) grid = Parser(lambda line: list(line.strip())) for board in boards1: grid.open(board) grid.parse() nodes = Grapher(Node, grid.parsed(), costmap, 'A', 'B') nodes.graph() root = nodes.Root goal = nodes.Goal Astar.solve(board[7:16], root, goal) world = Drawer(grid.parsed(), (30,30), colormap) Astar.visualize(world, Astar.path, 'black') Astar.save() for board in boards2: grid.open(board) grid.parse() nodes = Grapher(Node, grid.parsed(), costmap, 'A', 'B') nodes.graph()
class FrequencyResponseController(QMainWindow, Ui_FrequencyResponse): # pyqtSignals startMeasurement = pyqtSignal() updateExctration = pyqtSignal() saveGraph = pyqtSignal("QString") exportData = pyqtSignal("QString") loadMeasurement = pyqtSignal("QString") saveMeasurement = pyqtSignal("QString") def __init__(self, measurement_settings, audio_devices): """ Constructor to for the Frequency Response view. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating FrequencyResponseController") QMainWindow.__init__(self) self.setupUi(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self._populateWidgets() self._loadSettings() self._setupSignals() self._updateWidgets() self.showMaximized() def updateGraphs(self): """ Function called to update the graphs, called when the measurement is first loaded, also called when extraction options have been updated. """ self.logger.debug("Entering updateGraphs") self.grapher.graphImpulseResponse(self.freq_response.impulse_response, self.impulsePlot) self.grapher.graphFrequencyResponse(self.freq_response.frequency_response, self.frequencyPlot) def _setupSignals(self): """ Connects various signals that will be emitted to the required slots. """ self.logger.debug("Setting up signals") # Update measurement settings whenever a setting has updated # Combo Boxes self.inputDevices.currentIndexChanged["int"].connect(self._updateSettings) self.outputDevices.currentIndexChanged["int"].connect(self._updateSettings) self.signalType.currentIndexChanged["int"].connect(self._updateSettings) self.filterType.currentIndexChanged["int"].connect(self._updateSettings) self.signalType.currentIndexChanged["int"].connect(self._updateWidgets) self.filterType.currentIndexChanged["int"].connect(self._updateWidgets) # Signal Settings self.numTaps.valueChanged["int"].connect(self._updateSettings) self.numBursts.valueChanged["int"].connect(self._updateSettings) self.upperFreq.valueChanged["int"].connect(self._updateSettings) self.signalLength.valueChanged["int"].connect(self._updateSettings) self.numRepititions.valueChanged["int"].connect(self._updateSettings) # Filter Settings self.freqLPF.valueChanged["int"].connect(self._updateSettings) self.orderLPF.valueChanged["int"].connect(self._updateSettings) self.freqHPF.valueChanged["int"].connect(self._updateSettings) self.orderHPF.valueChanged["int"].connect(self._updateSettings) self.freqLow.valueChanged["int"].connect(self._updateSettings) self.orderLow.valueChanged["int"].connect(self._updateSettings) self.freqHigh.valueChanged["int"].connect(self._updateSettings) self.orderHigh.valueChanged["int"].connect(self._updateSettings) # Window Settings self.winLength.valueChanged["int"].connect(self._updateSettings) self.taperLength.valueChanged["int"].connect(self._updateSettings) # Emit signal when new measurement button is pressed self.startButton.clicked.connect(self.startMeasurement) load_func = self._showOpenDialog self.actionOpen.triggered.connect(lambda: load_func("measurement")) # Emit a signal when the window settings have changed self.winLength.valueChanged["int"].connect(self.updateExctration) self.taperLength.valueChanged["int"].connect(self.updateExctration) def _updateWidgets(self): """ Certain widgets have side-effects on other widgets. This method will keep widgets synchronized. """ self.logger.debug("Entering _updateWidgets") # The signal options stacked widget has two pages, one for MLS-type # signals, and one for swept sine signals. signal_type = str(self.signalType.currentText()) if (signal_type == "Inverse Repeat Sequence" or signal_type == "Maximum Length Sequence"): self.signalOptions.setCurrentIndex(0) else: self.signalOptions.setCurrentIndex(1) # The filter options stacked widget has 4 pages, one for when no filters # are enabled, one for low pass, one for high pass and one for band pass filter_type = str(self.filterType.currentText()) if filter_type == "Disabled": self.filterOptions.setCurrentIndex(0) elif filter_type == "Low Pass Filter": self.filterOptions.setCurrentIndex(1) elif filter_type == "High Pass Filter": self.filterOptions.setCurrentIndex(2) elif filter_type == "Bandpass Filter": self.filterOptions.setCurrentIndex(3) def _populateWidgets(self): """ Populates some widgets with default values. Adds excitation signals to the drop-down box Adds the various filters. Populates the input / output device. """ self.logger.debug("Entering populateWidgets") # Populate Audio device drop-down boxes self.inputDevices.clear() self.outputDevices.clear() for audio_device in self.audio_devices: if audio_device.input_channels > 0: self.inputDevices.addItem(audio_device.name, audio_device.index) if audio_device.output_channels > 0: self.outputDevices.addItem(audio_device.name, audio_device.index) # Populate Excitation Signals self.signalType.clear() self.signalType.addItem("Inverse Repeat Sequence") self.signalType.addItem("Maximum Length Sequence") self.signalType.addItem("Low Pass Swept Sine") self.signalType.addItem("Swept Sine") # Populate Filters self.filterType.clear() self.filterType.addItem("Disabled") self.filterType.addItem("Low Pass Filter") self.filterType.addItem("High Pass Filter") self.filterType.addItem("Bandpass Filter") def _updateSettings(self): """ When settings change, updated the measurement settings dictionary associated with the dialog. """ self.logger.debug("Updating measurement settings") # Update Audio Devices selected_index = self.inputDevices.currentIndex() input_device = self.inputDevices.itemData(selected_index).toInt() self.measurement_settings["input device"] = int(input_device[0]) selected_index = self.outputDevices.currentIndex() output_device = self.outputDevices.itemData(selected_index).toInt() self.measurement_settings["output device"] = int(output_device[0]) # Update excitation signal signal_type = str(self.signalType.currentText()) self.measurement_settings["signal type"] = signal_type upper_frequency = self.upperFreq.value() self.measurement_settings["upper frequency"] = int(upper_frequency) signal_length = self.signalLength.value() # signal_length is in ms, convert to seconds signal_length /= 1000 self.measurement_settings["signal length"] = signal_length num_taps = self.numTaps.value() self.measurement_settings["mls taps"] = int(num_taps) num_bursts = self.numBursts.value() self.measurement_settings["mls reps"] = int(num_bursts) signal_reps = self.numRepititions.value() self.measurement_settings["signal reps"] = int(signal_reps) # Update filter settings filter_type = self.filterType.currentText() if filter_type == "Bandpass Filter": lpf_cutoff = self.freqLow.value() lpf_order = self.orderLow.value() hpf_cutoff = self.freqHigh.value() hpf_order = self.orderHigh.value() lpf_enabled = 1 hpf_enabled = 1 self.measurement_settings["lpf cutoff"] = int(lpf_cutoff) self.measurement_settings["lpf order"] = int(lpf_order) self.measurement_settings["hpf cutoff"] = int(hpf_cutoff) self.measurement_settings["hpf order"] = int(hpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "Low Pass Filter": lpf_cutoff = self.freqLPF.value() lpf_order = self.orderLPF.value() lpf_enabled = 1 hpf_enabled = 0 self.measurement_settings["lpf cutoff"] = int(lpf_cutoff) self.measurement_settings["lpf order"] = int(lpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "High Pass Filter": hpf_cutoff = self.freqHPF.value() hpf_order = self.orderHPF.value() lpf_enabled = 0 hpf_enabled = 1 self.measurement_settings["hpf cutoff"] = int(hpf_cutoff) self.measurement_settings["hpf order"] = int(hpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "Disabled": lpf_enabled = 0 hpf_enabled = 0 self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled # Update Window options window_length = self.winLength.value() self.measurement_settings["window length"] = int(window_length) taper_length = self.taperLength.value() self.measurement_settings["taper length"] = int(taper_length) def _loadSettings(self): """ Loads the default settings for the frequency response measurements. """ self.logger.debug("Loading default settings") # Set the audio devices default_input_device = int(self.measurement_settings["input device"]) input_index = self.inputDevices.findData(default_input_device) self.inputDevices.setCurrentIndex(input_index) default_output_device = int(self.measurement_settings["output device"]) output_index = self.outputDevices.findData(default_output_device) self.outputDevices.setCurrentIndex(output_index) # Set Excitation Signal default_signal = str(self.measurement_settings["signal type"]) signal_index = self.signalType.findText(default_signal) self.signalType.setCurrentIndex(signal_index) # Set swept sine signal settings upper_frequency = int(self.measurement_settings["upper frequency"]) self.upperFreq.setValue(upper_frequency) # Signal length is in seconds, convert to ms signal_length = float(self.measurement_settings["signal length"]) signal_length *= 1000 self.signalLength.setValue(int(signal_length)) # Set MLS / IRS settings num_taps = int(self.measurement_settings["mls taps"]) print self.measurement_settings self.numTaps.setValue(num_taps) num_bursts = int(self.measurement_settings["mls reps"]) self.numBursts.setValue(num_bursts) signal_reps = int(self.measurement_settings["signal reps"]) self.numRepititions.setValue(signal_reps) # Set filter options lpf_cutoff = int(self.measurement_settings["lpf cutoff"]) lpf_order = int(self.measurement_settings["lpf order"]) hpf_cutoff = int(self.measurement_settings["hpf cutoff"]) hpf_order = int(self.measurement_settings["hpf order"]) # Band Pass Filter self.freqLow.setValue(lpf_cutoff) self.orderLow.setValue(lpf_order) self.freqHigh.setValue(hpf_cutoff) self.orderHigh.setValue(hpf_order) # Low Pass Filter self.freqLPF.setValue(lpf_cutoff) self.orderLPF.setValue(lpf_order) # High Pass Filter self.freqHPF.setValue(hpf_cutoff) self.orderHPF.setValue(hpf_order) # Set the correct drop-down options lpf_enabled = int(self.measurement_settings["lpf enabled"]) hpf_enabled = int(self.measurement_settings["hpf enabled"]) if lpf_enabled == 1 and hpf_enabled == 1: # Band pass filter bpf_index = self.filterType.findText("Bandpass Filter") self.filterType.setCurrentIndex(bpf_index) elif lpf_enabled == 1: # Low pass filter lpf_index = self.filterType.findText("Low Pass Filter") self.filterType.setCurrentIndex(lpf_index) elif hpf_enabled == 1: # High pass filter hpf_index = self.filterType.findText("High Pass Filter") self.filterType.setCurrentIndex(hpf_index) else: # Disabled index = self.filterType.findText("Disabled") self.filterType.setCurrentIndex(index) # Set window options window_length = int(self.measurement_settings["window length"]) taper_length = int(self.measurement_settings["taper length"]) self.winLength.setValue(window_length) self.taperLength.setValue(taper_length) def _showSaveDialog(self, file_type): """ Shows the save dialog to get the filename to save the required data to. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showSaveDialog") if file_type == "graph": caption = "Select file to save the graph" filter = "PNG (*.png)" signal = self.saveGraph elif file_type == "csv": caption = "Select file to export data to" filter = "CSV (*.csv)" signal = self.exportData elif file_type == "measurement": caption = "Select file to save the measurement to" filter = "FrequencyResponse (*.fdb)" signal = self.saveMeasurement else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getSaveFileName(self, caption, dir, filter) if filename != "": signal.emit(filename) def _showOpenDialog(self, file_type): """ Shows the open dialog to get the filename to load the required data. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showOpenDialog") if file_type == "measurement": caption = "Select Measurement File to Load" filter = "FrequencyResponse (*.fdb)" signal = self.loadMeasurement else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getOpenFileName(self, caption, dir, filter) # filename is a tuple (filename, selected filter) when file is selected # else a blank string if dialog closed print filename if filename != "": signal.emit(filename)
# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys, os from Grapher import Grapher if len(sys.argv) < 2: print "usage: python test_Grapher.py path" sys.exit(1) path = sys.argv[1] configNames = ["test_grapher0", "test_grapher1", "test_grapher2"] fullConfigPaths = [os.path.join(path, config) for config in configNames] grapher = Grapher(fullConfigPaths) outputs = grapher.readOutputs() for dataSet in outputs: print (dataSet.getLatestVar("config", "x") + " : " + dataSet.getLatestVar("test_section", "y")) fig, axes = grapher.simple2D("config", "x", "test_section", "y") grapher.setAxisLabels(axes, "x", "y") figurePath = os.path.join(path, "testFig") grapher.saveFigure(fig, figurePath)
from TrafficMonitor import TrafficMonitor import networkx as nx if __name__ == "__main__": # start parser with command line arg p = Parser( sys.argv[1] ) # this is the topology in json net = p.xml_to_json() # list of emulated flows emuflows = p.emuflows() # translate to networkx graph = Grapher( net ) g = graph.json_to_graph() d = Downscaler( emuflows, g ) pipes = d.get_pipes() for p in pipes: print p print '\n' st = SymbioTopo( net, pipes ) st.getNodes() for e in emuflows:
class RapidController(QMainWindow, Ui_RapidAlphaWindow): # pyqtSignals startMeasurement = pyqtSignal() saveGraph = pyqtSignal("QString") exportData = pyqtSignal("QString") loadMeasurement = pyqtSignal("QString") saveMeasurement = pyqtSignal("QString") showPreferences = pyqtSignal() savePreferences = pyqtSignal("QString") loadPreferences = pyqtSignal("QString") exit = pyqtSignal() def __init__(self, measurement_settings, audio_devices): """ Constructor for RapidController, sets up the view, signals and shows the window. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating RapidController") QMainWindow.__init__(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self.alpha = None self.setupUi(self) self._setupWidgets() self._setupSignals() self.showMaximized() def update(self): """ Updates the graph showing the absorption coefficient of the material measured. """ self.logger.debug("Entering update") self.grapher.graphAbsorption(self.alpha.alpha, self.AlphaPlot) self.grapher.graphCepstrum(self.alpha.microphone_cepstrum, self.alpha.generator_cepstrum, self.alpha.power_cepstrum, self.alpha.impulse_response, self.alpha.window, float(self.alpha.measurement_settings["window start"]), self.CepstrumPlot) def _setupWidgets(self): """ Setup the widgets to show the user. The graph is formatted with no data. """ self.logger.debug("Entering _setupWidgets") self.grapher.graphAbsorption([], self.AlphaPlot) self.grapher.graphCepstrum([], [], [], [], [], 0, self.CepstrumPlot) # Add Volume slider to toolbar self.gainSlider = QSlider(Qt.Horizontal) self.gainSlider.setMaximumWidth(100) self.gainSlider.setMaximum(0) self.gainSlider.setMinimum(-1000) self.gainSpin = QDoubleSpinBox() self.gainSpin.setMaximum(0) self.gainSpin.setMinimum(-10) self.gainSpin.setSingleStep(0.01) self.toolBar.addSeparator() self.toolBar.addWidget(QSpacerItem(0,0).widget()) self.toolBar.addWidget(QLabel("Gain: ")) self.toolBar.addWidget(self.gainSlider) self.toolBar.addWidget(self.gainSpin) self.toolBar.addWidget(QLabel(" dB")) self.updateWidgets() def updateWidgets(self): """ Set the values for widgets on the screen. """ gain = 20 * log10(float(self.measurement_settings["gain"]) ) self.gainSlider.setValue(gain) self.gainSpin.setValue(gain) def _updateMeasurementSettings(self): """ Update the Measurement Settings dictionary. For the Rapid View, the only settings that change are the input and output devices. """ self.logger.debug("Entering _updateMeasurementSettings") selected_index = self.InputDeviceList.currentIndex() input_device = self.InputDeviceList.itemData(selected_index).toInt() self.measurement_settings["input device"] = input_device[0] selected_index = self.OutputDeviceList.currentIndex() output_device = self.OutputDeviceList.itemData(selected_index).toInt() self.measurement_settings["output device"] = output_device[0] def _setupSignals(self): """ Connects the various button signals to the class signals. """ self.logger.debug("Entering _setupSignals") save_func = self._showSaveDialog self.actionSave.triggered.connect(lambda: save_func("measurement")) self.actionExport_Data.triggered.connect(lambda: save_func("csv")) self.actionExport_Graph.triggered.connect(lambda: save_func("graph")) self.actionSave_Preferences.triggered.connect(lambda: save_func("preferences")) load_func = self._showOpenDialog self.actionSave_Preferences.triggered.connect(lambda: load_func("preferences")) self.actionLoad_Measurement.triggered.connect(lambda: load_func("measurement")) self.actionExit.triggered.connect(self.exit) self.actionStart_Measurement.triggered.connect(self.startMeasurement) self.actionPreferences.triggered.connect(self.showPreferences) self.gainSlider.valueChanged.connect(self._updateWidgets) self.gainSpin.valueChanged.connect(self._updateWidgets) def _updateWidgets(self): """ Keeps widgets synchronized with the measurement settings, and each other """ self.logger.debug("Entering _updateWidgets") # Keep the gain in sync gain = float(self.measurement_settings["gain"]) gain_db = 20 * log10(gain) self.logger.debug("sender: %s" %(self.sender())) if self.sender() == self.gainSlider: self.logger.debug("Slider: %s" % (self.gainSlider.value())) self.gainSpin.setValue((self.gainSlider.value() / 100.0)) elif self.sender() == self.gainSpin: self.gainSlider.setValue(self.gainSpin.value() * 100.0) gain = 10 ** (self.gainSpin.value() / 20.0) self.measurement_settings["gain"] = gain def _showOpenDialog(self, file_type): """ Shows the open dialog to get the filename to load the required data. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showOpenDialog") if file_type == "measurement": caption = "Select Measurement File to Load" filter = "AlphaDb (*.db)" signal = self.loadMeasurement elif file_type == "preferences": caption = "Select Preferences File to Load" filter = "Preferences (*.db)" signal = self.loadPreferences else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getOpenFileName(self, caption, dir, filter) # filename is a tuple (filename, selected filter) when file is selected # else a blank string if dialog closed print filename if filename != "": signal.emit(filename) def _showSaveDialog(self, file_type): """ Shows the save dialog to get the filename to save the required data to. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showSaveDialog") if file_type == "graph": caption = "Select file to save the graph" supported_file_types = self.AlphaPlot.figure.canvas.get_supported_filetypes_grouped() # Get available output formats filter = [] for key, value in supported_file_types.items(): filter.append("%s (*.%s)" % (key, " *.".join(value))) filter = ";;".join(filter) signal = self.saveGraph elif file_type == "csv": caption = "Select file to export data to" filter = "CSV (*.csv)" signal = self.exportData elif file_type == "measurement": caption = "Select file to save the measurement to" filter = "AlphaDb (*.db)" signal = self.saveMeasurement elif file_type == "preferences": caption = "Select Filename to save Preferences" filter = "Preferences (*.db)" signal = self.savePreferences else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getSaveFileName(self, caption, dir, filter) if filename != "": signal.emit(filename)
class FrequencyResponseController(QMainWindow, Ui_FrequencyResponse): # pyqtSignals startMeasurement = pyqtSignal() updateExctration = pyqtSignal() saveGraph = pyqtSignal("QString") exportData = pyqtSignal("QString") loadMeasurement = pyqtSignal("QString") saveMeasurement = pyqtSignal("QString") def __init__(self, measurement_settings, audio_devices): """ Constructor to for the Frequency Response view. :param measurement_settings: A dictionary containing the settings to used for the measurement. :type measurement_settings: dict :param audio_devices: A list of all the input / output devices available in the system. :type: array of AudioDevice """ self.logger = logging.getLogger("Alpha") self.logger.debug("Creating FrequencyResponseController") QMainWindow.__init__(self) self.setupUi(self) self.measurement_settings = measurement_settings self.audio_devices = audio_devices self.grapher = Grapher(self.measurement_settings) self._populateWidgets() self._loadSettings() self._setupSignals() self._updateWidgets() self.showMaximized() def updateGraphs(self): """ Function called to update the graphs, called when the measurement is first loaded, also called when extraction options have been updated. """ self.logger.debug("Entering updateGraphs") self.grapher.graphImpulseResponse(self.freq_response.impulse_response, self.impulsePlot) self.grapher.graphFrequencyResponse( self.freq_response.frequency_response, self.frequencyPlot) def _setupSignals(self): """ Connects various signals that will be emitted to the required slots. """ self.logger.debug("Setting up signals") # Update measurement settings whenever a setting has updated # Combo Boxes self.inputDevices.currentIndexChanged["int"].connect( self._updateSettings) self.outputDevices.currentIndexChanged["int"].connect( self._updateSettings) self.signalType.currentIndexChanged["int"].connect( self._updateSettings) self.filterType.currentIndexChanged["int"].connect( self._updateSettings) self.signalType.currentIndexChanged["int"].connect(self._updateWidgets) self.filterType.currentIndexChanged["int"].connect(self._updateWidgets) # Signal Settings self.numTaps.valueChanged["int"].connect(self._updateSettings) self.numBursts.valueChanged["int"].connect(self._updateSettings) self.upperFreq.valueChanged["int"].connect(self._updateSettings) self.signalLength.valueChanged["int"].connect(self._updateSettings) self.numRepititions.valueChanged["int"].connect(self._updateSettings) # Filter Settings self.freqLPF.valueChanged["int"].connect(self._updateSettings) self.orderLPF.valueChanged["int"].connect(self._updateSettings) self.freqHPF.valueChanged["int"].connect(self._updateSettings) self.orderHPF.valueChanged["int"].connect(self._updateSettings) self.freqLow.valueChanged["int"].connect(self._updateSettings) self.orderLow.valueChanged["int"].connect(self._updateSettings) self.freqHigh.valueChanged["int"].connect(self._updateSettings) self.orderHigh.valueChanged["int"].connect(self._updateSettings) # Window Settings self.winLength.valueChanged["int"].connect(self._updateSettings) self.taperLength.valueChanged["int"].connect(self._updateSettings) # Emit signal when new measurement button is pressed self.startButton.clicked.connect(self.startMeasurement) load_func = self._showOpenDialog self.actionOpen.triggered.connect(lambda: load_func("measurement")) # Emit a signal when the window settings have changed self.winLength.valueChanged["int"].connect(self.updateExctration) self.taperLength.valueChanged["int"].connect(self.updateExctration) def _updateWidgets(self): """ Certain widgets have side-effects on other widgets. This method will keep widgets synchronized. """ self.logger.debug("Entering _updateWidgets") # The signal options stacked widget has two pages, one for MLS-type # signals, and one for swept sine signals. signal_type = str(self.signalType.currentText()) if (signal_type == "Inverse Repeat Sequence" or signal_type == "Maximum Length Sequence"): self.signalOptions.setCurrentIndex(0) else: self.signalOptions.setCurrentIndex(1) # The filter options stacked widget has 4 pages, one for when no filters # are enabled, one for low pass, one for high pass and one for band pass filter_type = str(self.filterType.currentText()) if filter_type == "Disabled": self.filterOptions.setCurrentIndex(0) elif filter_type == "Low Pass Filter": self.filterOptions.setCurrentIndex(1) elif filter_type == "High Pass Filter": self.filterOptions.setCurrentIndex(2) elif filter_type == "Bandpass Filter": self.filterOptions.setCurrentIndex(3) def _populateWidgets(self): """ Populates some widgets with default values. Adds excitation signals to the drop-down box Adds the various filters. Populates the input / output device. """ self.logger.debug("Entering populateWidgets") # Populate Audio device drop-down boxes self.inputDevices.clear() self.outputDevices.clear() for audio_device in self.audio_devices: if audio_device.input_channels > 0: self.inputDevices.addItem(audio_device.name, audio_device.index) if audio_device.output_channels > 0: self.outputDevices.addItem(audio_device.name, audio_device.index) # Populate Excitation Signals self.signalType.clear() self.signalType.addItem("Inverse Repeat Sequence") self.signalType.addItem("Maximum Length Sequence") self.signalType.addItem("Low Pass Swept Sine") self.signalType.addItem("Swept Sine") # Populate Filters self.filterType.clear() self.filterType.addItem("Disabled") self.filterType.addItem("Low Pass Filter") self.filterType.addItem("High Pass Filter") self.filterType.addItem("Bandpass Filter") def _updateSettings(self): """ When settings change, updated the measurement settings dictionary associated with the dialog. """ self.logger.debug("Updating measurement settings") # Update Audio Devices selected_index = self.inputDevices.currentIndex() input_device = self.inputDevices.itemData(selected_index).toInt() self.measurement_settings["input device"] = int(input_device[0]) selected_index = self.outputDevices.currentIndex() output_device = self.outputDevices.itemData(selected_index).toInt() self.measurement_settings["output device"] = int(output_device[0]) # Update excitation signal signal_type = str(self.signalType.currentText()) self.measurement_settings["signal type"] = signal_type upper_frequency = self.upperFreq.value() self.measurement_settings["upper frequency"] = int(upper_frequency) signal_length = self.signalLength.value() # signal_length is in ms, convert to seconds signal_length /= 1000 self.measurement_settings["signal length"] = signal_length num_taps = self.numTaps.value() self.measurement_settings["mls taps"] = int(num_taps) num_bursts = self.numBursts.value() self.measurement_settings["mls reps"] = int(num_bursts) signal_reps = self.numRepititions.value() self.measurement_settings["signal reps"] = int(signal_reps) # Update filter settings filter_type = self.filterType.currentText() if filter_type == "Bandpass Filter": lpf_cutoff = self.freqLow.value() lpf_order = self.orderLow.value() hpf_cutoff = self.freqHigh.value() hpf_order = self.orderHigh.value() lpf_enabled = 1 hpf_enabled = 1 self.measurement_settings["lpf cutoff"] = int(lpf_cutoff) self.measurement_settings["lpf order"] = int(lpf_order) self.measurement_settings["hpf cutoff"] = int(hpf_cutoff) self.measurement_settings["hpf order"] = int(hpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "Low Pass Filter": lpf_cutoff = self.freqLPF.value() lpf_order = self.orderLPF.value() lpf_enabled = 1 hpf_enabled = 0 self.measurement_settings["lpf cutoff"] = int(lpf_cutoff) self.measurement_settings["lpf order"] = int(lpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "High Pass Filter": hpf_cutoff = self.freqHPF.value() hpf_order = self.orderHPF.value() lpf_enabled = 0 hpf_enabled = 1 self.measurement_settings["hpf cutoff"] = int(hpf_cutoff) self.measurement_settings["hpf order"] = int(hpf_order) self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled elif filter_type == "Disabled": lpf_enabled = 0 hpf_enabled = 0 self.measurement_settings["lpf enabled"] = lpf_enabled self.measurement_settings["hpf enabled"] = hpf_enabled # Update Window options window_length = self.winLength.value() self.measurement_settings["window length"] = int(window_length) taper_length = self.taperLength.value() self.measurement_settings["taper length"] = int(taper_length) def _loadSettings(self): """ Loads the default settings for the frequency response measurements. """ self.logger.debug("Loading default settings") # Set the audio devices default_input_device = int(self.measurement_settings["input device"]) input_index = self.inputDevices.findData(default_input_device) self.inputDevices.setCurrentIndex(input_index) default_output_device = int(self.measurement_settings["output device"]) output_index = self.outputDevices.findData(default_output_device) self.outputDevices.setCurrentIndex(output_index) # Set Excitation Signal default_signal = str(self.measurement_settings["signal type"]) signal_index = self.signalType.findText(default_signal) self.signalType.setCurrentIndex(signal_index) # Set swept sine signal settings upper_frequency = int(self.measurement_settings["upper frequency"]) self.upperFreq.setValue(upper_frequency) # Signal length is in seconds, convert to ms signal_length = float(self.measurement_settings["signal length"]) signal_length *= 1000 self.signalLength.setValue(int(signal_length)) # Set MLS / IRS settings num_taps = int(self.measurement_settings["mls taps"]) print self.measurement_settings self.numTaps.setValue(num_taps) num_bursts = int(self.measurement_settings["mls reps"]) self.numBursts.setValue(num_bursts) signal_reps = int(self.measurement_settings["signal reps"]) self.numRepititions.setValue(signal_reps) # Set filter options lpf_cutoff = int(self.measurement_settings["lpf cutoff"]) lpf_order = int(self.measurement_settings["lpf order"]) hpf_cutoff = int(self.measurement_settings["hpf cutoff"]) hpf_order = int(self.measurement_settings["hpf order"]) # Band Pass Filter self.freqLow.setValue(lpf_cutoff) self.orderLow.setValue(lpf_order) self.freqHigh.setValue(hpf_cutoff) self.orderHigh.setValue(hpf_order) # Low Pass Filter self.freqLPF.setValue(lpf_cutoff) self.orderLPF.setValue(lpf_order) # High Pass Filter self.freqHPF.setValue(hpf_cutoff) self.orderHPF.setValue(hpf_order) # Set the correct drop-down options lpf_enabled = int(self.measurement_settings["lpf enabled"]) hpf_enabled = int(self.measurement_settings["hpf enabled"]) if lpf_enabled == 1 and hpf_enabled == 1: # Band pass filter bpf_index = self.filterType.findText("Bandpass Filter") self.filterType.setCurrentIndex(bpf_index) elif lpf_enabled == 1: # Low pass filter lpf_index = self.filterType.findText("Low Pass Filter") self.filterType.setCurrentIndex(lpf_index) elif hpf_enabled == 1: # High pass filter hpf_index = self.filterType.findText("High Pass Filter") self.filterType.setCurrentIndex(hpf_index) else: # Disabled index = self.filterType.findText("Disabled") self.filterType.setCurrentIndex(index) # Set window options window_length = int(self.measurement_settings["window length"]) taper_length = int(self.measurement_settings["taper length"]) self.winLength.setValue(window_length) self.taperLength.setValue(taper_length) def _showSaveDialog(self, file_type): """ Shows the save dialog to get the filename to save the required data to. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showSaveDialog") if file_type == "graph": caption = "Select file to save the graph" filter = "PNG (*.png)" signal = self.saveGraph elif file_type == "csv": caption = "Select file to export data to" filter = "CSV (*.csv)" signal = self.exportData elif file_type == "measurement": caption = "Select file to save the measurement to" filter = "FrequencyResponse (*.fdb)" signal = self.saveMeasurement else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getSaveFileName(self, caption, dir, filter) if filename != "": signal.emit(filename) def _showOpenDialog(self, file_type): """ Shows the open dialog to get the filename to load the required data. :param file_type: The type of data to be saved, could be one of "graph", "csv", "measurement" :type file_type: str """ self.logger.debug("Entering _showOpenDialog") if file_type == "measurement": caption = "Select Measurement File to Load" filter = "FrequencyResponse (*.fdb)" signal = self.loadMeasurement else: self.logger.debug("Invalid file_type passed: %s" % (file_type)) return dir = "./" filename = QFileDialog.getOpenFileName(self, caption, dir, filter) # filename is a tuple (filename, selected filter) when file is selected # else a blank string if dialog closed print filename if filename != "": signal.emit(filename)
#!/bin/python from Parser import Parser from Grapher import Grapher from networkx.readwrite import json_graph import networkx as nx import json import sys if __name__ == "__main__": p = Parser( sys.argv[1] ) g = Grapher ( p.xml_to_json() ) graph = g.json_to_graph() for n in graph: graph.node[n]['name'] = n d = json_graph.node_link_data( graph ) json.dump( d, open( 'graph.json', 'w' ) )
def __init__(self, nn_conf): print "[+] Building neural network... [NeuralNetwork]" self.__conf_params = nn_conf.get_NN_parameters() self.__iterations = self.__conf_params[Conf_Params.ITERATIONS] self.__nodes_per_layer = self.__conf_params[Conf_Params.NODES_PER_LAYER] self.__input_number = self.__conf_params[Conf_Params.INPUTS_NUMBER] self.__path_training = self.__conf_params[Conf_Params.TRAIN_FILE_PATH] self.__output_number = self.__nodes_per_layer[len(self.__nodes_per_layer) - 1] self.__path_weights = self.__conf_params[Conf_Params.WEIGHTS_FILE] self.__algorithm = self.__conf_params[Conf_Params.ALGORITHM] # The self.__conf_params[6] is the conf_file. Here it is not needed. self.__learning_rate = self.__conf_params[Conf_Params.LEARNING_RATE] self.__learning_type = self.__conf_params[Conf_Params.LEARNING_TYPE] self.__phase = self.__conf_params[Conf_Params.PHASE] self.__enabled_graphics = self.__conf_params[Conf_Params.ENABLED_GRAPHICS] if self.__enabled_graphics == "on": # Each point is the average error of all instances in that iteration self.__mean_grapher = Grapher("Error evolution", "Iteration", "Error") # Average output error of all instances for all iterations self.__grapher = Grapher("Average output error of all instances for all iterations", "Instance", "Error") # If something goes wrong initializating the graphers if not (self.__mean_grapher and self.__grapher): self.__enabled_graphics = "off" self.__sigmoid = self.__conf_params[Conf_Params.SIGMOID] self.__momentum = self.__conf_params[Conf_Params.MOMENTUM] # First of all, we add the input nodes as a layer. We will work with input nodes as nodes in a normal layer # Layer 0 will be the one with the inputs. ''' We don't have anymore the input nodes list. That data belongs to the topology parameter count = 0 nodes_list = [] for i in range(self.__input_number): node = Node(i) nodes_list.append(node) layer = Layer(count, nodes_list) self.__layers.append(layer) ''' count = 0 for n_nodes in self.__nodes_per_layer: nodes_list = [] count += 1 for i in range(n_nodes): node = Node(i) # pos_in_layer, error, weight list, value. If not specified, getting default values in node constructor. nodes_list.append(node) layer = Layer(count, nodes_list) self.__layers.append(layer) if not self.__layers: print "[-] There are no layers. Something went wrong. [NeuralNetwork]" print "[*] See you, neural cowboy." exit() if len(self.__layers) == 1: print "[-] The is only one layer (in theory, input layer). You need at least inputs and one more layer. [NeuralNetwork]" print "[*] See you, neural cowboy." exit() # Here we have built all the layers with the nodes of the neural network. # We have to obtain all the dataset instances. The instances will be stored in a list # of lists of n+1 positions where n is the number of inputs and x is the number of outputs ds = Dataset(self.__conf_params) self.__dataset = ds.get_instances() # Once here, we have to return and the activate method must be invoked. print "[+] Neural network built. [NeuralNetwork]"