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

[Question] 'NoneType' object has no attribute 'glfwGetCurrentContext' #1224

Open
qffof opened this issue Oct 21, 2024 · 5 comments · May be fixed by #1283
Open

[Question] 'NoneType' object has no attribute 'glfwGetCurrentContext' #1224

qffof opened this issue Oct 21, 2024 · 5 comments · May be fixed by #1283
Labels
question Further information is requested

Comments

@qffof
Copy link

qffof commented Oct 21, 2024

Question

Hi!I have some questions for you
background:

gymnasium: 1.0.0
glfw: 2.7.0

I run the code below:

import gymnasium as gym
env=gym.make('Humanoid-v5', render_mode='human')
obs=env.reset()
env.render()

An error was reported :

  logger.deprecation(
  File "D:\anaconda\envs\Gemma2b\lib\site-packages\gymnasium\envs\mujoco\mujoco_rendering.py", line 359, in __del__
  File "D:\anaconda\envs\Gemma2b\lib\site-packages\gymnasium\envs\mujoco\mujoco_rendering.py", line 352, in free
  File "D:\anaconda\envs\Gemma2b\lib\site-packages\glfw\__init__.py", line 2366, in get_current_context
AttributeError: 'NoneType' object has no attribute 'glfwGetCurrentContext'

When I take the solution given earlier:

import gymnasium as gym
env=gym.make('Humanoid-v5', render_mode='human')
obs=env.reset()
env.render()
breakpoint()

The result of the code run is: The mojoco simulation interface is not responding

@qffof qffof added the question Further information is requested label Oct 21, 2024
@Beanpow
Copy link
Contributor

Beanpow commented Oct 22, 2024

You may have to close the env before the program ends.

import gymnasium as gym
env=gym.make('Humanoid-v5', render_mode='human')
obs=env.reset()
env.render()
env.close()

@pseudo-rnd-thoughts
Copy link
Member

This might be a windows only issue

We don't officially support windows but will try to fix bugs

@Kallinteris-Andreas
Copy link
Collaborator

If you're using Windows, try the Linux subsystem.

@a-ayesh
Copy link

a-ayesh commented Dec 28, 2024

I ran into this issue as well while using gymnasium to render my MuJoCo environment in Stable-Baselines3. Details and how to replicate are as follows:

Details

OS: Ubuntu 22.04.5 LTS
Python Venv: Anaconda
Python Version: 3.10

How to replicate

from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3 import TD3

# Number of evaluation episodes
N_EVAL_EPISODES = 10

# Environment ID
ENV_ID = 'InvertedPendulum-v5'

# Optimized hyperparameters for the TD3 agent
TD3_OPTIMIZED_HYPERPARAMS = {
    'learning_rate': 0.001,
    'buffer_size': 100000,
    'tau': 0.01,
    'gamma': 0.999,
    'train_freq': 100,
    'gradient_steps': 200,
    'batch_size': 64,
    'policy_delay': 1
}

from lib.utils import *


class TD3Agent:
    """
    TD3 Agent implementation for training and evaluation.
    """

    def __init__(self, env_id: str, hyperparams: dict, verbose: int = 1):
        """
        Initializes the TD3Agent.

        Args:
            env_id (str): The Gym environment ID.
            hyperparams (dict): Dictionary containing hyperparameters for the TD3 agent.
            verbose (int, optional): Verbosity level (default: 1).
        """
        self.env_id = env_id
        self.env = make_vec_env(env_id, n_envs=1, env_kwargs={'render_mode': 'human'})
        self.hyperparams = hyperparams
        self.verbose = verbose
        self.model = None

    def evaluate(self, n_eval_episodes: int = 10) -> tuple:
        """
        Evaluates the TD3 model on the environment.

        Args:
            n_eval_episodes (int): Number of evaluation episodes.

        Returns:
            tuple: A tuple containing mean reward and standard deviation of rewards.
        """
        if self.model is None:
            raise ValueError("Model has not been created or trained yet.")
        mean_reward, std_reward = evaluate_policy(
            self.model,
            self.env,
            n_eval_episodes=n_eval_episodes
        )
        return mean_reward, std_reward

    def load(self, path: str):
        """
        Loads a pre-trained TD3 model from the specified path.

        Args:
            path (str): Path to the saved model file.
        """
        self.model = TD3.load(path, env=self.env)


def run_algorithm():
    """
    Creates and evaluates a TD3 agent using the specified environment and hyperparameters.
    """
    agent = TD3Agent(env_id=ENV_ID, hyperparams=TD3_OPTIMIZED_HYPERPARAMS, verbose=1)
    agent.load("agent")  # Path to the pre-trained agent

    print("Evaluating...")
    mean_reward, std_reward = agent.evaluate(n_eval_episodes=N_EVAL_EPISODES)
    print(f"Stats: Mean Reward: {mean_reward:.2f} +/- {std_reward}\n")

    # agent.env.close() # Comment this to see the error

if __name__ == "__main__":
    run_algorithm()

The above code evaluates a pre-trained TD3 agent using SB3 on the InvertedPendulum-v5 MuJoCo environment. The env component is handled by gymnasium and I was getting the same error as this issue.

What causes the issue

  • User doesn't call env.close() to gracefully shutdown the rendering context
  • Consequently, when the python program terminates, the dependencies for glfw are unloaded before glfw itself causing it to throw an AttributeError

How to fix this issue

  • Simply call env.close() before your python program terminates

@Kallinteris-Andreas
Copy link
Collaborator

  1. the bug of unresponsive UI when render_mode="human" and breakpoint() is because the execution of the program has paused
import gymnasium

env = gymnasium.make('Humanoid-v5', render_mode='human')
obs, info = env.reset()
# env.render()  # no need to call it with `render_mode="human"`
env.unwrapped.mujoco_renderer.viewer._paused = True  # this pauses the render window, it can be unpaused by pressing the SPACE key
for _ in range(1000):
    env.step(env.action_space.sample())
  1. The error is not descriptive to the user and should be fixed Add error message when terminating the MuJoCo renderer without calling env.close #1283
Exception ignored in: <function WindowViewer.__del__ at 0x7f058805ee80>
Traceback (most recent call last):
  File "/home/master-andreas/Gymnasium/gymnasium/envs/mujoco/mujoco_rendering.py", line 377, in __del__
  File "/home/master-andreas/Gymnasium/gymnasium/envs/mujoco/mujoco_rendering.py", line 365, in free
  File "/home/master-andreas/temp_env/lib/python3.13/site-packages/glfw/__init__.py", line 2369, in get_current_context
AttributeError: 'NoneType' object has no attribute 'glfwGetCurrentContext'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants