def updateRoomOccupancy (): users = roomParameters.defaultUsers print("Updating room occupancy... ", end=" ") for i in range(len(rooms)): rooms[str(i)]["peopleInRoom"] = 0 for j in range(1, len(users)): if users[str(j)]["location"] == str(i): rooms[str(i)]["peopleInRoom"] += 1 print("Done") print("Uploading room occupancy... ", end=" ") #s.Signal("", peopleInRoomToken).write(rooms["0"]["peopleInRoom"]) # Outside s.Signal("20978", peopleInRoomToken).write(rooms["1"]["peopleInRoom"]) # Toilet s.Signal("15116", peopleInRoomToken).write(rooms["2"]["peopleInRoom"]) # Bathroom s.Signal("9237", peopleInRoomToken).write(rooms["3"]["peopleInRoom"]) # Kitchen s.Signal("5933", peopleInRoomToken).write(rooms["4"]["peopleInRoom"]) # Livingroom s.Signal("30782", peopleInRoomToken).write(rooms["5"]["peopleInRoom"]) # Bedroom1 s.Signal("19013", peopleInRoomToken).write(rooms["6"]["peopleInRoom"]) # Bedtoom2 s.Signal("17378", peopleInRoomToken).write(rooms["7"]["peopleInRoom"]) # Bedroom3 s.Signal("19280", peopleInRoomToken).write(rooms["8"]["peopleInRoom"]) # Bedroom4 s.Signal("25397", peopleInRoomToken).write(rooms["9"]["peopleInRoom"]) # Bedroom5 s.Signal("24559", peopleInRoomToken).write(rooms["10"]["peopleInRoom"])# Bedroom6 print("Done")
def __init__(self): import gtk.glade import Paths import Signals root = 'first-time' self.__xml = gtk.glade.XML(Paths.glade, root) self.__dialog = self.__get_widget(root) Signals.autoconnect(self, self.__xml) # hook up GConf configuration monitoring import gconf from GConfDir import GConfDir self.__client = gconf.client_get_default() self.__dir = GConfDir(self.__client, Keys.root, gconf.CLIENT_PRELOAD_NONE) # hook up state-linked icons from StatusIcon import StatusIcon from WindowIcon import WindowIcon image = self.__get_widget('image') self.__image_updater = StatusIcon(self.__client, image, gtk.ICON_SIZE_DIALOG) self.__icon_updater = WindowIcon(self.__client, self.__dialog) # hook up state-linked radio buttons from MasterNotifier import MasterNotifier self.__notifier = MasterNotifier(self.__client, self.__enabled_refresh)
def __init__(self, client): xml = gtk.glade.XML(Paths.glade, 'about') self.__widget = xml.get_widget('about') Signals.autoconnect(self, xml) self.__widget.set_property('name', 'Bug Isolation Monitor') self.__widget.set_property('version', SamplerConfig.version) self.__icon_updater = WindowIcon(client, self.__widget) self.__notifier = MasterNotifier(client, self.__enabled_refresh)
def __init__(self, client, tray): xml = gtk.glade.XML(Paths.glade, 'popup') Signals.autoconnect(self, xml) self.__about = AboutDialog(client) self.__client = client self.__master = xml.get_widget('menu-master') self.__notifier = MasterNotifier(self.__client, self.__master.set_active) self.__tray = tray self.__widget = xml.get_widget('popup')
def updateRoomTempSP(self): hour = int(datetime.datetime.now().strftime("%H")) roomTempTable = self.getRoomTempTimetableFromFile() for i in self.rooms: if self.rooms[i]['roomName'] == 'outside': continue tempSV = int(roomTempTable.loc[hour, f"{self.rooms[i]['roomName']}"]) roomParameters.defaultRoomParameters[i]["tempSV"] = tempSV rooms = roomParameters.defaultRoomParameters s.Signal( "2543", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDg2In0.tyfmG1iU9rh9WTSgQWSjeFRB4hv8XfEH166Oz2MvUlg" ).write(rooms["1"]["tempSV"]) s.Signal( "22010", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjcxIn0.tcPW357AsU-ZQP8XrlSmbXu9q0Sto27hpiVv5pnSbGA" ).write(rooms["2"]["tempSV"]) s.Signal( "14456", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDg3In0.6MTURel9ZoJj50PN6aWAodakTv3k8rDjrF99Udk14nU" ).write(rooms["3"]["tempSV"]) s.Signal( "10733", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDg4In0.nw7WrxngCNMhk7SgNnmuSI2Ht8_ESCDfdhJZqB-joJc" ).write(rooms["4"]["tempSV"]) s.Signal( "25901", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDg5In0.BM73ysSfKKQDToNknonEI2KzO7oKwHQjLKUKIz9omyg" ).write(rooms["5"]["tempSV"]) s.Signal( "18399", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDkwIn0.-KW0hqJRmbC1W61EJNkv1HjI47RGzg6G30KzhQlGYbw" ).write(rooms["6"]["tempSV"]) s.Signal( "19772", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDkxIn0.aSusWa3j_LOPHIdmSh8vZ5GCzTTVaVOzoqqU_QfyCMw" ).write(rooms["7"]["tempSV"]) s.Signal( "19704", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDkyIn0.Wv9KcGzlGCMTB0cXM9t0s0jX8g0dmyG1CCzmvYE5V4k" ).write(rooms["8"]["tempSV"]) s.Signal( "10205", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDkzIn0.yQ3fNM61ecxH4U1f01kW9D8hUm5pbTlSNTPMMI9GKDc" ).write(rooms["9"]["tempSV"]) print( s.Signal( "22658", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDk0In0.yFXNG1sNpLgb30l7jGx7XFwLgxchWOMOQpHcwjcAZQE" ).write(rooms["10"]["tempSV"]))
def __init__(self): import gtk.glade import Paths import Signals xml = gtk.glade.XML(Paths.glade, 'preferences') Signals.autoconnect(self, xml) self.__dialog = xml.get_widget('preferences') import gconf from GConfDir import GConfDir self.__client = gconf.client_get_default() self.__dir = GConfDir(self.__client, Keys.root, gconf.CLIENT_PRELOAD_NONE) from AppFinder import AppFinder from AppModel import AppModel from Application import Application finder = AppFinder(self.__client) model = AppModel() for path in finder: Application(self.__client, model, path) from MasterNotifier import MasterNotifier from WindowIcon import WindowIcon self.__master = xml.get_widget('master') self.__apps_group = xml.get_widget('apps-group') self.__notifier = MasterNotifier(self.__client, self.__master_refresh) self.__icon = WindowIcon(self.__client, self.__dialog) view = xml.get_widget('applications') import gtk selection = view.get_selection() selection.set_mode(gtk.SELECTION_NONE) renderer = gtk.CellRendererText() column = gtk.TreeViewColumn('Application', renderer) column.set_cell_data_func(renderer, self.__name_data_func) column.set_sort_column_id(model.COLUMN_NAME) column.set_reorderable(True) column.set_resizable(True) view.append_column(column) renderer = gtk.CellRendererToggle() renderer.connect('toggled', self.on_application_toggled, model) column = gtk.TreeViewColumn('Enabled', renderer) column.set_cell_data_func(renderer, self.__enabled_data_func) column.set_sort_column_id(model.COLUMN_ENABLED) column.set_reorderable(True) view.append_column(column) view.set_model(model)
class EventsCore: signal_send_evnt = Signals.SignalSendEvnt() @staticmethod def _send_click_event(point, release_delay): press = EventsCore._create_press_event(point) release = EventsCore._create_release_event(point) EventsCore.signal_send_evnt.emit(press) sleep(release_delay) EventsCore.signal_send_evnt.emit(release) @staticmethod def _create_press_event(point): press = Qt.QMouseEvent(Qt.QMouseEvent.MouseButtonPress, point, Qt.Qt.LeftButton, Qt.Qt.LeftButton, Qt.Qt.NoModifier) return press @staticmethod def _create_release_event(point): release = Qt.QMouseEvent(Qt.QMouseEvent.MouseButtonRelease, point, Qt.Qt.LeftButton, Qt.Qt.LeftButton, Qt.Qt.NoModifier) return release
def testSynthetic(): '''Test against a synthetic set of pedestrians''' SIZE = 10.0 # define the domain minCorner = Vector2( -SIZE / 2.0, -SIZE / 2.0 ) domainSize = Vector2( SIZE, SIZE ) RES = int( SIZE / CELL_SIZE ) resolution = Vector2( RES, RES ) # define the signal ( a single point, moving from the origin to the corner traj, STEP_COUNT = syntheticPedestrians( SIZE ) print "Maximum kernel value:", kernel.data.max() print "Kernel sum: ", kernel.data.sum() grids = [] pedDomain = Grid.RectDomain( minCorner, domainSize ) sig = Signals.DiracSignal( pedDomain ) for i in xrange( STEP_COUNT ): sig.setData( traj[:, :, i] ) grid = Grid.DataGrid( minCorner, domainSize, resolution ) kernel.convolve( sig, grid ) ## grid.cells /= ( CELL_SIZE * CELL_SIZE ) grids.append( grid ) visGrids( grids )
def apriHDF(self, location): siglist = [] sigs = ss.Signals('SCAN_084.h5') for i in range(len(sigs.data)): siglist.append(sigs.data[i].Sig) return siglist
def __init__(self, base, content_type, body): import cgi import gnome import gtk.glade import gtkhtml2 import sys import BlipIcons import SamplerConfig import Paths import Signals argv = sys.argv sys.argv = [sys.argv[0]] gnome.program_init('wrapper', SamplerConfig.version) sys.argv = argv xml = gtk.glade.XML(Paths.glade) Signals.autoconnect(self, xml) self.__dialog = xml.get_widget('server-message') pixmap = self.__dialog.render_icon(BlipIcons.stock[True], BlipIcons.ICON_SIZE_EMBLEM, '') self.__dialog.set_icon(pixmap) document = gtkhtml2.Document() document.connect('request_url', self.on_request_url) document.connect('set_base', self.on_set_base) document.connect('link_clicked', self.on_link_clicked) document.connect('title_changed', self.on_title_changed) document.dialog = self.__dialog document.base = '' self.on_set_base(document, base) [mime_type, options] = cgi.parse_header(content_type) document.open_stream(mime_type) document.write_stream(body) document.close_stream() self.__document = document view = gtkhtml2.View() view.set_document(document) port = xml.get_widget('html-scroll') port.add(view) view.show()
def browseFile(self): fName = QtGui.QFileDialog.getOpenFileName( self, 'Browse file', "Open new file", self.tr("All Files (*);;Text Files (*txt)")) if fName.isEmpty() == False: self.segnali = Sig.Signals(str(fName)) self.allinea() self.stampa()
def printSig(self): import Signals as ss import PreAllinea segnali = ss.Signals(str(self.fileLocation)) lista_segnali = [] shift = PreAllinea.getShift() for i in range(24): if i < 8: segnale = segnali.SigData(i) lista_segnali.append(segnale) lista_segnali[i].SigShift(shift[i]) self.ax1.plot(segnale.x, segnale.SigFir(10)) self.ax1.set_xlim(1000, 2300) self.ax1.set_ylim(1e-1, 100000) elif (i > 7 and i < 16): segnale = segnali.SigData(i) lista_segnali.append(segnale) lista_segnali[i].SigShift(shift[i]) self.ax2.plot(segnale.x, segnale.SigFir(10)) self.ax2.set_xlim(1000, 2300) self.ax2.set_ylim(1e-1, 100000) elif (i > 15 and i < 24): segnale = segnali.SigData(i) lista_segnali.append(segnale) lista_segnali[i].SigShift(shift[i]) self.ax3.plot(segnale.x, segnale.SigFir(10)) self.ax3.set_xlim(1000, 2300) self.ax3.set_ylim(1e-1, 100000) else: segnale = segnali.SigData(i) lista_segnali.append(segnale) lista_segnali[i].SigShift(shift[i]) self.ax4.plot(segnale.x, segnale.SigFir(10)) self.ax4.set_xlim(1000, 2300) self.ax4.set_ylim(1e-1, 100000) self.ax1.semilogy() self.ax2.semilogy() self.ax3.semilogy() self.ax4.semilogy() self.canvas.show()
def generate_FSK_Signal(self, _symbolSequence, _modulationIndex, _phase=0.0): self.generate_BaseBandSignal(_symbolSequence) sineArguments = np.pi * self.baseBandSignal.timeLine * \ ( 2 * self.carrierFreq + _modulationIndex / \ self.symbolDuration * self.baseBandSignal.samples) + _phase FSK_samples = np.sin(sineArguments) FSK_signal = sig.Signal(FSK_samples, self.sampleRate) return FSK_signal
def updateDashboard(): #The user that is used as a dashboard is Person1 dashboardToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk1In0.9bD-g6Gi40yjEiEYGOY1eoWl0wEuAZZN67yzS5gYOQs" #Update PowerCost in øre/kWh powerPriceNow_key = "1753" powerPriceNow = forbruksModell.userPowerConsumption().recentPowerPrice() s.Signal(powerPriceNow_key, dashboardToken).write(powerPriceNow) #PowerUse #SolarPanel Production solarPP_key="2411" solarPanelPower = SolarPowerNow.SolarPower().getSolarPowerNow() s.Signal(solarPP_key, dashboardToken).write(solarPanelPower) #Weather currentWeather = SolarPowerNow.SolarPower().getWeatherNow() windSpeed = currentWeather["wind"]["speed"] temp = currentWeather["main"]["temp"] -273.15 weatherID = currentWeather["weather"][0]["id"] windSpeed_key = "12054" s.Signal(windSpeed_key, dashboardToken).write(windSpeed) Global_variabler2_Token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjcwIn0.4GshD9I6ZBE0roZzIsjHpIBLasIbH0JLc3TRhJwxJg8" weatherID_key = "39" s.Signal(weatherID_key, Global_variabler2_Token).write(weatherID) temp_key = "20183" s.Signal(temp_key, Global_variabler2_Token).write(temp)
def updateUserLocation(): print("Downloading user location data... ", end=" ") users = roomParameters.defaultUsers users["1"]["location"] = str(s.Signal("19808", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk1In0.9bD-g6Gi40yjEiEYGOY1eoWl0wEuAZZN67yzS5gYOQs").get()) users["2"]["location"] = str(s.Signal("24769", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk2In0.zADZlTeWjpJpbEmG_d1mcw07mDtT9ZJ30sMDtU1ex80").get()) users["3"]["location"] = str(s.Signal("20536", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk3In0.es9iHyTEfrYM3ksN0QWtiULhRlQEcwatXWHFc5_fscc").get()) users["4"]["location"] = str(s.Signal("3430", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk4In0.WP5pJqMaPL8AwEEii2TMFys9kQUabpl2iztyxBRdLuc").get()) users["5"]["location"] = str(s.Signal("2105", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk5In0.fbZfuVuDshnMdUMW6EXrB6fSYhtdq0l2-j92h6AtlbM").get()) users["6"]["location"] = str(s.Signal("10015", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjAwIn0.nGZXNRU34wVFtzex9tS-0gVky_ppn3Gjmj_riA4oLZY").get()) print("Done") updateRoomOccupancy ()
def updateGuestData(): print("Downloading guest data... ", end=" ") users = roomParameters.defaultUsers users["1"]["guests"] = fillStrToLen(s.Signal("24425", guestToken).get(), 2)[0] users["2"]["guests"] = fillStrToLen(s.Signal("10799", guestToken).get(), 2)[0] users["3"]["guests"] = fillStrToLen(s.Signal("9663", guestToken).get(), 2)[0] users["4"]["guests"] = fillStrToLen(s.Signal("2277", guestToken).get(), 2)[0] users["5"]["guests"] = fillStrToLen(s.Signal("31631", guestToken).get(), 2)[0] users["6"]["guests"] = fillStrToLen(s.Signal("27545", guestToken).get(), 2)[0] roomParameters.defaultUsers = users print("Done")
def __emit_main_wifi_changed(self, device_manager, device): self.__dbus_disconnect() # -- Connect our internal callback to the NM signal of this new object _signals = [[ 'changed', device.nm_dev, 'StateChanged', self.__nm_state_changed_cb ]] self.__dbus_signals = Signals.DBusSignals(_signals) self.__current_device = device self.__emit("main-wifi-changed", self.__current_device) if self.__trigger_state_change is True: self.__trigger_state_change = False self.__nm_state_changed_cb(int(device.nm_dev["State"]), NM_DEVICE_STATE_UNKNOWN, 0)
def updateRoomMaxCapacity(): print("Uploading Room Capacity... ", end=" ") s.Signal("1425", roomMaxCapacityToken).write(rooms["1"]["maxCapacity"]) # Toilet s.Signal("22847", roomMaxCapacityToken).write(rooms["2"]["maxCapacity"]) # Bathroom s.Signal("9237", roomMaxCapacityToken).write(rooms["3"]["maxCapacity"]) # Kitchen s.Signal("19992", roomMaxCapacityToken).write(rooms["4"]["maxCapacity"]) # Livingroom s.Signal("308868", roomMaxCapacityToken).write(rooms["5"]["maxCapacity"]) # Bedroom1 #s.Signal("308868", roomMaxCapacityToken).write(rooms["6"]["maxCapacity"]) # Bedtoom2 #s.Signal("308868", roomMaxCapacityToken).write(rooms["7"]["maxCapacity"]) # Bedroom3 #s.Signal("308868", roomMaxCapacityToken).write(rooms["8"]["maxCapacity"]) # Bedroom4 #s.Signal("308868", roomMaxCapacityToken).write(rooms["9"]["maxCapacity"]) # Bedroom5 #s.Signal("308868", roomMaxCapacityToken).write(rooms["10"]["maxCapacity"])# Bedroom6 s.Signal("23508", roomMaxCapacityToken).write(maxHouseCapacity) # House capacity s.Signal("19992", roomMaxCapacityToken).write(maxGuestsPrPersion) # guests pr. persion print("Done")
def splatAgents(self, gridDomain, radius, pedData, overwrite=True): '''Splats the agents onto a grid based on position and the given radius @param gridDomain An instance of AbstractGrid, specifying the grid domain and resolution over which the density field is calculated. @param radius The size (in world units) of the agent's visualization radius. @param pedData The pedestrian data to splat (the product of a call to trajectory.loadTrajectory). @param overwrite A boolean. Indicates whether files should be created even if they already exist or computed from scratch. If True, they are always created, if False, pre-existing files are used. @returns A string. The name of the output file. ''' kernel = Kernels.UniformCircleKernel(radius, gridDomain.cellSize[0], False) # False on reflect signal = Signals.PedestrianSignal(gridDomain.rectDomain) pedData.setNext(0) argsFunc = lambda: (signal.copyEmpty(), pedData, gridDomain, kernel) return self._threadWork('splat', threadConvolve, argsFunc, gridDomain, overwrite)
def __init(self): # -- Check if a modem is already connected so that we trigger a state check after emitting the main-modem-changed signal net_mgr = freedesktopnet.NetworkManager() for nm_dev in net_mgr.GetDevices(): if str(nm_dev["DeviceType"]) == "WIRELESS": self.__trigger_state_change = True break # -- These are the signals to be connected to Gobjects _signals = [ [ 'wifi-changed', self.device_manager, 'wifi-device-changed', self.__wifi_device_changed_cb ], [ 'device-removed', self.device_manager, 'device-removed', self.__device_removed_cb ], ] self.__signals = Signals.GobjectSignals(_signals)
def execute(self): '''Perform the work of the task''' if (self.work): print 'Density analysis: %s' % (self.workName) print "\tAccessing scb file:", self.scbName frameSet = NPFrameSet(self.scbName) workPath = self.getWorkPath('density') tempFile = os.path.join(workPath, self.workName) grids = Crowd.GridFileSequence(tempFile) if (self.work & AnalysisTask.COMPUTE): print "\tComputing" kernel = Kernels.GaussianKernel(self.smoothParam, self.cellSize, False) domain = makeDomain(self.domainX, self.domainY, self.cellSize) sigDomain = makeDomain(self.domainX, self.domainY) signal = Signals.PedestrianSignal( sigDomain ) # signal domain is the same as convolution domain s = time.clock() grids.convolveSignal(domain, kernel, signal, frameSet) print '\t\tdone in %.2f seconds' % (time.clock() - s) if (self.work & AnalysisTask.VIS): dataFile = grids.outFileName + ".density" if (not os.path.exists(dataFile)): print "\tCan't visualize density - unable to locate file: %s" % dataFile return imageName = os.path.join(workPath, '%s_density_' % self.workName) s = time.clock() reader = Crowd.GridFileSequenceReader(dataFile) try: colorMap = COLOR_MAPS[self.colorMapName] except: print '\tError loading color map: "%s", loading flame instead' % ( self.colorMapName) colorMap = COLOR_MAPS['flame'] print '\tCreating images' visualizeGFS(reader, colorMap, imageName, self.outImgType, 1.0, None) print '\t\tdone in %.2f seconds' % (time.clock() - s)
def testPedestrian(): '''Test against legitimate pedestrian data''' # pedestrian domain minCorner = Vector2( 0.0, -6 ) domainSize = Vector2( 2.4, 12 ) pedDomain = Grid.RectDomain( minCorner, domainSize ) # grid domain minCorner = Vector2( 0.0, -2 ) domainSize = Vector2( 2.4, 4 ) resolution = Vector2( domainSize.x / CELL_SIZE, domainSize.y / CELL_SIZE) gridDomain = Grid.AbstractGrid( minCorner, domainSize, resolution ) # load pedestrian data pedFile = '/projects/crowd/fund_diag/paper/pre_density/experiment/Inputs/Corridor_onewayDB/uo-065-240-240_combined_MB.txt' try: data = loadTrajectory ( pedFile ) except ValueError: print "Unable to recognize the data in the file: %s" % ( pedFile ) return grids = [] sig = Signals.PedestrianSignal( pedDomain ) print gridDomain while ( True ): try: sig.setData( data ) except StopIteration: break grid = gridDomain.getDataGrid() kernel.convolve( sig, grid ) ## grid.cells /= ( CELL_SIZE * CELL_SIZE ) print "Frame %d has min/max values: %f, %f" % ( sig.index, grid.minVal(), grid.maxVal() ) grids.append( grid ) ## break data.setNext( 0 ) visGrids( grids, data )
def updateUserLocation(self): """ Henter henter lokasjon til brukerne fra timeplanen, og oppdaterer den på CoT """ hour = int(datetime.datetime.now().strftime("%H")) tt = self.getUserHabitsFromFile() for i in self.users: location = str(tt.loc[hour, f"{self.users[i]['name']}_location"]) roomParameters.defaultUsers[i]["location"] = location users = roomParameters.defaultUsers s.Signal( "19808", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk1In0.9bD-g6Gi40yjEiEYGOY1eoWl0wEuAZZN67yzS5gYOQs" ).write(users["1"]["location"]) s.Signal( "24769", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk2In0.zADZlTeWjpJpbEmG_d1mcw07mDtT9ZJ30sMDtU1ex80" ).write(users["2"]["location"]) s.Signal( "20536", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk3In0.es9iHyTEfrYM3ksN0QWtiULhRlQEcwatXWHFc5_fscc" ).write(users["3"]["location"]) s.Signal( "3430", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk4In0.WP5pJqMaPL8AwEEii2TMFys9kQUabpl2iztyxBRdLuc" ).write(users["4"]["location"]) s.Signal( "2105", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTk5In0.fbZfuVuDshnMdUMW6EXrB6fSYhtdq0l2-j92h6AtlbM" ).write(users["5"]["location"]) s.Signal( "10015", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjAwIn0.nGZXNRU34wVFtzex9tS-0gVky_ppn3Gjmj_riA4oLZY" ).write(users["6"]["location"])
def debugFieldConvolve(): '''Test field convolution with a simple''' global CELL_SIZE if ( False ): # synthetic SCALE = 10#30 K_SIZE = 1.5 R = False ## kernel = Kernels.UniformKernel( K_SIZE * SCALE * CELL_SIZE, CELL_SIZE, R ) kernel = Kernels.TriangleKernel( K_SIZE * SCALE * CELL_SIZE / 1.1, CELL_SIZE, R ) ## kernel = Kernels.BiweightKernel( K_SIZE / 1.2 * SCALE * CELL_SIZE, CELL_SIZE, R ) ## kernel = Kernels.GaussianKernel( K_SIZE / 3.0 * SCALE * CELL_SIZE, CELL_SIZE, R ) # synthetic data # define the domain W = 8 * SCALE H = 10 * SCALE minCorner = Vector2( -W / 2.0, -H / 2.0 ) domainSize = Vector2( W * CELL_SIZE, H * CELL_SIZE ) resolution = ( W, H ) data = np.zeros( ( W, H ), dtype=np.float32 ) print data.shape winset = W / 2 - 2 * SCALE hinset = W / 2 - 2 * SCALE data[ winset:-winset, hinset:-hinset ] = 1.0 grid = Grid.DataGrid( minCorner, domainSize, resolution ) sigGrid = Grid.DataGrid() sigGrid.copyDomain( grid ) sigGrid.cells[ :, : ] = data signal = Signals.FieldSignal( sigGrid ) else: # voronoi signal CELL_SIZE = 0.025 K_SIZE = 1.0 R = True kernel = Kernels.UniformKernel( K_SIZE, CELL_SIZE, R ) ## kernel = Kernels.TriangleKernel( K_SIZE / 1.1, CELL_SIZE, R ) ## kernel = Kernels.BiweightKernel( K_SIZE / 1.2, CELL_SIZE, R ) ## kernel = Kernels.GaussianKernel( K_SIZE / 3.0, CELL_SIZE, R ) minCorner = Vector2( 0.0, -4.0 ) width = 2.4 height = 8.0 resolution = ( int( np.ceil( width / CELL_SIZE ) ), int( np.ceil( height / CELL_SIZE ) ) ) domainSize = Vector2( resolution[0] * CELL_SIZE, resolution[1] * CELL_SIZE ) sigGrid = Grid.DataGrid( minCorner, domainSize, resolution ) computeVornoiField( sigGrid ) signal = Signals.FieldSignal( sigGrid ) # set up convolution grid corner = Vector2( 0.0, -3 ) height = 6.0 resolution = ( int( np.ceil( width / CELL_SIZE ) ), int( np.ceil( height / CELL_SIZE ) ) ) domainSize = Vector2( resolution[0] * CELL_SIZE, resolution[1] * CELL_SIZE ) grid = Grid.DataGrid( corner, domainSize, resolution ) print "Input signal max:", sigGrid.cells.max() print "Input signal sum:", sigGrid.cells.sum() minVal = 0 maxVal = sigGrid.cells.max() s = sigGrid.surface( cMap, minVal, maxVal ) pygame.image.save( s, os.path.join( PATH, 'fieldBefore.png' ) ) kernel.convolve( signal, grid ) s = grid.surface( cMap, minVal, maxVal ) print "Convolved signal max:", grid.cells.max() print "Convolved signal sum:", grid.cells.sum() pygame.image.save( s, os.path.join( PATH, 'fieldAfter.png' ) )
ax1.plot([i for i in np.arange(0, 1.0, 0.01)], [i for i in np.arange(0, 1.0, 0.01)], "k-", markersize=1) ax1.legend(names, loc=4, prop={'size': 18}) ax1.set_xlabel("False Positive Rate", size=18) ax1.set_ylabel("True Positive Rate", size=18) plt.gcf().subplots_adjust(bottom=0.20) fig.savefig(filename, dpi=100) pt = [] SS = SSSDetect() n = 225 k = int(n**.5) S = Signals.EpsilonGraph(n, 2, 3.) mu = 3. rho = 80. iters = 500 pt.append(ROC(SS, S, n=n, d=2, k=k, mu=mu, iters=iters, rho=rho / k)) WD = TreeDetect() n = 225 k = int(n**.5) S = Signals.EpsilonGraph(n, 2, 3.) mu = 3. rho = 80. iters = 500 pt.append(ROC(WD, S, n=n, d=2, k=k, mu=mu, iters=iters, rho=rho / k)) MD = MaxDetect()
import Signals as Sig import matplotlib.pyplot as plt import numpy as np S = Sig.Record() S.ImportSac('data/CH.OTER2..EH2.D.2013.180.091135.SAC') S.ImportSac('data/CH.OTER2..EH2.D.2013.180.091135.SAC') S.ImportSac('data/CH.OTER2..EH2.D.2013.180.091135.SAC') a = S.CHN[0] S.Fourier(0) S.Fourier(1) b = S.CHN[0] S.Taper(0.2) c = S.CHN[0] S.Filter(0.0, 50., 4) d = S.CHN[0] plt.close('all') plt.figure() plt.plot(a, 'b') plt.plot(b, 'r') plt.plot(c, 'g') plt.plot(d, 'y') plt.show(block=False)
# === 读入数据 code = 'sz300001' df = Functions.import_stock_data(code) # 判断股票上市是否满一定时间,如果不满足,则不运行策略 if df.shape[0] < 250: print '股票上市未满一年,不运行策略' exit() # === 计算复权价 fuquan_type = '后复权' df[[i + '_' + fuquan_type for i in '开盘价', '最高价', '最低价', '收盘价' ]] = Functions.cal_fuquan_price(df, fuquan_type) # ===== 第二个模块:产生交易信号 # === 根据均线策略产生交易信号 df = Signals.signal_ma(df, ma_short=5, ma_long=50) # ===== 第三个模块: 根据交易信号计算每天的仓位 # ===计算仓位 df = Timing_Functions.position(df) # == 截取上市一年之后的交易日 df = df.iloc[250 - 1:] # 为什么是250-1? # 将第一天的仓位设置为 0 df.iloc[0, -1] = 0 # ===== 第四个模块: 根据仓位计算资金曲线 # === 简单方式 print Timing_Functions.equity_curve_simple(df) # === 实际方式
def main(): """Test the functionality""" from math import pi, exp import os, sys import optparse parser = optparse.OptionParser() # analysis to perform parser.add_option( "-d", "--density", help="Evaluate density.", action="store_true", dest='density', default=False ) parser.add_option( "-s", "--speed", help="Evaluate speed.", action="store_true", dest='speed', default=False ) parser.add_option( "-o", "--omega", help="Evaluate omega.", action="store_true", dest='omega', default=False ) parser.add_option( "-p", "--progress", help="Evaluate progress.", action="store_true", dest='progress', default=False ) parser.add_option( "-k", "--koshak", help="Evaluate koshak regions.", action="store_true", dest='koshak', default=False ) parser.add_option( "-i", "--include", help="Include all states", action="store_true", dest='includeAll', default=False ) # analysis domain - start, frame count, frame step parser.add_option( "-r", "--range", help="A triple of numbers: start frame, max frame count, frame step", nargs=3, action="store", dest='domain', type="int", default=(0, -1, 1) ) options, args = parser.parse_args() # input source file srcFile = sys.argv[1] pygame.init() CELL_SIZE = 0.2 MAX_AGENTS = -1 MAX_FRAMES = -1 FRAME_STEP = 1 FRAME_WINDOW = 1 START_FRAME = 0 EXCLUDE_STATES = () START_FRAME, MAX_FRAMES, FRAME_STEP = options.domain print "Command line:", START_FRAME, MAX_FRAMES, FRAME_STEP if ( True ): #increase the color bar specifications ColorMap.BAR_HEIGHT = 300 ColorMap.BAR_WIDTH = 30 ColorMap.FONT_SIZE = 20 timeStep = 1.0 outPath = '.' if ( True ): # This size doesn't work for 25k ## size = Vector2( 175.0, 120.0 ) ## minPt = Vector2( -75.0, -60.0 ) # this size DOES work for 25k size = Vector2( 215.0, 160.0 ) minPt = Vector2( -95.0, -80.0 ) res = (int( size.x / CELL_SIZE ), int( size.y / CELL_SIZE ) ) size = Vector2( res[0] * CELL_SIZE, res[1] * CELL_SIZE ) timeStep = 0.05 outPath = os.path.join( '/projects','tawaf','sim','jul2011','results' ) path = os.path.join( outPath, '{0}.scb'.format( srcFile ) ) print "Reading", path outPath = os.path.join( outPath, srcFile ) if ( not options.includeAll ): EXCLUDE_STATES = (1, 2, 3, 4, 5, 6, 7, 8, 9) domain = AbstractGrid( minPt, size, res ) print "Size:", size print "minPt:", minPt print "res:", res timeStep *= FRAME_STEP frameSet = FrameSet( path, START_FRAME, MAX_FRAMES, MAX_AGENTS, FRAME_STEP ) print "Total frames:", frameSet.totalFrames() grids = GridFileSequence( os.path.join( outPath, 'junk' ), Vector2(0,3.2), Vector2(-6., 6.)) colorMap = FlameMap() # output the parameters used to create the data # todo: R = 2.0 R = 1.5 def distFunc( dispX, dispY, radiusSqd ): """Constant distance function""" # This is the local density function provided by Helbing # using Gaussian, delta(in the equation) = radiusSqd return np.exp( -(dispX * dispX + dispY * dispY) / (2.0 * radiusSqd ) ) / ( 2.0 * np.pi * radiusSqd ) dfunc = lambda x, y: distFunc( x, y, R * R ) if ( options.density ): if ( not os.path.exists( os.path.join( outPath, 'dense' ) ) ): os.makedirs( os.path.join( outPath, 'dense' ) ) print "\tComputing density with R = %f" % R s = time.clock() kernel = Kernels.GaussianKernel( R, CELL_SIZE, False ) signal = Signals.PedestrianSignal( domain ) # signal domain is the same as convolution domain grids.convolveSignal( domain, kernel, signal, frameSet ) print "\t\tTotal computation time: ", (time.clock() - s), "seconds" print "\tComputing density images", s = time.clock() imageName = os.path.join( outPath, 'dense', 'dense' ) reader = GridFileSequenceReader( grids.outFileName + ".density" ) visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles ) print "Took", (time.clock() - s), "seconds" if ( options.speed ): if ( not os.path.exists( os.path.join( outPath, 'speed' ) ) ): os.makedirs( os.path.join( outPath, 'speed' ) ) print "\tComputing speeds", s = time.clock() stats = grids.computeSpeeds( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, GridFileSequence.BLIT_SPEED ) stats.write( os.path.join( outPath, 'speed', 'stat.txt' ) ) stats.savePlot( os.path.join( outPath, 'speed', 'stat.png' ), 'Average speed per step' ) print "Took", (time.clock() - s), "seconds" print "\tComputing speed images", s = time.clock() imageName = os.path.join( outPath, 'speed', 'speed' ) # the limit: 0.5 means the color map is saturated from from minVal to 50% of the range reader = GridFileSequenceReader( grids.outFileName + ".speed" ) visualizeGFS( reader, colorMap, imageName, 'png', 0.75, grids.obstacles ) print "Took", (time.clock() - s), "seconds" if ( options.omega ): if ( not os.path.exists( os.path.join( outPath, 'omega' ) ) ): os.makedirs( os.path.join( outPath, 'omega' ) ) print "\tComputing omega", s = time.clock() stats = grids.computeAngularSpeeds( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, GridFileSequence.BLIT_SPEED, FRAME_WINDOW ) stats.write( os.path.join( outPath, 'omega', 'stat.txt' ) ) stats.savePlot( os.path.join( outPath, 'omega', 'stat.png'), 'Average radial velocity per step' ) print "Took", (time.clock() - s), "seconds" print "\tComputing omega images", s = time.clock() imageName = os.path.join( outPath, 'omega', 'omega' ) colorMap = RedBlueMap() reader = GridFileSequenceReader( grids.outFileName + ".omega" ) visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles ) print "Took", (time.clock() - s), "seconds" if ( options.progress ): if ( not os.path.exists( os.path.join( outPath, 'progress' ) ) ): os.makedirs( os.path.join( outPath, 'progress' ) ) print "\tComputing progress", s = time.clock() stats = grids.computeProgress( minPt, size, res, R, frameSet, timeStep, EXCLUDE_STATES, FRAME_WINDOW ) stats.write( os.path.join( outPath, 'progress', 'stat.txt' ) ) stats.savePlot( os.path.join( outPath, 'progress', 'stat.png'), 'Average progress around Kaabah' ) print "Took", (time.clock() - s), "seconds" print "\tComputing progress images", s = time.clock() imageName = os.path.join( outPath, 'progress', 'progress' ) colorMap = FlameMap( (0.0, 1.0) ) reader = GridFileSequenceReader( grids.outFileName + ".progress" ) visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles ) print "Took", (time.clock() - s), "seconds" if ( False ): if ( not os.path.exists( os.path.join( outPath, 'advec' ) ) ): os.makedirs( os.path.join( outPath, 'advec' ) ) lines = [ Segment( Vector2(0.81592, 5.12050), Vector2( 0.96233, -5.27461) ) ] print "\tComputing advection", s = time.clock() grids.computeAdvecFlow( minPt, size, res, dfunc, 3.0, R, frameSet, lines ) print "Took", (time.clock() - s), "seconds" print "\tComputing advection images", s = time.clock() imageName = os.path.join( outPath, 'advec', 'advec' ) reader = GridFileSequenceReader( grids.outFileName + ".advec" ) visualizeGFS( reader, colorMap, imageName, 'png', 1.0, grids.obstacles ) print "Took", (time.clock() - s), "seconds" if ( options.koshak ): if ( not os.path.exists( os.path.join( outPath, 'regionSpeed' ) ) ): os.makedirs( os.path.join( outPath, 'regionSpeed' ) ) print "\tComputing region speeds" s = time.clock() vertices = ( Vector2( -0.551530, 0.792406 ), Vector2( 3.736435, -58.246524 ), Vector2( 42.376927, -56.160723 ), Vector2( 5.681046, -6.353232 ), Vector2( 92.823337, -4.904953 ), Vector2( 5.376837, 6.823865 ), Vector2( 92.526405, 9.199321 ), Vector2( 88.517822, -48.850902 ), Vector2( 6.416100, 53.293737 ), Vector2( -5.906582, 6.230001 ), Vector2( -6.203514, 53.739135 ), Vector2( 62.833196, 57.896184 ), Vector2( 93.268736, 43.643444 ), Vector2( -41.686899, -61.322050 ), Vector2( -74.794826, -25.838665 ), Vector2( -75.388691, 49.582085 ) ) vIDs = ( (0, 3, 4, 6, 5), (5, 6, 12, 11, 8), (5, 8, 10, 9, 0), (0, 9, 10, 15, 14, 13), (0, 13, 1), (0, 1, 2, 3), (3, 2, 7, 4) ) polygons = [] for ids in vIDs: p = Polygon() p.closed = True for id in ids: p.vertices.append( vertices[id] ) polygons.append( p ) grids.computeRegionSpeed( frameSet, polygons, timeStep, EXCLUDE_STATES ) print "Took", (time.clock() - s), "seconds" # output image imagePath = os.path.join( outPath, 'regionSpeed', 'region' ) colorMap = TwoToneHSVMap( (0, 0.63, 0.96), (100, 0.53, 0.75 ) ) regionSpeedImages( grids.outFileName + ".region", imagePath, polygons, colorMap, minPt, size, res ) if ( False ): # flow lines if ( not os.path.exists( os.path.join( outPath, 'flow' ) ) ): os.makedirs( os.path.join( outPath, 'flow' ) ) lines = ( Segment( Vector2( 4.56230, -7.71608 ), Vector2( 81.49586, -4.55443 ) ), Segment( Vector2( 5.08924, 5.72094 ), Vector2( 82.28628, 8.61913 ) ), Segment( Vector2( 3.50842, 8.09218 ), Vector2( 2.71800, 51.30145 ) ), Segment( Vector2( -5.97654, 5.72094 ), Vector2( -8.87472, 51.56492 ) ), Segment( Vector2( -6.50348, -7.18914 ), Vector2( -40.75473, -53.56005 ) ), Segment( Vector2( -1.23406, -6.92567 ), Vector2( 1.13718, -51.18881 ) ), Segment( Vector2( 3.50842, -7.45261 ), Vector2( 44.08297, -45.65592 ) ) ) flow = computeFlowLines( Vector2( 0, 0 ), lines, frameSet ) flowFile = os.path.join( outPath, 'flow', 'flow.txt' ) file = open( flowFile, 'w' ) flow.write( file ) file.close() if ( False ): # Traces print "Rendering traces" s = time.clock() grids.renderTraces( minPt, size, res, frameSet, 5, 5, 'data/trace11_' ) print "Took", (time.clock() - s), "seconds"
[i for i in np.arange(0, 1.0, 0.01)], "k-", markersize=1) ax1.legend(names, loc=4, prop={'size': 18}) ax1.set_xlabel("False Positive Rate", size=18) ax1.set_ylabel("True Positive Rate", size=18) plt.gcf().subplots_adjust(bottom=0.20) fig.savefig(filename, dpi=100) SD = SSSDetect() SM = submodDetect() pt = [] n1 = 10 S = Signals.Torus(n1**2, 2) k = int(n1**.5) n = n1**2. mu = 4. for alg, rho in [(SM, 4. * k), (SD, 4. / k)]: pt.append(ROC(alg, S, n=n1**2, d=2, k=k, mu=mu, iters=200, rho=rho)) plot_alg_scores(pt, ['SM', 'SSS'], ['k-', 'k-.'], 'torus_submod_beta=.5_n1=10_mu=4_SMSSS.png') import pickle pickle.dump(pt, open('torus_submod_beta=.5_n1=10_mu=4.pt', 'w')) n1 = 15 S = Signals.Torus(n1**2, 2)
last1hTime = None # Previous hourly function last1dTime = None # Previous daily function last1MTime = None # Previous monthy function runUpdateInit = True runRoomReservation = False #COT Konfig guestToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NDk1In0.EiWIxyQlEo84QAN1FwQe-q810LxQ1u1UOTjRGEwNW5U" peopleInRoomToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjYwIn0.Ss7cSg7z1Q4TJezDLgBiBbJj3E80kyjBoSeA6rSRqtQ" roomMaxCapacityToken = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NTcxIn0.0PyyZPjdG8-Hr5LxA2pNGWNq2oJAMRxdKAtFy_n-7MY" fireSignal = s.Signal("1324", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjcwIn0.4GshD9I6ZBE0roZzIsjHpIBLasIbH0JLc3TRhJwxJg8") parameterUpdate = s.Signal("4600", "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NjcwIn0.4GshD9I6ZBE0roZzIsjHpIBLasIbH0JLc3TRhJwxJg8") def fillStrToLen(n, length): s = str(n) if len(s) < length: s = "0"*(length - len(s)) + s return s return s def fireCheck(): return s.Signals.get() def updateUserLocation(): print("Downloading user location data... ", end=" ")