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

Sourcery Starbot ⭐ refactored brendanator/atari-rl #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

SourceryAI
Copy link

@SourceryAI SourceryAI commented Jan 26, 2024

Thanks for starring sourcery-ai/sourcery ✨ 🌟 ✨

Here's your pull request refactoring your most popular Python repo.

If you want Sourcery to refactor all your Python repos and incoming pull requests install our bot.

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch https://github.com/sourcery-ai-bot/atari-rl master
git merge --ff-only FETCH_HEAD
git reset HEAD^

Summary by CodeRabbit

  • New Features
    • Enhanced robustness in exploration bonus calculation with non-negative pseudo counts.
  • Bug Fixes
    • Simplified action selection in agents by always using the policy network.
    • Improved the reset functionality in Atari game simulations for clarity.
  • Refactor
    • Updated string formatting across various modules for better readability and maintainability.
    • Streamlined control flow and logic in training, replay memory management, and network input handling.
  • Style
    • Adopted consistent use of f-strings for string formatting in multiple files.

Comment on lines -158 to +161
elif config.async == 'n_step':
config.batch_size = 1
elif config.async == 'a3c':
elif config. async in ['n_step', 'a3c']:
config.batch_size = 1
else:
raise Exception('Unknown asynchronous algorithm: ' + config.async)
raise Exception(f'Unknown asynchronous algorithm: {config.async}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_config refactored with the following changes:

Comment on lines -25 to +30
# Epsilon greedy exploration/exploitation even for bootstrapped DQN
if np.random.rand() < self.epsilon(step):
return self.atari.sample_action()
else:
[action] = session.run(
self.policy_network.choose_action,
{self.policy_network.inputs.observations: [observation]})
return action
[action] = session.run(
self.policy_network.choose_action,
{self.policy_network.inputs.observations: [observation]})
return action
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Agent.action refactored with the following changes:

This removes the following comments ( why? ):

# Epsilon greedy exploration/exploitation even for bootstrapped DQN

Comment on lines -23 to +24
if pseudo_count < 0:
pseudo_count = 0 # Occasionally happens at start of training

# Return exploration bonus
exploration_bonus = self.beta / math.sqrt(pseudo_count + 0.01)
return exploration_bonus
pseudo_count = max(pseudo_count, 0)
return self.beta / math.sqrt(pseudo_count + 0.01)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ExplorationBonus.bonus refactored with the following changes:

This removes the following comments ( why? ):

# Return exploration bonus
# Occasionally happens at start of training

raise Exception('Unknown replay_priorities: ' + config.replay_priorities)
raise Exception(f'Unknown replay_priorities: {config.replay_priorities}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ReplayMemory.__init__ refactored with the following changes:

name = self.run_dir + 'replay_' + threading.current_thread().name + '.hdf'
name = f'{self.run_dir}replay_{threading.current_thread().name}.hdf'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ReplayMemory.save refactored with the following changes:

Comment on lines -50 to +51
discounted_reward = sum([
reward * config.discount_rate**(reward - 4) for reward in range(4, 11)
])
discounted_reward = sum(reward * config.discount_rate**(reward - 4)
for reward in range(4, 11))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ReplayMemoryTest.test_replay_memory refactored with the following changes:

if self.run_summary(step):
return [self.summary_op]
else:
return [self.dummy_summary_op]
return [self.summary_op] if self.run_summary(step) else [self.dummy_summary_op]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Summary.operation refactored with the following changes:

Comment on lines -16 to +27
return max([int(run) for run in runs])
return max(int(run) for run in runs)

return 0

if config.run_dir == 'latest':
parent_dir = 'runs/%s/' % config.game
parent_dir = f'runs/{config.game}/'
previous_run = find_previous_run(parent_dir)
run_dir = parent_dir + ('run_%d' % previous_run)
elif config.run_dir:
run_dir = config.run_dir
else:
parent_dir = 'runs/%s/' % config.game
parent_dir = f'runs/{config.game}/'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run_directory refactored with the following changes:

Comment on lines -44 to +48
return prefix + '_t_plus_' + str(t)
return f'{prefix}_t_plus_{str(t)}'
elif t == 0:
return prefix + '_t'
return f'{prefix}_t'
else:
return prefix + '_t_minus_' + str(-t)
return f'{prefix}_t_minus_{str(-t)}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function format_offset refactored with the following changes:

print('%s %s: %s' % (now, thread_id, message))
print(f'{now} {thread_id}: {message}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function log refactored with the following changes:

Copy link

coderabbitai bot commented Jan 26, 2024

Walkthrough

The recent modifications across various components of the codebase focus on enhancing readability, maintainability, and efficiency. Changes include the adoption of f-strings for string formatting, the use of conditional and generator expressions for more concise code, and minor logic adjustments for robustness. These updates streamline the code, making it easier to understand and work with, without altering the core functionality or control flow.

Changes

File(s) Change Summary
agents/agent.py Removed epsilon greedy logic for action selection, now directly uses policy network.
agents/exploration_bonus.py, networks/reward_scaling.py Improved robustness in calculations, ensuring non-negative and simplified return values.
agents/replay_memory.py, main.py, networks/dqn.py, networks/factory.py, networks/inputs.py, util/util.py Updated to use f-strings for better readability and string formatting.
agents/training.py, test/test_replay_memory.py Introduced walrus operator and generator expressions for efficiency in logic and control flow.
atari/atari.py Minor loop variable change for clarity, indicating unused variable.
networks/inputs.py, util/summary.py Refactored to use conditional expressions for streamlined control flow.

🐰✨
Changes abound, the code does leap,
With f-strings bright, and logic neat.
Through fields of code, we hop and tweak,
A cleaner path, for all to seek.
🌟🐾

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Type: Refactoring

PR Summary: The pull request consists of refactoring changes aimed at improving code readability and efficiency. It includes the use of f-strings for string formatting, simplification of conditional statements, and the use of list comprehensions and other Pythonic idioms. The changes also involve cleaning up the code by removing unnecessary else blocks after return statements and using more concise expressions for conditional assignments.

Decision: Comment

📝 Type: 'Refactoring' - not supported yet.
  • Sourcery currently only approves 'Typo fix' PRs.
✅ Issue addressed: this change correctly addresses the issue or implements the desired feature.
No details provided.
✅ Small diff: the diff is small enough to approve with confidence.
No details provided.

General suggestions:

  • Ensure that the refactoring changes do not alter the intended logic of the code, especially in conditional statements where the order of evaluation matters.
  • Verify that the use of f-strings and other modern Python features is consistent across the entire codebase to maintain readability and style consistency.
  • Review the changes for any potential syntax errors introduced during refactoring, such as the extra space found in 'config. async'.
  • Consider running the full test suite to ensure that the refactored code behaves as expected and that no regressions have been introduced.

Thanks for using Sourcery. We offer it for free for open source projects and would be very grateful if you could help us grow. If you like it, would you consider sharing Sourcery on your favourite social media? ✨

Share Sourcery

Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

@@ -81,15 +81,14 @@ def train_agent(self, session, agent):
agent.replay_memory.save()

def reset_target_network(self, session, step):
if self.reset_op:
if step > 0 and step % self.config.target_network_update_period == 0:
if step > 0 and step % self.config.target_network_update_period == 0:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question (llm): The refactoring to combine the conditions into a single if statement is good for readability, but ensure that the logic is equivalent and that self.reset_op is always defined when needed.

elif config.async == 'n_step':
config.batch_size = 1
elif config.async == 'a3c':
elif config. async in ['n_step', 'a3c']:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (llm): There's an extra space between 'config.' and 'async' which could lead to a syntax error. This should be corrected.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 14bde94 and f5bea8e.
Files selected for processing (13)
  • agents/agent.py (1 hunks)
  • agents/exploration_bonus.py (1 hunks)
  • agents/replay_memory.py (3 hunks)
  • agents/training.py (1 hunks)
  • atari/atari.py (1 hunks)
  • main.py (1 hunks)
  • networks/dqn.py (1 hunks)
  • networks/factory.py (1 hunks)
  • networks/inputs.py (3 hunks)
  • networks/reward_scaling.py (1 hunks)
  • test/test_replay_memory.py (1 hunks)
  • util/summary.py (1 hunks)
  • util/util.py (3 hunks)
Files skipped from review due to trivial changes (5)
  • agents/replay_memory.py
  • atari/atari.py
  • networks/dqn.py
  • util/summary.py
  • util/util.py
Additional comments: 11
agents/exploration_bonus.py (1)
  • 23-24: The modification to use max(pseudo_count, 0) for ensuring pseudo_count is non-negative is a good practice for simplifying logic and improving code readability.
test/test_replay_memory.py (1)
  • 50-51: Changing from a list comprehension to a generator expression within the sum function is a performance optimization that avoids creating an intermediate list. Good job on this improvement.
networks/reward_scaling.py (1)
  • 34-34: Simplifying the return statement in the batch_sigma_squared method to directly return sigma_squared if it's greater than 0, otherwise 1.0, is a clean and efficient approach.
agents/agent.py (1)
  • 27-30: Removing the epsilon greedy exploration/exploitation logic and always using the policy network to choose an action simplifies the agent's decision-making process. This aligns with the objective of simplifying logic.
agents/training.py (2)
  • 84-85: Directly checking if step is greater than 0 and a multiple of self.config.target_network_update_period before resetting the target network is a clear and efficient approach.
  • 91-91: Using the walrus operator for conditional assignment in the train_batch method is a modern Python practice that improves code readability and efficiency.
networks/factory.py (1)
  • 111-111: Updating string formatting from concatenation to f-string in the create_summary_ops method enhances readability and performance. Good use of modern Python features.
networks/inputs.py (3)
  • 69-69: Using a formatted string for the name parameter in the tf.placeholder_with_default call improves readability and is a good use of modern Python features.
  • 101-101: Initializing the feeds attribute in the RequiredFeeds class using a conditional expression simplifies the logic and improves code readability.
  • 150-166: Refactoring the required_feeds method to handle input tensors and cache results more efficiently is a good practice for improving code performance and maintainability.
main.py (1)
  • 158-161: Consolidating the logic for setting batch_size in the create_config function into a single if-elif-else block simplifies the control flow and improves clarity. Using an f-string for the exception message is also a readability improvement.

@brendanator
Copy link
Owner

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have skipped reviewing this pull request. It looks like we've already reviewed this pull request.

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

Successfully merging this pull request may close these issues.

2 participants