From d640cb36b5a52830a83ec51d215758491738c85c Mon Sep 17 00:00:00 2001 From: SpoonFll Date: Tue, 4 Mar 2025 09:57:44 -0500 Subject: [PATCH 1/2] updates to hyperneat --- src/gui/WebClient/mod.rs | 4 ++-- src/gui/main.rs | 25 +++++++++++++------------ src/simulation/agent.py | 5 +++++ src/simulation/enviroment.py | 4 +++- src/simulation/utils.py | 6 ++++++ 5 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/gui/WebClient/mod.rs b/src/gui/WebClient/mod.rs index 26e92f3..df1daee 100644 --- a/src/gui/WebClient/mod.rs +++ b/src/gui/WebClient/mod.rs @@ -23,7 +23,7 @@ pub async fn getConnection()->Result,tonic::transpo Ok(()) }*/ -pub async fn getSimStream(connection:CommunicationClient,sender:Sender)->Result<(),Box>{ +pub async fn getSimStream(mut connection:CommunicationClient,sender:Sender)->Result<(),Box>{ let request = Request::new(Command{ r#in:"start".into(), }); @@ -35,7 +35,7 @@ pub async fn getSimStream(connection:CommunicationClient,sender:Sender< Ok(()) } -pub async fn getNeuralNet(connection:&mut CommunicationClient,agent:i32)->JsonData{ +pub async fn getNeuralNet(mut connection: CommunicationClient,agent:i32)->JsonData{ let request = Request::new(Id{r#id:agent,}); let netString = connection.fetch_neural_net(request).await.unwrap().into_inner(); netString diff --git a/src/gui/main.rs b/src/gui/main.rs index 7fc9a3e..79d191f 100644 --- a/src/gui/main.rs +++ b/src/gui/main.rs @@ -3,15 +3,14 @@ use crate::WebClient::comms::communication_client::CommunicationClient; use crate::WebClient::comms::JsonData; -use crate::WebClient::comms::JsonData; -use iced::Executor; -use tokio::runtime::Runtime; -use tonic::{Request, Status}; use iced::widget::canvas::{Canvas, Fill, Frame, Geometry, Path}; use iced::widget::{button, canvas, column, row, text, Column, Row}; +use iced::Executor; use iced::{mouse, Color, Length, Point, Rectangle, Renderer, Size, Subscription, Theme}; +use tokio::runtime::Runtime; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; +use tonic::{Request, Status}; use WebClient::getConnection; mod WebClient; mod neural_net; @@ -34,7 +33,7 @@ struct View { simulation_data: SimulationData, receiver: Option>, sender: Option>, - connection: Option> + connection: Option>, } #[derive(Default, Clone)] struct SimulationView { @@ -75,7 +74,6 @@ struct Agent { struct SimulationData { agents: Vec, shapes: Vec, - layers: Vec, } pub fn main() -> iced::Result { @@ -99,7 +97,7 @@ impl View { simulation_data: SimulationData::default(), receiver: Some(recv), sender: Some(send), - connection: Some(conn) + connection: Some(conn), } } fn view(&self) -> Column { @@ -152,8 +150,11 @@ impl View { } Message::SimStart => { let rt = Runtime::new().unwrap(); - let cloneConn = *self.connection.as_mut().unwrap().clone(); - rt.spawn(async { WebClient::getSimStream(cloneConn, self.sender.unwrap()); }); + let cloneConn = self.connection.as_mut().unwrap().clone(); + let cloneSend = self.sender.as_mut().unwrap().clone(); + rt.spawn(async move { + WebClient::getSimStream(cloneConn, cloneSend).await; + }); } Message::SimPause => {} Message::SimEnd => {} @@ -297,16 +298,16 @@ impl View { ] } "#;*/ - + let received = &self.receiver.as_mut().unwrap().blocking_recv().unwrap().json_data;//should block until sim starts let json_data: SimulationData = - serde_json::from_str(&self.receiver.as_mut().unwrap().recv().unwrap().json_data) + serde_json::from_str(&received) .expect("Failed to parse JSON"); json_data } fn update_simulation_data(&mut self, simulation_data: SimulationData) { self.simulation_data = simulation_data; self.agent_view.color = Color::from_rgb(0.0, 1.0, 0.0); - self.nn_view.update_network(&self.simulation_data.layers); + //self.nn_view.update_network(&self.simulation_data.layers); self.sim_view.update_sim(&self.simulation_data.shapes); } fn subscription(&self) -> Subscription { diff --git a/src/simulation/agent.py b/src/simulation/agent.py index fdbe6af..15df156 100644 --- a/src/simulation/agent.py +++ b/src/simulation/agent.py @@ -201,6 +201,11 @@ def get_collisions(self): return self.state.collisions + def getAgentRenderData(self): + return {"id":self.id,"x":self.pos[0],"y":self.pos[1],"color":"white"} + + + def solve_collision(self): for collision in self.state.collisions[:]: if collision.shape == "circle": diff --git a/src/simulation/enviroment.py b/src/simulation/enviroment.py index 5d199d2..4827e68 100644 --- a/src/simulation/enviroment.py +++ b/src/simulation/enviroment.py @@ -287,4 +287,6 @@ def run(self): # Find the fittest predator and prey # Find amount of food left # self.view(real_time=True) - messageChannel.put() + sendData = {"agents":self.agents,"shapes":self.obstacles} + print(sendData) + #messageChannel.put(sendData) diff --git a/src/simulation/utils.py b/src/simulation/utils.py index c414cac..810fb2d 100644 --- a/src/simulation/utils.py +++ b/src/simulation/utils.py @@ -10,3 +10,9 @@ def __init__(self, shape, radius, width, height, pos): self.width = width self.height = height self.pos = pos + + def getRenderData(self): + if self.shape == "Circle": + return {"type":"Circle","x":self.pos[0],"y":self.pos[1],"radius":self.radius,"Color":"green"} + else: + return {"type":"Rectangle","x":self.pos[0],"y":self.pos[1],"witdth":self.width,"height":self.height,"Color":"red"} From 790ab17b88badc7f225775b39c7975d02aea877f Mon Sep 17 00:00:00 2001 From: SpoonFll Date: Tue, 4 Mar 2025 10:13:39 -0500 Subject: [PATCH 2/2] fixed grpcio --- src/grpc_json_server/generated/comms_pb2.py | 12 ++-- .../generated/comms_pb2_grpc.py | 65 +++++++++++++++---- src/simulation/server.py | 7 +- 3 files changed, 66 insertions(+), 18 deletions(-) diff --git a/src/grpc_json_server/generated/comms_pb2.py b/src/grpc_json_server/generated/comms_pb2.py index f625639..71e8463 100644 --- a/src/grpc_json_server/generated/comms_pb2.py +++ b/src/grpc_json_server/generated/comms_pb2.py @@ -24,7 +24,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0b\x63omms.proto\x12\x05\x63omms\"\x15\n\x07\x43ommand\x12\n\n\x02In\x18\x01 \x01(\t\"B\n\x0b\x45nvironment\x12\x11\n\tjson_data\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x0f\n\x07message\x18\x03 \x01(\t2P\n\x0eNeuroEvolution\x12>\n\x16\x46\x65tchEnvironmentStream\x12\x0e.comms.Command\x1a\x12.comms.Environment0\x01\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0b\x63omms.proto\x12\x05\x63omms\"\x15\n\x07\x43ommand\x12\n\n\x02In\x18\x01 \x01(\t\"\x10\n\x02ID\x12\n\n\x02id\x18\x01 \x01(\x05\"?\n\x08JSONData\x12\x11\n\tjson_data\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x0f\n\x07message\x18\x03 \x01(\t2z\n\rCommunication\x12;\n\x16\x46\x65tchEnvironmentStream\x12\x0e.comms.Command\x1a\x0f.comms.JSONData0\x01\x12,\n\x0e\x46\x65tchNeuralNet\x12\t.comms.ID\x1a\x0f.comms.JSONDatab\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -33,8 +33,10 @@ DESCRIPTOR._loaded_options = None _globals['_COMMAND']._serialized_start=22 _globals['_COMMAND']._serialized_end=43 - _globals['_ENVIRONMENT']._serialized_start=45 - _globals['_ENVIRONMENT']._serialized_end=111 - _globals['_NEUROEVOLUTION']._serialized_start=113 - _globals['_NEUROEVOLUTION']._serialized_end=193 + _globals['_ID']._serialized_start=45 + _globals['_ID']._serialized_end=61 + _globals['_JSONDATA']._serialized_start=63 + _globals['_JSONDATA']._serialized_end=126 + _globals['_COMMUNICATION']._serialized_start=128 + _globals['_COMMUNICATION']._serialized_end=250 # @@protoc_insertion_point(module_scope) diff --git a/src/grpc_json_server/generated/comms_pb2_grpc.py b/src/grpc_json_server/generated/comms_pb2_grpc.py index 6f7310c..8691dcd 100644 --- a/src/grpc_json_server/generated/comms_pb2_grpc.py +++ b/src/grpc_json_server/generated/comms_pb2_grpc.py @@ -25,7 +25,7 @@ ) -class NeuroEvolutionStub(object): +class CommunicationStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): @@ -35,13 +35,18 @@ def __init__(self, channel): channel: A grpc.Channel. """ self.FetchEnvironmentStream = channel.unary_stream( - '/comms.NeuroEvolution/FetchEnvironmentStream', + '/comms.Communication/FetchEnvironmentStream', request_serializer=comms__pb2.Command.SerializeToString, - response_deserializer=comms__pb2.Environment.FromString, + response_deserializer=comms__pb2.JSONData.FromString, + _registered_method=True) + self.FetchNeuralNet = channel.unary_unary( + '/comms.Communication/FetchNeuralNet', + request_serializer=comms__pb2.ID.SerializeToString, + response_deserializer=comms__pb2.JSONData.FromString, _registered_method=True) -class NeuroEvolutionServicer(object): +class CommunicationServicer(object): """Missing associated documentation comment in .proto file.""" def FetchEnvironmentStream(self, request, context): @@ -50,23 +55,34 @@ def FetchEnvironmentStream(self, request, context): context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') + def FetchNeuralNet(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + -def add_NeuroEvolutionServicer_to_server(servicer, server): +def add_CommunicationServicer_to_server(servicer, server): rpc_method_handlers = { 'FetchEnvironmentStream': grpc.unary_stream_rpc_method_handler( servicer.FetchEnvironmentStream, request_deserializer=comms__pb2.Command.FromString, - response_serializer=comms__pb2.Environment.SerializeToString, + response_serializer=comms__pb2.JSONData.SerializeToString, + ), + 'FetchNeuralNet': grpc.unary_unary_rpc_method_handler( + servicer.FetchNeuralNet, + request_deserializer=comms__pb2.ID.FromString, + response_serializer=comms__pb2.JSONData.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( - 'comms.NeuroEvolution', rpc_method_handlers) + 'comms.Communication', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) - server.add_registered_method_handlers('comms.NeuroEvolution', rpc_method_handlers) + server.add_registered_method_handlers('comms.Communication', rpc_method_handlers) # This class is part of an EXPERIMENTAL API. -class NeuroEvolution(object): +class Communication(object): """Missing associated documentation comment in .proto file.""" @staticmethod @@ -83,9 +99,36 @@ def FetchEnvironmentStream(request, return grpc.experimental.unary_stream( request, target, - '/comms.NeuroEvolution/FetchEnvironmentStream', + '/comms.Communication/FetchEnvironmentStream', comms__pb2.Command.SerializeToString, - comms__pb2.Environment.FromString, + comms__pb2.JSONData.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) + + @staticmethod + def FetchNeuralNet(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary( + request, + target, + '/comms.Communication/FetchNeuralNet', + comms__pb2.ID.SerializeToString, + comms__pb2.JSONData.FromString, options, channel_credentials, insecure, diff --git a/src/simulation/server.py b/src/simulation/server.py index ab01e6b..3c249e9 100644 --- a/src/simulation/server.py +++ b/src/simulation/server.py @@ -4,11 +4,14 @@ import json import time import threading -from .generated import json_transfer_pb2, json_transfer_pb2_grpc +from .generated import comms_pb2 +from .generated import comms_pb2_grpc from messenger import messageChannel -class JsonTransferService(json_transfer_pb2_grpc.JsonTransferServicer): +class CommunicationService(comms_pb2_grpc.CommunicationServicer): + def FetchNeuralNet(slef,request,context): + print("here") def FetchEnvironmentStream(self, request, context): while messageChannel.empty == False: data = messageChannel.get()