Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENVS] Envs updates #63

Open
wants to merge 100 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
100 commits
Select commit Hold shift + click to select a range
e1aa722
change abstract class to no server
samuelmyoussef Dec 8, 2023
19280da
add server class
samuelmyoussef Dec 8, 2023
c9ffbf3
modify viewer
samuelmyoussef Dec 8, 2023
56c468b
modify simulate & goal initializtion
samuelmyoussef Dec 8, 2023
7e3d0f0
simulation init and reset
samuelmyoussef Sep 23, 2024
a8ace0e
remove unneeded goal and reward update and unused reward update param
samuelmyoussef Sep 23, 2024
55cd226
add general methods to init and randomize states and goal
samuelmyoussef Sep 25, 2024
8215ff2
class instantiation
samuelmyoussef Sep 24, 2024
8d26c32
add some default configs
samuelmyoussef Sep 24, 2024
234e3a4
initialize states
samuelmyoussef Sep 25, 2024
f96c776
goal init and update
samuelmyoussef Sep 25, 2024
57b790f
class instantiation
samuelmyoussef Sep 26, 2024
5c8a2d5
add some default configs
samuelmyoussef Sep 26, 2024
75778c2
initialize states
samuelmyoussef Sep 26, 2024
5ad5883
goal init and update
samuelmyoussef Sep 26, 2024
8cfbc82
class instantiation
samuelmyoussef Sep 26, 2024
0797855
add some default configs
samuelmyoussef Sep 26, 2024
fa15f2a
initialize states
samuelmyoussef Sep 26, 2024
d5983ac
goal init and update
samuelmyoussef Sep 26, 2024
06a6479
class instantiation
samuelmyoussef Sep 26, 2024
3e3e0b7
add some default configs
samuelmyoussef Sep 26, 2024
ce2f431
initialize states
samuelmyoussef Sep 26, 2024
eacada1
goal remove
samuelmyoussef Sep 26, 2024
4a399fe
class instantiation
samuelmyoussef Sep 25, 2024
cb2eba3
add some default configs
samuelmyoussef Sep 25, 2024
96a40fb
initialize states
samuelmyoussef Sep 25, 2024
258b2bd
goal init and update
samuelmyoussef Sep 25, 2024
cefa233
class instantiation
samuelmyoussef Sep 25, 2024
896f74e
add some default configs
samuelmyoussef Sep 25, 2024
b186e12
initialize states
samuelmyoussef Sep 25, 2024
a945bd2
goal init and update
samuelmyoussef Sep 25, 2024
d75f9d9
add AnimationManager
samuelmyoussef Sep 25, 2024
d098419
class instantiation
samuelmyoussef Sep 25, 2024
afd0ec5
add some default configs
samuelmyoussef Sep 25, 2024
f498f98
initialize states
samuelmyoussef Sep 25, 2024
00f3290
goal init and update
samuelmyoussef Sep 25, 2024
24ef8cb
class instantiation
samuelmyoussef Sep 26, 2024
05e2189
add some default configs
samuelmyoussef Sep 26, 2024
1cff431
initialize states
samuelmyoussef Sep 26, 2024
00ad68a
goal init and update
samuelmyoussef Sep 26, 2024
21479f7
class instantiation
samuelmyoussef Sep 25, 2024
e925b86
add some default configs
samuelmyoussef Sep 25, 2024
497234a
initialize states
samuelmyoussef Sep 25, 2024
841836c
goal init and update
samuelmyoussef Sep 25, 2024
014f91e
class instantiation for no server or server env
samuelmyoussef Feb 8, 2024
092824d
add some default configs
samuelmyoussef Feb 8, 2024
549445e
initialize states
samuelmyoussef Feb 8, 2024
dbc5f91
goal init and update
samuelmyoussef Sep 25, 2024
1d63f61
class instantiation
samuelmyoussef Sep 25, 2024
f79435a
add some default configs
samuelmyoussef Sep 25, 2024
18580c0
initialize states
samuelmyoussef Sep 25, 2024
1f923ae
goal init and update
samuelmyoussef Sep 25, 2024
68c266f
class instantiation
samuelmyoussef Sep 25, 2024
b5a074e
add some default configs
samuelmyoussef Sep 25, 2024
9448604
initialize states
samuelmyoussef Sep 25, 2024
2ed982f
goal init and update
samuelmyoussef Sep 25, 2024
233b557
class instantiation
samuelmyoussef Sep 25, 2024
f4028fa
add some default configs
samuelmyoussef Sep 25, 2024
d804d9b
initialize states
samuelmyoussef Sep 25, 2024
2c3736d
goal remove
samuelmyoussef Sep 25, 2024
d1d5cec
no server
samuelmyoussef Dec 8, 2023
941b1f0
class instantiation
samuelmyoussef Sep 23, 2024
ec12b77
remove non-overriden methods
samuelmyoussef Sep 26, 2024
3a53e59
remove legacy viewer
samuelmyoussef Sep 26, 2024
346fb5b
remove non-overriden methods
samuelmyoussef Sep 26, 2024
1bc7b25
remove legacy viewer
samuelmyoussef Sep 26, 2024
fb363c2
remove non-overrinden methods
samuelmyoussef Sep 26, 2024
cef887f
remove non-overriden methods
samuelmyoussef Sep 26, 2024
20fb38f
remove non-overriden methods
samuelmyoussef Sep 26, 2024
ba90431
remove non-overriden methods
samuelmyoussef Sep 26, 2024
5795fb7
remove non-overriden methods
samuelmyoussef Sep 26, 2024
66d7458
remove non-overriden methods
samuelmyoussef Sep 26, 2024
85767d9
remove non-overriden methods
samuelmyoussef Sep 26, 2024
b181d14
remove non-overriden methods
samuelmyoussef Sep 26, 2024
6ff47bd
remove non-overriden methods
samuelmyoussef Sep 26, 2024
5de26b7
remove non-overriden methods
samuelmyoussef Sep 26, 2024
b210a12
remove non-overriden methods
samuelmyoussef Sep 26, 2024
995569f
remove unused goal components
samuelmyoussef Dec 8, 2023
929ffce
add some default configs
samuelmyoussef Dec 13, 2023
ac19ebc
initialize states
samuelmyoussef Sep 23, 2024
780f3a8
Update pole angle from position directly instead of calculation and d…
samuelmyoussef Jan 11, 2024
e9a3166
goal init
samuelmyoussef Sep 25, 2024
28c07b4
remove non-overriden methods
samuelmyoussef Sep 26, 2024
f0dd4e0
Merge branch 'CartpoleEnv' into no_server
samuelmyoussef Sep 26, 2024
5ef8273
Merge branch 'BubbleMotion' into envs_updates
samuelmyoussef Sep 26, 2024
c477b10
Merge branch 'CartStem' into envs_updates
samuelmyoussef Sep 26, 2024
e19bacf
Merge branch 'CartStemContact' into envs_updates
samuelmyoussef Sep 26, 2024
9a8dfd5
Merge branch 'CatchTheObject' into envs_updates
samuelmyoussef Sep 26, 2024
fb88db6
Merge branch 'CatheterBeamEnv' into envs_updates
samuelmyoussef Sep 26, 2024
9930577
Merge branch 'CTR' into envs_updates
samuelmyoussef Sep 26, 2024
c45b8e0
Merge branch 'Diamond' into envs_updates
samuelmyoussef Sep 26, 2024
de55117
Merge branch 'Gripper' into envs_updates
samuelmyoussef Sep 26, 2024
4a8e22a
Merge branch 'Maze' into envs_updates
samuelmyoussef Sep 26, 2024
5d93d93
Merge branch 'SimpleMaze' into envs_updates
samuelmyoussef Sep 26, 2024
cd322ba
Merge branch 'StemPendulum' into envs_updates
samuelmyoussef Sep 26, 2024
59d9df3
Merge branch 'Trunk' into envs_updates
samuelmyoussef Sep 26, 2024
68b2bae
Merge branch 'TrunkCup' into envs_updates
samuelmyoussef Sep 26, 2024
09f3817
[Core] Add no server architecture implementation to the environments …
samuelmyoussef Oct 18, 2024
915ebd0
Merge branch 'envs_updates' of https://github.com/samuelmyoussef/Sofa…
samuelmyoussef Oct 19, 2024
4acd33a
Fixing ServerEnv import
samuelmyoussef Oct 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
342 changes: 210 additions & 132 deletions sofagym/AbstractEnv.py

Large diffs are not rendered by default.

168 changes: 168 additions & 0 deletions sofagym/ServerEnv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
"""ServerEnv to use the server-client architecture.
"""

__authors__ = ("PSC", "dmarchal", "emenager")
__contact__ = ("[email protected]", "[email protected]", "[email protected]")
__version__ = "1.0.0"
__copyright__ = "(c) 2020, Robocath, CNRS, Inria"
__date__ = "Oct 7 2020"

from typing import Optional

import numpy as np
import copy

import splib3

from sofagym.rpc_server import start_server, add_new_step, get_result, clean_registry, close_scene

from sofagym.AbstractEnv import AbstractEnv


class ServerEnv(AbstractEnv):
def __init__(self, default_config, config=None, render_mode: Optional[str]=None, root=None):
super().__init__(default_config, config, root=root)

# Start the server which distributes the calculations to its clients
start_server(self.config)

def step(self, action):
"""Executes one action in the environment.

Apply action and execute scale_factor simulation steps of 0.01 s.

Parameters:
----------
action: int
Action applied in the environment.

Returns:
-------
obs(ObsType):
The new state of the agent.
reward(float):
The reward obtain after applying the action in the current state.
done(bool):
Whether the agent reaches the terminal state
info(dict):
additional information (not used here)
"""
# assert self.action_space.contains(action), "%r (%s) invalid" % (action, type(action))

action = self._formataction(action)

# Pass the actions to the server to launch the simulation.
result_id = add_new_step(self.past_actions, action)
self.past_actions.append(action)

# Request results from the server.
# print("[INFO] >>> Result id:", result_id)
results = get_result(result_id, timeout=self.timeout)

obs = np.array(results["observation"]) # to work with baseline
reward = results["reward"]
done = results["done"]

# Avoid long explorations by using a timer.
self.timer += 1
if self.timer >= self.config["timer_limit"]:
# reward = -150
truncated = True

info = {} #(not use here)

if self.config["planning"]:
self.clean()
return obs, reward, done, info

def async_step(self, action):
"""Executes one action in the environment.

Apply action and execute scale_factor simulation steps of 0.01 s.
Like step but useful if you want to parallelise (blocking "get").
Otherwise use step.

Parameters:
----------
action: int
Action applied in the environment.

Returns:
-------
LateResult:
Class which allows to store the id of the client who performs
the calculation and to return later the usual information
(observation, reward, done) thanks to a get method.

"""
assert self.action_space.contains(action), "%r (%s) invalid" % (action, type(action))

result_id = add_new_step(self.past_actions, action)
self.past_actions.append(action)

class LateResult:
def __init__(self, result_id):
self.result_id = result_id

def get(self, timeout=None):
results = get_result(self.result_id, timeout=timeout)
obs = results["observation"]
reward = results["reward"]
done = results["done"]
return obs, reward, done, {}

return LateResult(copy.copy(result_id))

def reset(self):
"""Reset simulation.

Parameters:
----------
None.

Returns:
-------
obs, info
"""
self.clean()
self.viewer = None

splib3.animation.animate.manager = None

self.timer = 0
self.past_actions = []

return

def clean(self):
"""Function to clean the registery .

Close clients who are processing unused sequences of actions (for
planning)

Parameters:
----------
None.

Returns:
-------
None.
"""
clean_registry(self.past_actions)

def close(self):
"""Terminate simulation.

Close the viewer and the scene.

Parametres:
----------
None.

Returns:
-------
None.
"""
super().close()
close_scene()
109 changes: 64 additions & 45 deletions sofagym/envs/BubbleMotion/BubbleMotionEnv.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,29 @@
__date__ = "Feb 3 2021"

from sofagym.AbstractEnv import AbstractEnv
from sofagym.ServerEnv import ServerEnv
from sofagym.rpc_server import start_scene

from gym import spaces
import os, sys
import numpy as np

class BubbleMotionEnv(AbstractEnv):
from typing import Optional

class BubbleMotionEnv:
"""Sub-class of AbstractEnv, dedicated to the gripper scene.

See the class AbstractEnv for arguments and methods.
"""
#Setting a default configuration
path = os.path.dirname(os.path.abspath(__file__))
metadata = {'render.modes': ['human', 'rgb_array']}
dim_state = 15
DEFAULT_CONFIG = {"scene": "BubbleMotion",
"deterministic": True,
"source": [5, -5, 20],
"target": [5, 5, 0],
"goal": True,
"goalList": [[7, 0, 20]],
"start_node": None,
"scale_factor": 20,
Expand All @@ -46,55 +51,69 @@ class BubbleMotionEnv(AbstractEnv):
"seed": None,
"dt": 0.01,
"max_pressure": 40,
"board_dim": 8
"board_dim": 8,
"nb_actions": -1,
"dim_state": dim_state,
"randomize_states": False,
"init_states": [0] * dim_state,
"use_server": False
}

def __init__(self, config = None):
super().__init__(config)
nb_actions = -1

def __init__(self, config = None, root=None, use_server: Optional[bool]=None):
if use_server is not None:
self.DEFAULT_CONFIG.update({'use_server': use_server})
self.use_server = self.DEFAULT_CONFIG["use_server"]
self.env = ServerEnv(self.DEFAULT_CONFIG, config, root=root) if self.use_server else AbstractEnv(self.DEFAULT_CONFIG, config, root=root)

self.initialize_states()

if self.env.config["goal"]:
self.init_goal()

low = np.array([-1]*9)
high = np.array([1]*9)
self.action_space = spaces.Box(low=low, high=high, shape=(9,), dtype='float32')
self.nb_actions = str(nb_actions)

dim_state = 15
low_coordinates = np.array([0]*dim_state)
high_coordinates = np.array([80]*dim_state)
self.observation_space = spaces.Box(low_coordinates, high_coordinates,
dtype='float32')


def step(self, action):
return super().step(action)

self.env.action_space = spaces.Box(low=low, high=high, shape=(9,), dtype=np.float32)
self.nb_actions = str(self.env.nb_actions)

low_coordinates = np.array([0]*self.env.dim_state)
high_coordinates = np.array([80]*self.env.dim_state)
self.env.observation_space = spaces.Box(low_coordinates, high_coordinates, dtype=np.float32)

if self.env.root is None and not self.use_server:
self.env.init_root()

# called when an attribute is not found:
def __getattr__(self, name):
# assume it is implemented by self.instance
return self.env.__getattribute__(name)

def initialize_states(self):
self.env.initialize_states()

bd = self.env.config["board_dim"]
init_pos = [4+(bd-4)*self.env.np_random.random(), 4+(bd-4)*self.env.np_random.random(), 5]
self.env.config.update({'init_pos': init_pos})

def init_goal(self):
bd = self.env.config["board_dim"]
pos_goal = [1+bd*self.env.np_random.random(), 1+bd*self.env.np_random.random(), 2]
self.env.goal = pos_goal
self.env.config.update({'goalPos': self.env.goal})

def reset(self):
"""Reset simulation.

Note:
----
We launch a client to create the scene. The scene of the program is
client_<scene>Env.py.

"""
super().reset()

self.config.update({'goalPos': self.goal})
obs = start_scene(self.config, self.nb_actions)
self.initialize_states()

return np.array(obs['observation'])

def get_available_actions(self):
"""Gives the actions available in the environment.

Parameters:
----------
None.

Returns:
-------
list of the action available in the environment.
"""
return self.action_space


if self.env.config["goal"]:
self.init_goal()

self.env.reset()

if self.use_server:
obs = start_scene(self.env.config, self.nb_actions)
state = np.array(obs['observation'], dtype=np.float32)
else:
state = np.array(self.env._getState(self.env.root), dtype=np.float32)

return state
5 changes: 3 additions & 2 deletions sofagym/envs/BubbleMotion/BubbleMotionScene.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def createScene(rootNode, config={"source": [5, -5, 20],
"zFar":4000,
"dt": 0.01,
"max_pressure": 40,
"init_pos": [5, 5, 5],
"board_dim": 8},
mode='simu_and_visu'):

Expand All @@ -56,10 +57,10 @@ def createScene(rootNode, config={"source": [5, -5, 20],
visu(rootNode, config, position_spot, direction_spot, cutoff=250)

bd = config["board_dim"]
pos_goal = [1+bd*np.random.random(), 1+bd*np.random.random(), 2]
pos_goal = config["goalPos"]
add_goal_node(rootNode, pos_goal)

init_pos = [4+(bd-4)*np.random.random(), 4+(bd-4)*np.random.random(), 5]
init_pos = config["init_pos"]
bubblemotion_config = {'init_pos': init_pos, "dt": config["dt"], "max_pressure": config["max_pressure"]}

bubblemotion = BubbleMotion(bubblemotion_config=bubblemotion_config)
Expand Down
7 changes: 4 additions & 3 deletions sofagym/envs/BubbleMotion/BubbleMotionToolbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def getReward(self):

return r, dist

def update(self):
def update(self, goal=None):
"""Update function.

This function is used as an initialization function.
Expand All @@ -97,6 +97,7 @@ def update(self):
None.

"""
self.goal = goal[:2]
current_sphere_pos = self._getSpherePos()
self.init_goal_dist = float(np.linalg.norm(current_sphere_pos-self.goal))

Expand Down Expand Up @@ -158,8 +159,8 @@ def __init__(self, *args, **kwargs):
if 'goalPos' in kwargs:
self.goalPos = kwargs["goalPos"]

def update(self):
pass
def update(self, goal):
self.goalPos = goal

def set_mo_pos(self, goal):
pass
Expand Down
Loading