def main(): """Initializes the application """ # Load settings and create the config object config = Configuration() settings = config.settings # Set up logger logs.configure_logging(settings['log_level'], settings['log_mode']) logger = structlog.get_logger() # Configure and run configured behaviour. exchange_interface = ExchangeInterface(config.exchanges) notifier = Notifier(config.notifiers) behaviour = Behaviour( config, exchange_interface, notifier ) while True: behaviour.run(settings['market_pairs'], settings['output_mode']) logger.info("Sleeping for %s seconds", settings['update_interval']) time.sleep(settings['update_interval'])
def run_from_config(config_ff, threadID): # Load settings and create the config object config = Configuration(config_ff) settings = config.settings # Set up logger logs.configure_logging(settings['log_level'], settings['log_mode']) logger = structlog.get_logger() logger.info(" %s", threadID) # Configure and run configured behaviour. exchange_interface = ExchangeInterface(config.exchanges) notifier = Notifier(config.notifiers, config) behaviour = Behaviour(config, exchange_interface, notifier) while True: if settings['run_on_start']: start = time.time() behaviour.run(settings['market_pairs'], settings['output_mode']) end = time.time() dif = end - start wait_for = settings['update_interval'] - int(dif) logger.info("Sleeping for %s seconds", wait_for) time.sleep(wait_for) else: logger.info("Run on start not enabled waiting for %s seconds", settings['wait_and_run']) time.sleep(settings['wait_and_run'])
def testSingletBetweenAlice1AndBobAndLocalOtherwiseIsNotInPolytope(self): scenario = SequentialBellScenario([[2, 2], [2, 2]], [2, 2]) alice1blochVectors = [[1, 0, 0], [0, 1, 0]] alice1Observables = list( map(lambda bloch: createQubitObservable(bloch), alice1blochVectors)) alice1Krauss = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), alice1Observables)) bobUnBlochVectors = [[-1, -1, 0], [-1, 1, 0]] bobObservables = list( map(lambda bloch: createQubitObservable(bloch), bobUnBlochVectors)) bobEffects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), bobObservables)) psi = createMaxEntState(2) expectedCorrelations = {((x1, x2), y, (a1, a2), b): int( (a2 == 0)) * ((qt.tensor(alice1Krauss[x1][a1], bobEffects[y][b]) * psi * psi.dag()).tr()) for ((x1, x2), y, (a1, a2), b) in scenario.getTuplesOfEvents()} expectedBehaviour = Behaviour(scenario, expectedCorrelations) poly = SequentialBellPolytope(scenario) self.assertFalse(poly.contains(expectedBehaviour.getProbabilityList()))
async def test_handle_ping_with_behav_fanout(self, core1): b = Behaviour(core1) b2 = Behaviour(core1) await core1.add_runtime_dependency(b) await core1.add_runtime_dependency(b2) assert b.started assert b2.started # Given control ping message and core with default behaviour msg = PingControl().serialize() # when control ping message is broadcast correlation_id = str(uuid.uuid4()) await core1.fanout_send( msg=msg, msg_type=RmqMessageTypes.CONTROL.name, correlation_id=correlation_id, ) await asyncio.sleep(0.2) # then response from itself with list of 2 behaviours dt, latest, correlation_id = core1.peers.latest() assert latest.name == "core1" assert len(latest.behaviours) == 2
def testRandProjMeasBetweenAlice1andBob(self): scenario = SequentialBellScenario([[2, 2], [2, 2]], [2, 2]) alice1blochVectors = [[1, 0, 0], [0, 1, 0]] alice1Observables = list( map(lambda bloch: createQubitObservable(bloch), alice1blochVectors)) alice1Krauss = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), alice1Observables)) phases = [ np.random.uniform(-np.pi / 2, np.pi / 2), np.random.uniform(-np.pi / 2, np.pi / 2) ] alice2blochVectors = [[np.sin(theta), 0, np.cos(theta)] for theta in phases] alice2Observables = list( map(lambda bloch: createQubitObservable(bloch), alice2blochVectors)) alice2Effects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), alice2Observables)) phasesBob = [ np.random.uniform(-np.pi / 2, np.pi / 2), np.random.uniform(-np.pi / 2, np.pi / 2) ] bobVectors = [[np.sin(theta), 0, np.cos(theta)] for theta in phasesBob] bobObservables = list( map(lambda bloch: createQubitObservable(bloch), bobVectors)) bobEffects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), bobObservables)) aux = alice1Krauss alice1Krauss = alice2Effects alice2Effects = aux psi = createMaxEntState(2) rho = psi * psi.dag() expectedCorrelations = {} for x1 in range(2): for a1 in range(2): postMeasrmntState = qt.tensor( alice1Krauss[x1][a1], qt.qeye(2)) * rho * (qt.tensor( alice1Krauss[x1][a1], qt.qeye(2))).dag() for x2, y, a2, b in product(range(2), repeat=4): expectedCorrelations[(x1, x2), y, (a1, a2), b] = ( qt.tensor(alice2Effects[x2][a2], bobEffects[y][b]) * postMeasrmntState).tr().real expectedBehaviour = Behaviour(scenario, expectedCorrelations) poly = BellPolytopeWithOneWayCommunication( SequentialBellPolytope(scenario)) self.assertTrue(poly.contains(expectedBehaviour.getProbabilityList()), 'phases:' + str(phases[0]) + ', ' + str(phases[1]))
def testBuildBehaviourFromDictionaryAndConvertToList(self): pr = {(x, y, a, b): 1 / 2 * int(x * y == (a + b) % 2) for x, y, a, b in product(range(2), repeat=4)} behaviour = Behaviour(BellScenario([2, 2], [2, 2]), pr) probabilities = behaviour.getProbabilityList() self.assertEqual(probabilities, [ 1 / 2, 0, 0, 1 / 2, 1 / 2, 0, 0, 1 / 2, 1 / 2, 0, 0, 1 / 2, 0, 1 / 2, 1 / 2, 0 ])
def testBuildBehaviourFromListAndConvertToDictionary(self): pr=[1/2,0,0,1/2,1/2,0,0,1/2,1/2,0,0,1/2,0,1/2,1/2,0] behaviour=Behaviour(BellScenario([2,2],[2,2]),pr) probabilities = behaviour.getProbabilityDictionary() for x,y,a,b in product(range(2),repeat=4): if x*y==(a+b)%2: self.assertEqual(probabilities[x,y,a,b],1/2) else: self.assertEqual(probabilities[x,y,a,b],0)
def testPRCorrBetweenAlice1andBobAndLocalOtherwiseIsNotInPolytope(self): scenario = SequentialBellScenario([[2, 2], [2, 2]], [2, 2]) expectedCorrelations = { ((x1, x2), y, (a1, a2), b): 1 / 2 * int((a2 == 0) & (x1 * y == (a1 + b) % 2)) for ((x1, x2), y, (a1, a2), b) in scenario.getTuplesOfEvents() } expectedBehaviour = Behaviour(scenario, expectedCorrelations) poly = SequentialBellPolytope(scenario) self.assertFalse(poly.contains(expectedBehaviour.getProbabilityList()))
def __init__(self, iot_config, peri_config, iot_disabled=False): self.behaviour = Behaviour(peri_config) self.iot_disabled = iot_disabled if not iot_disabled: topic_prefix = "iothydroponics/device/{}".format(iot_config.client_id) settings_topic = "{}/settings".format(topic_prefix) device_update_topic = "{}/update".format(topic_prefix) self.iot_config = iot_config self.client = IoTClient( settings_topic=settings_topic, device_update_topic=device_update_topic, **self.iot_config.__dict__ ) self.publish_thread = Thread(target=self.publish_at_interval)
def main(): # Load settings and create the config object config = conf.Configuration() settings = config.fetch_settings() # Set up logger logs.configure_logging(settings['loglevel'], settings['log_mode']) behaviour_manager = Behaviour(config) behaviour = behaviour_manager.get_behaviour(settings['selected_task']) # set up async behaviour.run(settings['market_pairs'], settings['update_interval'])
def main(): # Load settings and create the config object config = conf.Configuration() settings = config.fetch_settings() # Set up logger logs.configure_logging(settings['loglevel'], settings['log_mode']) # Configure and run configured behaviour. behaviour_manager = Behaviour(config) behaviour = behaviour_manager.get_behaviour(settings['selected_task']) while True: behaviour.run(settings['market_pairs']) time.sleep(settings['update_interval'])
def __init__(self, first_name, last_name, year_of_birth, gender): self.first_name = first_name self.last_name = last_name self.year_of_birth = year_of_birth self.gender = gender self.energizing = Energizing() self.behaviour = Behaviour()
def getGeneratorForVertices(self): #local vertices yield from self.underlyingPolytope.getGeneratorForVertices() communicationStrgs = [ format( i, '0' + str(self.underlyingPolytope.numberOfInputsAlice()) + 'b') for i in range( 1, 2**(self.underlyingPolytope.numberOfInputsAlice() - 1)) ] listOfAliceInputs = self.underlyingPolytope.listOfAliceInputs() aliceStrategies = [{ anInput: (stg[anInput], communication[listOfAliceInputs.index(anInput)]) for anInput in listOfAliceInputs } for stg in self.underlyingPolytope.getAliceStrategies() for communication in communicationStrgs] bobStrategiesWithComm = [(b1, b2) for b1, b2 in product( self.underlyingPolytope.getBobStrategies(), repeat=2) if not b1 == b2] yield from (Behaviour( self.underlyingPolytope.getBellScenario(), {(inputsAlice, inputsBob, outputsAlice, outputsBob): int((outputsAlice == stgAlice[inputsAlice][0]) & (outputsBob == pairOfStgsBob[int(stgAlice[inputsAlice][1])] [inputsBob])) for (inputsAlice, inputsBob, outputsAlice, outputsBob) in self.underlyingPolytope.getTuplesOfEvents()}) for stgAlice in aliceStrategies for pairOfStgsBob in bobStrategiesWithComm)
def _toSymmetricBehaviour(self, behaviour): return Behaviour( self.bellScenario, self._verticesToCG(behaviour.getProbabilityList(), self.numberOfInputsAlice(), self.getNumberOfOutputsPerInputAlice(), self.getNumberOfOutputsPerInputBob()))
def getGeneratorForVertices(self): #local vertices yield from self.underlyingPolytope.getGeneratorForVertices() aliceStrategiesWithComm = [(a1, a2) for a1, a2 in product( self.underlyingPolytope.getAliceStrategies(), repeat=2) if not a1 == a2] communicationStrgs = [ format( i, '0' + str(self.underlyingPolytope.numberOfInputsBob()) + 'b') for i in range( 1, 2**(self.underlyingPolytope.numberOfInputsBob() - 1)) ] bobStrategies = [{ y: (choiceOfOutputs[y], comm[y]) for y in range(self.underlyingPolytope.numberOfInputsBob()) } for choiceOfOutputs in product(*[ range(numberOfOutputs) for numberOfOutputs in self.underlyingPolytope.getNumberOfOutputsPerInputBob() ]) for comm in communicationStrgs] yield from (Behaviour( self.underlyingPolytope.getBellScenario(), {(inputsAlice, inputsBob, outputsAlice, outputsBob): int((outputsBob == stgBob[inputsBob][0]) & (outputsAlice == pairOfStgsAlice[int(stgBob[inputsBob][1])] [inputsAlice])) for (inputsAlice, inputsBob, outputsAlice, outputsBob) in self.underlyingPolytope.getTuplesOfEvents()}) for stgBob in bobStrategies for pairOfStgsAlice in aliceStrategiesWithComm)
def _strategyToBehaviour(self, stgAlice, stgBob): distribution = {(inputsAlice, inputsBob, outputsAliceSequence, outputsBob): int((outputsAliceSequence == stgAlice[inputsAlice]) & (outputsBob == stgBob[inputsBob])) for (inputsAlice, inputsBob, outputsAliceSequence, outputsBob) in self.getTuplesOfEvents()} return Behaviour(self.bellScenario, distribution)
async def test_behaviour_status(self, core1): status = '{"name": "core1", "state": "running", "behaviours": [{"name": "core1.Behaviour", "state": "running"}]}' b = Behaviour(core1) await core1.add_runtime_dependency(b) print(core1.status.to_json()) assert isinstance(core1.status, CoreStatus) assert core1.status.to_json() == status
async def test_behaviour(self, core1): b = Behaviour(core1) await core1.add_runtime_dependency(b) assert b.started await b.stop() assert b.state == 'shutdown'
def main(): """Initializes the application """ # Load settings and create the config object config = conf.Configuration() settings = config.get_settings() # Set up logger logs.configure_logging(settings['loglevel'], settings['log_mode']) # Configure and run configured behaviour. behaviour_manager = Behaviour(config) behaviour = behaviour_manager.get_behaviour(settings['selected_task']) while True: behaviour.run(settings['market_pairs']) time.sleep(settings['update_interval'])
def main(): """Initializes the application """ # Load settings and create the config object config = Configuration() settings = config.settings # Set up logger logs.configure_logging(settings['log_level'], settings['log_mode']) logger = structlog.get_logger() # Configure and run configured behaviour. exchange_interface = ExchangeInterface(config.exchanges) if settings['market_pairs']: market_pairs = settings['market_pairs'] logger.info("Found configured markets: %s", market_pairs) market_data = exchange_interface.get_exchange_markets( markets=market_pairs) else: logger.info("No configured markets, using all available on exchange.") market_data = exchange_interface.get_exchange_markets() # notifier = Notifier(config.notifiers, market_data) thread_list = [] for exchange in market_data: num = 1 for chunk in split_market_data(market_data[exchange]): market_data_chunk = dict() market_data_chunk[exchange] = { key: market_data[exchange][key] for key in chunk } notifier = Notifier(config.notifiers, config.indicators, market_data_chunk) behaviour = Behaviour(config, exchange_interface, notifier) workerName = "Worker-{}".format(num) worker = AnalysisWorker(workerName, behaviour, notifier, market_data_chunk, settings, logger) thread_list.append(worker) worker.daemon = True worker.start() time.sleep(60) num += 1 logger.info('All workers are running!') for worker in thread_list: worker.join()
def main(): # Load settings and create the config object config = conf.Configuration() settings = config.fetch_settings() exchange_config = config.fetch_exchange_config() notifier_config = config.fetch_notifier_config() behaviour_config = config.fetch_behaviour_config() # Set up logger logs.configure_logging(settings['loglevel'], settings['app_mode']) exchange_interface = ExchangeInterface(exchange_config) strategy_analyzer = StrategyAnalyzer(exchange_interface) notifier = Notifier(notifier_config) behaviour_manager = Behaviour(behaviour_config) behaviour = behaviour_manager.get_behaviour(settings['selected_task']) behaviour.run(settings['symbol_pairs'], settings['update_interval'], exchange_interface, strategy_analyzer, notifier)
def main(): """Initializes the application """ # Load settings and create the config object config = Configuration() settings = config.settings # Set up logger logs.configure_logging(settings['log_level'], settings['log_mode']) logger = structlog.get_logger() # Configure and run configured behaviour. exchange_interface = ExchangeInterface(config.exchanges) notifier = Notifier(config.notifiers) behaviour = Behaviour(config, exchange_interface, notifier) while True: behaviour.run(settings['market_pairs'], settings['output_mode']) logger.info("Sleeping for %s seconds", settings['update_interval']) time.sleep(settings['update_interval'])
def testCHSHBetweenAlice1AndBobAndIdentityInAlice2IsInPolytope(self): scenario = SequentialBellScenario([[2, 2], [2, 2]], [2, 2]) alice1blochVectors = [[1, 0, 0], [0, 1, 0]] alice1Observables = list( map(lambda bloch: createQubitObservable(bloch), alice1blochVectors)) alice1Krauss = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), alice1Observables)) alice2Effects = [[qt.qeye(2), 0 * qt.qeye(2)], [qt.qeye(2), 0 * qt.qeye(2)]] bobUnBlochVectors = [[-1, -1, 0], [-1, 1, 0]] bobObservables = list( map(lambda bloch: createQubitObservable(bloch), bobUnBlochVectors)) bobEffects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), bobObservables)) psi = createMaxEntState(2) rho = psi * psi.dag() expectedCorrelations = {} for x1 in range(2): for a1 in range(2): postMeasrmntState = qt.tensor( alice1Krauss[x1][a1], qt.qeye(2)) * rho * (qt.tensor( alice1Krauss[x1][a1], qt.qeye(2))).dag() for x2, y, a2, b in product(range(2), repeat=4): expectedCorrelations[(x1, x2), y, (a1, a2), b] = ( qt.tensor(alice2Effects[x2][a2], bobEffects[y][b]) * postMeasrmntState).tr().real expectedBehaviour = Behaviour(scenario, expectedCorrelations) poly = BellPolytopeWithOneWayCommunication( SequentialBellPolytope(scenario)) self.assertTrue(poly.contains(expectedBehaviour.getProbabilityList()))
def main(): """Initializes the application """ # Load settings and create the config object config = conf.Configuration() settings = config.settings # Set up logger logs.configure_logging(settings['loglevel'], settings['log_mode']) logger = structlog.get_logger() # Configure and run configured behaviour. behaviour_manager = Behaviour(config) behaviour = behaviour_manager.get_behaviour(settings['selected_task']) if isinstance(behaviour, ServerBehaviour): behaviour.run(debug=False) else: while True: behaviour.run(settings['market_pairs']) logger.info("Sleeping for %s seconds", settings['update_interval']) time.sleep(settings['update_interval'])
def load_exchange(exchange): global config, market_data, fibonacci, new_results try: single_config = dict() single_config[exchange] = config.exchanges[exchange] single_exchange_interface = ExchangeInterface(single_config) single_market_data = dict() single_market_data[exchange] = market_data[exchange] behaviour = Behaviour(config, single_exchange_interface) new_result = behaviour.run(exchange, single_market_data, fibonacci, config.settings['output_mode']) new_results[exchange] = new_result[exchange] return True except Exception as exc: logger.info('Exception while processing exchange: %s', exchange) #logger.info('%s', exc) raise exc
def testMeasurementsOverSeparableStateAreLocal(self): alice1outputs = [2, 2] alice2outputs = [2, 3] bobOutputs = [2, 2] scenario = SequentialBellScenario([alice1outputs, alice2outputs], bobOutputs) epsilon = 0 plus = 1 / np.sqrt(2) * (qt.basis(2, 0) + qt.basis(2, 1)) minus = 1 / np.sqrt(2) * (qt.basis(2, 0) - qt.basis(2, 1)) Kplus = np.cos(epsilon) * plus * plus.dag() + np.sin( epsilon) * minus * minus.dag() Kminus = -np.cos(epsilon) * minus * minus.dag() + np.sin( epsilon) * plus * plus.dag() alice1Krauss = [ projectorsForQubitObservable(createQubitObservable([0, 0, 1])), [Kplus, Kminus] ] alice2blochVectors = [[0, 0, 1]] alice2Observables = list( map(lambda bloch: createQubitObservable(bloch), alice2blochVectors)) alice2Effects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), alice2Observables)) trineAlice2 = [[0, 0, 1], [np.sin(2 * np.pi / 3), 0, np.cos(2 * np.pi / 3)], [np.sin(4 * np.pi / 3), 0, np.cos(4 * np.pi / 3)]] paulies = [qt.sigmax(), qt.sigmay(), qt.sigmaz()] alice2Effects.append( list( map( lambda bloch: effectForQubitPovm( 1 / 3, sum([paulies[i] * bloch[i] for i in range(3)])), trineAlice2))) mu = np.arctan(np.sin(2 * epsilon)) bobUnBlochVectors = [[np.sin(mu), 0, np.cos(mu)], [-np.sin(mu), 0, np.cos(mu)]] bobObservables = list( map(lambda bloch: createQubitObservable(bloch), bobUnBlochVectors)) bobEffects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), bobObservables)) psi = qt.tensor(qt.basis(2, 0), qt.basis(2, 0)) rho = psi * psi.dag() expectedCorrelations = {} for x1, x2, y in product(range(len(alice1outputs)), range(len(alice2outputs)), range(len(bobOutputs))): for a1, a2, b in product(range(alice1outputs[x1]), range(alice2outputs[x2]), range(bobOutputs[y])): postMeasrmntState = qt.tensor( alice1Krauss[x1][a1], qt.qeye(2)) * rho * (qt.tensor( alice1Krauss[x1][a1], qt.qeye(2))).dag() expectedCorrelations[(x1, x2), y, (a1, a2), b] = ( qt.tensor(alice2Effects[x2][a2], bobEffects[y][b]) * postMeasrmntState).tr().real expectedBehaviour = Behaviour(scenario, expectedCorrelations) polytope = BellPolytopeWithOneWayCommunication( SequentialBellPolytope(scenario)) self.assertTrue( polytope.contains(expectedBehaviour.getProbabilityList()))
class Hydroponics: def __init__(self, iot_config, peri_config, iot_disabled=False): self.behaviour = Behaviour(peri_config) self.iot_disabled = iot_disabled if not iot_disabled: topic_prefix = "iothydroponics/device/{}".format(iot_config.client_id) settings_topic = "{}/settings".format(topic_prefix) device_update_topic = "{}/update".format(topic_prefix) self.iot_config = iot_config self.client = IoTClient( settings_topic=settings_topic, device_update_topic=device_update_topic, **self.iot_config.__dict__ ) self.publish_thread = Thread(target=self.publish_at_interval) @property def current_settings(self): return self.behaviour.settings @property def current_data(self): self.behaviour.update_temp_hum() return self.behaviour.data @run_task_interval(0.5) def publish_at_interval(self): self.publish() @run_task_interval(0.5) def timed_events(self): self.behaviour.update_all() @run_task_interval(0.4) def overflow_prevention(self): print('test') self.behaviour.water_level_flood_control() def publish(self): self.client.publish_update(self.current_data, self.current_settings) # Callback when the subscribed topic receives a message def on_message_received(self, topic, payload, **kwargs): new_settings = json.loads(payload) print("New settings: {}\n".format(new_settings)) self.behaviour.update_settings(new_settings) self.publish() # republish immediately def start(self): self.overflow_monitor_thread = Thread(target=self.overflow_prevention) if not self.iot_disabled: self.client.subscribe_topic(self.on_message_received) self.iot_client_run_thread = Thread(target=self.client.run) self.edge_behaviour = Thread(target=self.timed_events) if not self.iot_disabled: self.iot_client_run_thread.start() self.publish_thread.start() self.edge_behaviour.start() self.overflow_monitor_thread.start()
async def rpc_behav(core1): b = Behaviour(core1, configure_rpc=True) await core1.add_runtime_dependency(b) yield b
async def pubsub_behav(core1): topics = ["x.y", "x.z", "a.#"] b = Behaviour(core1, binding_keys=topics) await core1.add_runtime_dependency(b) yield b
async def behav(core1): b = Behaviour(core1) await core1.add_runtime_dependency(b) yield b
[-np.sin(mu), 0, np.cos(mu)]] bobObservables = list( map(lambda bloch: createQubitObservable(bloch), bobUnBlochVectors)) bobEffects = list( map( lambda qubitObservable: projectorsForQubitObservable( qubitObservable), bobObservables)) psi = createMaxEntState(2) rho = psi * psi.dag() expectedCorrelations = {} for x1, x2, y in product(range(len(alice1outputs)), range(len(alice2outputs)), range(len(bobOutputs))): for a1, a2, b in product(range(alice1outputs[x1]), range(alice2outputs[x2]), range(bobOutputs[y])): postMeasrmntState = qt.tensor( alice1Krauss[x1][a1], qt.qeye(2)) * rho * (qt.tensor( alice1Krauss[x1][a1], qt.qeye(2))).dag() expectedCorrelations[(x1, x2), y, (a1, a2), b] = ( qt.tensor(alice2Effects[x2][a2], bobEffects[y][b]) * postMeasrmntState).tr().real expectedBehaviour = Behaviour(scenario, expectedCorrelations) polytope = BellPolytopeWithOneWayCommunication( SequentialBellPolytope(scenario)) print(polytope.contains(expectedBehaviour.getProbabilityList()))
def behaviour(self) -> Behaviour: return Behaviour(self, binding_keys=["system"], configure_rpc=True)