text
stringlengths
0
1.05M
meta
dict
"""Advanced VTGraph usage example.""" from vt_graph_api import VTGraph from vt_graph_api.errors import NodeNotFoundError API_KEY = "" # Add your VT API Key here. graph = VTGraph( API_KEY, verbose=False, private=True, name="First Graph", user_editors=["jinfantes"], group_viewers=["virustotal"]) # Adding first node. WannyCry hash graph.add_node( "ed01ebfbc9eb5bbea545af4d01bf5f1071661840480439c6e5babe8e080e41aa", "file", label="Investigation node") print("Expanding... this might take a few seconds.") graph.expand_n_level(level=1, max_nodes_per_relationship=10, max_nodes=200) # Adding second node, Kill Switch domain graph.add_node( "www.ifferfsodp9ifjaposdfjhgosurijfaewrwergwea.com", "domain", label="Kill Switch", fetch_information=True ) # Expanding the communicating files of the kill switch domain. graph.expand( "www.ifferfsodp9ifjaposdfjhgosurijfaewrwergwea.com", "communicating_files", max_nodes_per_relationship=20 ) # Deleting nodes nodes_to_delete = [ "52.57.88.48", "54.153.0.145", "52.170.89.193", "184.168.221.43", "144.217.254.91", "144.217.254.3", "98.143.148.47", "104.41.151.54", "144.217.74.156", "fb0b6044347e972e21b6c376e37e1115dab494a2c6b9fb28b92b1e45b45d0ebc", "428f22a9afd2797ede7c0583d34a052c32693cbb55f567a60298587b6e675c6f", "b43b234012b8233b3df6adb7c0a3b2b13cc2354dd6de27e092873bf58af2693c", "85ce324b8f78021ecfc9b811c748f19b82e61bb093ff64f2eab457f9ef19b186", "3f3a9dde96ec4107f67b0559b4e95f5f1bca1ec6cb204bfe5fea0230845e8301", "2c2d8bc91564050cf073745f1b117f4ffdd6470e87166abdfcd10ecdff040a2e", "a93ee7ea13238bd038bcbec635f39619db566145498fe6e0ea60e6e76d614bd3", "7a828afd2abf153d840938090d498072b7e507c7021e4cdd8c6baf727cafc545", "a897345b68191fd36f8cefb52e6a77acb2367432abb648b9ae0a9d708406de5b", "5c1f4f69c45cff9725d9969f9ffcf79d07bd0f624e06cfa5bcbacd2211046ed6" ] for node in nodes_to_delete: try: graph.delete_node(node) except NodeNotFoundError: pass # Ignoring if the node does not exist in the graph. graph.save_graph() print("Graph ID: %s" % graph.graph_id)
{ "repo_name": "VirusTotal/vt-graph-api", "path": "examples/advanced_graph.py", "copies": "1", "size": "2136", "license": "apache-2.0", "hash": 242503899338419800, "line_mean": 31.3636363636, "line_max": 79, "alpha_frac": 0.7649812734, "autogenerated": false, "ratio": 2.316702819956616, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.35816840933566163, "avg_score": null, "num_lines": null }
"""Advantage Actor-Critic (A2C) algorithm for reinforcement learning.""" import time try: from collections.abc import Sequence as SequenceCollection except: from collections import Sequence as SequenceCollection import numpy as np import tensorflow as tf from deepchem.models import KerasModel from deepchem.models.optimizers import Adam class A2CLossDiscrete(object): """This class computes the loss function for A2C with discrete action spaces.""" def __init__(self, value_weight, entropy_weight, action_prob_index, value_index): self.value_weight = value_weight self.entropy_weight = entropy_weight self.action_prob_index = action_prob_index self.value_index = value_index def __call__(self, outputs, labels, weights): prob = outputs[self.action_prob_index] value = outputs[self.value_index] reward, advantage = weights action = labels[0] advantage = tf.expand_dims(advantage, axis=1) prob = prob + np.finfo(np.float32).eps log_prob = tf.math.log(prob) policy_loss = -tf.reduce_mean( advantage * tf.reduce_sum(action * log_prob, axis=1)) value_loss = tf.reduce_mean(tf.square(reward - value)) entropy = -tf.reduce_mean(tf.reduce_sum(prob * log_prob, axis=1)) return policy_loss + self.value_weight * value_loss - self.entropy_weight * entropy class A2CLossContinuous(object): """This class computes the loss function for A2C with continuous action spaces. Note ---- This class requires tensorflow-probability to be installed. """ def __init__(self, value_weight, entropy_weight, mean_index, std_index, value_index): try: import tensorflow_probability as tfp # noqa: F401 except ModuleNotFoundError: raise ValueError( "This class requires tensorflow-probability to be installed.") self.value_weight = value_weight self.entropy_weight = entropy_weight self.mean_index = mean_index self.std_index = std_index self.value_index = value_index def __call__(self, outputs, labels, weights): import tensorflow_probability as tfp mean = outputs[self.mean_index] std = outputs[self.std_index] value = outputs[self.value_index] reward, advantage = weights action = labels[0] distrib = tfp.distributions.Normal(mean, std) reduce_axes = list(range(1, len(action.shape))) log_prob = tf.reduce_sum(distrib.log_prob(action), reduce_axes) policy_loss = -tf.reduce_mean(advantage * log_prob) value_loss = tf.reduce_mean(tf.square(reward - value)) entropy = tf.reduce_mean(distrib.entropy()) return policy_loss + self.value_weight * value_loss - self.entropy_weight * entropy class A2C(object): """ Implements the Advantage Actor-Critic (A2C) algorithm for reinforcement learning. The algorithm is described in Mnih et al, "Asynchronous Methods for Deep Reinforcement Learning" (https://arxiv.org/abs/1602.01783). This class supports environments with both discrete and continuous action spaces. For discrete action spaces, the "action" argument passed to the environment is an integer giving the index of the action to perform. The policy must output a vector called "action_prob" giving the probability of taking each action. For continuous action spaces, the action is an array where each element is chosen independently from a normal distribution. The policy must output two arrays of the same shape: "action_mean" gives the mean value for each element, and "action_std" gives the standard deviation for each element. In either case, the policy must also output a scalar called "value" which is an estimate of the value function for the current state. The algorithm optimizes all outputs at once using a loss that is the sum of three terms: 1. The policy loss, which seeks to maximize the discounted reward for each action. 2. The value loss, which tries to make the value estimate match the actual discounted reward that was attained at each step. 3. An entropy term to encourage exploration. This class supports Generalized Advantage Estimation as described in Schulman et al., "High-Dimensional Continuous Control Using Generalized Advantage Estimation" (https://arxiv.org/abs/1506.02438). This is a method of trading off bias and variance in the advantage estimate, which can sometimes improve the rate of convergance. Use the advantage_lambda parameter to adjust the tradeoff. This class supports Hindsight Experience Replay as described in Andrychowicz et al., "Hindsight Experience Replay" (https://arxiv.org/abs/1707.01495). This is a method that can enormously accelerate learning when rewards are very rare. It requires that the environment state contains information about the goal the agent is trying to achieve. Each time it generates a rollout, it processes that rollout twice: once using the actual goal the agent was pursuing while generating it, and again using the final state of that rollout as the goal. This guarantees that half of all rollouts processed will be ones that achieved their goals, and hence received a reward. To use this feature, specify use_hindsight=True to the constructor. The environment must have a method defined as follows: def apply_hindsight(self, states, actions, goal): ... return new_states, rewards The method receives the list of states generated during the rollout, the action taken for each one, and a new goal state. It should generate a new list of states that are identical to the input ones, except specifying the new goal. It should return that list of states, and the rewards that would have been received for taking the specified actions from those states. The output arrays may be shorter than the input ones, if the modified rollout would have terminated sooner. Note ---- Using this class on continuous action spaces requires that `tensorflow_probability` be installed. """ def __init__(self, env, policy, max_rollout_length=20, discount_factor=0.99, advantage_lambda=0.98, value_weight=1.0, entropy_weight=0.01, optimizer=None, model_dir=None, use_hindsight=False): """Create an object for optimizing a policy. Parameters ---------- env: Environment the Environment to interact with policy: Policy the Policy to optimize. It must have outputs with the names 'action_prob' and 'value' (for discrete action spaces) or 'action_mean', 'action_std', and 'value' (for continuous action spaces) max_rollout_length: int the maximum length of rollouts to generate discount_factor: float the discount factor to use when computing rewards advantage_lambda: float the parameter for trading bias vs. variance in Generalized Advantage Estimation value_weight: float a scale factor for the value loss term in the loss function entropy_weight: float a scale factor for the entropy term in the loss function optimizer: Optimizer the optimizer to use. If None, a default optimizer is used. model_dir: str the directory in which the model will be saved. If None, a temporary directory will be created. use_hindsight: bool if True, use Hindsight Experience Replay """ self._env = env self._policy = policy self.max_rollout_length = max_rollout_length self.discount_factor = discount_factor self.advantage_lambda = advantage_lambda self.value_weight = value_weight self.entropy_weight = entropy_weight self.use_hindsight = use_hindsight self._state_is_list = isinstance(env.state_shape[0], SequenceCollection) if optimizer is None: self._optimizer = Adam(learning_rate=0.001, beta1=0.9, beta2=0.999) else: self._optimizer = optimizer output_names = policy.output_names self.continuous = ('action_mean' in output_names) self._value_index = output_names.index('value') if self.continuous: self._action_mean_index = output_names.index('action_mean') self._action_std_index = output_names.index('action_std') else: self._action_prob_index = output_names.index('action_prob') self._rnn_final_state_indices = [ i for i, n in enumerate(output_names) if n == 'rnn_state' ] self._rnn_states = policy.rnn_initial_states self._model = self._build_model(model_dir) self._checkpoint = tf.train.Checkpoint() self._checkpoint.save_counter # Ensure the variable has been created self._checkpoint.listed = self._model.model.trainable_variables def _build_model(self, model_dir): """Construct a KerasModel containing the policy and loss calculations.""" policy_model = self._policy.create_model() if self.continuous: loss = A2CLossContinuous(self.value_weight, self.entropy_weight, self._action_mean_index, self._action_std_index, self._value_index) else: loss = A2CLossDiscrete(self.value_weight, self.entropy_weight, self._action_prob_index, self._value_index) model = KerasModel( policy_model, loss, batch_size=self.max_rollout_length, model_dir=model_dir, optimize=self._optimizer) model._ensure_built() return model def fit(self, total_steps, max_checkpoints_to_keep=5, checkpoint_interval=600, restore=False): """Train the policy. Parameters ---------- total_steps: int the total number of time steps to perform on the environment, across all rollouts on all threads max_checkpoints_to_keep: int the maximum number of checkpoint files to keep. When this number is reached, older files are deleted. checkpoint_interval: float the time interval at which to save checkpoints, measured in seconds restore: bool if True, restore the model from the most recent checkpoint and continue training from there. If False, retrain the model from scratch. """ if restore: self.restore() manager = tf.train.CheckpointManager( self._checkpoint, self._model.model_dir, max_checkpoints_to_keep) checkpoint_time = time.time() self._env.reset() rnn_states = self._policy.rnn_initial_states # Training loop. step_count = 0 while step_count < total_steps: initial_rnn_states = rnn_states states, actions, rewards, values, rnn_states = self._create_rollout( rnn_states) self._process_rollout(states, actions, rewards, values, initial_rnn_states) if self.use_hindsight: self._process_rollout_with_hindsight(states, actions, initial_rnn_states) step_count += len(actions) self._model._global_step.assign_add(len(actions)) # Do checkpointing. if step_count >= total_steps or time.time( ) >= checkpoint_time + checkpoint_interval: manager.save() checkpoint_time = time.time() def predict(self, state, use_saved_states=True, save_states=True): """Compute the policy's output predictions for a state. If the policy involves recurrent layers, this method can preserve their internal states between calls. Use the use_saved_states and save_states arguments to specify how it should behave. Parameters ---------- state: array or list of arrays the state of the environment for which to generate predictions use_saved_states: bool if True, the states most recently saved by a previous call to predict() or select_action() will be used as the initial states. If False, the internal states of all recurrent layers will be set to the initial values defined by the policy before computing the predictions. save_states: bool if True, the internal states of all recurrent layers at the end of the calculation will be saved, and any previously saved states will be discarded. If False, the states at the end of the calculation will be discarded, and any previously saved states will be kept. Returns ------- the array of action probabilities, and the estimated value function """ results = self._predict_outputs(state, use_saved_states, save_states) if self.continuous: return [ results[i] for i in (self._action_mean_index, self._action_std_index, self._value_index) ] else: return [results[i] for i in (self._action_prob_index, self._value_index)] def select_action(self, state, deterministic=False, use_saved_states=True, save_states=True): """Select an action to perform based on the environment's state. If the policy involves recurrent layers, this method can preserve their internal states between calls. Use the use_saved_states and save_states arguments to specify how it should behave. Parameters ---------- state: array or list of arrays the state of the environment for which to select an action deterministic: bool if True, always return the best action (that is, the one with highest probability). If False, randomly select an action based on the computed probabilities. use_saved_states: bool if True, the states most recently saved by a previous call to predict() or select_action() will be used as the initial states. If False, the internal states of all recurrent layers will be set to the initial values defined by the policy before computing the predictions. save_states: bool if True, the internal states of all recurrent layers at the end of the calculation will be saved, and any previously saved states will be discarded. If False, the states at the end of the calculation will be discarded, and any previously saved states will be kept. Returns ------- the index of the selected action """ outputs = self._predict_outputs(state, use_saved_states, save_states) return self._select_action_from_outputs(outputs, deterministic) def restore(self): """Reload the model parameters from the most recent checkpoint file.""" last_checkpoint = tf.train.latest_checkpoint(self._model.model_dir) if last_checkpoint is None: raise ValueError('No checkpoint found') self._checkpoint.restore(last_checkpoint) def _predict_outputs(self, state, use_saved_states, save_states): """Compute a set of outputs for a state. """ if not self._state_is_list: state = [state] if use_saved_states: state = state + list(self._rnn_states) else: state = state + list(self._policy.rnn_initial_states) inputs = [np.expand_dims(s, axis=0) for s in state] results = self._compute_model(inputs) results = [r.numpy() for r in results] if save_states: self._rnn_states = [ np.squeeze(results[i], 0) for i in self._rnn_final_state_indices ] return results @tf.function(experimental_relax_shapes=True) def _compute_model(self, inputs): return self._model.model(inputs) def _select_action_from_outputs(self, outputs, deterministic): """Given the policy outputs, select an action to perform.""" if self.continuous: action_mean = outputs[self._action_mean_index] action_std = outputs[self._action_std_index] if deterministic: return action_mean[0] else: return np.random.normal(action_mean[0], action_std[0]) else: action_prob = outputs[self._action_prob_index] if deterministic: return action_prob.argmax() else: action_prob = action_prob.flatten() return np.random.choice(np.arange(len(action_prob)), p=action_prob) def _create_rollout(self, rnn_states): """Generate a rollout.""" states = [] actions = [] rewards = [] values = [] # Generate the rollout. for i in range(self.max_rollout_length): if self._env.terminated: break state = self._env.state states.append(state) results = self._compute_model( self._create_model_inputs(state, rnn_states)) results = [r.numpy() for r in results] value = results[self._value_index] rnn_states = [ np.squeeze(results[i], 0) for i in self._rnn_final_state_indices ] action = self._select_action_from_outputs(results, False) actions.append(action) values.append(float(value)) rewards.append(self._env.step(action)) # Compute an estimate of the reward for the rest of the episode. if not self._env.terminated: results = self._compute_model( self._create_model_inputs(self._env.state, rnn_states)) final_value = self.discount_factor * results[self._value_index].numpy()[0] else: final_value = 0.0 values.append(final_value) if self._env.terminated: self._env.reset() rnn_states = self._policy.rnn_initial_states return states, actions, np.array( rewards, dtype=np.float32), np.array( values, dtype=np.float32), rnn_states def _process_rollout(self, states, actions, rewards, values, initial_rnn_states): """Train the network based on a rollout.""" # Compute the discounted rewards and advantages. discounted_rewards = rewards.copy() discounted_rewards[-1] += values[-1] advantages = rewards - values[:-1] + self.discount_factor * np.array( values[1:]) for j in range(len(rewards) - 1, 0, -1): discounted_rewards[j - 1] += self.discount_factor * discounted_rewards[j] advantages[ j - 1] += self.discount_factor * self.advantage_lambda * advantages[j] # Record the actions, converting to one-hot if necessary. actions_matrix = [] if self.continuous: for action in actions: actions_matrix.append(action) else: n_actions = self._env.n_actions for action in actions: a = np.zeros(n_actions, np.float32) a[action] = 1.0 actions_matrix.append(a) actions_matrix = np.array(actions_matrix, dtype=np.float32) # Rearrange the states into the proper set of arrays. if self._state_is_list: state_arrays = [[] for i in range(len(self._env.state_shape))] for state in states: for j in range(len(state)): state_arrays[j].append(state[j]) else: state_arrays = [states] state_arrays = [np.stack(s) for s in state_arrays] # Build the inputs and apply gradients. inputs = state_arrays + [ np.expand_dims(s, axis=0) for s in initial_rnn_states ] self._apply_gradients(inputs, actions_matrix, discounted_rewards, advantages) @tf.function(experimental_relax_shapes=True) def _apply_gradients(self, inputs, actions_matrix, discounted_rewards, advantages): """Compute the gradient of the loss function for a rollout and update the model.""" vars = self._model.model.trainable_variables with tf.GradientTape() as tape: outputs = self._model.model(inputs) loss = self._model._loss_fn(outputs, [actions_matrix], [discounted_rewards, advantages]) gradients = tape.gradient(loss, vars) self._model._tf_optimizer.apply_gradients(zip(gradients, vars)) def _process_rollout_with_hindsight(self, states, actions, initial_rnn_states): """Create a new rollout by applying hindsight to an existing one, then train the network.""" hindsight_states, rewards = self._env.apply_hindsight( states, actions, states[-1]) if self._state_is_list: state_arrays = [[] for i in range(len(self._env.state_shape))] for state in hindsight_states: for j in range(len(state)): state_arrays[j].append(state[j]) else: state_arrays = [hindsight_states] state_arrays = [np.stack(s) for s in state_arrays] inputs = state_arrays + [ np.expand_dims(s, axis=0) for s in initial_rnn_states ] outputs = self._compute_model(inputs) values = outputs[self._value_index].numpy() values = np.append(values.flatten(), 0.0) self._process_rollout(hindsight_states, actions[:len(rewards)], np.array(rewards, dtype=np.float32), np.array(values, dtype=np.float32), initial_rnn_states) def _create_model_inputs(self, state, rnn_states): """Create the inputs to the model for use during a rollout.""" if not self._state_is_list: state = [state] state = state + rnn_states return [np.expand_dims(s, axis=0) for s in state]
{ "repo_name": "deepchem/deepchem", "path": "deepchem/rl/a2c.py", "copies": "3", "size": "21033", "license": "mit", "hash": -4810348788625973000, "line_mean": 39.920233463, "line_max": 105, "alpha_frac": 0.6708505682, "autogenerated": false, "ratio": 3.9699886749716873, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6140839243171687, "avg_score": null, "num_lines": null }
"""Advantage Actor-Critic (A2C) algorithm for reinforcement learning.""" from deepchem.models import KerasModel from deepchem.models.optimizers import Adam import numpy as np import tensorflow as tf import collections import copy import multiprocessing import os import re import threading import time class A2CLossDiscrete(object): """This class computes the loss function for A2C with discrete action spaces.""" def __init__(self, value_weight, entropy_weight, action_prob_index, value_index): self.value_weight = value_weight self.entropy_weight = entropy_weight self.action_prob_index = action_prob_index self.value_index = value_index def __call__(self, outputs, labels, weights): prob = outputs[self.action_prob_index] value = outputs[self.value_index] reward, advantage = weights action = labels[0] advantage = tf.expand_dims(advantage, axis=1) prob = prob + np.finfo(np.float32).eps log_prob = tf.math.log(prob) policy_loss = -tf.reduce_mean( advantage * tf.reduce_sum(action * log_prob, axis=1)) value_loss = tf.reduce_mean(tf.square(reward - value)) entropy = -tf.reduce_mean(tf.reduce_sum(prob * log_prob, axis=1)) return policy_loss + self.value_weight * value_loss - self.entropy_weight * entropy class A2CLossContinuous(object): """This class computes the loss function for A2C with continuous action spaces. Note ---- This class requires tensorflow-probability to be installed. """ def __init__(self, value_weight, entropy_weight, mean_index, std_index, value_index): try: import tensorflow_probability as tfp except ModuleNotFoundError: raise ValueError( "This class requires tensorflow-probability to be installed.") self.value_weight = value_weight self.entropy_weight = entropy_weight self.mean_index = mean_index self.std_index = std_index self.value_index = value_index def __call__(self, outputs, labels, weights): import tensorflow_probability as tfp mean = outputs[self.mean_index] std = outputs[self.std_index] value = outputs[self.value_index] reward, advantage = weights action = labels[0] distrib = tfp.distributions.Normal(mean, std) reduce_axes = list(range(1, len(action.shape))) log_prob = tf.reduce_sum(distrib.log_prob(action), reduce_axes) policy_loss = -tf.reduce_mean(advantage * log_prob) value_loss = tf.reduce_mean(tf.square(reward - value)) entropy = tf.reduce_mean(distrib.entropy()) return policy_loss + self.value_weight * value_loss - self.entropy_weight * entropy class A2C(object): """ Implements the Advantage Actor-Critic (A2C) algorithm for reinforcement learning. The algorithm is described in Mnih et al, "Asynchronous Methods for Deep Reinforcement Learning" (https://arxiv.org/abs/1602.01783). This class supports environments with both discrete and continuous action spaces. For discrete action spaces, the "action" argument passed to the environment is an integer giving the index of the action to perform. The policy must output a vector called "action_prob" giving the probability of taking each action. For continuous action spaces, the action is an array where each element is chosen independently from a normal distribution. The policy must output two arrays of the same shape: "action_mean" gives the mean value for each element, and "action_std" gives the standard deviation for each element. In either case, the policy must also output a scalar called "value" which is an estimate of the value function for the current state. The algorithm optimizes all outputs at once using a loss that is the sum of three terms: 1. The policy loss, which seeks to maximize the discounted reward for each action. 2. The value loss, which tries to make the value estimate match the actual discounted reward that was attained at each step. 3. An entropy term to encourage exploration. This class supports Generalized Advantage Estimation as described in Schulman et al., "High-Dimensional Continuous Control Using Generalized Advantage Estimation" (https://arxiv.org/abs/1506.02438). This is a method of trading off bias and variance in the advantage estimate, which can sometimes improve the rate of convergance. Use the advantage_lambda parameter to adjust the tradeoff. This class supports Hindsight Experience Replay as described in Andrychowicz et al., "Hindsight Experience Replay" (https://arxiv.org/abs/1707.01495). This is a method that can enormously accelerate learning when rewards are very rare. It requires that the environment state contains information about the goal the agent is trying to achieve. Each time it generates a rollout, it processes that rollout twice: once using the actual goal the agent was pursuing while generating it, and again using the final state of that rollout as the goal. This guarantees that half of all rollouts processed will be ones that achieved their goals, and hence received a reward. To use this feature, specify use_hindsight=True to the constructor. The environment must have a method defined as follows: def apply_hindsight(self, states, actions, goal): ... return new_states, rewards The method receives the list of states generated during the rollout, the action taken for each one, and a new goal state. It should generate a new list of states that are identical to the input ones, except specifying the new goal. It should return that list of states, and the rewards that would have been received for taking the specified actions from those states. The output arrays may be shorter than the input ones, if the modified rollout would have terminated sooner. Note ---- Using this class on continuous action spaces requires that `tensorflow_probability` be installed. """ def __init__(self, env, policy, max_rollout_length=20, discount_factor=0.99, advantage_lambda=0.98, value_weight=1.0, entropy_weight=0.01, optimizer=None, model_dir=None, use_hindsight=False): """Create an object for optimizing a policy. Parameters ---------- env: Environment the Environment to interact with policy: Policy the Policy to optimize. It must have outputs with the names 'action_prob' and 'value' (for discrete action spaces) or 'action_mean', 'action_std', and 'value' (for continuous action spaces) max_rollout_length: int the maximum length of rollouts to generate discount_factor: float the discount factor to use when computing rewards advantage_lambda: float the parameter for trading bias vs. variance in Generalized Advantage Estimation value_weight: float a scale factor for the value loss term in the loss function entropy_weight: float a scale factor for the entropy term in the loss function optimizer: Optimizer the optimizer to use. If None, a default optimizer is used. model_dir: str the directory in which the model will be saved. If None, a temporary directory will be created. use_hindsight: bool if True, use Hindsight Experience Replay """ self._env = env self._policy = policy self.max_rollout_length = max_rollout_length self.discount_factor = discount_factor self.advantage_lambda = advantage_lambda self.value_weight = value_weight self.entropy_weight = entropy_weight self.use_hindsight = use_hindsight self._state_is_list = isinstance(env.state_shape[0], collections.Sequence) if optimizer is None: self._optimizer = Adam(learning_rate=0.001, beta1=0.9, beta2=0.999) else: self._optimizer = optimizer output_names = policy.output_names self.continuous = ('action_mean' in output_names) self._value_index = output_names.index('value') if self.continuous: self._action_mean_index = output_names.index('action_mean') self._action_std_index = output_names.index('action_std') else: self._action_prob_index = output_names.index('action_prob') self._rnn_final_state_indices = [ i for i, n in enumerate(output_names) if n == 'rnn_state' ] self._rnn_states = policy.rnn_initial_states self._model = self._build_model(model_dir) self._checkpoint = tf.train.Checkpoint() self._checkpoint.save_counter # Ensure the variable has been created self._checkpoint.listed = self._model.model.trainable_variables def _build_model(self, model_dir): """Construct a KerasModel containing the policy and loss calculations.""" policy_model = self._policy.create_model() if self.continuous: loss = A2CLossContinuous(self.value_weight, self.entropy_weight, self._action_mean_index, self._action_std_index, self._value_index) else: loss = A2CLossDiscrete(self.value_weight, self.entropy_weight, self._action_prob_index, self._value_index) model = KerasModel( policy_model, loss, batch_size=self.max_rollout_length, model_dir=model_dir, optimize=self._optimizer) model._ensure_built() return model def fit(self, total_steps, max_checkpoints_to_keep=5, checkpoint_interval=600, restore=False): """Train the policy. Parameters ---------- total_steps: int the total number of time steps to perform on the environment, across all rollouts on all threads max_checkpoints_to_keep: int the maximum number of checkpoint files to keep. When this number is reached, older files are deleted. checkpoint_interval: float the time interval at which to save checkpoints, measured in seconds restore: bool if True, restore the model from the most recent checkpoint and continue training from there. If False, retrain the model from scratch. """ if restore: self.restore() manager = tf.train.CheckpointManager( self._checkpoint, self._model.model_dir, max_checkpoints_to_keep) checkpoint_time = time.time() self._env.reset() rnn_states = self._policy.rnn_initial_states # Training loop. step_count = 0 while step_count < total_steps: initial_rnn_states = rnn_states states, actions, rewards, values, rnn_states = self._create_rollout( rnn_states) self._process_rollout(states, actions, rewards, values, initial_rnn_states) if self.use_hindsight: self._process_rollout_with_hindsight(states, actions, initial_rnn_states) step_count += len(actions) self._model._global_step.assign_add(len(actions)) # Do checkpointing. if step_count >= total_steps or time.time( ) >= checkpoint_time + checkpoint_interval: manager.save() checkpoint_time = time.time() def predict(self, state, use_saved_states=True, save_states=True): """Compute the policy's output predictions for a state. If the policy involves recurrent layers, this method can preserve their internal states between calls. Use the use_saved_states and save_states arguments to specify how it should behave. Parameters ---------- state: array or list of arrays the state of the environment for which to generate predictions use_saved_states: bool if True, the states most recently saved by a previous call to predict() or select_action() will be used as the initial states. If False, the internal states of all recurrent layers will be set to the initial values defined by the policy before computing the predictions. save_states: bool if True, the internal states of all recurrent layers at the end of the calculation will be saved, and any previously saved states will be discarded. If False, the states at the end of the calculation will be discarded, and any previously saved states will be kept. Returns ------- the array of action probabilities, and the estimated value function """ results = self._predict_outputs(state, use_saved_states, save_states) if self.continuous: return [ results[i] for i in (self._action_mean_index, self._action_std_index, self._value_index) ] else: return [results[i] for i in (self._action_prob_index, self._value_index)] def select_action(self, state, deterministic=False, use_saved_states=True, save_states=True): """Select an action to perform based on the environment's state. If the policy involves recurrent layers, this method can preserve their internal states between calls. Use the use_saved_states and save_states arguments to specify how it should behave. Parameters ---------- state: array or list of arrays the state of the environment for which to select an action deterministic: bool if True, always return the best action (that is, the one with highest probability). If False, randomly select an action based on the computed probabilities. use_saved_states: bool if True, the states most recently saved by a previous call to predict() or select_action() will be used as the initial states. If False, the internal states of all recurrent layers will be set to the initial values defined by the policy before computing the predictions. save_states: bool if True, the internal states of all recurrent layers at the end of the calculation will be saved, and any previously saved states will be discarded. If False, the states at the end of the calculation will be discarded, and any previously saved states will be kept. Returns ------- the index of the selected action """ outputs = self._predict_outputs(state, use_saved_states, save_states) return self._select_action_from_outputs(outputs, deterministic) def restore(self): """Reload the model parameters from the most recent checkpoint file.""" last_checkpoint = tf.train.latest_checkpoint(self._model.model_dir) if last_checkpoint is None: raise ValueError('No checkpoint found') self._checkpoint.restore(last_checkpoint) def _predict_outputs(self, state, use_saved_states, save_states): """Compute a set of outputs for a state. """ if not self._state_is_list: state = [state] if use_saved_states: state = state + list(self._rnn_states) else: state = state + list(self._policy.rnn_initial_states) inputs = [np.expand_dims(s, axis=0) for s in state] results = self._compute_model(inputs) results = [r.numpy() for r in results] if save_states: self._rnn_states = [ np.squeeze(results[i], 0) for i in self._rnn_final_state_indices ] return results @tf.function(experimental_relax_shapes=True) def _compute_model(self, inputs): return self._model.model(inputs) def _select_action_from_outputs(self, outputs, deterministic): """Given the policy outputs, select an action to perform.""" if self.continuous: action_mean = outputs[self._action_mean_index] action_std = outputs[self._action_std_index] if deterministic: return action_mean[0] else: return np.random.normal(action_mean[0], action_std[0]) else: action_prob = outputs[self._action_prob_index] if deterministic: return action_prob.argmax() else: action_prob = action_prob.flatten() return np.random.choice(np.arange(len(action_prob)), p=action_prob) def _create_rollout(self, rnn_states): """Generate a rollout.""" n_actions = self._env.n_actions states = [] actions = [] rewards = [] values = [] # Generate the rollout. for i in range(self.max_rollout_length): if self._env.terminated: break state = self._env.state states.append(state) results = self._compute_model( self._create_model_inputs(state, rnn_states)) results = [r.numpy() for r in results] value = results[self._value_index] rnn_states = [ np.squeeze(results[i], 0) for i in self._rnn_final_state_indices ] action = self._select_action_from_outputs(results, False) actions.append(action) values.append(float(value)) rewards.append(self._env.step(action)) # Compute an estimate of the reward for the rest of the episode. if not self._env.terminated: results = self._compute_model( self._create_model_inputs(self._env.state, rnn_states)) final_value = self.discount_factor * results[self._value_index].numpy()[0] else: final_value = 0.0 values.append(final_value) if self._env.terminated: self._env.reset() rnn_states = self._policy.rnn_initial_states return states, actions, np.array( rewards, dtype=np.float32), np.array( values, dtype=np.float32), rnn_states def _process_rollout(self, states, actions, rewards, values, initial_rnn_states): """Train the network based on a rollout.""" # Compute the discounted rewards and advantages. discounted_rewards = rewards.copy() discounted_rewards[-1] += values[-1] advantages = rewards - values[:-1] + self.discount_factor * np.array( values[1:]) for j in range(len(rewards) - 1, 0, -1): discounted_rewards[j - 1] += self.discount_factor * discounted_rewards[j] advantages[ j - 1] += self.discount_factor * self.advantage_lambda * advantages[j] # Record the actions, converting to one-hot if necessary. actions_matrix = [] if self.continuous: for action in actions: actions_matrix.append(action) else: n_actions = self._env.n_actions for action in actions: a = np.zeros(n_actions, np.float32) a[action] = 1.0 actions_matrix.append(a) actions_matrix = np.array(actions_matrix, dtype=np.float32) # Rearrange the states into the proper set of arrays. if self._state_is_list: state_arrays = [[] for i in range(len(self._env.state_shape))] for state in states: for j in range(len(state)): state_arrays[j].append(state[j]) else: state_arrays = [states] state_arrays = [np.stack(s) for s in state_arrays] # Build the inputs and apply gradients. inputs = state_arrays + [ np.expand_dims(s, axis=0) for s in initial_rnn_states ] self._apply_gradients(inputs, actions_matrix, discounted_rewards, advantages) @tf.function(experimental_relax_shapes=True) def _apply_gradients(self, inputs, actions_matrix, discounted_rewards, advantages): """Compute the gradient of the loss function for a rollout and update the model.""" vars = self._model.model.trainable_variables with tf.GradientTape() as tape: outputs = self._model.model(inputs) loss = self._model._loss_fn(outputs, [actions_matrix], [discounted_rewards, advantages]) gradients = tape.gradient(loss, vars) self._model._tf_optimizer.apply_gradients(zip(gradients, vars)) def _process_rollout_with_hindsight(self, states, actions, initial_rnn_states): """Create a new rollout by applying hindsight to an existing one, then train the network.""" hindsight_states, rewards = self._env.apply_hindsight( states, actions, states[-1]) if self._state_is_list: state_arrays = [[] for i in range(len(self._env.state_shape))] for state in hindsight_states: for j in range(len(state)): state_arrays[j].append(state[j]) else: state_arrays = [hindsight_states] state_arrays = [np.stack(s) for s in state_arrays] inputs = state_arrays + [ np.expand_dims(s, axis=0) for s in initial_rnn_states ] outputs = self._compute_model(inputs) values = outputs[self._value_index].numpy() values = np.append(values.flatten(), 0.0) self._process_rollout(hindsight_states, actions[:len(rewards)], np.array(rewards, dtype=np.float32), np.array(values, dtype=np.float32), initial_rnn_states) def _create_model_inputs(self, state, rnn_states): """Create the inputs to the model for use during a rollout.""" if not self._state_is_list: state = [state] state = state + rnn_states return [np.expand_dims(s, axis=0) for s in state]
{ "repo_name": "miaecle/deepchem", "path": "deepchem/rl/a2c.py", "copies": "1", "size": "21017", "license": "mit", "hash": -1867734408119984400, "line_mean": 39.6518375242, "line_max": 105, "alpha_frac": 0.670647571, "autogenerated": false, "ratio": 3.9662200415172673, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006255182103831794, "num_lines": 517 }
"""Advantage Air climate integration.""" from datetime import timedelta import logging from advantage_air import ApiError, advantage_air from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import ADVANTAGE_AIR_RETRY, DOMAIN ADVANTAGE_AIR_SYNC_INTERVAL = 15 ADVANTAGE_AIR_PLATFORMS = ["climate", "cover", "binary_sensor", "sensor"] _LOGGER = logging.getLogger(__name__) async def async_setup(hass, config): """Set up AdvantageAir.""" hass.data[DOMAIN] = {} return True async def async_setup_entry(hass, config_entry): """Set up AdvantageAir Config.""" ip_address = config_entry.data[CONF_IP_ADDRESS] port = config_entry.data[CONF_PORT] api = advantage_air( ip_address, port=port, session=async_get_clientsession(hass), retry=ADVANTAGE_AIR_RETRY, ) async def async_get(): try: return await api.async_get() except ApiError as err: raise UpdateFailed(err) from err coordinator = DataUpdateCoordinator( hass, _LOGGER, name="Advantage Air", update_method=async_get, update_interval=timedelta(seconds=ADVANTAGE_AIR_SYNC_INTERVAL), ) async def async_change(change): try: if await api.async_change(change): await coordinator.async_refresh() except ApiError as err: _LOGGER.warning(err) await coordinator.async_refresh() if not coordinator.data: raise ConfigEntryNotReady hass.data[DOMAIN][config_entry.entry_id] = { "coordinator": coordinator, "async_change": async_change, } for platform in ADVANTAGE_AIR_PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) return True class AdvantageAirEntity(CoordinatorEntity): """Parent class for Advantage Air Entities.""" def __init__(self, instance, ac_key, zone_key=None): """Initialize common aspects of an Advantage Air sensor.""" super().__init__(instance["coordinator"]) self.async_change = instance["async_change"] self.ac_key = ac_key self.zone_key = zone_key @property def _ac(self): return self.coordinator.data["aircons"][self.ac_key]["info"] @property def _zone(self): if not self.zone_key: return None return self.coordinator.data["aircons"][self.ac_key]["zones"][self.zone_key] @property def device_info(self): """Return parent device information.""" return { "identifiers": {(DOMAIN, self.coordinator.data["system"]["rid"])}, "name": self.coordinator.data["system"]["name"], "manufacturer": "Advantage Air", "model": self.coordinator.data["system"]["sysType"], "sw_version": self.coordinator.data["system"]["myAppRev"], }
{ "repo_name": "GenericStudent/home-assistant", "path": "homeassistant/components/advantage_air/__init__.py", "copies": "1", "size": "3205", "license": "apache-2.0", "hash": 6346648736788701000, "line_mean": 28.1363636364, "line_max": 84, "alpha_frac": 0.6408736349, "autogenerated": false, "ratio": 3.8990267639902676, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5039900398890268, "avg_score": null, "num_lines": null }
"""Advantage Air climate integration.""" import asyncio from datetime import timedelta import logging from advantage_air import ApiError, advantage_air from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ADVANTAGE_AIR_RETRY, DOMAIN ADVANTAGE_AIR_SYNC_INTERVAL = 15 PLATFORMS = ["climate", "cover", "binary_sensor", "sensor", "switch"] _LOGGER = logging.getLogger(__name__) async def async_setup(hass, config): """Set up Advantage Air integration.""" hass.data[DOMAIN] = {} return True async def async_setup_entry(hass, entry): """Set up Advantage Air config.""" ip_address = entry.data[CONF_IP_ADDRESS] port = entry.data[CONF_PORT] api = advantage_air( ip_address, port=port, session=async_get_clientsession(hass), retry=ADVANTAGE_AIR_RETRY, ) async def async_get(): try: return await api.async_get() except ApiError as err: raise UpdateFailed(err) from err coordinator = DataUpdateCoordinator( hass, _LOGGER, name="Advantage Air", update_method=async_get, update_interval=timedelta(seconds=ADVANTAGE_AIR_SYNC_INTERVAL), ) async def async_change(change): try: if await api.async_change(change): await coordinator.async_refresh() except ApiError as err: _LOGGER.warning(err) await coordinator.async_refresh() if not coordinator.data: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = { "coordinator": coordinator, "async_change": async_change, } for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) return True async def async_unload_entry(hass, entry): """Unload Advantage Air Config.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
{ "repo_name": "partofthething/home-assistant", "path": "homeassistant/components/advantage_air/__init__.py", "copies": "1", "size": "2429", "license": "mit", "hash": 2565255219440372700, "line_mean": 25.402173913, "line_max": 88, "alpha_frac": 0.6480032935, "autogenerated": false, "ratio": 3.9240710823909533, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00012212994626282364, "num_lines": 92 }
# advection_inverse.py from __future__ import print_function, division import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from advection_solver import forward as forward from advection_solver import forwardGradient as forwardGradient def gradient(x, u_final_data, f, psi, T, R, M): """ Gradient of the objective function $$ F = 0.5 * || u_final - u_final_data ||_2^2 $$ Args: x: physical space grid f: source in advection equation u_final_data: observation of the field at time $T$ psi: advection coefficient T: final time M: Nb of time intervals R: Source support is contained in $[- R / 2, R / 2]$ Returns: F_f: gradient with respect to the source term F_psi: derivative with respect to advection coefficient """ # grid related definitions dt = T / M N = len(x) dx = np.zeros(N) dx[0] = x[0] - (- R / 2.0) dx[1 : N] = x[1 : N] - x[0 : N - 1] # we will accumulate the gradient over time F_f = np.zeros(len(x)) F_psi = 0.0 u_final = forward(x, np.zeros(len(x)), psi, f, T, R) for i in range(1, M + 1): t = i * dt # solve adjoint problem in w w = forward(x, u_final - u_final_data, -psi, np.zeros(len(x)), T - t, R) # solve forward problem for u_x u_x = forwardGradient(x, np.zeros(len(x)), psi, f, t, R) # accumulate gradient F_f = F_f + dt * w F_psi = F_psi + np.dot(u_x * w, dx) * dt return F_f, F_psi def gradientTest(): # problem parameters T = 0.0001 R = 1.0 N = 100 # Nb of grid points in physical space M = 10 # Nb of grid points in time space # synthetic data x = np.linspace(- R / 2.0 + R / N, R / 2.0, N) t_f = T f_optimal = ( (1.0 / t_f) * np.exp( - x * x / (4.0 * t_f)) / np.sqrt( 4.0 * np.pi * t_f)) psi_optimal = 2000 u_final_data = forward(x, np.zeros(len(x)), psi_optimal, f_optimal, T, R) # initial coefficients f = np.zeros(len(x)) psi = 0.0 F_f, F_psi = gradient(x, u_final_data, f, psi, T, R, M) return F_f, F_psi def recoverDemo(): # problem parameters T = 0.0001 R = 1.0 N = 1000 # Nb of grid points in physical space M = 10 # Nb of grid points in time space nb_grad_steps = 1000 # Nb of updates with the gradient alpha_f = 100000000.0 # gradient update size alpha_psi = 1000.0 sigma = 0.02 # plots pp = PdfPages('./images/recover_demo.pdf') # synthetic data x = np.linspace(- R / 2.0 + R / N, R / 2.0, N) t_f = T f_optimal = ( (1.0 / t_f) * np.exp( - (x - 0.1) * (x - 0.1) / (4.0 * t_f)) / np.sqrt( 4.0 * np.pi * t_f)) f_optimal = f_optimal + ( (1.0 / t_f) * np.exp( - (x + 0.1) * (x + 0.1) / (4.0 * t_f)) / np.sqrt( 4.0 * np.pi * t_f)) f_optimal = f_optimal / 2.0 psi_optimal = 900 u_final_data = forward(x, np.zeros(len(x)), psi_optimal, f_optimal, T, R) # add noise to the data u_final_data = u_final_data + np.random.normal(0, sigma, len(u_final_data)) # initial coefficients #f = f_optimal #f = np.zeros(len(x)) f = ( (1.0 / t_f) * np.exp( - (x) * (x) / (4.0 * t_f)) / np.sqrt( 4.0 * np.pi * t_f)) psi = 900.0 # plot f plt.figure() plt.plot(x, f, 'r', label="initial source") plt.plot(x, f_optimal, 'b', label="true source") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$f$') pp.savefig() for i in range(0, nb_grad_steps): F_f, F_psi = gradient(x, u_final_data, f, psi, T, R, M) f = f - alpha_f * F_f psi = psi - alpha_psi * F_psi print("psi_recovered : ", psi) print("psi_optimal : ", psi_optimal) print("F_psi : ", F_psi) print("psi_recovered : ", psi) print("psi_optimal : ", psi_optimal) print("F_psi : ", F_psi) u_final_recovered = forward(x, np.zeros(len(x)), psi, f, T, R) # plot u_final_data plt.figure() plt.plot(x, u_final_data, 'b', label="data") plt.plot(x, u_final_recovered, 'r--', label="recovered") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$u_{T}$') pp.savefig() # plot f plt.figure() plt.plot(x, f, 'r', label="source recovered") plt.plot(x, f_optimal, 'b', label="true source") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$f$') pp.savefig() #plot F_f plt.figure() plt.plot(x, F_f, label="source sensitivity") plt.xlabel('$x$') plt.ylabel('$F_f$') pp.savefig() # show and close pdf file pp.close() plt.show() # if module runs as a script, run Test if __name__ == "__main__": recoverDemo()
{ "repo_name": "vidalalcala/source-recovery", "path": "advection_inverse.py", "copies": "1", "size": "5176", "license": "mit", "hash": 9218859400362556000, "line_mean": 27.4395604396, "line_max": 80, "alpha_frac": 0.5349690881, "autogenerated": false, "ratio": 2.847084708470847, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38820537965708474, "avg_score": null, "num_lines": null }
"""Advection-related quantities.""" from aospy.utils.vertcoord import to_radians from indiff import Upwind from .. import LAT_STR, LON_STR, PFULL_STR from .numerics import (latlon_deriv_prefactor, wraparound, d_dx_from_latlon, d_dy_from_lat, d_dp_from_p, d_dx_at_const_p_from_eta, d_dy_at_const_p_from_eta, d_dp_from_eta, horiz_gradient_spharm, horiz_gradient_from_eta_spharm) def zonal_advec(arr, u, radius): """Zonal advection of the given field.""" return u*d_dx_from_latlon(arr, radius) def merid_advec(arr, v, radius): """Meridional advection of the given field.""" return v*d_dy_from_lat(arr, radius) def horiz_advec(arr, u, v, radius): """Horizontal advection of the given field.""" return zonal_advec(arr, u, radius) + merid_advec(arr, v, radius) def vert_advec(arr, omega, p): """Vertical advection of the given field.""" return omega*d_dp_from_p(arr, p) def total_advec(arr, u, v, omega, p, radius): """Total advection of the given field.""" return horiz_advec(arr, u, v, radius) + vert_advec(arr, omega, p) def zonal_advec_upwind(arr, u, radius, order=2): """Advection in the zonal direction using upwind differencing.""" prefactor = latlon_deriv_prefactor(to_radians(arr.coords[LAT_STR]), radius, d_dy_of_scalar_field=False) arr_ext = wraparound(arr, LON_STR, left=order, right=order, circumf=360.) lon_rad_ext = to_radians(arr_ext[LON_STR]) return prefactor*Upwind(u, arr_ext, LON_STR, coord=lon_rad_ext, order=order, fill_edge=False).advec() def merid_advec_upwind(arr, v, radius, order=2): """Advection in the meridional direction using upwind differencing.""" lat_rad = to_radians(arr.coords[LAT_STR]) prefactor = 1. / radius return prefactor*Upwind(v, arr, LAT_STR, coord=lat_rad, order=order, fill_edge=True).advec() def horiz_advec_upwind(arr, u, v, radius, order=2): """Horizontal (meridional plus zonal) upwind advection.""" return (zonal_advec_upwind(arr, u, radius, order=order) + merid_advec_upwind(arr, v, radius, order=order)) def total_advec_upwind(arr, u, v, omega, p, radius, p_str=PFULL_STR, order=1): """Total (horizontal plus vertical) upwind advection.""" return (horiz_advec_upwind(arr, u, v, radius, order=order) + Upwind(omega, p_str, arr, coord=p, order=order, fill_edge=True).advec()) def zonal_advec_const_p_from_eta(arr, u, ps, radius, bk, pk): """Zonal advection at constant pressure of the given scalar field.""" return u*d_dx_at_const_p_from_eta(arr, ps, radius, bk, pk) def merid_advec_const_p_from_eta(arr, v, ps, radius, bk, pk): """Meridional advection at constant pressure of the given scalar field.""" return v*d_dy_at_const_p_from_eta(arr, ps, radius, bk, pk) def horiz_advec_const_p_from_eta(arr, u, v, ps, radius, bk, pk): """Horizontal advection at constant pressure of the given scalar field.""" return (zonal_advec_const_p_from_eta(arr, u, ps, radius, bk, pk) + merid_advec_const_p_from_eta(arr, v, ps, radius, bk, pk)) def vert_advec_from_eta(arr, omega, ps, bk, pk): """Vertical advection of the given field.""" return omega*d_dp_from_eta(arr, ps, bk, pk) def total_advec_from_eta(arr, u, v, omega, p, ps, radius, bk, pk): """Total advection of the given scalar field.""" return (horiz_advec_const_p_from_eta(arr, u, v, ps, radius, bk, pk) + vert_advec(arr, omega, p)) def horiz_advec_spharm(arr, u, v, radius): """Horizontal advection using spherical harmonics.""" d_dx, d_dy = horiz_gradient_spharm(arr, radius) return u * d_dx + v * d_dy def zonal_advec_spharm(arr, u, radius): """Zonal advection using spherical harmonics.""" d_dx, _ = horiz_gradient_spharm(arr, radius) return u * d_dx def merid_advec_spharm(arr, v, radius): """Meridional advection using spherical harmonics.""" _, d_dy = horiz_gradient_spharm(arr, radius) return v * d_dy def horiz_advec_from_eta_spharm(arr, u, v, ps, radius, bk, pk): """Horizontal advection using spherical harmonics from model coords.""" d_dx, d_dy = horiz_gradient_from_eta_spharm(arr, ps, radius, bk, pk) return u * d_dx + v * d_dy def zonal_advec_from_eta_spharm(arr, u, ps, radius, bk, pk): """Zonal advection using spherical harmonics from model coords.""" d_dx, _ = horiz_gradient_from_eta_spharm(arr, ps, radius, bk, pk) return u * d_dx def merid_advec_from_eta_spharm(arr, v, ps, radius, bk, pk): """Meridional advection using spherical harmonics from model coords.""" _, d_dy = horiz_gradient_from_eta_spharm(arr, ps, radius, bk, pk) return v * d_dy
{ "repo_name": "spencerahill/aospy-obj-lib", "path": "aospy_user/calcs/advection.py", "copies": "1", "size": "4882", "license": "apache-2.0", "hash": -2969156350791672000, "line_mean": 36.5538461538, "line_max": 78, "alpha_frac": 0.6374436706, "autogenerated": false, "ratio": 2.865023474178404, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40024671447784044, "avg_score": null, "num_lines": null }
# advection/shiiba.py # to calculate the advection coefficiations after Shi-iba et al # Takasao T. and Shiiba M. 1984: Development of techniques for on-line forecasting of rainfall and flood runoff (Natural Disaster Science 6, 83) # with upwind scheme etc # # use: 1) python shiiba.py # or 2) import advection.shiiba # # plan for 3-1-2012: # # A. write the functions # 0. basic I/O (input/output/display; use/enhance basics.py) # 1. central difference scheme # 2. upwind scheme # B. write some test codes # 1. get the dbz images # 2. do the regression # 3. see/plot the output vector field # C. (if there's time) do the advection - use another module # overall plan for the future: # multilevel shiiba regression, or local regression with pre-defined segmentation # (e.g. from k-means, or another shiiba regression, or thresholding, etc) # imports import numpy as np import numpy.ma as ma from .. import pattern import copy ################################################################ # the functions def centralDifference(phi0, phi1): """ adapted from shiiba.py, internalising the parameters into the objects dt, dx, dy comes from the latter dbz image phi1 25 January 2013, Yau Kwan Kiu. ---- to compute the advection coefficients via the central difference scheme as a step to the shiiba method use numpy.linalg.lstsq for linear regression: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html We shall use the C/python convention for coordinate axes, but with the first axis going up, following the convention of the Central Weather Bureau and matplotlib (meshgrid) usage first axis ^ | | + ----> second axis input: phi0,phi1 - two armor.pattern.DBZ objects (wrapping a masked array) output: v - an armor.pattern.VectorField object (wrapping a pair of masked arrays) """ # setting up the parameters dt = phi1.dt # use the attribute of the latter DBZ image dj = phi1.dx di = phi1.dy #################################################### # defining the shifted masked arrays # [ref: http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html # http://docs.scipy.org/doc/numpy/reference/routines.ma.html ] ######## initialise # phi0_up.matrix = np.roll(phi0.matrix,+1,axis=0) # phi0_down.matrix = np.roll(phi0.matrix,-1,axis=0) # phi0_left.matrix = np.roll(phi0.matrix,-1,axis=1) # phi0_right.matrix = np.roll(phi0.matrix,+1,axis=1) ######## to set the masks # phi0_up.mask[ 0,:] = 1 #mask the first (=bottom) row # phi0_down.mask[-1,:]= 1 #mask the last (=top) row # phi0_left.mask[:,-1]= 1 #mask the last (=right) column # phi0_right.mask[:,0]= 1 #mask the first (=left) column phi0_up = phi0.shiftMatrix( 1, 0) # a new armor.pattern.DBZ object defined via DBZ's own methods phi0_down = phi0.shiftMatrix(-1, 0) phi0_left = phi0.shiftMatrix( 0,-1) phi0_right = phi0.shiftMatrix( 0, 1) ############################################## # applying the advection equation # see ARMOR annual report (1/3), section 4.2.1, esp. eqn (4.3) Y = (phi1.matrix-phi0.matrix) # regression: Y = X.c, where c = (c1,...,c6) # (up to signs or permutations) are the unknowns # setting up the proper mask for regression Y.mask = Y.mask + phi0_up.matrix.mask + phi0_down.matrix.mask +\ phi0_left.matrix.mask + phi0_right.matrix.mask # setting up the proper mask # for regression if phi1.verbose or phi0.verbose: print 'sum(sum(Y.mask))=', sum(sum(Y.mask)) X = np.zeros((phi0.matrix.shape[0], phi0.matrix.shape[1], 6)) # a 2x3 matrix for each pixel # -> 6 vector for (c1,c2,c3,c4,c5,c6) # where u=c1x+c2y+c3, v=c4x+c5y+c6, j=x, i=y, # therefore up to +- signs or permutations, # X=(A1c1, A1c2, A1c3, A2c1, A2c2, A2c3) # Central difference scheme: phi(i+1)-phi(i-1) / 2di, etc if phi1.verbose or phi0.verbose: print "phi0,1.matrix.shape", phi0.matrix.shape, phi1.matrix.shape #debug A = ma.array([-dt*(phi0_down.matrix - phi0_up.matrix) /(2*di),\ -dt*(phi0_left.matrix - phi0_right.matrix)/(2*dj)]) A = np.transpose(A, (1,2,0)) #swap the axes: pixel dim1, pixel dim2, internal A.fill_value = -999 Bj, Bi = np.meshgrid( range(phi0.matrix.shape[1]), range(phi0.matrix.shape[0]) ) #location stuff, from the bottom left corner ############################# # IS THE ABOVE CORRECT??? # # or should that be something like # meshgrid(phi0.matrix.shape[1], phi0.matrix.shape[0] # and we have transpose (1,2,0) below? ############################# B = ma.array([Bi,Bj]).transpose((1,2,0)) # (881x921x2), (i,j, (i,j) ) #[a,b] * [[x,y],[z,w]] * [c,d].T = [acx+ady+bcz+bdw]; want: [ac, ad, bc, bd] # debug #if phi0.verbose or phi1.verbose: # print '== shapes for X, A and B: ==' # print X.shape, A.shape, B.shape X[:,:,0] = A[:,:,0]*B[:,:,0] # coeffs for c1,..,c6 up to a permutation i,j=y,x # which we don't care for now X[:,:,1] = A[:,:,0]*B[:,:,1] X[:,:,2] = A[:,:,0] # the constant term X[:,:,3] = A[:,:,1]*B[:,:,0] X[:,:,4] = A[:,:,1]*B[:,:,1] X[:,:,5] = A[:,:,1] if phi0.verbose or phi1.verbose: # debug print "== stats for X, A and B ==" print "X.max, X.sum() = " print X.max(), X.sum() print "A.max, A.sum() = " print A.max(), A.sum() print "B.max, B.sum() = " print B.max(), B.sum() print Y.shape Y = Y.reshape(phi0.matrix.size,1) # convert the pixel data into a column vector X = X.reshape(phi0.matrix.size,6) # HACK FOR numpy problem: dealing with numpy.linalg.lstsq which sees not the mask for masked arrays Y1 = ma.array(Y.view(np.ndarray)*(Y.mask==False)) X1 = ma.array(X.view(np.ndarray)*(Y.mask==False)) #yes, that's right. X* (Y.mask==0)d Y1.mask = Y.mask C, residues, rank, s = np.linalg.lstsq(X1,Y1) c1,c2,c3,c4,c5,c6 = C SStotal = ((Y1-Y1.mean())**2).sum() # total sum of squares # http://en.wikipedia.org/wiki/Coefficient_of_determination # array operations respect masks # !!!! debug !!!! # print "SStotal=", SStotal # print "sum of residues=",residues[0] # #print C.shape, X1.shape, Y1.shape #print [v[0] for v in C] #C = np.array([v[0] for v in C]) #residue2 = ((C * X1).sum(axis=1) - Y1)**2 # #print "((C * X1).sum(axis=1) - Y1)**2 = ", residue2 #print "difference:", residue-residue2 print "Number of points effective, total variance, sum of squared residues:" print (1-Y.mask).sum(), ((Y-Y.mean())**2).sum(), ((Y1-Y1.mean())**2).sum(), print (1-Y.mask).sum() * Y.var(), (1-Y1.mask).sum() * Y1.var(), residues print '\n+++++ size of window (unmasked points): ', (Y.mask==False).sum() R_squared = 1 - (residues[0]/SStotal) print "R_squared=", R_squared, '\n=======================================\n' return ([c1[0],c2[0],c3[0],c4[0],c5[0],c6[0]], R_squared) ################################################################################################### def upWind(phi0, phi1, convergenceMark = 0.000000001): """ adapted to object oriented form 27-1-2013 ----- to compute the advection coefficients via the central difference scheme as a step to the shiiba method u(k-1) and v(k-1) are given, possibly, from previous upWind steps or from the central differnece scheme builds upon the central difference scheme 11-1-2013 """ # algorithm: 1. start with the central difference scheme to obtain an initial (u0,v0) # 2. recursively regress for the next u(n+1), v(n+1) until convergence #to get the shifted arrays - copied from def centralDifference ########### dt = phi1.dt # use the attribute of the latter DBZ image dj = phi1.dx di = phi1.dy verbose = phi0.verbose or phi1.verbose if verbose: print '===========================================================================' print 'di, dj, dt, convergenceMark =', di, dj, dt, convergenceMark phi0_up = phi0.shiftMatrix( 1, 0) # a new armor.pattern.DBZ object defined via DBZ's own methods phi0_down = phi0.shiftMatrix(-1, 0) phi0_left = phi0.shiftMatrix( 0,-1) phi0_right = phi0.shiftMatrix( 0, 1) [c1_, c2_, c3_, c4_, c5_, c6_ ], R_squared_ = centralDifference(phi0=phi0, phi1=phi1) if phi0.verbose and phi1.verbose: # need to be very verbose to show pic! vect = getShiibaVectorField((c1_, c2_, c3_, c4_, c5_, c6_ ),phi1) vect.show() J,I = np.meshgrid(np.arange(0,phi0.matrix.shape[1]), np.arange(0,phi0.matrix.shape[0])) # see our ARMOR December 2012 annual report (1/3), section 4.2.1, esp. eqn (4.3) c1 = 9999; c2 = 9999 ; c3=-9999 ; c4=9999 ; c5=-9999 ; c6= -9999 #initialise # perhaps I should change the following convergence criterion # from absolute value to component-wise-scaled correlations while (c1_-c1)**2 + (c2_-c2)**2 + (c3_-c3)**2 + (c4_-c4)**2 + (c5_-c5)**2 + \ (c6_-c6)**2 > convergenceMark: c1_=c1; c2_= c2; c3_=c3; c4_=c4; c5_=c5; c6_=c6 #debug #print " print U0.shape, V0.shape, phi0.shape, \nprint di.shape, dj.shape " #print U0.shape, V0.shape, phi0.shape, #print di.shape, dj.shape U0 = c1_*I + c2_*J + c3_ # use old (c1,..c6) to compute old U,V V0 = c4_*I + c5_*J + c6_ # to be used as estimates for the new U,V upWindCorrectionTerm = abs(U0/(2*di)) * (2*phi0.matrix -phi0_down.matrix -phi0_up.matrix) +\ abs(V0/(2*dj)) * (2*phi0.matrix -phi0_left.matrix -phi0_right.matrix) upWindCorrectionTerm = pattern.DBZ(dataTime=phi1.dataTime, matrix=upWindCorrectionTerm) # the following line doesn't work: takes up too much computation resource #upWindCorrectionTerm = abs(U0/(2*di)) * (2*phi0 -phi0_down -phi0_up) +\ # abs(V0/(2*dj)) * (2*phi0 -phi0_left -phi0_right) #print 'sum(upWindCorrectionTerm.mask==0)=',sum( (upWindCorrectionTerm.mask==0)) #debug [c1, c2, c3, c4, c5, c6], R_squared = centralDifference(phi0=phi0 + dt *upWindCorrectionTerm,\ phi1=phi1) if verbose: print "\n##################################################################\n" print "c1, c2, c3, c4, c5, c6: ", c1, c2, c3, c4, c5, c6 print "\nR^2: ", R_squared print "\n##################################################################\n" return [c1, c2, c3, c4, c5, c6], R_squared def getShiibaVectorField(shiibaCoeffs, phi1, gridSize=25, name="",\ key="Shiiba vector field", title="UpWind Scheme"): """ plotting vector fields from shiiba coeffs input: shiiba coeffs (c1,c2,c3,..,c6) for Ui=c1.I + c2.J +c3, Vj=c4.I +c5.J+c6 and transform it via I=y, J=x, to Ux = c5.x+c4.y+c6, Vy = c2.x+c1.y+c3 """ # 1. setting the variables # 2. setting the stage # 3. plotting # 4. no need to save or print to screen # 1. setting the variables c1, c2, c3, c4, c5, c6 = shiibaCoeffs c5, c4, c6, c2, c1, c3 = c1, c2, c3, c4, c5, c6 # x,y <- j, i switch # 2. setting the stage height= phi1.matrix.shape[0] width = phi1.matrix.shape[1] mask = phi1.matrix.mask name = "shiiba vector field for "+ phi1.name imagePath = phi1.name+"shiibaVectorField.png" key = key ploTitle = title gridSize = gridSize X, Y = np.meshgrid(range(width), range(height)) Ux = c1*X + c2*Y + c3 Vy = c4*X + c5*Y + c6 Ux = ma.array(Ux, mask=mask) Vy = ma.array(Vy, mask=mask) #constructing the vector field object vect = pattern.VectorField(Ux, Vy, name=name, imagePath=imagePath, key=key, title=title, gridSize=gridSize) return vect def convert(shiibaCoeffs, phi1, gridSize=25, name="",\ key="Shiiba vector field", title="UpWind Scheme"): """alias """ return getShiibaVectorField(shiibaCoeffs, phi1, gridSize, name,\ key, title) def showShiibaVectorField(phi0,phi1): shiibaCoeffs, R_squared = upWind(phi0,phi1) vect = getShiibaVectorField(shiibaCoeffs, phi0) vect.show() return shiibaCoeffs, R_squared #def shiiba(phi0, phi1, convergenceMark = 0.00001): # ### a pointer for the moment # ### # return upWind(phi0, phi1, convergenceMark = 0.00001) def shiiba(phi0, phi1): """alias """ shiibaCoeffs, R_squared = showShiibaVectorField(phi0, phi1) return shiibaCoeffs, R_squared def shiibaNonCFL(phi0, phi1, mask=None, windowHeight=5, windowWidth=5,\ convergenceMark=0.000001,): """ to find the shiiba coeffs without the CFL condition plan: to shift and regress, minimising the average R^2 """ #parameters verbose = phi0.verbose or phi1.verbose #0. initialise a matrix for the r^2 #1. put the mask on phi0 #2. roll back phi1 by (m,n); per our convention, internal stuff we use (i,j), not (x,y); i=y, j=x R2s = {} #dict to record the R^2s ShiibaCoeffs = {} #dict to record the shiiba coeffs if mask!=None: phi0.matrix.mask = mask # put the mask on phi0 for m in range(-(windowHeight-1)/2, (windowHeight+1)/2): for n in range(-(windowWidth-1)/2, (windowWidth+1)/2): phi1_temp = phi1.shiftMatrix(m,n) [c1, c2, c3, c4, c5, c6], R2 = upWind(phi0=phi0, phi1=phi1_temp,\ convergenceMark=convergenceMark) R2s [(m,n)] = R2 ShiibaCoeffs[(m,n)] = [c1, c2, c3, c4, c5, c6] if phi0.verbose and phi1.verbose: print "\n-++++++++++++++++++++++++++++-\n(m,n), [c1,c2,c3,c4,c5,c6], R2 = \n",\ (m,n), [c1,c2,c3,c4,c5,c6], R2 #getting the (m,n) for max(R2) (m, n) = max(R2s, key=R2s.get) if verbose: print "\nfor the given mask, \nMax R2:+++++++++++++++++++++++++++-\n",\ "(m,n), [c1,c2,c3,c4,c5,c6], R2 = \n", (m,n), [c1,c2,c3,c4,c5,c6], R2 return (m,n), ShiibaCoeffs, R2s def interpolation(): """to interpolate after movements (translation, advection, rotation, etc) estimate phi1^(x,y) = sum_{s=x-1,x,x+1; t=y-1,y,y+1} H(s-x_pullback)*H(t-y_pullback)*phi0(s,t) where H = weight function: H(x)=x cut-off and levelled at two ends 0,1 _ H = _/ """ pass def semiLagrangeAdvect(): """to compute the semi-Lagrangian advection of a grid, given a velocity field """ pass
{ "repo_name": "yaukwankiu/armor", "path": "shiiba/regression.py", "copies": "1", "size": "16020", "license": "cc0-1.0", "hash": -5872930744573893000, "line_mean": 40.71875, "line_max": 145, "alpha_frac": 0.5331460674, "autogenerated": false, "ratio": 3.094456248792737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9008067180259636, "avg_score": 0.023907027186620262, "num_lines": 384 }
# advection-solver.py from __future__ import print_function, division import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from nufft import nufft1 as nufft_fortran from nufft import nufft3 as nufft3 from random import uniform as uniform def nufftfreqs(M, df=1): """Compute the frequency range used in nufft for M frequency bins""" return df * np.arange(-(M // 2), M - (M // 2)) def nudft(x, y, xi, iflag=1): """Non-Uniform Direct Fourier Transform""" sign = -1 if iflag < 0 else 1 return (1.0 / len(x)) *np.dot(y, np.exp(sign * 1j * xi * x[:, np.newaxis])) def forward_dft(x, u_initial, psi, f, T, R): """Solves advection-diffusion equation forward in time. The equation is $$ u_t - u_{xx} - \psi u_x - f(x) = 0 \:, $$ with initial condition $u(x,0) = u_initial$. We assume that the support of f(x) is a subset of [-R/2, R/2]. Args: x: uniform grid in physical space, dx = $R / N$ u_initial: initial field value psi: advection coefficient f: time independent source T: final time R: The support of the source is a subset of $[-R,R]$ Returns: u_final: final field value """ N = len(x) # nufft frecuencies xi = np.arange(-(N // 2), N - (N // 2)) zero_freq_index = N // 2 # Fourier transform u_hat_initial = R * nudft(x, u_initial, xi, 1) f_hat = R * nudft(x, f, xi, 1) # Solve ODE's analitically in Fourier space a = (1j * psi - xi) * xi u_hat_final = np.zeros(N) u_hat_final = np.array(u_hat_final, dtype=complex) for n in range (0, zero_freq_index): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) for n in range (zero_freq_index + 1, N): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) u_hat_final[zero_freq_index] = ( u_hat_initial[zero_freq_index] + (T + 0j) * f_hat[zero_freq_index]) # inverse Fourier transform u_final = (1.0 / (2.0 * np.pi)) * N * nudft(xi, u_hat_final, x, -1) return np.real(u_final) def forward(x, u_initial, psi, f, T, R): """Solves advection-diffusion equation forward in time using the FFT. The equation is $$ u_t - u_{xx} - \psi u_x - f(x) = 0 \:, $$ with initial condition $u(x,0) = u_initial$. We assume that the support of f(x) is a subset of [-R/2, R/2]. Args: x: grid in physical space u_initial: initial field value psi: advection coefficient f: time independent source T: final time R: The support of the source is a subset of $[-R / 2, R / 2]$ Returns: u_final: final field value """ # add $R / 2$ to the grid, and evaluate Riemann sums on the right endpoint x = np.append(x, R / 2.0) u_initial = np.append(u_initial, 0.0) f = np.append(f, 0.0) N = len(x) dx = np.zeros(N) dx[0] = x[0] - (- R / 2.0) dx[1 : N] = x[1 : N] - x[0 : N - 1] # nufft frecuencies xi = (np.arange(-N // 2, N // 2) + N % 2) zero_freq_index = N // 2 # Fourier transform, NOTICE that nufft3 calculates the normalized # sum: line 71 in https://github.com/dfm/python-nufft/blob/master/nufft/nufft.py u_hat_initial = N * nufft3(x, u_initial * dx, xi) f_hat = N * nufft3(x, f * dx, xi) # solve ODE's analitically in Fourier space a = (-1j * psi - xi) * xi u_hat_final = np.zeros(N) u_hat_final = np.array(u_hat_final, dtype=complex) for n in range (0, zero_freq_index): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) for n in range (zero_freq_index + 1, N): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) u_hat_final[zero_freq_index] = ( u_hat_initial[zero_freq_index] + (T + 0j) * f_hat[zero_freq_index]) # inverse Fourier transform, NOTICE that nufft3 calculates the normalized # sum: line 71 in https://github.com/dfm/python-nufft/blob/master/nufft/nufft.py u_final = ( (1.0 / (2 * np.pi)) * N * nufft3(xi, u_hat_final, x, iflag=-1)) return np.real(u_final[0 : N - 1]) def forward_fft(x, u_initial, psi, f, T, R): """Solves advection-diffusion equation forward in time using the FFT. The equation is $$ u_t - u_{xx} - \psi u_x - f(x) = 0 \:, $$ with initial condition $u(x,0) = u_initial$. We assume that the support of f(x) is a subset of [-R/2, R/2]. Args: x: uniform grid in physical space, $dx = R / N$ u_initial: initial field value psi: advection coefficient f: time independent source T: final time R: The support of the source is a subset of $[-R,R]$ Returns: u_final: final field value """ N = len(x) # nufft frecuencies xi = (np.arange(-N // 2, N // 2) + N % 2) zero_freq_index = N // 2 # Fourier transform u_hat_initial = R * nufft_fortran(x, u_initial, N) f_hat = R * nufft_fortran(x, f, N) # Solve ODE's analitically in Fourier space a = (1j * psi - xi) * xi u_hat_final = np.zeros(N) u_hat_final = np.array(u_hat_final, dtype=complex) for n in range (0, zero_freq_index): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) for n in range (zero_freq_index + 1, N): u_hat_final[n] = ( u_hat_initial[n] * np.exp(a[n] * T) - (f_hat[n] / a[n]) * (1.0 - np.exp(a[n] * T))) u_hat_final[zero_freq_index] = ( u_hat_initial[zero_freq_index] + (T + 0j) * f_hat[zero_freq_index]) # inverse Fourier transform u_final = ( (1.0 / (2 * np.pi)) * N * nufft_fortran(xi * (R / N), u_hat_final, N, iflag=-1)) return np.real(u_final) def forwardGradient(x, u_initial, psi, f, T, R): """Solves for u_{x} in the advection-diffusion equation, forward in time using the FFT. The equation is $$ u_t - u_{xx} - \psi u_x - f(x) = 0 \:, $$ with initial condition $u(x,0) = u_initial$. We assume that the support of f(x) is a subset of [-R/2, R/2]. Args: x: grid in physical space. u_initial: initial field value psi: advection coefficient f: time independent source T: final time R: The support of the source is a subset of $[-R,R]$ Returns: u_final: final field value """ # add $R / 2$ to the grid, and evaluate Riemann sums on the right endpoint x = np.append(x, R / 2.0) u_initial = np.append(u_initial, 0.0) f = np.append(f, 0.0) N = len(x) dx = np.zeros(N) dx[0] = x[0] - (- R / 2.0) dx[1 : N] = x[1 : N] - x[0 : N - 1] # nufft frecuencies xi = (np.arange(-N // 2, N // 2) + N % 2) zero_freq_index = N // 2 # Fourier transform u_hat_initial = N * nufft3(x, u_initial * dx, xi) f_hat = N * nufft3(x, f * dx, xi) # Solve ODE's analitically in Fourier space a = (-1j * psi - xi) * xi u_hat_final_x = np.zeros(N) u_hat_final_x = np.array(u_hat_final_x, dtype=complex) # $u_x$ in Fourier space is equivalent to multiplication by $-i * \xi$ u_hat_initial_x = u_hat_initial * (-1j * xi) f_hat_x = f_hat * (-1j * xi) for n in range (0, zero_freq_index): u_hat_final_x[n] = ( u_hat_initial_x[n] * np.exp(a[n] * T) - (f_hat_x[n] / a[n]) * (1.0 - np.exp(a[n] * T))) for n in range (zero_freq_index + 1, N): u_hat_final_x[n] = ( u_hat_initial_x[n] * np.exp(a[n] * T) - (f_hat_x[n]/a[n]) * (1.0 - np.exp(a[n] * T))) u_hat_final_x[zero_freq_index] = ( u_hat_initial_x[zero_freq_index] + (T + 0j) * f_hat_x[zero_freq_index]) # inverse Fourier transform u_final_x = ( (1.0 / (2.0 * np.pi)) * N * nufft3(xi, u_hat_final_x, x, iflag=-1)) return np.real(u_final_x[0 : N - 1]) def forwardDemo(): """ Quick demo of the forward functions """ N = 1000 # number of observations T = 0.0001 t = 0.0001 psi = 2000 R = 1 dx = R / N x = np.linspace(- R / 2.0 + dx, R / 2.0, N ) # position along the rod u_initial = np.exp(- x * x / (4.0 * t)) / np.sqrt(4.0 * np.pi * t) f = 1000 * np.exp( - x * x / (4.0 * t)) / np.sqrt( 4.0 * np.pi * t) u_final = forward(x, u_initial, psi, f, T, R) u_final_x = forwardGradient(x, u_initial, psi, f, T, R) # plots pp = PdfPages('./images/advection_solver_demo.pdf') # plot u plt.plot(x, u_initial, 'r', label="$t=0$") plt.plot(x, u_final, 'b', label="$t=T$") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$u$') pp.savefig() # plot u_x plt.figure() plt.plot(x, u_final_x, 'b', label="$t=T$") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$u_x$') pp.savefig() # show plots and close pdf plt.show() pp.close() def u_advection(x, t, psi): """Analytical solution of advection-diffusion equation forward in time. The equation is $$ u_t - u_{xx} - \psi u_x = 0 \:, $$ with initial condition $u(x,0) = \delta_{x=0}$. Args: x: grid in physical space t: time psi: advection coefficient, units [x]/[t] Returns: u: field value at time t evaluated over the vector x """ u = ( np.exp(- (x + psi * t) * (x + psi * t) / (4.0 * t)) / np.sqrt(4.0 * np.pi * t)) return u def forwardTest(): """ Quick test of the forward function, with ZERO SOURCE""" N = 10000 # number of observations T = 0.0001 t = 0.0001 psi = 1000.0 R = 2.0 # position along the rod x = np.zeros(N) for i in range(0, N): x[i] = uniform(-R / 2, R / 2) x = np.sort(x) u_initial = u_advection(x, t, psi) f = np.zeros(N) u_final = forward(x, u_initial, psi, f, T, R) u_final_analytical = u_advection(x, t + T, psi) plt.plot(x, u_initial, 'g', label="$t = 0$") print("length x : ", len(x)) print("length u_final : ", len(u_final)) plt.plot(x, u_final, 'b', label="numerical soln, $t = T$") plt.plot(x, u_final_analytical, 'r--', label="analytical soln, $t = T$") plt.legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.xlabel('$x$') plt.ylabel('$u$') pp = PdfPages('./images/advection_solver_test.pdf') pp.savefig() plt.show() pp.close() # if module runs as a script run demo if __name__ == "__main__": forwardDemo()
{ "repo_name": "vidalalcala/source-recovery", "path": "advection_solver.py", "copies": "1", "size": "11279", "license": "mit", "hash": -3831893404817381400, "line_mean": 30.243767313, "line_max": 84, "alpha_frac": 0.5297455448, "autogenerated": false, "ratio": 2.7509756097560976, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37807211545560976, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import minmod_lf from rk import euler from grid import grid import numpy from matplotlib import pyplot Ngz = 2 Npoints_all = 40 * 2**numpy.arange(6) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, minmod_lf, euler, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, L-F, Minmod, Euler") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_minmod_lf_euler_convergence.py", "copies": "1", "size": "1359", "license": "mit", "hash": -7771623714526097000, "line_mean": 32.1707317073, "line_max": 80, "alpha_frac": 0.6401766004, "autogenerated": false, "ratio": 2.7962962962962963, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3936472896696296, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import minmod_lf from rk import rk2 from grid import grid import numpy from matplotlib import pyplot Ngz = 2 Npoints_all = 20 * 2**numpy.arange(6) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) sims = [] for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, minmod_lf, rk2, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') sims.append(sim) norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, L-F, Minmod, RK2") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_minmod_lf_rk2_convergence.py", "copies": "1", "size": "1384", "license": "mit", "hash": 598409845458393900, "line_mean": 31.2093023256, "line_max": 80, "alpha_frac": 0.6365606936, "autogenerated": false, "ratio": 2.756972111553785, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3893532805153785, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import minmod_lf from rk import rk3 from grid import grid import numpy from matplotlib import pyplot Ngz = 2 Npoints_all = 40 * 2**numpy.arange(6) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, minmod_lf, rk3, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, L-F, Minmod, RK3") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_minmod_lf_rk3_convergence.py", "copies": "1", "size": "1353", "license": "mit", "hash": -6020247008435009000, "line_mean": 32.0243902439, "line_max": 80, "alpha_frac": 0.6385809313, "autogenerated": false, "ratio": 2.766871165644172, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.881791052353563, "avg_score": 0.017508314681708374, "num_lines": 41 }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import minmod_upwind from rk import rk2 from grid import grid import numpy from matplotlib import pyplot Ngz = 2 Npoints_all = 40 * 2**numpy.arange(6) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, minmod_upwind, rk2, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') sim.plot_scalar_vs_initial() pyplot.show() norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, upwind, Minmod, RK2") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_minmod_upwind_rk2_convergence.py", "copies": "1", "size": "1415", "license": "mit", "hash": -3104754650590191600, "line_mean": 31.9302325581, "line_max": 80, "alpha_frac": 0.6416961131, "autogenerated": false, "ratio": 2.7909270216962523, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3932623134796252, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import weno3_lf from rk import rk3 from grid import grid import numpy from matplotlib import pyplot Ngz = 3 Npoints_all = 40 * 2**numpy.arange(5) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) sims = [] for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, weno3_lf, rk3, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') sims.append(sim) norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, L-F, WENO3, RK3") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_weno3_lf_rk3_convergence.py", "copies": "1", "size": "1381", "license": "mit", "hash": 4896217019173157000, "line_mean": 31.1395348837, "line_max": 80, "alpha_frac": 0.6357711803, "autogenerated": false, "ratio": 2.7238658777120315, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38596370580120315, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import weno3_upwind from rk import rk3 from grid import grid import numpy from matplotlib import pyplot Ngz = 3 Npoints_all = 40 * 2**numpy.arange(4) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) sims = [] for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, weno3_upwind, rk3, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') sims.append(sim) norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, Upwind, WENO3, RK3") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_weno3_upwind_rk3_convergence.py", "copies": "1", "size": "1392", "license": "mit", "hash": 9038623340459631000, "line_mean": 31.3953488372, "line_max": 80, "alpha_frac": 0.6393678161, "autogenerated": false, "ratio": 2.7401574803149606, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38795252964149607, "avg_score": null, "num_lines": null }
# Advection test evolution: convergence test from models import advection from bcs import periodic from simulation import simulation from methods import weno5_upwind from rk import rk3 from grid import grid import numpy from matplotlib import pyplot Ngz = 4 Npoints_all = 40 * 2**numpy.arange(5) dx_all = 1 / Npoints_all errors = numpy.zeros((3,len(dx_all))) sims = [] for i, Npoints in enumerate(Npoints_all): print(Npoints) interval = grid([-0.5, 0.5], Npoints, Ngz) model = advection.advection(v=1, initial_data = advection.initial_sine(period=1)) sim = simulation(model, interval, weno5_upwind, rk3, periodic) sim.evolve(1.0) errors[0, i] = sim.error_norm(1) errors[1, i] = sim.error_norm(2) errors[2, i] = sim.error_norm('inf') sims.append(sim) norm_string = ("1", "2", "\infty") fig = pyplot.figure(figsize=(12,6)) ax = fig.add_subplot(111) for norm in range(3): p = numpy.polyfit(numpy.log(dx_all), numpy.log(errors[norm,:]), 1) ax.loglog(dx_all, errors[norm,:], 'x', label=r"$\| Error \|_{}$".format(norm_string[norm])) ax.loglog(dx_all, numpy.exp(p[1])*dx_all**p[0], label=r"$\propto \Delta x^{{{:.3f}}}$".format(p[0])) ax.set_xlabel(r"$\Delta x$") ax.set_ylabel("Error") ax.legend(loc= "upper left") pyplot.title("Advection, sine, Upwind, WENO5, RK3") pyplot.show()
{ "repo_name": "IanHawke/toy-evolve", "path": "toy-evolve/advection_sine_weno5_upwind_rk3_convergence.py", "copies": "1", "size": "1392", "license": "mit", "hash": 5333662460947552000, "line_mean": 31.3953488372, "line_max": 80, "alpha_frac": 0.6393678161, "autogenerated": false, "ratio": 2.7401574803149606, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38795252964149607, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 11 - Corporate Policy # http://adventofcode.com/2015/day/11 import sys import itertools # Return whether a password is valid per company policy def is_valid_password(password): return not contains(password, 'iol') and has_straight_of_three(password) and has_two_pairs(password) # Return true if a string contains an increasing straight of three letters def has_straight_of_three(string): for i in range(len(string) - 2): if ord(string[i]) == ord(string[i + 1]) - 1 and ord(string[i]) == ord(string[i + 2]) - 2: return True return False # Return true if a string contains at least a letter from a given set def contains(string, letters): for letter in letters: if letter in string: return True return False # Return true if a string contains at least two non-overlapping pairs of letters def has_two_pairs(string): return len(list(filter(lambda x: x >= 2, [len(list(values)) for value, values in itertools.groupby(string)]))) >= 2 # Increment a password def increment_password(password): if len(password) == 0: return 'a' if password[-1] == 'z': return increment_password(password[:-1]) + 'a' else: return password[:-1] + chr(ord(password[-1]) + 1) # Return the next valid password, given the current one def next_valid_password(current_password): current_password = increment_password(current_password) while not is_valid_password(current_password): current_password = increment_password(current_password) return current_password # Main if __name__ == '__main__': print(next_valid_password(sys.stdin.readline().strip()))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day11_part1.py", "copies": "1", "size": "1681", "license": "mit", "hash": 6740848770202713000, "line_mean": 34.7659574468, "line_max": 119, "alpha_frac": 0.6847114813, "autogenerated": false, "ratio": 3.6783369803063457, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4863048461606346, "avg_score": null, "num_lines": null }
"""Advent of Code 2015 - Day 11.""" import itertools import re import string def rule_1(password): """Check if a password adheres to the 1st password rule.""" characters = list(password) for index in range(len(characters) - 2): a, b, c = characters[index:index + 3] if ord(a) + 1 == ord(b) == ord(c) - 1: return True return False # 2nd password rule: Forbidden characters. RULE_2 = re.compile(r'[iol]') # 3rd password rule: Two non-overlapping different pairs. RULE_3 = re.compile(r'([a-z])\1.*(?!\1)([a-z])\2') def valid_password(password): """Check if a password is valid according to all given password rules.""" return (not RULE_2.search(password) and RULE_3.search(password) and rule_1(password)) def string_range(start, stop=None, symbols=string.ascii_lowercase): """Yield lexicographically increasing fixed-length strings.""" item_sym = list(start) if stop is None: stop = symbols[-1] * len(start) last_symbol = len(symbols) - 1 item_int = list(map(symbols.index, item_sym)) stop_int = list(map(symbols.index, stop)) while item_int < stop_int: yield ''.join(item_sym) # Handle overflow in least-significant symbols. index = -1 while item_int[index] == last_symbol: item_int[index] = 0 item_sym[index] = symbols[0] index -= 1 # Advance right-most symbol that will not overflow. item_int[index] += 1 item_sym[index] = symbols[item_int[index]] def main(): """Main entry point of puzzle solution.""" INPUT_PASSWORD = 'hepxcrrq' # Make sure to skip over input password, even if it would be valid. next_passwords = itertools.islice(string_range(INPUT_PASSWORD), 1, None) good_passwords = filter(valid_password, next_passwords) for part, password in zip(['One', 'Two'], good_passwords): print('Part {}: {}'.format(part, password)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-11/main.py", "copies": "1", "size": "2024", "license": "bsd-2-clause", "hash": 2171255914974208300, "line_mean": 28.3333333333, "line_max": 77, "alpha_frac": 0.6175889328, "autogenerated": false, "ratio": 3.563380281690141, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.968096921449014, "avg_score": 0, "num_lines": 69 }
"""Advent of Code 2015 - Day 12.""" import json import numbers from pathlib import Path def read_input(): """Read input file.""" return Path(__file__).with_name('input.json').read_text() def traverse_json(data, filter=None): """Recursively traverse JSON structure yielding all its elements.""" if filter and filter(data): return yield data # Handle nested structures like dicts/lists and yield their values, too. if isinstance(data, dict): for item in data.values(): yield from traverse_json(item, filter=filter) elif isinstance(data, list): for item in data: yield from traverse_json(item, filter=filter) def is_number(item): """Check if the item is a number.""" return isinstance(item, numbers.Number) def is_red_dict(item): """Check if the item is a dict that contains a red value.""" return isinstance(item, dict) and 'red' in item.values() def main(): """Main entry point of puzzle solution.""" data = json.loads(read_input()) part_one = sum(filter(is_number, traverse_json(data))) part_two = sum(filter(is_number, traverse_json(data, filter=is_red_dict))) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-12/main.py", "copies": "1", "size": "1314", "license": "bsd-2-clause", "hash": -4505804983037938700, "line_mean": 25.28, "line_max": 78, "alpha_frac": 0.6415525114, "autogenerated": false, "ratio": 3.786743515850144, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9928296027250144, "avg_score": 0, "num_lines": 50 }
# Advent of Code 2015 - Day 13 - Knights of the Dinner Table # http://adventofcode.com/2015/day/13 import sys import itertools # Parse the guest list as a map def parse_guest_list(guest_list): guests = {} for line in guest_list: tokens = line.split(' ') guest = tokens[0] other_guest = tokens[10][:-2] happiness_value = int(tokens[3]) * (-1 if tokens[2] == 'lose' else 1) if guest not in guests: guests[guest] = {} guests[guest][other_guest] = happiness_value return guests # Return the total happiness for the best seating arrangement def best_seating_outcome(guests): return max([sum(happiness(seating, guests)) for seating in itertools.permutations(guests)]) # Calculate the happiness value for each guest in a seating def happiness(seating, guests): outcome = [] for i in range(len(seating)): guest = seating[i] previous_guest = seating[i - 1] next_guest = seating[(i + 1) % len(seating)] outcome.append(guests[guest][previous_guest] + guests[guest][next_guest]) return outcome # Main if __name__ == '__main__': print(best_seating_outcome(parse_guest_list(sys.stdin.readlines())))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day13_part1.py", "copies": "1", "size": "1222", "license": "mit", "hash": 2003310645852681700, "line_mean": 32.9444444444, "line_max": 95, "alpha_frac": 0.6440261866, "autogenerated": false, "ratio": 3.329700272479564, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44737264590795645, "avg_score": null, "num_lines": null }
"""Advent of Code 2015 - Day 13.""" import itertools import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class AmityMap: """Map of people and their mutual amities (not symmetric).""" # Regular expression for parsing amity pairs from the input file. SEATING_REGEXP = re.compile(r'^(?P<foo>.+) would (?P<sign>gain|lose) ' r'(?P<happiness>\d+) happiness units by ' r'sitting next to (?P<bar>.+)\.$') @classmethod def from_lines(cls, lines): """Initialize a map from lines read from the input file.""" amity_map = cls() for line in lines: match = cls.SEATING_REGEXP.search(line) happiness = int(match.group('happiness')) if match.group('sign') == 'lose': happiness *= -1 amity_map.add_amity_pair(match.group('foo'), match.group('bar'), happiness) return amity_map def __init__(self): """Initialize an empty map.""" self.names = {} self.amity = {} def add_amity_pair(self, foo, bar, happiness): """Add a pair of people and their (directed) amity to the map.""" foo_id = self.names.setdefault(foo, len(self.names)) bar_id = self.names.setdefault(bar, len(self.names)) self.amity[(foo_id, bar_id)] = happiness def add_self(self): """Add a neutral (in terms of amity) self to the map.""" for other in list(self.names): self.add_amity_pair('Self', other, 0) self.add_amity_pair(other, 'Self', 0) # Simplify chaining method calls. return self def arrangements(self): """Yield all possible seating arrangements.""" for name_list in itertools.permutations(self.names.values()): yield name_list, (*name_list[1:], name_list[0]) def arrangement_happinesses(self): """Yield happinesses for all possible seating arrangements.""" for pair in self.arrangements(): happiness = 0 for foo, bar in zip(*pair): happiness += self.amity[(foo, bar)] + self.amity[(bar, foo)] yield happiness def main(): """Main entry point of puzzle solution.""" amity_map = AmityMap.from_lines(read_input()) part_one = max(amity_map.arrangement_happinesses()) part_two = max(amity_map.add_self().arrangement_happinesses()) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-13/main.py", "copies": "1", "size": "2775", "license": "bsd-2-clause", "hash": 6563535458537892000, "line_mean": 32.8414634146, "line_max": 77, "alpha_frac": 0.5686486486, "autogenerated": false, "ratio": 3.719839142091153, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9788487790691153, "avg_score": 0, "num_lines": 82 }
"""Advent of Code 2015 - Day 14.""" import itertools import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class Reindeer: """Reindeer with a name and various racing properties.""" def __init__(self, name, speed, race_time, rest_time): """Initialize reindeer with its name and other properties.""" self.name = name self.speed = speed self.race_time = race_time self.rest_time = rest_time def race(self): """Yield traveled distances at discrete times for an infinite race.""" lap_time = self.race_time + self.rest_time time = 0 distance = 0 while True: yield distance if (time % lap_time) < self.race_time: distance += self.speed time += 1 class ReindeerRace: """Reindeer race with a stable and various racing options.""" # Regular expression for parsing reindeer specs from the input file. REINDEER_REGEXP = re.compile(r'^(?P<name>.+) can fly (?P<speed>\d+) km/s ' r'for (?P<race_time>\d+) seconds, but then ' r'must rest for (?P<rest_time>\d+) ' r'seconds\.$') @classmethod def from_lines(cls, lines): """Initialize a reindeer race from lines from the input file.""" race = cls() for line in lines: match = cls.REINDEER_REGEXP.search(line) reindeer = Reindeer(match.group('name'), int(match.group('speed')), int(match.group('race_time')), int(match.group('rest_time'))) race.stable.append(reindeer) return race def __init__(self): """Initialize a reindeer race with an empty stable.""" self.stable = [] def winning_distance_after(self, target_time): """Determine the winning distance of the best reindeer of a race.""" def distance_after_race(reindeer): """Determine distance traveled by reindeer after a given time.""" return next(itertools.islice(reindeer.race(), target_time, None)) return max(map(distance_after_race, self.stable)) def winning_points_after(self, target_time): """Determine the winning points of the best reindeer of a race.""" def distances_during_race(reindeer): """Yield distances traveled by reindeer during a finite race.""" return itertools.islice(reindeer.race(), 1, target_time + 1) points = [0] * len(self.stable) for distances in zip(*map(distances_during_race, self.stable)): leading_distance = max(distances) for index, distance in enumerate(distances): if distance == leading_distance: points[index] += 1 return max(points) def main(): """Main entry point of puzzle solution.""" reindeer_race = ReindeerRace.from_lines(read_input()) part_one = reindeer_race.winning_distance_after(2503) part_two = reindeer_race.winning_points_after(2503) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-14/main.py", "copies": "1", "size": "3415", "license": "bsd-2-clause", "hash": 8019265077881520000, "line_mean": 33.8469387755, "line_max": 78, "alpha_frac": 0.5792093704, "autogenerated": false, "ratio": 3.916284403669725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4995493774069725, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 14 - Reindeer Olympics # http://adventofcode.com/2015/day/14 import sys # Parse reindeer descriptions as a list of tuples def parse_reindeers(reindeer_specs): def parse_reindeer(reindeer_spec): tokens = reindeer_spec.split(' ') speed, fly_time, rest_time = int(tokens[3]), int(tokens[6]), int(tokens[13]) return (speed, fly_time, rest_time) return [parse_reindeer(reindeer_spec) for reindeer_spec in reindeer_specs] # Calculte the traveled distances for all reindeers after a given time def distances_traveled(reindeers, time): def distance_traveled(reindeer, time): speed, fly_time, rest_time = reindeer flights = (time // (fly_time + rest_time)) extra_time = time % (fly_time + rest_time) extra_distance = speed * extra_time if (extra_time < fly_time) else fly_time * speed return flights * speed * fly_time + extra_distance return [distance_traveled(reindeer, time) for reindeer in reindeers] # Main if __name__ == '__main__': print(max(distances_traveled(parse_reindeers(sys.stdin.readlines()), 2503)))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day14_part1.py", "copies": "1", "size": "1123", "license": "mit", "hash": -5234898185693221000, "line_mean": 42.1923076923, "line_max": 92, "alpha_frac": 0.6821015138, "autogenerated": false, "ratio": 2.9867021276595747, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9145088760491642, "avg_score": 0.004742976193586336, "num_lines": 26 }
"""Advent of Code 2015 - Day 15.""" import itertools import operator import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() def dotproduct(lhs, rhs): """Compute the dot product of two vectors.""" return sum(map(operator.mul, lhs, rhs)) def transposed(matrix): """Transpose a matrix (list of nested lists of equal length).""" return [list(column) for column in zip(*matrix)] class Ingredient: """Ingredient with name, calories, and other properties.""" def __init__(self, name, properties): """Initialize ingredient with its name and properties.""" self.name = name self.calories = properties.pop('calories') self.properties = properties class Recipe: """Recipe with ingredients and methods to optimally balance those.""" # Regular expression for extracting name and properties from ingredient. INGREDIENT_REGEXP = re.compile(r'^(?P<name>\w+): (?P<properties>.*)$') # Regular expression for splitting properties into name-value pairs. PROPERTY_REGEXP = re.compile(r'(\w+) ([+-]?\d+)') @classmethod def from_lines(cls, lines): """Initialize a recipe from lines from the input file.""" recipe = cls() for line in lines: match = cls.INGREDIENT_REGEXP.search(line) properties = cls.PROPERTY_REGEXP.findall(match.group('properties')) recipe.add_ingredient(match.group('name'), dict((k, int(v)) for k, v in properties)) return recipe def __init__(self): """Initialize an empty recipe.""" self.ingredients = [] def add_ingredient(self, name, properties): """Add a named ingredient with its properties to the recipe.""" self.ingredients.append(Ingredient(name, properties)) def best_score(self, **kwargs): """Best score of all valid combinations of ingredients.""" return max(self.__all_scores(**kwargs), default=None) def __all_scores(self, teaspoons=None, calories=None): """Yield scores for valid combinations of ingredients.""" calo_weights, prop_weights = self.__setup_weights() ranges = [range(teaspoons + 1) for _ in self.ingredients] ranges.pop() for parts in itertools.product(*ranges): # Make sure we only test canonical combinations where the sum of # the individual parts adds up to the given number of teaspoons. filler = teaspoons - sum(parts) if filler < 0: continue i_spoons = parts + (filler,) # If we have a target for the number of calories, check that. if calories and dotproduct(i_spoons, calo_weights) != calories: continue # Yield scores where all contributing factors are positive. full_score = 1 for prop_weight in prop_weights: prop_score = dotproduct(i_spoons, prop_weight) if prop_score <= 0: break full_score *= prop_score else: yield full_score def __setup_weights(self): """Set up weighting vector/matrix for calories/properties.""" prop_names = self.ingredients[0].properties.keys() name2value = operator.itemgetter(*prop_names) calo_weights = [] prop_weights = [] for ingredient in self.ingredients: calo_weights.append(ingredient.calories) prop_weights.append(name2value(ingredient.properties)) return calo_weights, transposed(prop_weights) def main(): """Main entry point of puzzle solution.""" NUM_CALORIES = 500 NUM_TEASPOONS = 100 recipe = Recipe.from_lines(read_input()) part_one = recipe.best_score(teaspoons=NUM_TEASPOONS) part_two = recipe.best_score(teaspoons=NUM_TEASPOONS, calories=NUM_CALORIES) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-15/main.py", "copies": "1", "size": "4218", "license": "bsd-2-clause", "hash": -7612628735092856000, "line_mean": 32.744, "line_max": 79, "alpha_frac": 0.6119013751, "autogenerated": false, "ratio": 3.998104265402844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5110005640502844, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 15 - Science for Hungry People # http://adventofcode.com/2015/day/15 import sys import operator import functools def parse_input(text): return [parse_input_line(line.rstrip()) for line in text] def parse_input_line(line): # Ignore the calories value altogether return list(map(lambda x: int(x.split(" ")[-1]), line.split(":")[1].split(",")))[:-1:] def partitions(): partitions = [] for i in range(101): for j in range(101-i): for k in range(101-i-j): l = 100-i-j-k partitions.append([i,j,k,l]) return partitions def recipe_score(ingredients, quantities): weighted_ingredients = [list(map(lambda param: q*param, i)) for q,i in zip(quantities, ingredients)] properties = list(map(lambda a,b,c,d: a+b+c+d, *weighted_ingredients)) no_negatives = list(map(lambda x: x if x>0 else 0, properties)) return functools.reduce(operator.mul, no_negatives) def best_recipe_score(ingredients): return max([recipe_score(ingredients, quantities) for quantities in partitions()]) # Main ingredients = parse_input(sys.stdin.readlines()) print(best_recipe_score(ingredients))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day15_part1.py", "copies": "1", "size": "1191", "license": "mit", "hash": 5166392135666451000, "line_mean": 33.0285714286, "line_max": 104, "alpha_frac": 0.6675062972, "autogenerated": false, "ratio": 3.125984251968504, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9207429603111488, "avg_score": 0.017212189211403234, "num_lines": 35 }
# Advent of Code 2015 - Day 15 - Science for Hungry People - Part 2 # http://adventofcode.com/2015/day/15 import sys import operator import functools def parse_input(text): return [parse_input_line(line.rstrip()) for line in text] def parse_input_line(line): return list(map(lambda x: int(x.split(" ")[-1]), line.split(":")[1].split(","))) def partitions(): partitions = [] for i in range(101): for j in range(101-i): for k in range(101-i-j): l = 100-i-j-k partitions.append([i,j,k,l]) return partitions def recipe_score(ingredients, quantities): weighted_ingredients = [list(map(lambda param: q*param, i)) for q,i in zip(quantities, ingredients)] properties = list(map(lambda a,b,c,d: a+b+c+d, *weighted_ingredients)) no_negatives = list(map(lambda x: x if x>0 else 0, properties)) # Calories score must be exactly 500 if no_negatives[-1] != 500: return 0 # Ignore calories for total scoring anyway return functools.reduce(operator.mul, no_negatives[:-1:]) def best_recipe_score(ingredients): return max([recipe_score(ingredients, quantities) for quantities in partitions()]) # Main ingredients = parse_input(sys.stdin.readlines()) print(best_recipe_score(ingredients))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day15_part2.py", "copies": "1", "size": "1294", "license": "mit", "hash": 1395055776826004700, "line_mean": 33.0526315789, "line_max": 104, "alpha_frac": 0.6615146832, "autogenerated": false, "ratio": 3.1793611793611793, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43408758625611793, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 16 - Aunt Sue # http://adventofcode.com/2015/day/16 import sys class Aunt(dict): def __missing__(self, key): return None def parse_input(text): def parse_line(line): aunt = Aunt() aunt['id'] = int(line.split(':')[0].split(' ')[-1]) items = map(lambda x: x.split(' '),' '.join(line.split(': ')[1:]).split(', ')) for item, count in items: aunt[item] = int(count) return aunt return [parse_line(line) for line in text] def filter_aunt(key, value): return lambda aunt: aunt[key] in [None, value] def filter_aunts(filter_function, known, aunts): for key in known: aunts = list(filter(filter_function(key, known[key]), aunts)) return aunts[0]; def aunt_number(aunt): return aunt['id'] # Main if __name__ == '__main__': known = {'children':3, 'cats':7, 'samoyeds':2, 'pomeranians':3, 'akitas':0, 'vizslas':0, 'goldfish':5, 'trees':3, 'cars':2, 'perfumes':1} print(aunt_number(filter_aunts(filter_aunt, known, parse_input(sys.stdin.readlines()))))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day16_part1.py", "copies": "1", "size": "1088", "license": "mit", "hash": -5906314791585458000, "line_mean": 30.0857142857, "line_max": 141, "alpha_frac": 0.59375, "autogenerated": false, "ratio": 2.8556430446194225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39493930446194225, "avg_score": null, "num_lines": null }
"""Advent of Code 2015 - Day 16.""" import operator import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class Aunt: """Aunt identified by a number and described by various information.""" # Regular expression for extracting number and description of aunt. AUNT_REGEXP = re.compile(r'^Sue (\d+): (.*)$') # Regular expression for further processing an aunt description. INFO_REGEXP = re.compile(r'(\w+): (\d+)') @classmethod def from_line(cls, line): """Initialize an aunt from a line from the input file.""" number, infos = cls.AUNT_REGEXP.search(line).groups() return cls(int(number), [(k, int(v)) for k, v in cls.INFO_REGEXP.findall(infos)]) def __init__(self, number, infos): """Initialize an aunt with its number and a description.""" self.number = number self.infos = infos def match(self, wanted_value, wanted_relop): """Check if the aunt matches the given description.""" for key, value in self.infos: relop = wanted_relop.get(key, operator.eq) if not relop(value, wanted_value[key]): return False return True def find_aunt(aunts, wanted_value, wanted_relop={}): """Find aunt that uniquely matches the given description.""" matcher = operator.methodcaller('match', wanted_value, wanted_relop) matched = list(filter(matcher, aunts)) if len(matched) == 1: return matched[0] raise RuntimeError('Failed to find uniquely matching aunt.') def main(): """Main entry point of puzzle solution.""" WANTED_VALUE = { 'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1, } WANTED_RELOP = { 'cats': operator.gt, 'trees': operator.gt, 'pomeranians': operator.lt, 'goldfish': operator.lt, } aunts = [Aunt.from_line(line) for line in read_input()] part_one = find_aunt(aunts, WANTED_VALUE).number part_two = find_aunt(aunts, WANTED_VALUE, WANTED_RELOP).number print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-16/main.py", "copies": "1", "size": "2471", "license": "bsd-2-clause", "hash": 6552116190828865000, "line_mean": 28.4166666667, "line_max": 77, "alpha_frac": 0.5969243221, "autogenerated": false, "ratio": 3.5863570391872277, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9683281361287228, "avg_score": 0, "num_lines": 84 }
"""Advent of Code 2015 - Day 17.""" import itertools from pathlib import Path def read_input(): """Read input file and return as a list of integers (one per line).""" lines = Path(__file__).with_name('input.txt').read_text().splitlines() return [int(line) for line in lines] def powerset(x): """Yield elements of the power set of the given list.""" return itertools.chain.from_iterable(itertools.combinations(x, r) for r in range(len(x) + 1)) def precompute_half(containers): """Prepare all possible half container combinations, keyed by volume.""" sums = {} for sizes in powerset(containers): sums.setdefault(sum(sizes), []).append(sizes) return sums def precompute_sums(containers): """Prepare all possible left/right container combinations by volume.""" if len(containers) < 2: raise RuntimeError('List of containers is too short.') middle = len(containers) // 2 l_half = precompute_half(containers[:middle]) r_half = precompute_half(containers[middle:]) return l_half, r_half def enum_variants(containers, target_volume): """Yield container combinations that match the target volume. Use a divide-and-conquer approach by computing the volumes of all possible container combinations for the left and right side of the container list. Then use that to find pairs whose summed volume matches the target volume. """ l_half, r_half = precompute_sums(containers) for l_volume, l_sizes in l_half.items(): r_volume = target_volume - l_volume if (r_volume < 0) or (r_volume not in r_half): continue r_sizes = r_half[r_volume] for l_size, r_size in itertools.product(l_sizes, r_sizes): yield l_size + r_size def enum_shortest(variants): """Yield container combinations of minimum length.""" optimal_length = len(min(variants, key=len)) return (variant for variant in variants if len(variant) == optimal_length) def main(): """Main entry point of puzzle solution.""" EGGNOG_VOLUME = 150 containers = read_input() part_one = list(enum_variants(containers, EGGNOG_VOLUME)) part_two = list(enum_shortest(part_one)) print('Part One: {}'.format(len(part_one))) print('Part Two: {}'.format(len(part_two))) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-17/main.py", "copies": "1", "size": "2395", "license": "bsd-2-clause", "hash": 6904944232063721000, "line_mean": 30.5131578947, "line_max": 78, "alpha_frac": 0.6530271399, "autogenerated": false, "ratio": 3.887987012987013, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5041014152887013, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 18 - Like a GIF For Your Yard # http://adventofcode.com/2015/day/18 import sys def parse_input(lines): return [[(lambda x: 1 if x == "#" else 0)(x) for x in line.rstrip()] for line in lines] def count_neighbours(grid, line, column, state): size = len(grid) total = 0 for x in range(line-1, line+2): for y in range(column-1, column+2): if (x == line and y == column) or x < 0 or x > size-1 or y < 0 or y > size-1: continue total += (1 if grid[x][y] == state else 0) return total def cellular_rules(grid, line, column): cell = grid[line][column] if cell == 1 and count_neighbours(grid, line, column, 1) in [2,3]: return 1 elif cell == 0 and count_neighbours(grid, line, column, 1) == 3: return 1 else: return 0 def step(grid): size = len(grid) outcome = [[None for x in range(size)] for y in range(size)] for line in range(size): for column in range(size): outcome[line][column] = cellular_rules(grid, line, column) return outcome def step_through(grid, steps): outcome = grid for s in range(steps): outcome = step(outcome) return outcome def lights_on(grid): return sum([sum(line) for line in grid]) # Main if __name__ == '__main__': start = parse_input(sys.stdin.readlines()) print(lights_on(step_through(start, 100)))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day18_part1.py", "copies": "1", "size": "1431", "license": "mit", "hash": -6283747450643568000, "line_mean": 28.8125, "line_max": 91, "alpha_frac": 0.5960866527, "autogenerated": false, "ratio": 3.2522727272727274, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43483593799727277, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 19 - Medicine for Rudolph # http://adventofcode.com/2015/day/19 import sys import re def parse_input(parse_replacement, lines): separator = ' => ' replacements = {} for line in lines: if separator in line: source, replacement = parse_replacement(separator, line) if source in replacements: replacements[source].append(replacement) else: replacements[source] = [replacement] continue if line.rstrip() == '': continue molecule = line.rstrip() return replacements, molecule def parse_replacement(separator, line): return line.rstrip().split(separator) def split_molecule(molecule): return re.findall('[A-Z][a-z]*|e', molecule) def replace(replacements, molecule): possible_outcomes = [] atoms = split_molecule(molecule) for i in range(len(atoms)): atom = atoms[i] if atom in replacements: for replacement in replacements[atom]: outcome = atoms[:] outcome[i] = replacement joined = ''.join(outcome) if joined not in possible_outcomes: possible_outcomes.append(joined) return possible_outcomes # Main if __name__ == '__main__': replacements, molecule = parse_input(parse_replacement, sys.stdin.readlines()) possible_outcomes = replace(replacements, molecule) print(len(possible_outcomes))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day19_part1.py", "copies": "1", "size": "1502", "license": "mit", "hash": -1007085621520632000, "line_mean": 30.9574468085, "line_max": 82, "alpha_frac": 0.6098535286, "autogenerated": false, "ratio": 4.316091954022989, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5425945482622988, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 21 - RPG Simulator 20XX # http://adventofcode.com/2015/day/21 import sys def parse_input(lines): boss = {} for line in lines: key, value = line.rstrip().split(': ') if key == 'Hit Points': boss['hp'] = int(value) if key == 'Damage': boss['da'] = int(value) if key == 'Armor': boss['ar'] = int(value) return boss def victory(outcome): hero, boss = outcome return hero['hp'] > 0 and boss['hp'] <= 0 def combat(hero, boss): hero_turn = True while hero['hp'] > 0 and boss['hp'] > 0: if hero_turn: attack = hero['da'] - boss['ar'] boss['hp'] -= attack if attack > 1 else 1 else: attack = boss['da'] - hero['ar'] hero['hp'] -= attack if attack > 1 else 1 hero_turn = not hero_turn return (hero, boss) def make_outfits(weapons, armours, rings): outfits = [] for weapon in weapons: for armour in armours: for left_ring in rings: for right_ring in rings: if left_ring == right_ring and left_ring['co'] != 0: continue outfit = {} for stat in ['co', 'ar', 'da']: outfit[stat] = weapon[stat] + armour[stat] + left_ring[stat] + right_ring[stat] outfits.append(outfit) return outfits def equip(hero, outfit): equipped = {'co': 0, 'hp': hero['hp'], 'da': hero['da'], 'ar': hero['ar']} for stat in ['co', 'ar', 'da']: equipped[stat] += outfit[stat] return equipped def cheapest_victory(weapons, armours, rings, hero, boss): outfits = make_outfits(weapons, armours, rings) equipped = [equip(hero, outfit) for outfit in outfits] good_outfits = [o for o in equipped if victory(combat(o, boss.copy()))] by_cost = sorted(good_outfits, key = lambda outfit: outfit['co']) return by_cost[0]['co'] weapons = [ {'co': 8, 'da': 4, 'ar': 0}, {'co': 10, 'da': 5, 'ar': 0}, {'co': 25, 'da': 6, 'ar': 0}, {'co': 40, 'da': 7, 'ar': 0}, {'co': 74, 'da': 8, 'ar': 0} ] armours = [ {'co': 0, 'ar': 0, 'da': 0}, # no armor {'co': 13, 'ar': 1, 'da': 0}, {'co': 31, 'ar': 2, 'da': 0}, {'co': 53, 'ar': 3, 'da': 0}, {'co': 75, 'ar': 4, 'da': 0}, {'co': 102, 'ar': 5, 'da': 0}, ] rings = [ {'co': 0, 'ar': 0, 'da': 0}, # no ring {'co': 25, 'da': 1, 'ar': 0}, {'co': 50, 'da': 2, 'ar': 0}, {'co': 100, 'da': 3, 'ar': 0}, {'co': 20, 'ar': 1, 'da': 0}, {'co': 40, 'ar': 2, 'da': 0}, {'co': 80, 'ar': 3, 'da': 0} ] boss = parse_input(sys.stdin.readlines()) hero = {'hp': 100, 'da': 0, 'ar': 0} # Main if __name__ == '__main__': print(cheapest_victory(weapons, armours, rings, hero, boss))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day21_part1.py", "copies": "1", "size": "2859", "license": "mit", "hash": 257311788634485200, "line_mean": 30.7666666667, "line_max": 103, "alpha_frac": 0.4823364813, "autogenerated": false, "ratio": 2.8112094395280236, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8770995485095217, "avg_score": 0.004510087146561444, "num_lines": 90 }
"""Advent of Code 2015 - Day 2.""" from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() def one_paper(l, w, h): """Compute needed wrapping paper for one present. Arguments l, w, and h are expected to be sorted for a correct result. """ area = 2 * (l * w + l * h + w * h) slack = l * w return area + slack def one_ribbon(l, w, h): """Compute needed ribbon for one present. Arguments l, w, and h are expected to be sorted for a correct result. """ return 2 * (l + w) + l * w * h def main(): """Main entry point of puzzle solution.""" lines = read_input() paper = 0 ribbon = 0 for line in lines: dims = sorted(map(int, line.split('x'))) paper += one_paper(*dims) ribbon += one_ribbon(*dims) print('Part One: {}'.format(paper)) print('Part Two: {}'.format(ribbon)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-02/main.py", "copies": "1", "size": "1049", "license": "bsd-2-clause", "hash": 4655634703012188000, "line_mean": 21.8043478261, "line_max": 77, "alpha_frac": 0.5795996187, "autogenerated": false, "ratio": 3.450657894736842, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9521380701842639, "avg_score": 0.0017753623188405798, "num_lines": 46 }
"""Advent of Code 2015 - Day 3.""" import re from pathlib import Path def read_input(): """Read input file, return string, and drop unexpected characters.""" text = Path(__file__).with_name('input.txt').read_text() return re.sub(r'[^<>^v]', '', text) def read_instructions(): """Convert textual movement instructions to 2D offsets.""" item_to_offset = { '<': (-1, 0), '>': (+1, 0), '^': (0, -1), 'v': (0, +1), } return [item_to_offset[item] for item in read_input()] def walk(instructions): """Determine trail resulting from walking the given instruction.""" x = 0 y = 0 trail = {(x, y)} for x_offset, y_offset in instructions: x += x_offset y += y_offset trail.add((x, y)) return trail def walk_with_robo_santa(instructions): """Split instructions for real/robo Santa and let them walk in parallel.""" instructions_real_santa = instructions[0::2] instructions_robo_santa = instructions[1::2] return walk(instructions_real_santa) | walk(instructions_robo_santa) def main(): """Main entry point of puzzle solution.""" instructions = read_instructions() part_one = len(walk(instructions)) part_two = len(walk_with_robo_santa(instructions)) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-03/main.py", "copies": "1", "size": "1420", "license": "bsd-2-clause", "hash": 6275089963084746000, "line_mean": 23.4827586207, "line_max": 79, "alpha_frac": 0.5992957746, "autogenerated": false, "ratio": 3.514851485148515, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9614147259748514, "avg_score": 0, "num_lines": 58 }
# Advent of Code 2015 - Day 3 - Perfectly Spherical Houses in a Vacuum - Part 2 # http://adventofcode.com/2015/day/3 import sys # Return a list of visited houses given a moves list # The starting position counts as visited # This version uses two actors: Santa and a robot, moving each one after the other # This means that, starting with zero, even-numbered steps will move Santa and odd-numbered steps will move the robot def visited_positions_with_robot(directions): position_santa = (0, 0) position_robot = (0, 0) visited = [(0, 0)] for step_number in range(len(directions)): if step_number % 2 == 0: x, y = position_santa else: x, y = position_robot if directions[step_number] == '<': x -= 1 elif directions[step_number] == '>': x += 1 elif directions[step_number] == 'v': y -= 1 elif directions[step_number] == '^': y += 1 position = (x, y) if position not in visited: visited.append(position) if step_number % 2 == 0: position_santa = position else: position_robot = position return visited # Main directions = sys.stdin.readline().strip() print(len(visited_positions_with_robot(directions)))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day03_part2.py", "copies": "1", "size": "1311", "license": "mit", "hash": -7942631752647985000, "line_mean": 33.5, "line_max": 117, "alpha_frac": 0.6041189931, "autogenerated": false, "ratio": 3.8, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9895425384772819, "avg_score": 0.001738721665436242, "num_lines": 38 }
# Advent of Code 2015 - Day 5 - Doesn't He Have Intern-Elves For This? - Part 2 # http://adventofcode.com/2015/day/5 import sys # Return True if a string is "nice": # - contains a two-characters substring that appears twice # - contains one letter that appears twice with exactly one letter in between def is_nice(string): return has_double_pair(string) and has_pair_with_insert(string) # Return True if a string contains a two-characters substring that appears twice def has_double_pair(string): for substring in substrings(string, 2): first_position = string.find(substring) if first_position != -1 and string.find(substring, first_position + 2) != -1: return True return False # Return True if a string contains one letter that appears twice with exactly one letter in between def has_pair_with_insert(string): return any(map(lambda x: x[0] == x[-1], substrings(string, 3))) # Return a list of substrings of a given length def substrings(string, length): output = [] for i in range(len(string) - (length - 1)): output.append(string[i:i+length]) return output # Main strings = sys.stdin print(len(list(filter(is_nice, strings))))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day05_part2.py", "copies": "1", "size": "1202", "license": "mit", "hash": -7048110926507246000, "line_mean": 35.4242424242, "line_max": 99, "alpha_frac": 0.7038269551, "autogenerated": false, "ratio": 3.5667655786350148, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4770592533735015, "avg_score": null, "num_lines": null }
"""Advent of Code 2015 - Day 5.""" import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() def count_if(predicate, iterable): """Count the number of items of an iterable that satisfy predicate.""" return sum(1 for item in iterable if predicate(item)) class RulesOne: """Helper for checking words against the 1st set of niceness rules.""" # 1st rule: At least three vowels. _RULE_1 = re.compile(r'([aeiou].*){3,}') # 2nd rule: At least one letter twice in a row. _RULE_2 = re.compile(r'(.)\1') # 3rd rule: None of the listed letter pairs. _RULE_3 = re.compile(r'(ab|cd|pq|xy)') @classmethod def is_nice(cls, word): """Check if a word is nice according to the 1st set of rules.""" return (cls._RULE_1.search(word) and cls._RULE_2.search(word) and not cls._RULE_3.search(word)) class RulesTwo: """Helper for checking words against the 2nd set of niceness rules.""" # 1st rule: Two consecutive letters at least twice (no overlap). _RULE_1 = re.compile(r'(..).*\1') # 2nd rule: Repeated letter with exactly one letter between them. _RULE_2 = re.compile(r'(.).\1') @classmethod def is_nice(cls, word): """Check if a word is nice according to the 2nd set of rules.""" return cls._RULE_1.search(word) and cls._RULE_2.search(word) def main(): """Main entry point of puzzle solution.""" lines = read_input() part_one = count_if(RulesOne.is_nice, lines) part_two = count_if(RulesTwo.is_nice, lines) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-05/main.py", "copies": "1", "size": "1835", "license": "bsd-2-clause", "hash": 5024776283139555000, "line_mean": 27.671875, "line_max": 77, "alpha_frac": 0.6223433243, "autogenerated": false, "ratio": 3.475378787878788, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45977221121787876, "avg_score": null, "num_lines": null }
"""Advent of Code 2015 - Day 6.""" import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class Rect: """Rectangular region represented as a pair of ranges.""" def __init__(self, x_range, y_range): """Initialize a rectangle from a pair of ranges.""" self.x_range = x_range self.y_range = y_range def coordinates(self): """Yield all integer coordinate pairs covered by the rectangle.""" for x in self.x_range: for y in self.y_range: yield x, y class Command: """Command used for updating light arrays.""" # Regular expression for parsing commands from the input file. COMMAND_REGEXP = re.compile(r'^(toggle|turn (?:off|on)) ' r'(\d+),(\d+) through (\d+),(\d+)$') @classmethod def parse(cls, line): """Parse a command from a line of text read from the input file.""" action, *rect = cls.COMMAND_REGEXP.search(line).groups() x_min, y_min, x_max, y_max = map(int, rect) x_range = range(x_min, x_max + 1) y_range = range(y_min, y_max + 1) return cls(action, Rect(x_range, y_range)) def __init__(self, action, rect): """Initialize command from an action verb and a rectangular region.""" self.action = action self.rect = rect class LightArray: """Abstract rectangular light array that can be updated with commands.""" def __init__(self, width=1000, height=1000): """Initialize light array with all elements set to zero.""" self.matrix = [[0] * height for _ in range(width)] def apply_commands(self, commands): """Apply a list of commands to update the state of the light array.""" for command in commands: self._apply_command(command) return self def brightness(self): """Compute the total brightness of the light array.""" return sum(sum(column) for column in self.matrix) def _apply_command(self, command): """Update the state of the light array per the given command.""" mapping = self._action_to_mapping(command.action) for x, y in command.rect.coordinates(): self.matrix[x][y] = mapping(self.matrix[x][y]) class BinaryLightArray(LightArray): """Light array where elements are either on or off.""" # Actions and corresponding lambdas for updating the brightness. ACTION_TO_MAPPING = { 'toggle': lambda brightness: 1 - brightness, 'turn off': lambda _: 0, 'turn on': lambda _: 1, } def _action_to_mapping(self, action): """Map action to a callable that transforms the brightness.""" return self.ACTION_TO_MAPPING[action] class SteppedLightArray(LightArray): """Light array with positive integer brightness.""" # Actions and corresponding lambdas for updating the brightness. ACTION_TO_MAPPING = { 'toggle': lambda brightness: brightness + 2, 'turn off': lambda brightness: max(brightness - 1, 0), 'turn on': lambda brightness: brightness + 1, } def _action_to_mapping(self, action): """Map action to a callable that transforms the brightness.""" return self.ACTION_TO_MAPPING[action] def main(): """Main entry point of puzzle solution.""" commands = [Command.parse(line) for line in read_input()] part_one = BinaryLightArray().apply_commands(commands).brightness() part_two = SteppedLightArray().apply_commands(commands).brightness() print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-06/main.py", "copies": "1", "size": "3808", "license": "bsd-2-clause", "hash": 7656894385216288000, "line_mean": 31.2711864407, "line_max": 78, "alpha_frac": 0.6205357143, "autogenerated": false, "ratio": 4.072727272727272, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5193262987027272, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 6 - Probably a Fire Hazard # http://adventofcode.com/2015/day/6 import sys # Run one instruction and return the resulting lights array def run_instruction(instruction, lights): action, x_min, y_min, x_max, y_max = parse_instruction(instruction) for x in range(x_min, x_max + 1): for y in range(y_min, y_max + 1): if action == 'turn on': lights[x][y] = True elif action == 'turn off': lights[x][y] = False elif action == 'toggle': lights[x][y] = not lights[x][y] return lights # Parse one instruction def parse_instruction(instruction): if instruction.startswith('turn on'): action = 'turn on' elif instruction.startswith('turn off'): action = 'turn off' elif instruction.startswith('toggle'): action = 'toggle' else: action = None corners = instruction[len(action):].strip().split(' through ') x_min, y_min = map(int, corners[0].split(',')) x_max, y_max = map(int, corners[1].split(',')) return action, x_min, y_min, x_max, y_max # Count the lights that are in a lit state def count_lit_lights(lights): return sum(map(sum, lights)) # Main lights = [[False for x in range(1000)] for y in range(1000)] for instruction in sys.stdin: lights = run_instruction(instruction, lights) print(count_lit_lights(lights))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day06_part1.py", "copies": "1", "size": "1417", "license": "mit", "hash": -1257437476436986600, "line_mean": 32.7380952381, "line_max": 71, "alpha_frac": 0.6175017643, "autogenerated": false, "ratio": 3.430992736077482, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4548494500377482, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 6 - Probably a Fire Hazard - Part 2 # http://adventofcode.com/2015/day/6 import sys # Run one instruction and return the resulting lights array def run_instruction(instruction, lights): action, x_min, y_min, x_max, y_max = parse_instruction(instruction) for x in range(x_min, x_max + 1): for y in range(y_min, y_max + 1): if action == 'turn on': lights[x][y] += 1 elif action == 'turn off': lights[x][y] -= 1 if lights[x][y] > 0 else 0 elif action == 'toggle': lights[x][y] += 2 return lights # Parse one instruction def parse_instruction(instruction): if instruction.startswith('turn on'): action = 'turn on' elif instruction.startswith('turn off'): action = 'turn off' elif instruction.startswith('toggle'): action = 'toggle' else: action = None corners = instruction[len(action):].strip().split(' through ') x_min, y_min = map(int, corners[0].split(',')) x_max, y_max = map(int, corners[1].split(',')) return action, x_min, y_min, x_max, y_max # Count the lights that are in a lit state def count_lit_lights(lights): return sum(map(sum, lights)) # Main lights = [[0 for x in range(1000)] for y in range(1000)] for instruction in sys.stdin: lights = run_instruction(instruction, lights) print(count_lit_lights(lights))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day06_part2.py", "copies": "1", "size": "1430", "license": "mit", "hash": 4480704079025117700, "line_mean": 33.0476190476, "line_max": 71, "alpha_frac": 0.6118881119, "autogenerated": false, "ratio": 3.3966745843230406, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9496364542107594, "avg_score": 0.0024396308230894698, "num_lines": 42 }
"""Advent of Code 2015 - Day 7.""" import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class Literal: """Literal with an integer value.""" def __init__(self, value): """Initialize a literal with its value.""" self.value = value class Variable: """Variable with a name.""" def __init__(self, name): """Initialize a variable with its name.""" self.name = name class Gate: """Gate representing a constant, variable, or bit-wise operation.""" # Regular expression for parsing gate expressions. EXPR_REGEXP = re.compile(r'^(?:(?:([a-z]+|\d+) )?([A-Z]+) )?([a-z]+|\d+)$') @classmethod def from_expr(cls, expr): """Initialize a gate by parsing an expression.""" lhs, operator, rhs = cls.EXPR_REGEXP.search(expr).groups() return cls(cls._parse_operand(lhs), operator, cls._parse_operand(rhs)) @staticmethod def _parse_operand(operand): """Parse operand and return a literal, a variable, or nothing.""" if operand is None: return None elif re.search(r'^\d+$', operand): return Literal(int(operand)) else: return Variable(operand) def __init__(self, lhs, operator, rhs): """Initialize a gate from LHS, operator, and RHS.""" self._value = None self.lhs = lhs self.operator = operator self.rhs = rhs def eval(self, circuit): """Evaluate the value of the gate and cache it for later retrieval.""" if self._value is None: self._value = self._eval(circuit) return self._value def flush(self): """Flush cache with previously computed gate value.""" self._value = None def _eval(self, circuit): """Prepare operands and perform actual evaluation of the gate.""" lhs = self._fetch(circuit, self.lhs) rhs = self._fetch(circuit, self.rhs) if self.operator is None: return rhs elif self.operator == 'AND': return lhs & rhs elif self.operator == 'LSHIFT': return lhs << rhs elif self.operator == 'NOT': return ~rhs elif self.operator == 'OR': return lhs | rhs elif self.operator == 'RSHIFT': return lhs >> rhs def _fetch(self, circuit, operand): """Fetch operand, possibly delegating to circuit for wire reference.""" if operand is None: return None elif isinstance(operand, Literal): return operand.value elif isinstance(operand, Variable): return circuit.eval(operand.name) class Circuit: """Logic circuit represented by a bunch of named gates.""" # Regular expression for parsing gates from the input file. GATE_REGEXP = re.compile(r'^(.+) -> ([a-z]+)$') @classmethod def from_lines(cls, lines): """Initialize a logic circuit from lines from the input file.""" circuit = cls() for line in lines: expr, wire = cls.GATE_REGEXP.search(line).groups() circuit.wire_gate(wire, expr) return circuit def __init__(self): """Initialize an empty logic circuit.""" self.gates = {} def eval(self, wire): """Evaluate a wire by asking the associated gate for its value.""" return self.gates[wire].eval(self) def flush(self): """Flush caches of all gates in the circuit.""" for gate in self.gates.values(): gate.flush() # Simplify chaining method calls. return self def wire_gate(self, wire, expr): """Parse a gate expression and assign it to a wire.""" self.gates[wire] = Gate.from_expr(expr) # Simplify chaining method calls. return self def main(): """Main entry point of puzzle solution.""" circuit = Circuit.from_lines(read_input()) part_one = circuit.eval('a') part_two = circuit.flush().wire_gate('b', str(part_one)).eval('a') print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-07/main.py", "copies": "1", "size": "4321", "license": "bsd-2-clause", "hash": -101252457394250260, "line_mean": 28.1959459459, "line_max": 79, "alpha_frac": 0.5815783383, "autogenerated": false, "ratio": 4.1748792270531405, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5256457565353141, "avg_score": null, "num_lines": null }
# Advent of Code 2015 - Day 7 - Some Assembly Required # http://adventofcode.com/2015/day/7 import sys GATE_INPUT = 0 GATE_NOT = 1 GATE_AND = 2 GATE_OR = 3 GATE_RSHIFT = 4 GATE_LSHIFT = 5 GATE_CONNECT = 6 # Parse the input and return a map def parse_input(s): circuit = {} for line in s: gate, output = line.strip().split(' -> ') if gate.isdigit(): operator = GATE_INPUT operand_a = int(gate) operand_b = None elif 'NOT' in gate: operator = GATE_NOT operand_a = gate[4:] operand_b = None elif 'AND' in gate: operator = GATE_AND operand_a, operand_b = gate.split(' AND ') elif 'OR' in gate: operator = GATE_OR operand_a, operand_b = gate.split(' OR ') elif 'RSHIFT' in gate: operator = GATE_RSHIFT operand_a, operand_b = gate.split(' RSHIFT ') operand_b = int(operand_b) elif 'LSHIFT' in gate: operator = GATE_LSHIFT operand_a, operand_b = gate.split(' LSHIFT ') operand_b = int(operand_b) else: # eg a -> b operator = GATE_CONNECT operand_a = gate operand_b = None circuit[output] = (operator, operand_a, operand_b) return circuit # Solve the circuit for a given wire def solve_for(circuit, memo, wire): # Some gates have direct inputs if wire.isdigit(): return int(wire) if not wire in memo: operator, operand_a, operand_b = circuit[wire] if operator == GATE_INPUT: result = operand_a elif operator == GATE_NOT: result = ~solve_for(circuit, memo, operand_a) elif operator == GATE_AND: result = solve_for(circuit, memo, operand_a) & solve_for(circuit, memo, operand_b) elif operator == GATE_OR: result = solve_for(circuit, memo, operand_a) | solve_for(circuit, memo, operand_b) elif operator == GATE_RSHIFT: result = solve_for(circuit, memo, operand_a) >> operand_b elif operator == GATE_LSHIFT: result = solve_for(circuit, memo, operand_a) << operand_b elif operator == GATE_CONNECT: result = solve_for(circuit, memo, operand_a) memo[wire] = result return memo[wire] # Cast as unsigned 16-bit integer def u16(integer): return integer & 0xFFFF # Main if __name__ == '__main__': circuit = parse_input(sys.stdin.readlines()) print(u16(solve_for(circuit, {}, 'a')))
{ "repo_name": "jkbockstael/adventofcode-2015", "path": "day07_part1.py", "copies": "1", "size": "2574", "license": "mit", "hash": 1252661258661063000, "line_mean": 31.582278481, "line_max": 94, "alpha_frac": 0.5629370629, "autogenerated": false, "ratio": 3.6, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.964829003746017, "avg_score": 0.002929405087966047, "num_lines": 79 }
"""Advent of Code 2015 - Day 9.""" import itertools import re from pathlib import Path def read_input(): """Read input file and split into individual lines returned as a list.""" return Path(__file__).with_name('input.txt').read_text().splitlines() class CityMap: """Map of cities and their mutual distances.""" # Regular expression for parsing city pair distances from the input file. CITY_PAIR_REGEXP = re.compile(r'^(.+) to (.+) = (\d+)$') @classmethod def from_lines(cls, lines): """Initialize a map from lines read from the input file.""" city_map = cls() for line in lines: source, target, dist = cls.CITY_PAIR_REGEXP.search(line).groups() city_map.add_city_pair(source, target, int(dist)) return city_map def __init__(self): """Initialize an empty map.""" self.city = {} self.link = {} def add_city_pair(self, source, target, dist): """Add a pair of cities and their mutual distance to the map.""" source_id = self.city.setdefault(source, len(self.city)) target_id = self.city.setdefault(target, len(self.city)) self.link[(source_id, target_id)] = dist self.link[(target_id, source_id)] = dist def routes(self): """Yield all possible routes between cities.""" for city_list in itertools.permutations(self.city.values()): yield city_list[:-1], city_list[1:] def route_lengths(self): """Yield the lengths of all possible routes between cities.""" for sources, targets in self.routes(): yield sum(self.link[pair] for pair in zip(sources, targets)) def main(): """Main entry point of puzzle solution.""" route_lengths = list(CityMap.from_lines(read_input()).route_lengths()) part_one = min(route_lengths) part_two = max(route_lengths) print('Part One: {}'.format(part_one)) print('Part Two: {}'.format(part_two)) if __name__ == '__main__': main()
{ "repo_name": "UniqMartin/adventofcode-2015", "path": "day-09/main.py", "copies": "1", "size": "2016", "license": "bsd-2-clause", "hash": 4819158294097842000, "line_mean": 30.5, "line_max": 77, "alpha_frac": 0.6130952381, "autogenerated": false, "ratio": 3.8037735849056604, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.491686882300566, "avg_score": null, "num_lines": null }
"""advent of code 2015 no. 6""" class Matrix(object): """represents the grid""" def __init__(self, width, height): super(Matrix, self).__init__() self.width = width self.height = height self.array = [[0 for x in range(width)] for x in range(height)] def _toggle(self, x, y): self.array[x][y] += 2 # value = self.array[x][y] # if value == 0: # self.array[x][y] = 1 # else: # self.array[x][y] = 0 def _processArea(self, operation, x1, y1, x2, y2): assert x1 < x2 and y1 < y2 for x in range(x1, x2+1): for y in range(y1, y2+1): if operation == 'toggle': self._toggle(x, y) elif operation == 'on': self._on(x, y) elif operation == 'off': self._off(x, y) else: raise AttributeError("illegal operation " + operation) def _on(self, x, y): self.array[x][y] += 1 def _off(self, x, y): if self.array[x][y] > 0: self.array[x][y] -= 1 def _isOn(self, x, y): return self.array[x][y] > 0 def _getBrightness(self, x, y): return self.array[x][y] def getTotalBrighness(self): totalBrightness = 0 for x in range(self.width): for y in range(self.height): totalBrightness += self.array[x][y] return totalBrightness def getLitLights(self): counter = 0 totalChecked = 0 for x in range(self.width): for y in range(self.height): totalChecked += 1 if self._isOn(x, y): counter += 1 assert totalChecked == self.width * self.height return counter def execute(self, line): elements = line.split() if len(elements) < 4: raise Exception('invalid line') if elements[0] == 'turn': operation = elements[1] corner1 = elements[2] corner2 = elements[4] self._processArea( operation, int(corner1.split(',')[0]), int(corner1.split(',')[1]), int(corner2.split(',')[0]), int(corner2.split(',')[1])) elif elements[0] == 'toggle': operation = elements[0] corner1 = elements[1] corner2 = elements[3] self._processArea( operation, int(corner1.split(',')[0]), int(corner1.split(',')[1]), int(corner2.split(',')[0]), int(corner2.split(',')[1])) else: raise Exception("Illegal argument: "+elements[0]) # if line.startswith('turn'): def main(): grid = Matrix(1000, 1000) assert grid.getLitLights() == 0 with open('input6.txt') as infile: line = infile.readline() while line: grid.execute(line) line = infile.readline() print "lit lights: " + str(grid.getLitLights()) print "brighness:" + str(grid.getTotalBrighness()) if __name__ == '__main__': main()
{ "repo_name": "FilipBrinkmann/adventofcode2015", "path": "advent6/advent6.py", "copies": "1", "size": "3214", "license": "apache-2.0", "hash": 6709457074320303000, "line_mean": 29.6095238095, "line_max": 74, "alpha_frac": 0.4797759801, "autogenerated": false, "ratio": 3.8035502958579883, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4783326275957988, "avg_score": null, "num_lines": null }
## Advent of code 2016, AoC day 15 part 1. ## This solution (python2.7) by kannix68, @ 2016-12-16. ##** imports import re ##** Helpers def assert_msg(assertion, msg): assert assertion, "ERROR on assert: {}".format(msg) print "assert-OK: {}".format(msg) def reverse_str(s): #return s[::-1] return "".join(reversed(s)) def copy_full(inlist): # < deep-copy of list-of-lists if isinstance(inlist, list): return list( map(copy_full, inlist) ) return inlist ##** Problem domain functions def parse_disks(mlstr): rx = '''^Disc #(\d+) has (\d+) positions; at time=(\d+), it is at position (\d+).$''' rxc = re.compile(rx) strdata = input.splitlines() disks = [] print "disks={}".format(disks) for line in strdata: # iterate lines print "line={}".format(line) mr = rxc.match(line) #print " rx result={}".format(mr) disknr = mr.group(1) numposns = mr.group(2) diskt0 = mr.group(3) post0 = mr.group(4) print " rx mresult={}, {}, {}, {}".format(disknr, numposns, diskt0, post0) inner = [int(numposns), int(post0)] disks.append(inner) print "disks={}".format(disks) return disks def tick(disks): res = copy_full(disks) loop = 0 #print "tick:" for disk in res: loop += 1 newpos = (disk[1] + 1) % disk[0] #print " disc#{} newpos={}; from pos={} of #disks={}".format(loop, newpos, disk[1], disk[0]) disk[1] = newpos return res def tick_n(disks, ticks): res = copy_full(disks) loop = 0 #print "tick:" for disk in res: loop += 1 newpos = (disk[1] + ticks) % disk[0] #print " disc#{} newpos={}; from pos={} of #disks={}".format(loop, newpos, disk[1], disk[0]) disk[1] = newpos return res def process(disks): max_preticks = 1000000 #10000 # CONSTANT numdisks = len(disks) print "found num disks={}".format(numdisks) initdisks = copy_full(disks) state = False preticks = -1 while state == False and preticks < max_preticks: preticks += 1 disks = initdisks #print "preticks={}".format(preticks) #for n in range(preticks): # n preticks clockticks # disks = tick(disks) disks = tick_n(disks, preticks) for n in range(numdisks): #print " loop t={} n={}".format(preticks+n, n) disks = tick(disks) state = disks[n][1] == 0 if not state: if n > 1: print " loop n={} FAIL for disk {}; preticks t0={}; tsum={}".format(n, n, preticks, preticks+n) break #else: # #print " ok for disk {}".format(n) #-print "State={} after disc-ticks={} and pre-ticks={}.".format(state,numdisks, preticks) if state == True: return preticks else: return -preticks ## INITialisation # nothing to do ## MAIN ##** testing input = ''' Disc #1 has 5 positions; at time=0, it is at position 4. Disc #2 has 2 positions; at time=0, it is at position 1. '''.strip() disks = parse_disks(input) t0 = process(disks) print "TEST t0 !=! {}".format(t0) ##** problem domain input = ''' Disc #1 has 13 positions; at time=0, it is at position 10. Disc #2 has 17 positions; at time=0, it is at position 15. Disc #3 has 19 positions; at time=0, it is at position 17. Disc #4 has 7 positions; at time=0, it is at position 1. Disc #5 has 5 positions; at time=0, it is at position 0. Disc #6 has 3 positions; at time=0, it is at position 1. '''.strip() disks = parse_disks(input) t0 = process(disks) print "RESULT t0 !=! {}".format(t0)
{ "repo_name": "kannix68/advent_of_code_2016", "path": "day15/day15a.py", "copies": "1", "size": "3441", "license": "mit", "hash": 1549045817122583000, "line_mean": 25.4692307692, "line_max": 106, "alpha_frac": 0.6120313862, "autogenerated": false, "ratio": 2.98438855160451, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8969278258212671, "avg_score": 0.025428335918367833, "num_lines": 130 }
## Advent of code 2016, AoC day 15 part 2. ## This solution (python2.7) by kannix68, @ 2016-12-16. ##** imports import re ##** Helpers def assert_msg(assertion, msg): assert assertion, "ERROR on assert: {}".format(msg) print "assert-OK: {}".format(msg) def reverse_str(s): #return s[::-1] return "".join(reversed(s)) def copy_full(inlist): # < deep-copy of list-of-lists if isinstance(inlist, list): return list( map(copy_full, inlist) ) return inlist ##** Problem domain functions def parse_disks(mlstr): rx = '''^Disc #(\d+) has (\d+) positions; at time=(\d+), it is at position (\d+).$''' rxc = re.compile(rx) strdata = input.splitlines() disks = [] print "disks={}".format(disks) for line in strdata: # iterate lines print "line={}".format(line) mr = rxc.match(line) #print " rx result={}".format(mr) disknr = mr.group(1) numposns = mr.group(2) diskt0 = mr.group(3) post0 = mr.group(4) print " rx mresult={}, {}, {}, {}".format(disknr, numposns, diskt0, post0) inner = [int(numposns), int(post0)] disks.append(inner) print "disks={}".format(disks) return disks def tick(disks): res = copy_full(disks) loop = 0 #print "tick:" for disk in res: loop += 1 newpos = (disk[1] + 1) % disk[0] #print " disc#{} newpos={}; from pos={} of #disks={}".format(loop, newpos, disk[1], disk[0]) disk[1] = newpos return res def tick_n(disks, ticks): res = copy_full(disks) loop = 0 #print "tick:" for disk in res: loop += 1 newpos = (disk[1] + ticks) % disk[0] #print " disc#{} newpos={}; from pos={} of #disks={}".format(loop, newpos, disk[1], disk[0]) disk[1] = newpos return res def process(disks): max_preticks = 1000000*11*2 #10000 # CONSTANT numdisks = len(disks) print "found num disks={}".format(numdisks) initdisks = copy_full(disks) state = False preticks = -1 while state == False and preticks < max_preticks: preticks += 1 disks = initdisks #print "preticks={}".format(preticks) #for n in range(preticks): # n preticks clockticks # disks = tick(disks) disks = tick_n(disks, preticks) for n in range(numdisks): #print " loop t={} n={}".format(preticks+n, n) disks = tick(disks) state = disks[n][1] == 0 if not state: if n > 3: print " loop n={} FAIL for disk {}; preticks t0={}; tsum={}".format(n, n, preticks, preticks+n) break #else: # #print " ok for disk {}".format(n) #-print "State={} after disc-ticks={} and pre-ticks={}.".format(state,numdisks, preticks) if state == True: return preticks else: return -preticks ## INITialisation # nothing to do ## MAIN ##** testing input = ''' Disc #1 has 5 positions; at time=0, it is at position 4. Disc #2 has 2 positions; at time=0, it is at position 1. '''.strip() disks = parse_disks(input) t0 = process(disks) print "TEST t0 !=! {}".format(t0) ##** problem domain input = ''' Disc #1 has 13 positions; at time=0, it is at position 10. Disc #2 has 17 positions; at time=0, it is at position 15. Disc #3 has 19 positions; at time=0, it is at position 17. Disc #4 has 7 positions; at time=0, it is at position 1. Disc #5 has 5 positions; at time=0, it is at position 0. Disc #6 has 3 positions; at time=0, it is at position 1. Disc #7 has 11 positions; at time=0, it is at position 0. '''.strip() disks = parse_disks(input) t0 = process(disks) print "RESULT t0 !=! {}".format(t0)
{ "repo_name": "kannix68/advent_of_code_2016", "path": "day15/day15b.py", "copies": "1", "size": "3504", "license": "mit", "hash": -4396208222747435500, "line_mean": 25.7480916031, "line_max": 106, "alpha_frac": 0.6135844749, "autogenerated": false, "ratio": 2.979591836734694, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4093176311634694, "avg_score": null, "num_lines": null }
## Advent of code 2016, AoC day 16 part 1. ## This solution (python2.7) by kannix68, @ 2016-12-16. def assert_msg(assertion, msg): assert assertion, "ERROR on assert: {}".format(msg) print "assert-OK: {}".format(msg) def reverse_str(s): #return s[::-1] return "".join(reversed(s)) def gen_pseudorand_data(input): a = input b = reverse_str(input) b = b.replace("0","o").replace("1","0").replace("o","1") return "{}0{}".format(a,b) def gen_filldisk_data(input, disklen): intermed = input while True: intermed = gen_pseudorand_data(intermed) print "loop: intermed-filldiskdata={}".format(intermed) if len(intermed) >= disklen: break # while if len(intermed) != disklen: intermed = intermed[0:disklen] return intermed def gen_cksum(input): n = 2 chk = 0 intermed = input started = False while (not started) or (chk % 2 == 0): started = True zz = "" print "loop: intermed-cksum={}".format(intermed) for i in range(0, len(intermed), n): p = intermed[i:i+n] #print " pair={}".format(p) if p == "00" or p == "11": zz += "1" else: zz += "0" intermed = zz chk = len(intermed) #print " zz={}, chk-len={}, chk-len % 2={}".format(zz,chk,chk%2) return zz def process(input, disklen): filldiskdata = gen_filldisk_data(input, disklen) diskcksum = gen_cksum(filldiskdata) print "process: cksum={}, filldiskdata={}".format(diskcksum, filldiskdata) return [filldiskdata, diskcksum] ## INITialisation # nothing to do ## MAIN ##** testing # 1 becomes 100. # 0 becomes 001. # 11111 becomes 11111000000. # 111100001010 becomes 1111000010100101011110000. input = "1" expected = "100" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "0" expected = "001" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "11111" expected = "11111000000" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "111100001010" expected = "1111000010100101011110000" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "110010110100" expected = "100" result = gen_cksum(input) assert_msg( result == expected, "result cksum={} expected={} of input={}".format(result, expected, input)) #** testing, "whole process" input = "10000" disklen = 20 expected = "10000011110010000111" diskdata = gen_filldisk_data(input, disklen) result = diskdata assert_msg( result == expected, "result diskdata={} expected={} of input={}".format(result, expected, input)) # >continue> input = diskdata expected = "01100" result = gen_cksum(input) assert_msg( result == expected, "result disk-cksum={} expected={} of input={}".format(result, expected, input)) result_ary = process(input, disklen) print "test process-result: {}".format(result_ary) ##** problem domain input = "10111011111001111" disklen = 272 result = process(input, disklen) print "RESULT cksum={}".format(result[1])
{ "repo_name": "kannix68/advent_of_code_2016", "path": "day16/day16a.py", "copies": "1", "size": "3263", "license": "mit", "hash": -4955074703425305000, "line_mean": 27.3739130435, "line_max": 111, "alpha_frac": 0.6662580447, "autogenerated": false, "ratio": 3.012927054478301, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4179185099178301, "avg_score": null, "num_lines": null }
## Advent of code 2016, AoC day 16 part 2. ## This solution (python2.7) by kannix68, @ 2016-12-16. def assert_msg(assertion, msg): assert assertion, "ERROR on assert: {}".format(msg) print "assert-OK: {}".format(msg) def reverse_str(s): #return s[::-1] return "".join(reversed(s)) def gen_pseudorand_data(input): a = input b = reverse_str(input) b = b.replace("0","o").replace("1","0").replace("o","1") return "{}0{}".format(a,b) def gen_filldisk_data(input, disklen): intermed = input while True: intermed = gen_pseudorand_data(intermed) #print "loop: intermed-filldiskdata={}".format(intermed) if len(intermed) >= disklen: break # while if len(intermed) != disklen: intermed = intermed[0:disklen] return intermed def gen_cksum(input): n = 2 chk = 0 intermed = input started = False while (not started) or (chk % 2 == 0): started = True zz = "" #print "loop: intermed-cksum={}".format(intermed) for i in range(0, len(intermed), n): p = intermed[i:i+n] #print " pair={}".format(p) if p == "00" or p == "11": zz += "1" else: zz += "0" intermed = zz chk = len(intermed) #print " zz={}, chk-len={}, chk-len % 2={}".format(zz,chk,chk%2) return zz def process(input, disklen): filldiskdata = gen_filldisk_data(input, disklen) diskcksum = gen_cksum(filldiskdata) #print "process: cksum={}, filldiskdata={}".format(diskcksum, filldiskdata) return [filldiskdata, diskcksum] ## INITialisation # nothing to do ## MAIN ##** testing # 1 becomes 100. # 0 becomes 001. # 11111 becomes 11111000000. # 111100001010 becomes 1111000010100101011110000. input = "1" expected = "100" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "0" expected = "001" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "11111" expected = "11111000000" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "111100001010" expected = "1111000010100101011110000" result = gen_pseudorand_data(input) assert_msg( result == expected, "result enc={} expected={} of input={}".format(result, expected, input)) input = "110010110100" expected = "100" result = gen_cksum(input) assert_msg( result == expected, "result cksum={} expected={} of input={}".format(result, expected, input)) #** testing, "whole process" input = "10000" disklen = 20 expected = "10000011110010000111" diskdata = gen_filldisk_data(input, disklen) result = diskdata assert_msg( result == expected, "result diskdata={} expected={} of input={}".format(result, expected, input)) # >continue> input = diskdata expected = "01100" result = gen_cksum(input) assert_msg( result == expected, "result disk-cksum={} expected={} of input={}".format(result, expected, input)) result_ary = process(input, disklen) print "test process-result: {}".format(result_ary) ##** problem domain input = "10111011111001111" disklen = 35651584 result = process(input, disklen) print "RESULT cksum={}".format(result[1])
{ "repo_name": "kannix68/advent_of_code_2016", "path": "day16/day16b.py", "copies": "1", "size": "3271", "license": "mit", "hash": -1943915277998864400, "line_mean": 27.4434782609, "line_max": 111, "alpha_frac": 0.6661571385, "autogenerated": false, "ratio": 3.0064338235294117, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4172590962029412, "avg_score": null, "num_lines": null }
input = open("day3.txt", 'r').readlines() # Quick-o triangle check def is_triangle(trig): trig.sort() return ((trig[0] + trig[1]) > trig[2]) def part1(): trigs = 0 for sides in input: line = sides.split() trig = [int(line[0]), int(line[1]), int(line[2])] if is_triangle(trig): trigs += 1 print (trigs) def part2(): trigs = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] dimension = 0 count = 0 for sides in input: line = sides.split() for i in range(0, 3): trigs[i][dimension] = int(line[i]) if dimension is not 2: dimension += 1 continue else: # We've reached the third line, time to start the next 3 triangles dimension = 0 for i in range(0, 3): if is_triangle(trigs[i]): count += 1 trigs = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] print (count)
{ "repo_name": "ChbShoot/advent-of-code", "path": "2016/day3.py", "copies": "1", "size": "1025", "license": "mit", "hash": 1339611723680883200, "line_mean": 26, "line_max": 80, "alpha_frac": 0.4956097561, "autogenerated": false, "ratio": 3.144171779141104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4139781535241104, "avg_score": null, "num_lines": null }
input = open('day8.txt', 'r').read().split('\n') width = 50 height = 6 screen = [ [ 0 for __ in range(width) ] for _ in range (height)] import sys def rect(a,b): global screen for row in range (int(b)): #total height for col in range (int(a)): # across our row screen[row][col] = 1 def rotate(row, n): return (row[-int(n):] + row[:-int(n)]) def rotate_row(a,b): global screen screen[int(a)] = rotate(screen[int(a)], int(b)) def rotate_col(a, b): global screen col = [screen[i][int(a)] for i in range(height)] # turn our col into a row col = rotate(col, int(b)) for i in range(height): screen[i][int(a)] = col[i] for line in input: line = line.split() if 'rect' in line: #we have a rect op (a,b) = line[1].split('x') rect(a, b) print ("RECT A: {0}, B:{1}".format(a, b)) if 'row' in line: #we have a row op a = line[2][line[2].find('=') + 1:] b = line[4] rotate_row(a,b) print ("ROW A: {0}, B:{1}".format(a, b)) if 'column' in line: a = line[2][line[2].find('=') + 1:] b = line[4] rotate_col(a,b) print ("COL A: {0}, B:{1}".format(a, b)) def lit (): # it is not lit.. IT'S NOT lit. its lit again global screen return sum(sum(line) for line in screen) def display(): for y in range(height): for x in range(width): if screen[y][x]: sys.stdout.write('@') else: sys.stdout.write(' ') sys.stdout.write('\n') print ('Part 1: {0} lit.'.format(lit())) print ('Part 2:') display()
{ "repo_name": "ChbShoot/advent-of-code", "path": "2016/day8.py", "copies": "1", "size": "1707", "license": "mit", "hash": 6151136523667628000, "line_mean": 27.4666666667, "line_max": 78, "alpha_frac": 0.5243116579, "autogenerated": false, "ratio": 2.989492119089317, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4013803776989317, "avg_score": null, "num_lines": null }
"""Advent of Code 2018 Day 1: Chronal Calibration""" import itertools import aoc_common import pytest DAY = 1 PART_ONE_CASES = [ ('+1\n+1\n+1', 3), ('+1\n+1\n-2', 0), ('-1\n-2\n-3', -6), ] @pytest.mark.parametrize('puzzle_input,expected', PART_ONE_CASES) def test_solve_part_one(puzzle_input, expected): assert solve_part_one(puzzle_input) == expected @pytest.mark.parametrize('puzzle_input,expected', [ ('+1\n-1', 0), ('+3\n+3\n+4\n-2\n-4', 10), ('-6\n+3\n+8\n+5\n-6', 5), ('+7\n+7\n-2\n-7\n-4', 14), ]) def test_solve_part_two(puzzle_input, expected): assert solve_part_two(puzzle_input) == expected @pytest.mark.parametrize('puzzle_input,parsed', zip( (case_input for case_input, expected in PART_ONE_CASES), ([1, 1, 1], [1, 1, -2], [-1, -2, -3]) )) def test_parse(puzzle_input, parsed): assert parse(puzzle_input) == parsed def test_known_part_one_solution(): part_one_solution = 400 puzzle_input = aoc_common.load_puzzle_input(DAY) assert solve_part_one(puzzle_input) == part_one_solution def test_known_part_two_solution(): part_two_solution = 232 puzzle_input = aoc_common.load_puzzle_input(DAY) assert solve_part_two(puzzle_input) == part_two_solution def parse(puzzle_input): """Parses puzzle input into a list of ints""" return [int(n) for n in puzzle_input.splitlines()] def solve_part_one(puzzle_input): """Return the sum of the frequency changes listed in input""" frequency_changes = parse(puzzle_input) return sum(frequency_changes) def solve_part_two(puzzle_input): """Return the first repeated frequency""" frequency_changes = parse(puzzle_input) frequency = 0 seen = {frequency} for change in itertools.cycle(frequency_changes): frequency += change if frequency in seen: return frequency seen.add(frequency) if __name__ == '__main__': puzzle_input = aoc_common.load_puzzle_input(DAY) print(__doc__) part_one_solution = solve_part_one(puzzle_input) print('Part one:', part_one_solution) part_two_solution = solve_part_two(puzzle_input) print('Part two:', part_two_solution)
{ "repo_name": "robjwells/adventofcode-solutions", "path": "2018/python/2018_01.py", "copies": "1", "size": "2188", "license": "mit", "hash": 3647309820643076000, "line_mean": 25.0476190476, "line_max": 65, "alpha_frac": 0.6467093236, "autogenerated": false, "ratio": 2.9408602150537635, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9087569538653764, "avg_score": 0, "num_lines": 84 }
"""Advent of Code 2018 Day 2: Inventory Management System""" from collections import Counter import aoc_common DAY = 2 def test_solve_part_one(): """solve_part_one produces correct checksum for box ids""" puzzle_input = '\n'.join([ 'abcdef', 'bababc', 'abbcde', 'abcccd', 'aabcdd', 'abcdee', 'ababab', ]) expected = 12 assert solve_part_one(puzzle_input) == expected def test_known_part_one_solution(): part_one_solution = 9633 puzzle_input = aoc_common.load_puzzle_input(DAY) assert solve_part_one(puzzle_input) == part_one_solution def test_solve_part_two(): """solve_part_two returns common letters between almost-matching ids Almost-matching is defined as differing at one position in the string. """ puzzle_input = '\n'.join([ 'abcde', 'fghij', 'klmno', 'pqrst', 'fguij', 'axcye', 'wvxyz', ]) expected = 'fgij' assert solve_part_two(puzzle_input) == expected def test_known_part_two_solution(): part_two_solution = 'lujnogabetpmsydyfcovzixaw' puzzle_input = aoc_common.load_puzzle_input(DAY) assert solve_part_two(puzzle_input) == part_two_solution def solve_part_one(puzzle_input): """Return checksum of box ids provided in puzzle input""" return checksum(puzzle_input.split('\n')) def checksum(box_ids): """Return integer checksum of box_ids list Checksum is defined as the number of ids containing exactly two of any letter, multiplied by the number of ids that contain exactly three of any letter. """ two_count = boxes_with_n_of_any_letter(box_ids, 2) three_count = boxes_with_n_of_any_letter(box_ids, 3) return two_count * three_count def boxes_with_n_of_any_letter(boxes, count): """Returns the number of boxes where a letter appears `count` times""" return sum(some_element_appers_n_times(box, count) for box in boxes) def some_element_appers_n_times(iterable, count): """Returns whether any element of string appears exactly `count` times""" return count in Counter(iterable).values() def solve_part_two(puzzle_input): """Return matching characters of two almost-identical box ids The box ids differ at only one character position, and the string returned is the common box id absent the differing position. """ first, second = first_almost_matching_pair(puzzle_input.split('\n')) matching_letters = ''.join(a for a, b in zip(first, second) if a == b) return matching_letters def first_almost_matching_pair(strings): """Return the first two strings that differ by only one position""" for x in strings: for y in strings: number_of_differing_positions = sum( char_x != char_y for char_x, char_y in zip(x, y)) if number_of_differing_positions == 1: return x, y if __name__ == '__main__': puzzle_input = aoc_common.load_puzzle_input(DAY) print(__doc__) part_one_solution = solve_part_one(puzzle_input) print('Part one:', part_one_solution) part_two_solution = solve_part_two(puzzle_input) print('Part two:', part_two_solution)
{ "repo_name": "robjwells/adventofcode-solutions", "path": "2018/python/2018_02.py", "copies": "1", "size": "3154", "license": "mit", "hash": -8621042360641065000, "line_mean": 29.6213592233, "line_max": 77, "alpha_frac": 0.665187064, "autogenerated": false, "ratio": 3.439476553980371, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46046636179803707, "avg_score": null, "num_lines": null }
# Advent of Code 2019 Solutions: Day 2, Puzzle 2 # https://github.com/emddudley/advent-of-code-solutions with open('input', 'r') as f: memory = [int(x) for x in f.read().strip().split(',')] done = False for noun in range(0, 100): for verb in range(0, 100): program = memory.copy() program[1] = noun program[2] = verb for opcode_index in range(0, len(program), 4): opcode = program[opcode_index] if opcode == 99: break addr_a = program[opcode_index + 1] addr_b = program[opcode_index + 2] dest = program[opcode_index + 3] if opcode == 1: program[dest] = program[addr_a] + program[addr_b] elif opcode == 2: program[dest] = program[addr_a] * program[addr_b] if program[0] == 19690720: print(noun) print(verb) print(100 * noun + verb) done = True break if done: break
{ "repo_name": "emddudley/advent-of-code-solutions", "path": "2019/day-2/advent-2019-day-2-puzzle-2.py", "copies": "1", "size": "1026", "license": "unlicense", "hash": 4835435443597699000, "line_mean": 25.3076923077, "line_max": 65, "alpha_frac": 0.5097465887, "autogenerated": false, "ratio": 3.612676056338028, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4622422645038028, "avg_score": null, "num_lines": null }
"""adventofcode 5""" import re def hasMinVowels(amount, string): count = 0 for i in xrange(0, len(string)): if string[i] in ['a','e','i','o','u']: count += 1 if count >= amount: return True return False def hasDoubleLetter(string): if len(string) == 0: return False lastletter = None for i in xrange(0, len(string)): if string[i] is lastletter: return True else: lastletter = string[i] return False def containsBadSequence(string): for sequence in ['ab', 'cd', 'pq', 'xy']: if sequence in string: return True return False def containsDoublePairs(line): if len(line) < 4: return False for i in xrange(0, len(line)-1): pattern = line[i:i+2] for j in xrange(i+2,len(line)-1): sequence = line[j:j+2] if len(sequence) is 2: # print "comparing " + pattern + " <-> " + sequence if pattern == sequence: return True return False def containsRepeatingLetter(line): if len(line) < 3: return False for i in xrange(0, len(line)-2): if line[i] == line [i+2]: return True return False def isNice(line): # return (hasMinVowels(3, line) and hasDoubleLetter(line) and not containsBadSequence(line)) return containsDoublePairs(line) and containsRepeatingLetter(line) # Tests for containsDoublePairs() assert not containsDoublePairs('') assert not containsDoublePairs('aaa') assert not containsDoublePairs('abc') assert not containsDoublePairs('abcde') assert containsDoublePairs('abfeab') assert containsDoublePairs('abab') # Tests for containsRepeatingLetter assert containsRepeatingLetter('xyx') assert containsRepeatingLetter('abcdefeghi') assert containsRepeatingLetter('aaa') assert not containsRepeatingLetter('abc') assert not containsRepeatingLetter('') assert not containsRepeatingLetter('a') assert not containsRepeatingLetter('aa') # exit() with open('input5.txt') as infile: nicewords = 0 line = infile.readline() while(line): if(isNice(line)): nicewords += 1 line = infile.readline() print "nice words: " + str(nicewords)
{ "repo_name": "FilipBrinkmann/adventofcode2015", "path": "advent5/adventofcode5.py", "copies": "1", "size": "2275", "license": "apache-2.0", "hash": -5854353452706641000, "line_mean": 26.743902439, "line_max": 96, "alpha_frac": 0.6285714286, "autogenerated": false, "ratio": 3.7112561174551386, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9817975154836669, "avg_score": 0.004370478243693985, "num_lines": 82 }
"""advent of code day 1. http://adventofcode.com/2016/day/1 """ import sys import string def face(direction, facing): """Keep track of facing direction.""" try: lr = direction[0] if lr == "R": facing += 1 elif lr == "L": facing -= 1 facing = facing % 4 return facing except Exception, exc: print exc def move(direction, facing, lat, lon): """Move around and return new lat or lon position.""" try: spaces = int(direction[1:]) # Track total longitude and latitude from start point if facing == 0: lon += spaces elif facing == 2: lon -= spaces elif facing == 1: lat += spaces elif facing == 3: lat -= spaces return lat, lon except Exception, exc: print exc if __name__ == "__main__": indir = [] with open(sys.argv[1]) as f: indir = string.split(f.read(), ", ") facing = 0 lat = 0 lon = 0 # lat is +E -W # lon is +N -S for direction in indir: direction = direction.strip() facing = face(direction, facing) lat, lon = move(direction, facing, lat, lon) total = abs(lon) + abs(lat) print total
{ "repo_name": "shaggy245/adventofcode", "path": "day01/day1.py", "copies": "1", "size": "1282", "license": "mit", "hash": -7089696670718290000, "line_mean": 20.0163934426, "line_max": 61, "alpha_frac": 0.515600624, "autogenerated": false, "ratio": 3.7485380116959064, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47641386356959065, "avg_score": null, "num_lines": null }
"""advent of code day 1. http://adventofcode.com/2016/day/1 --- Part Two --- Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice. For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due East. How many blocks away is the first location you visit twice? """ import sys import string def face(direction, compass, facing): """Keep track of facing direction.""" try: lr = direction[0] if lr == "R": facing += 1 elif lr == "L": facing -= 1 # If facing tracker is > compass length, circle back to beginning of # list if facing >= len(compass): facing = facing - len(compass) # Always set facing to the positive-valued index of the list # this prevents issues regarding facing being < -len(compass) facing = compass.index(compass[facing]) return facing except Exception, exc: print exc def move(direction, compass, facing, last_point): """Move around and return new last_point position.""" try: spaces = int(direction[1:]) # Track total longitude and latitude from start point if compass[facing] == "n": last_point[1] += spaces elif compass[facing] == "s": last_point[1] -= spaces elif compass[facing] == "e": last_point[0] += spaces elif compass[facing] == "w": last_point[0] -= spaces return last_point except Exception, exc: print exc def crosscheck(lat, check_line, past_lines): """Check if current line crosses past_lines.""" try: sort_check_line = sorted(check_line) # print "check line:", sort_check_line if lat: # line is horizontal # check current line against all past lines, except most-recent # past line. for past_line in past_lines[:-1]: sort_past_line = sorted(past_line) # print "past line:", sort_past_line in_lat = (sort_check_line[0][0] <= sort_past_line[0][0] and sort_check_line[1][0] >= sort_past_line[1][0]) in_lon = (sort_check_line[0][1] >= sort_past_line[0][1] and sort_check_line[1][1] <= sort_past_line[1][1]) if in_lat and in_lon: printout(sort_past_line[0][0], sort_check_line[0][1]) else: # line is vertical # check current line against all past lines, except most-recent # past line. for past_line in past_lines[:-1]: sort_past_line = sorted(past_line) # print "past line:", sort_past_line in_lat = (sort_check_line[0][0] >= sort_past_line[0][0] and sort_check_line[1][0] <= sort_past_line[1][0]) in_lon = (sort_check_line[0][1] <= sort_past_line[0][1] and sort_check_line[1][1] >= sort_past_line[1][1]) if in_lat and in_lon: printout(sort_check_line[0][0], sort_past_line[0][1]) except Exception, exc: print exc def printout(lat, lon): """Print distance from 0,0 and exit.""" total = abs(lat) + abs(lon) print total sys.exit() if __name__ == "__main__": indir = [] with open(sys.argv[1]) as f: indir = string.split(f.read(),", ") compass = ["n", "e", "s", "w"] facing = 0 lat = 0 lon = 0 # lat is +E -W # lon is +N -S visited_coords = [[0, 0]] vert_lines = [] hor_lines = [] for direction in indir: direction = direction.strip() facing = face(direction, compass, facing) [lat, lon] = visited_coords[-1] new_point = move(direction, compass, facing, [lat, lon]) if compass[facing] == "n" or compass[facing] == "s": crosscheck(False, [visited_coords[-1], new_point], hor_lines) vert_lines.append([visited_coords[-1], new_point]) else: crosscheck(True, [visited_coords[-1], new_point], vert_lines) hor_lines.append([visited_coords[-1], new_point]) visited_coords.append(new_point) printout(visited_coords[-1][0], visited_coords[-1][1])
{ "repo_name": "shaggy245/adventofcode", "path": "day01/day1-2.py", "copies": "1", "size": "4425", "license": "mit", "hash": -4902855737951909000, "line_mean": 33.5703125, "line_max": 76, "alpha_frac": 0.5496045198, "autogenerated": false, "ratio": 3.565672844480258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9614389580189349, "avg_score": 0.0001775568181818182, "num_lines": 128 }
# Advent of Code - Day 1 - No Time for a Taxicab http://adventofcode.com/2016/day/1 # From http://adventofcode.com/2016/day/1 # Typer : Ginny C Ghezzo # Given the input of R#, L# how far is the HQ ? # Read in the data # Loop through the enteries, pull out the number, import sys # file if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'day1data16.txt' file = open(filename,'r') print(filename) place = 0 totalR = 0 totalL = 0 NS = 0 EW = 0 for line in file: myline = line.rsplit(',') for items in myline: try: item = items.strip() print('This is item', item, ' and 1', item[0]) if item[0] == 'R': totalR += 1 mod = (totalR % 4) print('Right mod', mod) if mod == 1: EW = EW + int(item[1]) # East elif mod == 3: EW = EW - int(item[1]) # West elif mod == 2: NS = NS + int(item[1]) # North elif mod == 0: NS = NS - int(item[1]) # South if item[0] == 'L': totalL += 1 mod = (totalL % 4) print('Left mod', mod) if mod == 3: EW = EW + int(item[1]) # East elif mod == 1: EW = EW - int(item[1]) # West elif mod == 0: NS = NS + int(item[1]) # North elif mod == 2: NS = NS - int(item[1]) # South except: print(place) print('NS = ', NS) print('EW = ' , EW)
{ "repo_name": "gghezzo/prettypython", "path": "advent/bad_advent2016d1.py", "copies": "1", "size": "1287", "license": "mit", "hash": -6957437367438007000, "line_mean": 22.8333333333, "line_max": 83, "alpha_frac": 0.5508935509, "autogenerated": false, "ratio": 2.3877551020408165, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.34386486529408167, "avg_score": null, "num_lines": null }
#Advent of Code December 11 #Written by C Shi - icydoge AT gmail dot com def increment(input_string): input_string = list(input_string.lower()) letters = map(chr,range(97,123)) #Get lower case alphabet in a list if input_string[-1] != 'z': input_string[-1] = letters[letters.index(input_string[-1])+1] #Increment the left-most letter if it's not z else: i = len(input_string) - 1 input_string[i] = 'a' while i>0: #Try to wrap around each letter to the left, until success (none-z) or exhaustion if input_string[i-1] == 'z': input_string[i-1] = 'a' i -= 1 else: input_string[i-1] = letters[letters.index(input_string[i-1])+1] break return "".join(input_string) def password_check(input_string): input_string = list(input_string.lower()) disallowed_letters = ['i', 'o', 'l'] if len(input_string) != 8: print "Password","".join(input_string),"failed due to length." return False if set(disallowed_letters).intersection(input_string): print "Password","".join(input_string),"failed due to disallowed letters." return False has_straight_three = False has_two_pairs = False prev_letter = input_string[0] pairs = [] for i in range(1,8): if input_string[i] == prev_letter: #Found a pair pair = input_string[i]+prev_letter if pair not in pairs: #Check if the same pair is already known, if not, remember the discovered pair pairs.append(pair) elif ord(input_string[i]) == (ord(prev_letter) + 1): #The letter is in increasing straight of the previous if i < 7: if ord(input_string[i]) == (ord(input_string[i+1]) - 1): #Next letter is in increasing straight of this letter has_straight_three = True prev_letter = input_string[i] if len(pairs) >= 2: has_two_pairs = True if (not has_straight_three) or (not has_two_pairs): print "Password","".join(input_string),"failed due to lack of straights or pairs." return False return True input_string = raw_input("Enter puzzle input:") if len(input_string) != 8: raise ValueError("Input is not of length 8.") if not input_string.isalpha(): raise ValueError("Input is not a string of letters.") input_string = input_string.lower() #This while loop is guaranteed to terminate by finding a qualifying password, due to the aaaaaaaa-zzzzzzzz loop, as per the problem requirements. #A formal proof for the guarantee of termination is an exercise for the reader :) while (not password_check(input_string)): input_string = increment(input_string) part_one_answer = input_string input_string = increment(part_one_answer) while (not password_check(input_string)): input_string = increment(input_string) part_two_answer = input_string print "===========================================" print "Next password (Part One):",part_one_answer print "Next password after expiry (Part Two):",part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day11.py", "copies": "1", "size": "3130", "license": "mit", "hash": -949286415044979000, "line_mean": 34.5795454545, "line_max": 145, "alpha_frac": 0.6261980831, "autogenerated": false, "ratio": 3.6910377358490565, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48172358189490566, "avg_score": null, "num_lines": null }
#Advent of Code December 12 #Written by C Shi - icydoge AT gmail dot com import json def has_value(dicti, item): #Returns true if the dictionary dicti has value item in one of the keys, false otherwise. contain_item = False for i in dicti: if dicti[i] == item: contain_item = True return contain_item def json_sum(JSONData, exclude_red): #Recursive search and sum in the input's data structure. if isinstance(JSONData,unicode): return 0 elif isinstance(JSONData, int): return JSONData elif isinstance(JSONData, list): return sum(json_sum(x, exclude_red) for x in JSONData) elif isinstance(JSONData, dict): if exclude_red and has_value(JSONData, u'red'): return 0 sum_value = 0 for i in JSONData: if isinstance(JSONData[i], int): sum_value += JSONData[i] else: sum_value += json_sum(JSONData[i], exclude_red) return sum_value with open('inputs/accounting.json') as JSONFile: JSONData = json.load(JSONFile) part_one_result = json_sum(JSONData, False) print "Sum of accounting data (Part One):",part_one_result part_two_result = json_sum(JSONData, True) print "Sum of accounting data excluding red (Part Two):",part_two_result
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day12.py", "copies": "1", "size": "1337", "license": "mit", "hash": 6533481846913064000, "line_mean": 24.7307692308, "line_max": 93, "alpha_frac": 0.636499626, "autogenerated": false, "ratio": 3.703601108033241, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4840100734033241, "avg_score": null, "num_lines": null }
#Advent of Code December 13 #Written by C Shi - icydoge AT gmail dot com #I changed from a TSP(Day9)-adapted solution to brute force due to debugging an unrelated isssue, therefore brute force searching is used for this solution. The same algorithm in Day 9 can be applied here with minimum adaptation. import itertools def get_happiness(lose_gain, happiness_units): if lose_gain == "lose": return -1 * int(happiness_units) elif lose_gain == "gain": return int(happiness_units) else: raise ValueError("Unexpected input for happiness unit value.") def get_plan_happiness(happiness_map, seating_plan): happiness = 0 for i in range(0,len(seating_plan)-1): happiness += int(happiness_map[seating_plan[i]][seating_plan[i+1]]) + int(happiness_map[seating_plan[i+1]][seating_plan[i]]) #Two people ended up seating next to each other at the end. happiness += int(happiness_map[seating_plan[0]][seating_plan[-1]]) + int(happiness_map[seating_plan[-1]][seating_plan[0]]) return happiness with open('inputs/table.txt') as f: content = f.read().splitlines() #Part One #Construct the table happiness = {} for statement in content: line = statement[:-1].split(' ') #Build 2-D dictionary (happiness table) if line[0] in happiness: happiness[line[0]][line[10]] = get_happiness(line[2], line[3]) else: happiness[line[0]] = {} happiness[line[0]][line[10]] = get_happiness(line[2], line[3]) people = happiness.keys() #Start from the first permutation people_permutations = [list(i) for i in list(itertools.permutations(people))] best_plan = people_permutations[0] best_happiness = get_plan_happiness(happiness, people_permutations[0]) #Iterate through every possible permutation to find the plan with most happiness change for i in range(1,len(people_permutations)): if get_plan_happiness(happiness, people_permutations[i]) > best_happiness: best_plan = people_permutations[i] best_happiness = get_plan_happiness(happiness, people_permutations[i]) part_one_answer = best_happiness print "Maximum happiness change (Part One) is:", part_one_answer #Part Two #Add 'You' to the happiness table with value 0 to everyone. happiness['You'] = {} for person in people: happiness[person]['You'] = 0 happiness['You'][person] = 0 people.append('You') #Start from the first permutation people_permutations = [list(i) for i in list(itertools.permutations(people))] best_plan = people_permutations[0] best_happiness = get_plan_happiness(happiness, people_permutations[0]) #Iterate through every possible permutation to find the plan with most happiness change for i in range(1,len(people_permutations)): if get_plan_happiness(happiness, people_permutations[i]) > best_happiness: best_plan = people_permutations[i] best_happiness = get_plan_happiness(happiness, people_permutations[i]) part_two_answer = best_happiness print "Maximum happiness change with 'You' (Part Two) is:", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day13.py", "copies": "1", "size": "3039", "license": "mit", "hash": -3679174646370000000, "line_mean": 35.1785714286, "line_max": 229, "alpha_frac": 0.7127344521, "autogenerated": false, "ratio": 3.2090813093980994, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9326708861830764, "avg_score": 0.019021379933467232, "num_lines": 84 }
#Advent of Code December 14 #Written by C Shi - icydoge AT gmail dot com def reindeer_fly(reindeer, time): #Give the distance the reindeer covered until that time cycles = time / (reindeer[2] + reindeer[3]) remainder = time % (reindeer[2] + reindeer[3]) distance = cycles * reindeer[1] * reindeer[2] #Distance travelled in full fly-break cycles #Distance travelled in the remainder time if remainder <= reindeer[2]: distance += remainder * reindeer[1] else: distance += reindeer[2] * reindeer[1] return distance def look_up_reindeer(name, reindeers): #Return the index for the reindeer with that name for reindeer in reindeers: if reindeer[0] == name: return reindeers.index(reindeer) with open('inputs/reindeer.txt') as f: content = f.read().splitlines() reindeers = [] for reindeer in content: line = reindeer.split(' ') reindeers.append([line[0], int(line[3]), int(line[6]), int(line[13])]) #Part One fly_time = 2503 best_distance = -1 for reindeer in reindeers: if reindeer_fly(reindeer, fly_time) > best_distance: best_distance = reindeer_fly(reindeer, fly_time) part_one_answer = best_distance print "Distance the winning reindeer travelled (Part One):", part_one_answer #Part Two for reindeer in reindeers: reindeer.append(0) #points for t in range(1, fly_time+1): best_distance = -1 best_reindeers = [] for reindeer in reindeers: flying = reindeer_fly(reindeer, t) if flying > best_distance: #Only one reindeer in the lead best_distance = flying best_reindeers = [reindeer[0]] elif flying == best_distance: #multiple reindeers in the lead best_reindeers.append(reindeer[0]) for i in best_reindeers: reindeers[look_up_reindeer(i,reindeers)][4] += 1 #Add point to reindeer(s) in the lead. #Find the reindeer with the highest point highest_point = -1 for reindeer in reindeers: if reindeer[4] > highest_point: highest_point = reindeer[4] part_two_answer = highest_point print "Points of the winning reindeer (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day14.py", "copies": "1", "size": "2168", "license": "mit", "hash": -3782773042120934400, "line_mean": 28.2972972973, "line_max": 95, "alpha_frac": 0.6674354244, "autogenerated": false, "ratio": 2.8451443569553807, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4012579781355381, "avg_score": null, "num_lines": null }
#Advent of Code December 15 #Written by C Shi - icydoge AT gmail dot com #Trust me, this is exactly not the way I want to do it. #However, I am short on time today, and an attempt with scipy.optimize has failed. #Might come back to this later, but brute force is the best I can write #with limited time today, without consulting other solutions. def calc(a, b, c, d, ingredients): #Calculate the score capacity = max(0, ingredients[0][1] * a + ingredients[1][1] * b + ingredients[2][1] * c + ingredients[3][1] * d) durability = max(0, ingredients[0][2] * a + ingredients[1][2] * b + ingredients[2][2] * c + ingredients[3][2] * d) flavour = max(0, ingredients[0][3] * a + ingredients[1][3] * b + ingredients[2][3] * c + ingredients[3][3] * d) texture = max(0, ingredients[0][4] * a + ingredients[1][4] * b + ingredients[2][4] * c + ingredients[3][4] * d) calories = ingredients[0][5] * a + ingredients[1][5] * b + ingredients[2][5] * c + ingredients[3][5] * d return [capacity * durability * flavour * texture, calories] with open('inputs/ingredients.txt') as f: content = f.read().splitlines() #Parse input into ingredients ingredients = [] for item in content: line = item.split(' ') ingredients.append([line[0][:-1], int(line[2][:-1]), int(line[4][:-1]), int(line[6][:-1]), int(line[8][:-1]), int(line[10])]) #Brute force score and calories calculation scores = [] calories = [] for a in range(0, 101): for b in range(0, 101-a): for c in range(0, 101-a-b): d = 100 - a - b - c result = calc(a, b, c, d, ingredients) score = result[0] if score != 0: cookie_calories = result[1] scores.append(score) calories.append(cookie_calories) #Part One part_one_answer = max(scores) print "Maximum possible score (Part One):", part_one_answer #Part Two best_500_calories_score = -1 for i in range(0, len(calories)): if calories[i] == 500: if scores[i] > best_500_calories_score: best_500_calories_score = scores[i] part_two_answer = best_500_calories_score print "Best possible score with 500 calories (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day15.py", "copies": "1", "size": "2205", "license": "mit", "hash": -4242998701278151000, "line_mean": 39.8333333333, "line_max": 129, "alpha_frac": 0.6231292517, "autogenerated": false, "ratio": 2.777078085642317, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39002073373423174, "avg_score": null, "num_lines": null }
#Advent of Code December 16 #Written by C Shi - icydoge AT gmail dot com with open('inputs/aunt_matching.txt') as fi: content = fi.read().splitlines() properties = {} for item in content: line = item.split(' ') properties[line[0][:-1]] = int(line[1]) with open('inputs/aunts.txt') as f: content = f.read().splitlines() #Part One for item in content: line = item.split(' ') if (properties[line[2][:-1]] == int(line[3][:-1])) and (properties[line[4][:-1]] == int(line[5][:-1])) and (properties[line[6][:-1]] == int(line[7])): part_one_answer = int(line[1][:-1]) break print "The Aunt giving the gift (Part One) is Sue", part_one_answer #Part Two for item in content: line = item.split(' ') aunt_properties = {} aunt_properties[line[2][:-1]] = int(line[3][:-1]) aunt_properties[line[4][:-1]] = int(line[5][:-1]) aunt_properties[line[6][:-1]] = int(line[7]) is_that_aunt = True for key in aunt_properties: if key == "cats" or key == "trees": if properties[key] >= aunt_properties[key]: is_that_aunt = False elif key == "pomeranians" or key == "goldfish": if properties[key] <= aunt_properties[key]: is_that_aunt = False elif properties[key] != aunt_properties[key]: is_that_aunt = False if is_that_aunt: part_two_answer = line[1][:-1] break print "The real Aunt giving the gift (Part Two) is Sue", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day16.py", "copies": "1", "size": "1510", "license": "mit", "hash": -9065370090311400000, "line_mean": 25.0517241379, "line_max": 154, "alpha_frac": 0.5768211921, "autogenerated": false, "ratio": 3.0628803245436105, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.911414472113409, "avg_score": 0.005111359101904153, "num_lines": 58 }
#Advent of Code December 17 #Written by C Shi - icydoge AT gmail dot com from itertools import combinations with open('inputs/containers.txt') as f: content = sorted(map(int,f.read().splitlines())) min_comb = 150 / max(content) #At least this many containers needed achieve 150. count = 0 #Number of ways to pack. packing = {} #Dictionary with keys as number of containers sum to 150, #values as number of ways with that many containers. for i in range(min_comb, len(content)): combs = combinations(content, i) #All possible combinations with i many of containers. for way in combs: if sum(way) == 150: count += 1 if len(way) in packing: packing[len(way)] += 1 else: packing[len(way)] = 1 part_one_answer = count part_two_answer = packing[min(packing)] print "Number of possible ways to pack 150 litres (Part One):", part_one_answer print "Number of possible ways to pack 150 litres with minimum number of containers (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day17.py", "copies": "1", "size": "1049", "license": "mit", "hash": -5374124853157489000, "line_mean": 29.8823529412, "line_max": 113, "alpha_frac": 0.6701620591, "autogenerated": false, "ratio": 3.642361111111111, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4812523170211111, "avg_score": null, "num_lines": null }
#Advent of Code December 18 #Written by C Shi - icydoge AT gmail dot com LIGHT_OFF = '.' LIGHT_ON = '#' def make_grid(lines): lights = [] for line in lines: light_line = list(line) lights.append(light_line) return lights def get_state(i, j, lights): #Coordinates beyond the edges are counted as off. if (i < 0) or (i > 99): return LIGHT_OFF if (j < 0) or (j > 99): return LIGHT_OFF return lights[j][i] def operation(lights, part): new_arrangement = [[0 for x in range(100)] for x in range(100)] for i in range(0, len(lights)): for j in range(0, len(lights[i])): #For Part Two, the four corners are always on. if (part == 2) and (i in [0, 99]) and (j in [0, 99]): new_arrangement[i][j] = LIGHT_ON continue #Get the states of neighbours, including non-existent neighbouring coordinates beyond the edges. neighbours = [] neighbours.append(get_state(i+1, j, lights)) neighbours.append(get_state(i+1, j+1, lights)) neighbours.append(get_state(i+1, j-1, lights)) neighbours.append(get_state(i, j+1, lights)) neighbours.append(get_state(i, j-1, lights)) neighbours.append(get_state(i-1, j, lights)) neighbours.append(get_state(i-1, j+1, lights)) neighbours.append(get_state(i-1, j-1, lights)) current_light = get_state(i, j, lights) #Set the new state of the light in new_arrangement. if current_light == LIGHT_ON: if (neighbours.count(LIGHT_ON) == 2) or (neighbours.count(LIGHT_ON) == 3): new_arrangement[i][j] = LIGHT_ON else: new_arrangement[i][j] = LIGHT_OFF else: if neighbours.count(LIGHT_ON) == 3: new_arrangement[i][j] = LIGHT_ON else: new_arrangement[i][j] = LIGHT_OFF return new_arrangement with open('inputs/lights_2.txt') as f: content = f.read().splitlines() #Part One #Perform 100 steps of operations. lights = make_grid(content) for i in range(100): lights = operation(lights, 1) part_one_answer = 0 for line in lights: for light in line: if light == LIGHT_ON: part_one_answer += 1 print "Number of lights on after 100 steps (Part One):", part_one_answer #Part Two lights = make_grid(content) #Set the four corners to ON. lights[0][0] = LIGHT_ON lights[0][99] = LIGHT_ON lights[99][0] = LIGHT_ON lights[99][99] = LIGHT_ON for i in range(100): lights = operation(lights, 2) part_two_answer = 0 for line in lights: for light in line: if light == LIGHT_ON: part_two_answer += 1 print "Number of lights on after 100 steps, with 4 corners always on (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day18.py", "copies": "1", "size": "2936", "license": "mit", "hash": -4804125802325167000, "line_mean": 24.7543859649, "line_max": 108, "alpha_frac": 0.5728882834, "autogenerated": false, "ratio": 3.237045203969129, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43099334873691286, "avg_score": null, "num_lines": null }
#Advent of Code December 19 #Written by C Shi - icydoge AT gmail dot com from random import shuffle def get_all_indices(input_string, search_string, offset): #Get all indices of the appearance of search_string in input_string, taken from Day 5. try: index = input_string.index(search_string) + offset except ValueError: return [] return [index]+(get_all_indices(input_string[(index+len(search_string)-offset):], search_string, index+len(search_string))) with open('inputs/molecules.txt') as f: content = f.read().splitlines() #Separate replacement table and medicine molecule medicine_molecule = content[-1] content = content[:-2] #Parse replacement table. replacements = [] for line in content: replacement = line.split(" => ") replacements.append([replacement[0], replacement[1]]) #Part One products = [] for replacement in replacements: occurrences = get_all_indices(medicine_molecule, replacement[0], 0) for i in occurrences: new_product = medicine_molecule[:i] + replacement[1] + medicine_molecule[i+len(replacement[0]):] products.append(new_product) products_unique = list(set(products)) part_one_answer = len(products_unique) print "Number of unique products (Part One):", part_one_answer #Part Two #I have given up on this one -- several different recursive methods didn't work, can't spend a day on this, so I went to the subreddit. #Turns out for most data, apparently shuffle-and-retry of replacements work the fastest. #Formatted solution courtesy of /u/What-A-Baller (https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4cu5b) target = medicine_molecule part_two_answer = 0 while target != 'e': target_copy = target for replacement in replacements: if replacement[1] not in target: continue target = target.replace(replacement[1], replacement[0], 1) part_two_answer += 1 if target_copy == target: target = medicine_molecule part_two_answer = 0 shuffle(replacements) print "Number of steps to make the medcine (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day19.py", "copies": "1", "size": "2137", "license": "mit", "hash": -4897202744765698000, "line_mean": 29.9855072464, "line_max": 135, "alpha_frac": 0.7023865232, "autogenerated": false, "ratio": 3.5735785953177257, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47759651185177254, "avg_score": null, "num_lines": null }
#Advent of Code December 20 #Written by C Shi - icydoge AT gmail dot com #My input: 33100000 #Efficient get-all-factors courtesy of http://stackoverflow.com/a/6800214/5693062 def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) puzzle_input = int(raw_input("Puzzle input: ")) #Part One present_count = 0 house_number = int((puzzle_input/10) ** 0.5) #No less than this number required. #Number if gifts in Part One is just ten times the sum of all factors, including the house_number itself and 1. while present_count < (puzzle_input/10): house_number += 1 present_count = sum(factors(house_number)) part_one_answer = house_number print "Lowest house number to receive at least", puzzle_input, "gifts (Part One):", part_one_answer #Part Two present_count = 0.0 house_number = int((puzzle_input/11.0) ** 0.5) #The samething, but we drop factors that is less than one-fiftieth of the house number. while present_count < (puzzle_input/11.0): house_number += 1 factors_of_number = factors(house_number) present_count = 0 #Can probably be done with a sum on filter with a lambda, but not bothered. for n in factors_of_number: if float(house_number) / n <= 50.0: present_count += n part_two_answer = house_number print "Lowest house number to receive at least", puzzle_input, "gifts with changed rules (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day20.py", "copies": "1", "size": "1466", "license": "mit", "hash": -1660249027721673200, "line_mean": 33.9285714286, "line_max": 118, "alpha_frac": 0.6848567531, "autogenerated": false, "ratio": 3.1459227467811157, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43307794998811155, "avg_score": null, "num_lines": null }
#Advent of Code December 21 #Written by C Shi - icydoge AT gmail dot com import itertools import math weapons = [["Dagger", 8, 4], ["Shortsword", 10, 5], ["Warhammer", 25, 6], ["Longsword", 40, 7], ["Greataxe", 74, 8]] armors = [["No Armor", 0, 0], ["Leather", 13, 1], ["Chainmail", 31, 2], ["Splintmail", 53, 3], ["Bandedmail", 75, 4], ["Platemail", 102, 5]] rings = [["Empty Ring Slot 1", 0, 0, 0], ["Empty Ring Slot 2", 0, 0, 0], ["Damage +1", 25, 1, 0], ["Damage +2", 50, 2, 0], ["Damage +3", 100, 3, 0], ["Defense +1", 20, 0, 1], ["Defense +2", 40, 0, 2], ["Defense +3", 80, 0, 3]] def get_damage(attacker_damage, defender_armor): damage = attacker_damage - defender_armor if damage < 1: damage = 1 return damage with open('inputs/rpg.txt') as f: content = f.read().splitlines() boss_HP = int(content[0].split(' ')[2]) boss_damage = int(content[1].split(' ')[1]) boss_armor = int(content[2].split(' ')[1]) player_HP = 100 solutions = [] non_solutions = [] for weapon in weapons: for armor in armors: for ring_set in list(itertools.combinations(rings, 2)): player_damage = weapon[2] + sum([x[2] for x in ring_set]) player_armor = armor[2] + sum([x[3] for x in ring_set]) gold_expense = weapon[1] + armor[1] + sum([x[1] for x in ring_set]) #Seems easy enough to formulate as a MMORPG player... if (math.ceil(float(player_HP) / float(get_damage(boss_damage, player_armor)))) >= (math.ceil(float(boss_HP) / float(get_damage(player_damage, boss_armor)))): solutions.append([weapon, armor, ring_set, gold_expense]) else: non_solutions.append([weapon, armor, ring_set, gold_expense]) part_one_solution = min([x[3] for x in solutions]) print "Least amount of gold spent to kill the boss (Part One):", part_one_solution part_two_solution = max([x[3] for x in non_solutions]) print "Most amount of gold to spend without killing the boss (Part Two):", part_two_solution
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day21.py", "copies": "1", "size": "2019", "license": "mit", "hash": -4300342912157140000, "line_mean": 39.38, "line_max": 226, "alpha_frac": 0.6072313026, "autogenerated": false, "ratio": 2.8801711840228243, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3987402486622824, "avg_score": null, "num_lines": null }
#Advent of Code December 22 #Written by C Shi - icydoge AT gmail dot com #Note: this is not a solution, but only the user-facing game simulation that requires human inputs. #I played this game manually for around 25 minutes and found the lowest mana spent for Part One, #and the immediately higher rotation turned out to the the solution to Part Two. spells = [["Magic Missile (M)", "M", 53], ["Drain (D)", "D", 73], ["Shield (S)", "S", 113], ["Poison (P)", "P", 173], ["Recharge (R)", "R", 229]] def get_damage(attacker_damage, defender_armor): damage = attacker_damage - defender_armor if damage < 1: damage = 1 return damage with open('inputs/rpg2.txt') as f: content = f.read().splitlines() boss_HP = int(content[0].split(' ')[2]) boss_damage = int(content[1].split(' ')[1]) boss_poison = 0 player_HP = 50 player_mana = 500 player_armor = 0 player_shield = 0 player_recharge = 0 mana_spent = 0 game_over = False whos_turn = "Player" while (not game_over): print "" print "=========================================================" print "Round start." if player_recharge > 0: player_recharge -= 1 player_mana += 101 print "Player gains 101 mana from recharge, fading in", player_recharge, "rounds." print "Player HP:", player_HP, "Player Mana:", player_mana if player_shield > 0: player_shield -= 1 player_armor = 7 print "Player has 7 armor, fading in", player_shield, "rounds." else: player_armor = 0 print "Player has 0 armor." if boss_poison > 0: boss_poison -= 1 boss_HP -= 3 print "Boss loses 3 HP due to poison, poison fading in", boss_poison, "rounds." if boss_HP <= 0: print "Boss is defeated." game_over = True continue print "Boss HP:", boss_HP if player_mana < 53: game_over = True print "Player lost due to running out of mana." continue print "" if whos_turn == "Player": available_moves = [] for spell in spells: if spell[2] <= player_mana: if spell[1] == "S": if player_shield > 0: continue elif spell[1] == "P": if boss_poison > 0: continue elif spell[1] == "R": if player_recharge > 0: continue available_moves.append(spell[1]) print "Available Spells:", available_moves player_action = "" while player_action not in available_moves: player_action = str(raw_input("Enter your action (single uppercase letter): ")) if player_action == "M": player_mana -= 53 mana_spent += 53 boss_HP -= 4 whos_turn = "Boss" continue if player_action == "D": player_mana -= 73 mana_spent += 73 boss_HP -= 2 player_HP += 2 whos_turn = "Boss" continue if player_action == "S": player_shield = 6 player_mana -= 113 mana_spent += 113 whos_turn = "Boss" continue if player_action == "P": boss_poison = 6 player_mana -= 173 mana_spent += 173 whos_turn = "Boss" continue if player_action == "R": player_recharge = 5 player_mana -= 229 mana_spent += 229 whos_turn = "Boss" continue elif whos_turn == "Boss": damage = get_damage(boss_damage, player_armor) player_HP -= damage print "Boss does", damage, "damage to player; player HP is now", player_HP if player_HP <= 0: game_over = True print "Player is defeated due to lack of HP." whos_turn = "Player" continue print "Total mana spent =", mana_spent
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day22.py", "copies": "1", "size": "4041", "license": "mit", "hash": 6973470965851026000, "line_mean": 24.9038461538, "line_max": 145, "alpha_frac": 0.5211581292, "autogenerated": false, "ratio": 3.6904109589041094, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9670872149186646, "avg_score": 0.008139387783492732, "num_lines": 156 }
#Advent of Code December 23 #Written by C Shi - icydoge AT gmail dot com #Thanks, Freeman. def execute(program, registers): program_counter = 0 while program_counter < len(program): line = program[program_counter].split(' ') if line[0] == "hlf": registers[line[1]] = registers[line[1]]/2 program_counter += 1 elif line[0] == "tpl": registers[line[1]] = registers[line[1]] * 3 program_counter += 1 elif line[0] == "inc": registers[line[1]] += 1 program_counter += 1 elif line[0] == "jmp": program_counter += int(line[1]) elif line[0] == "jie": if registers[line[1][:-1]] % 2 == 0: program_counter += int(line[2]) else: program_counter += 1 elif line[0] == "jio": if registers[line[1][:-1]] == 1: program_counter += int(line[2]) else: program_counter += 1 else: raise ValueError("Unidentified instruction.") return registers with open('inputs/assembly.txt') as f: content = f.read().splitlines() #Part One registers = {'a': 0, 'b': 0} part_one_answer = execute(content, registers)['b'] print "Value in register b after execution (Part One):", part_one_answer #Part Two registers = {'a': 1, 'b': 0} part_two_answer = execute(content, registers)['b'] print "Value in register b after execution, with a starting from 1 (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day23.py", "copies": "1", "size": "1555", "license": "mit", "hash": 2506587549400561700, "line_mean": 23.296875, "line_max": 96, "alpha_frac": 0.5440514469, "autogenerated": false, "ratio": 3.684834123222749, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4728885570122749, "avg_score": null, "num_lines": null }
#Advent of Code December 24 #Written by C Shi - icydoge AT gmail dot com from operator import mul from itertools import combinations def find_answer(content, section_weight): #Find the lowest subset with a sum equal to section_weight, and get QE. for i in range(1, len(content)): combs = combinations(content, i) solution_found = False for comb in combs: if sum(comb) == section_weight: QE = reduce(mul, comb) group_min = len(comb) solutions = [group_min, QE] solution_found = True break if solution_found: break return solutions with open('inputs/gifts.txt') as f: content = map(int,f.read().splitlines()) #Part One section_weight = sum(content) / 3 part_one_answer = find_answer(content, section_weight)[1] print "QE for minimal Group 1 quantity (Part One):", part_one_answer #Part Two section_weight = sum(content) / 4 part_two_answer = find_answer(content, section_weight)[1] print "QE for minimal Group 1 quantity with four sections (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day24.py", "copies": "1", "size": "1131", "license": "mit", "hash": -8889788299166489000, "line_mean": 26.6097560976, "line_max": 87, "alpha_frac": 0.6392572944, "autogenerated": false, "ratio": 3.7450331125827816, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.984571661056294, "avg_score": 0.007714759283968261, "num_lines": 41 }
#Advent of Code December 25 #Written by C Shi - icydoge AT gmail dot com with open('inputs/machine.txt') as f: content = f.read().splitlines()[0].split(' ') code_row = int(content[-3][:-1]) code_col = int(content[-1][:-1]) code = 20151125 row_number = 2 col_number = 1 #Start from (2,1) due to Python not having do while. diagonal_width = 2 current_width = 1 while True: #Transform the code. code = (code * 252533) % 33554393 #Correct code found. if (row_number == code_row) and (col_number == code_col): part_one_answer = code break #Wrap around when end of diagonal reached. if current_width == diagonal_width: diagonal_width += 1 current_width = 1 row_number = col_number + 1 col_number = 1 #Increment on the diagonal. else: current_width += 1 row_number -= 1 col_number += 1 print "Code for the input location is (Part One):", part_one_answer print "Part Two: Congratulations, we have finished Advent of Code 2015!"
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day25.py", "copies": "1", "size": "1042", "license": "mit", "hash": 7208122111950745000, "line_mean": 25.05, "line_max": 72, "alpha_frac": 0.6238003839, "autogenerated": false, "ratio": 3.383116883116883, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4506917267016883, "avg_score": null, "num_lines": null }
#Advent of Code December 3 #Written by C Shi - icydoge AT gmail dot com with open('inputs/directions.txt') as f: content = f.read()[:-1] #remove new line character at the end route = list(content) #Part One moves = [(0,0)] current_x = 0 current_y = 0 #Santa moves then deliver a present for i in route: if i == "^": current_y += 1 elif i == "v": current_y -= 1 elif i == ">": current_x += 1 elif i == "<": current_x -= 1 else: raise ValueError("Unacceptable direction.") moves += [(current_x, current_y)] part_one_answer = len(set(moves)) print "Number of houses with at lest one present (Part One):", part_one_answer #Part Two moves = [(0,0), (0,0)] santa_coordinate = [0,0] robot_coordinate = [0,0] last_delivery = "robot" for i in route: #Robot moves to deliver a present as according to the script if last_delivery == "santa": if i == "^": robot_coordinate[1] += 1 elif i == "v": robot_coordinate[1] -= 1 elif i == ">": robot_coordinate[0] += 1 elif i == "<": robot_coordinate[0] -= 1 else: raise ValueError("Unacceptable robot direction.") last_delivery = "robot" #Santa moves to deliver a present as according to the script else: if i == "^": santa_coordinate[1] += 1 elif i == "v": santa_coordinate[1] -= 1 elif i == ">": santa_coordinate[0] += 1 elif i == "<": santa_coordinate[0] -= 1 else: raise ValueError("Unacceptable santa direction.") last_delivery = "santa" moves += [(santa_coordinate[0], santa_coordinate[1]), (robot_coordinate[0], robot_coordinate[1])] part_two_answer = len(set(moves)) print "Number of houses with at lest one present with robot (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day3.py", "copies": "1", "size": "1929", "license": "mit", "hash": 8038079261961262000, "line_mean": 20.9204545455, "line_max": 101, "alpha_frac": 0.5557283567, "autogenerated": false, "ratio": 3.532967032967033, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45886953896670324, "avg_score": null, "num_lines": null }
#Advent of Code December 5 #Written by C Shi - icydoge AT gmail dot com def get_all_indices(input_string, search_string, offset): #Get all indices of the appearance of search_string in input_string try: index = input_string.index(search_string) + offset except ValueError: return [] return [index]+(get_all_indices(input_string[(index+len(search_string)-offset):], search_string, index+len(search_string))) with open('inputs/naughty-nice-strings.txt') as f: content = f.read().splitlines() nice_strings = [] naughty_strings = [] #Part One for pstring in content: #Check for disallowed string patterns disallowed_patterns_discovered = False disallowed_patterns = ["ab", "cd", "pq", "xy"] for pattern in disallowed_patterns: if pattern in pstring: naughty_strings.append(pstring) disallowed_patterns_discovered = True break if disallowed_patterns_discovered: continue #If no disallowed patterns, scan for replicates and three vowels vowels = ['a', 'e', 'i', 'o', 'u'] if pstring[0] in vowels: vowels_found = [pstring[0]] else: vowels_found = [] pairs = [] prev_letter = pstring[0] for i in range(1, len(pstring)): if pstring[i] in vowels: vowels_found.append(pstring[i]) if pstring[i] == prev_letter: pair = pstring[i] + prev_letter if pair not in pairs: pairs.append(pair) prev_letter = pstring[i] if (len(vowels_found) >= 3) and (len(pairs) >= 1): nice_strings.append(pstring) else: naughty_strings.append(pstring) part_one_answer = len(nice_strings) print "Number of strings that are nice (Part One):", part_one_answer nice_strings = [] naughty_strings = [] #Part Two for pstring in content: #Check with the second rule first if len(pstring) < 3: #Will not fit the first rule naughty_strings.append(pstring) continue has_one_between_two = False first_letter = pstring[0] second_letter = pstring[1] third_letter = pstring[2] if first_letter == third_letter: has_one_between_two = True else: for i in range(1,len(pstring)-2): first_letter = pstring[i] second_letter = pstring[i+2] third_letter = pstring[i+2] if first_letter == third_letter: has_one_between_two = True break if not has_one_between_two: naughty_strings.append(pstring) #Does not have one letter between any two same letters continue #Then check the first rule by searching nice_string_found = False for j in range(0,len(pstring)-1): search_string = pstring[j]+pstring[j+1] indices = get_all_indices(pstring, search_string, 0) if len(indices) > 1: for i in range(0,len(indices)-1): if (indices[i+1] - indices[i]) > 1: #non-overlapping nice_string_found = True break if nice_string_found: break if nice_string_found: nice_strings.append(pstring) else: naughty_strings.append(pstring) part_two_answer = len(nice_strings) print "Number of strings that are nice with modified requirements (Part Two):", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day5.py", "copies": "1", "size": "3386", "license": "mit", "hash": -3535636731832979000, "line_mean": 28.1896551724, "line_max": 127, "alpha_frac": 0.6086828116, "autogenerated": false, "ratio": 3.549266247379455, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4657949058979455, "avg_score": null, "num_lines": null }
#Advent of Code December 6 #Written by C Shi - icydoge AT gmail dot com #Dumb and ugly code, be aware with open('inputs/lights.txt') as f: content = f.read().splitlines()[:-1] lights = [[0 for i in range(1000)] for i in range(1000)] for line in content: line_split = line.split(' ') if line_split[0] == "toggle": lower_indices = line_split[1].split(',') higher_indices = line_split[3].split(',') for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): if lights[i][j] == 1: lights[i][j] = 0 else: lights[i][j] = 1 elif line_split[0] == "turn": lower_indices = line_split[2].split(',') higher_indices = line_split[4].split(',') if line_split[1] == "on": for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): lights[i][j] = 1 elif line_split[1] == "off": for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): lights[i][j] = 0 else: raise ValueError("Not turning on or turning off!") else: raise ValueError("Unexpected action!") part_one_answer = sum(row.count(1) for row in lights) print "Lights lit after operations (Part One): ", part_one_answer lights = [[0 for i in range(1000)] for i in range(1000)] for line in content: line_split = line.split(' ') if line_split[0] == "toggle": lower_indices = line_split[1].split(',') higher_indices = line_split[3].split(',') for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): lights[i][j] += 2 elif line_split[0] == "turn": lower_indices = line_split[2].split(',') higher_indices = line_split[4].split(',') if line_split[1] == "on": for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): lights[i][j] += 1 elif line_split[1] == "off": for i in range(int(lower_indices[0]),int(higher_indices[0])+1): for j in range(int(lower_indices[1]),int(higher_indices[1])+1): if lights[i][j] > 0: lights[i][j] -= 1 else: raise ValueError("Not turning on or turning off!") else: raise ValueError("Unexpected action!") part_two_answer = 0 for i in lights: for j in i: part_two_answer += j print "Total brightness after operations (Part Two): ", part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day6.py", "copies": "1", "size": "2932", "license": "mit", "hash": 2273298613012186600, "line_mean": 29.8631578947, "line_max": 79, "alpha_frac": 0.5443383356, "autogenerated": false, "ratio": 3.4132712456344585, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44576095812344585, "avg_score": null, "num_lines": null }
#Advent of Code December 7, with dynamic planning #Written by C Shi - icydoge AT gmail dot com #Updated to include result for Part Two. def intval(s): try: int(s) return True except ValueError: return False def process_gate(target, content, target_list): global value_table if intval(target): return int(target) input = content[target_list.index(target)] input_exploded = input.split(' ') if input_exploded[1] == "->": #either wire-wire or number-wire if intval(input_exploded[0]): result = int(input_exploded[0]) value_table[input_exploded[-1]] = result return result #number else: result = process_gate(input_exploded[0], content, target_list) value_table[input_exploded[-1]] = result return result #another wire elif input_exploded[0] == "NOT": #NOT gate if input_exploded[1] in value_table: return ~value_table(input_exploded[1]) else: result = ~process_gate(input_exploded[1], content, target_list) value_table[input_exploded[-1]] = result return result elif input_exploded[1] == "AND": #AND gate if input_exploded[0] in value_table: left = value_table[input_exploded[0]] else: left = process_gate(input_exploded[0], content, target_list) if input_exploded[2] in value_table: right = value_table[input_exploded[2]] else: right = process_gate(input_exploded[2], content, target_list) result = left & right value_table[input_exploded[-1]] = result return result elif input_exploded[1] == "OR": #OR gate if input_exploded[0] in value_table: left = value_table[input_exploded[0]] else: left = process_gate(input_exploded[0], content, target_list) if input_exploded[2] in value_table: right = value_table[input_exploded[2]] else: right = process_gate(input_exploded[2], content, target_list) result = left | right value_table[input_exploded[-1]] = result return result elif input_exploded[1] == "LSHIFT": #LSHIFT operation if intval(input_exploded[2]): if input_exploded[2] in value_table: return value_table[input_exploded[2]] << int(input_exploded[2]) else: result = process_gate(input_exploded[0], content, target_list) << int(input_exploded[2]) value_table[input_exploded[-1]] = result return result else: raise ValueError("Invalid LSHIFT value.") elif input_exploded[1] == "RSHIFT": #RSHIFT operation if intval(input_exploded[2]): if input_exploded[2] in value_table: return value_table[input_exploded[2]] >> int(input_exploded[2]) else: result = process_gate(input_exploded[0], content, target_list) >> int(input_exploded[2]) value_table[input_exploded[-1]] = result return result else: raise ValueError("Invalid RSHIFT value.") else: raise ValueError("Unexpected operation!") target_list = [] value_table = {} with open('inputs/puzzle.txt') as f: content = f.read().splitlines() for i in range(0,len(content)): row = content[i].split(' ') target_list.append(row[-1]) if target_list[-1] == '': target_list = target_list[:-1] content = content[:-1] #strip last empty line if present part_one_result = process_gate("a", content, target_list) print "Result for Part One: ",part_one_result content[target_list.index("b")] = str(part_one_result) + " -> b" value_table = {} #reset lookup table part_two_result = process_gate("a", content, target_list) print "Result for Part Two: ",part_two_result
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day7.py", "copies": "1", "size": "3931", "license": "mit", "hash": -7387413936488757000, "line_mean": 32.5982905983, "line_max": 104, "alpha_frac": 0.5950139914, "autogenerated": false, "ratio": 3.6635601118359737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4758574103235974, "avg_score": null, "num_lines": null }
#Advent of Code December 8 #Written by C Shi - icydoge AT gmail dot com with open('inputs/strings.txt') as f: content = f.read().splitlines()[:-1] content_for_encode = content total_original_length = 0 total_string_length = 0 for i in range(0,len(content)): total_original_length += len(content[i]) #Remove quote marks from two ends of each line if (content[i][0] == '\"') and (content[i][-1] == '\"'): content[i] = content[i][1:-1] #"Parse" the line line_length = 0 j = 0 while j<len(content[i]): if (content[i][j] == '\\') and (content[i][j+1] == 'x'): #Assuming legal input provided by the question, otherwise will need to have additional checks for list index line_length += 1 j += 4 elif (content[i][j] == '\\') and (content[i][j+1] == '\"'): line_length += 1 j += 2 elif (content[i][j] == '\\') and (content[i][j+1] == '\\'): line_length += 1 j += 2 else: line_length += 1 j += 1 total_string_length += line_length part_one_result = total_original_length - total_string_length print "Original Length - Total String Length (Part One): ", part_one_result total_encoded_length = 0 for i in range(0,len(content_for_encode)): j = 0 line_len = len(content_for_encode[i]) encoded_string = "\"\\\"" #Assuming legal input, with quotes on each side while j < line_len: if (content_for_encode[i][j] == '\\') and (content_for_encode[i][j+1] == '"'): encoded_string += "\\\\\\\"" j += 2 elif (content_for_encode[i][j] == '"'): encoded_string += "\\\"" j += 1 elif (content_for_encode[i][j] == '\\') and (content_for_encode[i][j+1] == '\\'): encoded_string += "\\\\\\\\" j += 2 elif (content_for_encode[i][j] == '\\') and (content_for_encode[i][j+1] == 'x'): encoded_string += "\\\\" j += 1 else: encoded_string += content_for_encode[i][j] j += 1 encoded_string += "\\\"\"" total_encoded_length += len(encoded_string) part_two_result = total_encoded_length - total_original_length print "Total Encoded Length - Original Length (Part Two): ", part_two_result
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day8.py", "copies": "1", "size": "2331", "license": "mit", "hash": -7371375518138301000, "line_mean": 32.3, "line_max": 173, "alpha_frac": 0.5315315315, "autogenerated": false, "ratio": 3.393013100436681, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4424544631936681, "avg_score": null, "num_lines": null }
#Advent of Code December 9 #Written by C Shi - icydoge AT gmail dot com #Implementing TSP algorithm def get_dict_min(dicti, disjoint_list): #Get the minimum key value in dicti where the key is not in disjoint_list minkey = '' minvalue = None for item in dicti: if item not in disjoint_list: if minvalue == None: minkey = item minvalue = dicti[item] else: if dicti[item] < minvalue: minkey = item minvalue = dicti[item] if minvalue != None: return [minkey, minvalue] else: raise ValueError("Disjoint list covers the whole route map.") #Should never happen on legal input. def get_dict_max(dicti, disjoint_list): #Get the maximum key value in dicti where the key is not in disjoint_list maxkey = '' maxvalue = None for item in dicti: if item not in disjoint_list: if maxvalue == None: maxkey = item maxvalue = dicti[item] else: if dicti[item] > maxvalue: maxkey = item maxvalue = dicti[item] if maxvalue != None: return [maxkey, maxvalue] else: raise ValueError("Disjoint list covers the whole route map.") #Should never happen on legal input. def get_route_distance(distance_map, route): distance = 0 for i in range(0,len(route)-1): distance += int(distance_map[route[i]][route[i+1]]) return [route, distance] with open('inputs/routes.txt') as f: content = f.read().splitlines()[:-1] #Construct the table distance = {} for edge in content: line = edge.split(' ') #Build 2-D dictionary (distance table) in both directions if line[0] in distance: distance[line[0]][line[2]] = int(line[4]) else: distance[line[0]] = {} distance[line[0]][line[2]] = int(line[4]) if line[2] in distance: distance[line[2]][line[0]] = int(line[4]) else: distance[line[2]] = {} distance[line[2]][line[0]] = int(line[4]) nodes = distance.keys(); #Get minimum distance all_routes = [] for node in nodes: route = [node] while (len(route) < len(distance)): route.append(get_dict_min(distance[route[-1]], route)[0]) all_routes.append(route) part_one_answer = min(get_route_distance(distance, route)[1] for route in all_routes) print "Shortest distance (Part One) is:",part_one_answer #Get maximum distance all_routes = [] for node in nodes: route = [node] while (len(route) < len(distance)): route.append(get_dict_max(distance[route[-1]], route)[0]) all_routes.append(route) part_two_answer = max(get_route_distance(distance, route)[1] for route in all_routes) print "Longest distance (Part Two) is:",part_two_answer
{ "repo_name": "icydoge/AdventOfCodeSolutions", "path": "day9.py", "copies": "1", "size": "2879", "license": "mit", "hash": -2113793547989148000, "line_mean": 27.2352941176, "line_max": 85, "alpha_frac": 0.5974296631, "autogenerated": false, "ratio": 3.5587144622991347, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4656144125399134, "avg_score": null, "num_lines": null }
# Advent of Code - http://adventofcode.com/day/1 # From http://adventofcode.com/day/1 # Coder : Ginny C Ghezzo # What I learned: import sys if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'day5data.txt' print(filename) def checkForDoubleChar(myStr): judgement = False i=1 # last one is broken while i < len(myStr): if myStr[i-1] == myStr[i]: return(True) i += 1 return judgement def checkForVowel(myStr): judgement = True count = 0 count = myStr.count('a') + myStr.count('e') + myStr.count('i') + myStr.count('o') + myStr.count('u') if count < 3: judgement = False return judgement def checkSantaList(myStr): judgement = True if ('ab' in myStr): return(False) if ('cd' in myStr): return(False) if ('pq' in myStr): return(False) if ('xy' in myStr): return(False) if (not checkForVowel(myStr)): return(False) if (not checkForDoubleChar(myStr)): return(False) return judgement naughty = 0 nice = 0 f = open(filename,'r') line = f.readline() while line: if checkSantaList(line): nice += 1 else: naughty += 1 line = f.readline() print('Nice = ', nice, " Naughty = ", naughty)
{ "repo_name": "gghezzo/prettypython", "path": "PythonEveryDay2015/advent2015d5.py", "copies": "1", "size": "1235", "license": "mit", "hash": 7939142456084597000, "line_mean": 24.7291666667, "line_max": 104, "alpha_frac": 0.6089068826, "autogenerated": false, "ratio": 2.9058823529411764, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8854455921899362, "avg_score": 0.03206666272836284, "num_lines": 48 }
# Advent of Code - http://adventofcode.com/day/3 # From http://adventofcode.com/day/3 # Coder : Ginny C Ghezzo # What I learned: import sys if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'day6data.txt' if len(sys.argv) > 2: letter = sys.argv[2] else: letter = 'a' print(filename) print(letter) f = open(filename,'r') line = f.readline() mindstorm = {} def isInt(x): try: int(x) return(True) except: return(False) def updateValue(key): if isInt(key): return(int(key)) #just a number action = mindstorm[key] if isInt(action): mindstorm[key] = int(action) #not sure if this is needed return(int(action)) else: a = action.split(' ') if 'NOT' in a: # This is the NOT case t = ~(updateValue(a[1])) #Take the value of the not as a key and find its int elif 'AND' in a: t = (updateValue(a[0])) & (updateValue(a[2])) elif 'OR' in a: t = (updateValue(a[0])) | (updateValue(a[2])) elif 'LSHIFT' in a: t = (updateValue(a[0]) << int(a[2])) elif 'RSHIFT' in a: t = (updateValue(a[0]) >> int(a[2])) else: t = updateValue(a[0]) mindstorm[key] = int(t) #not sure if this is needed return(int(t)) return() while line: key = line.split('->')[1].rstrip().lstrip() action = line.split('->')[0].lstrip() if key not in mindstorm: mindstorm[key] = action line = f.readline() print("The value of ", letter) print(updateValue(letter)) f.close
{ "repo_name": "gghezzo/prettypython", "path": "PythonEveryDay2015/advent2015d7.py", "copies": "1", "size": "1625", "license": "mit", "hash": 1823555441661711000, "line_mean": 28.0178571429, "line_max": 98, "alpha_frac": 0.5458461538, "autogenerated": false, "ratio": 3.0602636534839927, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4106109807283993, "avg_score": null, "num_lines": null }
# Advent of Code - http://adventofcode.com/day/8 - THIS SI WRONG SOLUTION # From http://adventofcode.com/day/8 # Coder : Ginny C Ghezzo # What I learned: This is my bad failed code. I could not figure out which \x## evaluated and which did not import sys if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'day8data.txt' print(filename) file = open(filename,'r') ofCode = 0 ofMemory = 0 solution = 0 for line in file: # Loop through each line in the data file # Find the length of the line to the end? Not sure why -1 takes off the line feed ofCode = ofCode + len(line[:-1]) # eval will evaluate the line through a python and thus interpret ASCII code & escapes ofMemory = ofMemory + len(eval(line)) solution = ofCode - ofMemory + 1 print("ofCode - ofMemory + 1 =", ofCode, " - ", ofMemory," +1 = ", solution ) # Part 2: Taken from orangut on reddit . Just the delta, not the full amount of char print sum(2+s.count('\\')+s.count('"') for s in open('inputs/problem8-input'))
{ "repo_name": "gghezzo/prettypython", "path": "PythonEveryDay2015/advent2015d8.py", "copies": "1", "size": "1044", "license": "mit", "hash": -7834348106238647000, "line_mean": 39.1923076923, "line_max": 107, "alpha_frac": 0.6647509579, "autogenerated": false, "ratio": 3.1926605504587156, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9262905923620572, "avg_score": 0.018901116947628725, "num_lines": 26 }
# Advent of Code - http://adventofcode.com/day/9 # From http://adventofcode.com/day/9 # Typer : Ginny C Ghezzo # Taking the dijkstra algorithm from http://www.bogotobogo.com/python/python_Dijkstras_Shortest_Path_Algorithm.php # or # http://stackoverflow.com/questions/22897209/dijkstras-algorithm-in-python # What I learned: This is my bad failed code. I could not figure out which \x## evaluated and which did not import sys if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'day9data.txt' file = open(filename,'r') print(filename) nodes = [] # names of the cities (node) TODO: They use a list, why not a set? distances = {} # vertex def getCities(): # get the city names and the distances mynodes = [] mydis = {} # TODO : Find the cities not as source for line in file: myline = line.rsplit(' ') mynodes.append(myline[0]) mynodes.append(myline[2]) if myline[0] not in mydis: mydis[myline[0]] = {} if myline[2] not in mydis: mydis[myline[2]] = {} mydis[myline[0]][myline[2]] = int(myline[4].rstrip()) mynodes = list(set(mynodes)) current = mynodes[0] print(mynodes) return(mynodes, mydis, current) nodes, distances, current = getCities() unvisited = {node: None for node in nodes} # use None as +inf ?? print("unvisited at start: ", unvisited) visited = {} currentDistance = 0 unvisited[current] = currentDistance while True: if current not in distances: print('Something wrong with ', current) for neighbor, distance in distances[current].items(): if neighbor not in unvisited: continue newDistance = currentDistance + distance if unvisited[neighbor] is None or unvisited[neighbor] > newDistance: unvisited[neighbor] = newDistance visited[current] = currentDistance try: del unvisited[current] except: print("What is unvisited when this goes wrong? ", unvisited, " ", current) if not unvisited: break candidates = [node for node in unvisited.items() if node[1]] try: current, currentDistance = sorted(candidates, key = lambda x: x[1])[0] except IndexError: print("error ", current, currentDistance) print(visited)
{ "repo_name": "gghezzo/prettypython", "path": "PythonEveryDay2015/advent2015d9.py", "copies": "1", "size": "2290", "license": "mit", "hash": -7171617276808787000, "line_mean": 34.2307692308, "line_max": 115, "alpha_frac": 0.6524017467, "autogenerated": false, "ratio": 3.4539969834087483, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4606398730108748, "avg_score": null, "num_lines": null }
# Advent of Code # Dec 1, Part 1 # @geekygirlsarah import struct inputFile = "input.txt" # Tracking vars x = 0 y = 0 facing = "N" with open(inputFile) as f: while True: contents = f.readline(-1) if not contents: # print "End of file" break # print ("Contents: ", contents) coords = contents.split(", ") # print ("Split contents: ") # print (coords) for coord in coords: dir = coord[0] num = int(coord[1:]) if dir == "L": print("Left " + str(num) + " blocks") if facing == "N": facing = "W" x = x - num elif facing == "E": facing = "N" y = y + num elif facing == "S": facing = "E" x = x + num elif facing == "W": facing = "S" y = y - num elif dir == "R": print("Right " + str(num) + " blocks") if facing == "N": facing = "E" x = x + num elif facing == "E": facing = "S" y = y - num elif facing == "S": facing = "W" x = x - num elif facing == "W": facing = "N" y = y + num print("Now facing " + facing) print(" x = " + str(x) + ", y = " + str(y)) print ("X = " + str(x)) print ("Y = " + str(y)) print ("Distance = " + str(abs(x) + abs(y)))
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec01/dec01part1.py", "copies": "1", "size": "1679", "license": "mit", "hash": -1320154369405230000, "line_mean": 27.4576271186, "line_max": 56, "alpha_frac": 0.3502084574, "autogenerated": false, "ratio": 3.886574074074074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9727837145410043, "avg_score": 0.0017890772128060263, "num_lines": 59 }
# Advent of Code # Dec 1, Part 2 # @geekygirlsarah import struct inputFile = "input.txt" # Tracking vars x = 0 y = 0 facing = "N" places = [] placesX = [] placesY = [] firstTwiceVisitedPlace = "" firstTwiceVisitedPlaceDist = 0 with open(inputFile) as f: while True: contents = f.readline(-1) if not contents: # print "End of file" break # print ("Contents: ", contents) coords = contents.split(", ") # print ("Split contents: ") # print (coords) # Hey, ya gotta start somewhere... place = "x = " + str(x) + ", y = " + str(y) places.append(place) placesX.append(x) placesY.append(y) for coord in coords: dir = coord[0] num = int(coord[1:]) xchange = 0 ychange = 0 if dir == "L": # print("Left " + str(num) + " blocks") if facing == "N": facing = "W" xchange = -1 elif facing == "E": facing = "N" ychange = 1 elif facing == "S": facing = "E" xchange = 1 elif facing == "W": facing = "S" ychange = -1 elif dir == "R": # print("Right " + str(num) + " blocks") if facing == "N": facing = "E" xchange = 1 elif facing == "E": facing = "S" ychange = -1 elif facing == "S": facing = "W" xchange = -1 elif facing == "W": facing = "N" ychange = 1 for i in range(0, num): x = x + xchange y = y + ychange place = "x = " + str(x) + ", y = " + str(y) places.append(place) placesX.append(x) placesY.append(y) # print("Place: " + place) # print ("Places:", places) # Check for duplicate places if firstTwiceVisitedPlace == "": for p1 in range(0, len(places)): for p2 in range (p1 + 1, len(places)): if places[p1] == places[p2]: # print ("Found second place: " + places[p1]) # print ("Found second place X: " + str(placesX[p1])) # print ("Found second place Y: " + str(placesY[p1])) firstTwiceVisitedPlace = places[p1] firstTwiceVisitedPlaceDist = abs(placesX[p1]) + abs(placesY[p1]) # Add it either way # places.append(place) else: break # print ("X = " + str(x)) # print ("Y = " + str(y)) # print ("Distance = " + str(abs(x) + abs(y))) print ("First twice visited place = " + firstTwiceVisitedPlace) print ("First twice visited place distance = " + str(firstTwiceVisitedPlaceDist))
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec01/dec01part2.py", "copies": "1", "size": "3169", "license": "mit", "hash": 6719667970936429000, "line_mean": 31.6701030928, "line_max": 92, "alpha_frac": 0.4140107289, "autogenerated": false, "ratio": 3.9811557788944723, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4895166507794472, "avg_score": null, "num_lines": null }
# Advent of Code # Dec 2, Part 1 # @geekygirlsarah inputFile = "input.txt" # Tracking vars finalCode = "" lastNumber = 5 # start here tempNumber = 0 with open(inputFile) as f: while True: line = f.readline(-1) if not line: # print "End of file" break # print ("Line: ", line) print ("First number=" + str(lastNumber)) for dir in line: print("dir=" + dir) if dir == "U": tempNumber = lastNumber - 3 elif dir == "D": tempNumber = lastNumber + 3 elif dir == "L": tempNumber = lastNumber - 1 elif dir == "R": tempNumber = lastNumber + 1 elif dir == "\n": break # Boundary checks to undo out of bounds if dir == "U" and tempNumber < 1: tempNumber = lastNumber elif dir == "D" and tempNumber > 9: tempNumber = lastNumber elif dir == "L" and (tempNumber == 0 or tempNumber == 3 or tempNumber == 6): tempNumber = lastNumber elif dir == "R" and (tempNumber == 10 or tempNumber == 7 or tempNumber == 4): tempNumber = lastNumber print ("New number: " + str(tempNumber)) lastNumber = tempNumber # last number validated, so add to code finalCode = finalCode + str(tempNumber) print("Final code: " + finalCode)
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec02/dec02part1.py", "copies": "1", "size": "1494", "license": "mit", "hash": -7619066071688123000, "line_mean": 28.88, "line_max": 89, "alpha_frac": 0.500669344, "autogenerated": false, "ratio": 4.12707182320442, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012242998139118555, "num_lines": 50 }
# Advent of Code # Dec 2, Part 1 # @geekygirlsarah inputFile = "input.txt" # Tracking vars finalCode = "" lastNumber = 5 # start here tempNumber = lastNumber with open(inputFile) as f: while True: line = f.readline(-1) if not line: # print "End of file" break # print ("Line: ", line) print ("First number=" + str(lastNumber)) for dir in line: print("dir=" + dir) if dir == "U": if lastNumber == 3: tempNumber = lastNumber - 2 if lastNumber > 5 and lastNumber < 9: tempNumber = lastNumber - 4 if lastNumber >= 10 and lastNumber <= 12: tempNumber = lastNumber - 4 if lastNumber == 13: tempNumber = lastNumber - 2 elif dir == "D": if lastNumber == 1: tempNumber = lastNumber + 2 if lastNumber >= 2 and lastNumber <= 4: tempNumber = lastNumber + 4 if lastNumber >= 6 and lastNumber <= 8: tempNumber = lastNumber + 4 if lastNumber == 11: tempNumber = lastNumber + 2 elif dir == "L": if lastNumber == 6: tempNumber = lastNumber - 1 if lastNumber == 3 or lastNumber == 7 or lastNumber == 11: tempNumber = lastNumber - 1 if lastNumber == 4 or lastNumber == 8 or lastNumber == 12: tempNumber = lastNumber - 1 if lastNumber == 9: tempNumber = lastNumber - 1 elif dir == "R": if lastNumber == 5: tempNumber = lastNumber + 1 if lastNumber == 2 or lastNumber == 6 or lastNumber == 10: tempNumber = lastNumber + 1 if lastNumber == 3 or lastNumber == 7 or lastNumber == 11: tempNumber = lastNumber + 1 if lastNumber == 8: tempNumber = lastNumber + 1 elif dir == "\n": break lastNumber = tempNumber print ("New number: " + str(lastNumber)) # last number validated, so add to code lastChar = str(lastNumber) if lastNumber == 10: lastChar = "A" elif lastNumber == 11: lastChar = "B" elif lastNumber == 12: lastChar = "C" elif lastNumber == 13: lastChar = "D" finalCode = finalCode + lastChar print("Final code: " + finalCode)
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec02/dec02part2.py", "copies": "1", "size": "2682", "license": "mit", "hash": 4826960084361623000, "line_mean": 33.3846153846, "line_max": 74, "alpha_frac": 0.4656972409, "autogenerated": false, "ratio": 4.584615384615384, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5550312625515385, "avg_score": null, "num_lines": null }
# Advent of Code # Dec 4, Part 1 # @geekygirlsarah import re inputFile = "input.txt" # Tracking vars letterUsage = [] sumSectorIds = 0 commonLetters = ['a'] * 5 commonLettersCount = [0] * 5 with open(inputFile) as f: while True: line = f.readline(-1) if not line: break # Grab 3 numbers letterUsage = [0] * 26 for char in line: ascii = ord(char) - 97 if char == '-': continue if ascii < 0: break if char == '[': # just in case break letterUsage[ascii] += 1 parts = re.split(r"[\[\]-]", line) sizeParts = len(parts) checksum = sizeParts - 2 sectorId = sizeParts - 3 maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[0] = maxLetter commonLettersCount[0] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[1] = maxLetter commonLettersCount[1] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[2] = maxLetter commonLettersCount[2] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97) or commonLetters[2] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[3] = maxLetter commonLettersCount[3] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97) or commonLetters[2] == chr(i+97) or commonLetters[3] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[4] = maxLetter commonLettersCount[4] = maxCount # for i in range(ord('a'), ord('z')): # for j in range(0, 5): # if letterUsage[i] > commonLettersCount[j]: # for k in range(j+1, 5): # commonLetters[k+1] = commonLetters[k] # commonLettersCount[k+1] = commonLettersCount[k] # commonLetters[j] = i # commonLettersCount[j] = letterUsage[i] print ("Top 5 letters: ") print (commonLetters) print ("Code: " + parts[int(checksum)]) if ("".join(commonLetters) == parts[int(checksum)]): print("VALID!") sumSectorIds += int(parts[int(sectorId)]) print ("Sum of sector IDs: " + str(sumSectorIds))
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec04/dec04part1.py", "copies": "1", "size": "3535", "license": "mit", "hash": -4046089335241709600, "line_mean": 30.2831858407, "line_max": 148, "alpha_frac": 0.5035360679, "autogenerated": false, "ratio": 3.813376483279396, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4816912551179396, "avg_score": null, "num_lines": null }
# Advent of Code # Dec 4, Part 2 # @geekygirlsarah import re inputFile = "input.txt" # Tracking vars letterUsage = [] sumSectorIds = 0 commonLetters = ['a'] * 5 commonLettersCount = [0] * 5 with open(inputFile) as f: while True: line = f.readline(-1) if not line: break # Grab 3 numbers letterUsage = [0] * 26 for char in line: ascii = ord(char) - 97 if char == '-': continue if ascii < 0: break if char == '[': # just in case break letterUsage[ascii] += 1 parts = re.split(r"[\[\]-]", line) sizeParts = len(parts) checksum = sizeParts - 2 sectorId = sizeParts - 3 maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[0] = maxLetter commonLettersCount[0] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[1] = maxLetter commonLettersCount[1] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[2] = maxLetter commonLettersCount[2] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97) or commonLetters[2] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[3] = maxLetter commonLettersCount[3] = maxCount maxCount = 0 maxLetter = 'a' for i in range(0, 26): # through letterusage if letterUsage[i] > maxCount: if commonLetters[0] == chr(i+97) or commonLetters[1] == chr(i+97) or commonLetters[2] == chr(i+97) or commonLetters[3] == chr(i+97): continue maxLetter = chr(i+97) maxCount = letterUsage[i] commonLetters[4] = maxLetter commonLettersCount[4] = maxCount # for i in range(ord('a'), ord('z')): # for j in range(0, 5): # if letterUsage[i] > commonLettersCount[j]: # for k in range(j+1, 5): # commonLetters[k+1] = commonLetters[k] # commonLettersCount[k+1] = commonLettersCount[k] # commonLetters[j] = i # commonLettersCount[j] = letterUsage[i] if ("".join(commonLetters) == parts[int(checksum)]): print("VALID!") # print ("Top 5 letters: ") # print (commonLetters) print ("Code: " + parts[int(checksum)]) sumSectorIds += int(parts[int(sectorId)]) # Decrypt sectorMod = int(parts[int(sectorId)]) % 26 # why shift hundreds when you can shift a little? decryptedLine = "" for c in line: if c == '-': decryptedLine += " " continue if c == "[" or c.isdigit(): break ascii = (ord(c) - 97) + sectorMod if ascii > 25: ascii %= 26 ascii += 97 c = chr(ascii) decryptedLine += c print ("Decrypted line: " + decryptedLine) if decryptedLine == "northpole object storage ": print ("SECTION ID: " + parts[int(sectorId)]) print ("Sum of sector IDs: " + str(sumSectorIds))
{ "repo_name": "geekygirlsarah/adventofcode2016", "path": "dec04/dec04part2.py", "copies": "1", "size": "4291", "license": "mit", "hash": -3293319740919088000, "line_mean": 31.5075757576, "line_max": 148, "alpha_frac": 0.4856676765, "autogenerated": false, "ratio": 3.965804066543438, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4951471743043438, "avg_score": null, "num_lines": null }
# Advent of Code Solutions: Day 7, part 1 # https://github.com/emddudley/advent-of-code-solutions from collections import namedtuple Connection = namedtuple('Connection', 'l op r') def add_connection(connection, circuit): tokens = connection.strip().split(' ') l = tokens[len(tokens) - 5] if len(tokens) > 4 else None op = tokens[len(tokens) - 4] if len(tokens) > 3 else None r = tokens[len(tokens) - 3] wire = tokens[len(tokens) - 1] circuit[wire] = Connection(l, op, r) def eval_wire(wire, circuit, signals = None): if signals == None: signals = {} if wire.isdigit(): return int(wire) if wire in signals: return signals[wire] if circuit[wire].op == None: signals[wire] = eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'NOT': signals[wire] = ~eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'AND': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) & eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'OR': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) | eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'LSHIFT': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) << eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'RSHIFT': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) >> eval_wire(circuit[wire].r, circuit, signals) return signals[wire] circuit = {} with open('input', 'r') as input: for connection in input: add_connection(connection, circuit) print(eval_wire('a', circuit))
{ "repo_name": "emddudley/advent-of-code-solutions", "path": "2015/day-7/advent-day-7-1.py", "copies": "1", "size": "1676", "license": "unlicense", "hash": -8488930149415497000, "line_mean": 38.9047619048, "line_max": 116, "alpha_frac": 0.6515513126, "autogenerated": false, "ratio": 3.352, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9438213353345657, "avg_score": 0.013067591850868646, "num_lines": 42 }
# Advent of Code Solutions: Day 7, part 2 # https://github.com/emddudley/advent-of-code-solutions from collections import namedtuple Connection = namedtuple('Connection', 'l op r') def add_connection(connection, circuit): tokens = connection.strip().split(' ') l = tokens[len(tokens) - 5] if len(tokens) > 4 else None op = tokens[len(tokens) - 4] if len(tokens) > 3 else None r = tokens[len(tokens) - 3] wire = tokens[len(tokens) - 1] circuit[wire] = Connection(l, op, r) def eval_wire(wire, circuit, signals = None): if signals == None: signals = {} if wire.isdigit(): return int(wire) if wire in signals: return signals[wire] if circuit[wire].op == None: signals[wire] = eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'NOT': signals[wire] = ~eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'AND': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) & eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'OR': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) | eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'LSHIFT': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) << eval_wire(circuit[wire].r, circuit, signals) elif circuit[wire].op == 'RSHIFT': signals[wire] = eval_wire(circuit[wire].l, circuit, signals) >> eval_wire(circuit[wire].r, circuit, signals) return signals[wire] circuit = {} with open('input', 'r') as input: for connection in input: add_connection(connection, circuit) a = eval_wire('a', circuit) add_connection(str(a) + ' -> b', circuit) print(eval_wire('a', circuit))
{ "repo_name": "emddudley/advent-of-code-solutions", "path": "2015/day-7/advent-day-7-2.py", "copies": "1", "size": "1746", "license": "unlicense", "hash": 2856473482642655700, "line_mean": 38.6818181818, "line_max": 116, "alpha_frac": 0.6494845361, "autogenerated": false, "ratio": 3.3130929791271346, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44625775152271346, "avg_score": null, "num_lines": null }
#Adventure Cubed import pygame, sys, os from pygame.locals import * class Player(object): def __init__(self, pos): self.rect = pygame.Rect(pos[0],pos[1],16,16) self.moveX = 0 self.moveY = 0 def move(self, moveX, moveY): if moveX !=0: self.moveX = moveX self.moveOneAxis(moveX,0) if moveY !=0: self.moveY = moveY self.moveOneAxis(0,moveY) def moveOneAxis(self, moveX, moveY): self.rect.x += moveX self.rect.y += moveY self.moveX = moveX self.moveY = moveY for wall in walls: if self.rect.colliderect(wall.rect): if moveX > 0: self.rect.right = wall.rect.left if moveX < 0: self.rect.left = wall.rect.right if moveY > 0: self.rect.bottom = wall.rect.top if moveY < 0: self.rect.top = wall.rect.bottom for boulder in boulders: if self.rect.colliderect(boulder.rect): if moveX > 0: self.rect.right = boulder.rect.left boulder.rect.x += 1 boulder.moveBoulder(moveX, moveY) if moveX < 0: self.rect.left = boulder.rect.right boulder.rect.x += -1 boulder.moveBoulder(moveX, moveY) if moveY > 0: self.rect.bottom = boulder.rect.top boulder.rect.y += 1 boulder.moveBoulder(moveX, moveY) if moveY < 0: self.rect.top = boulder.rect.bottom boulder.rect.y += -1 boulder.moveBoulder(moveX, moveY) class Wall(object): def __init__(self, pos): walls.append(self) self.rect = pygame.Rect(pos[0],pos[1],16,16) class Boulder(object): def __init__(self, pos): self.moveX = 0 self.moveY = 0 boulders.append(self) self.rect = pygame.Rect(pos[0],pos[1],16,16) def moveBoulder(self, moveX, moveY): self.moveX = moveX self.moveY = moveY for wall in walls: if self.rect.colliderect(wall.rect): if moveX > 0: self.rect.right = wall.rect.left if moveX < 0: self.rect.left = wall.rect.right if moveY > 0: self.rect.bottom = wall.rect.top if moveY < 0: self.rect.top = wall.rect.bottom for boulder in boulders: if self.rect.colliderect(boulder.rect) and boulder.rect != self.rect: if moveX > 0: self.rect.right = boulder.rect.left if moveX < 0: self.rect.left = boulder.rect.right if moveY > 0: self.rect.bottom = boulder.rect.top if moveY < 0: self.rect.top = boulder.rect.bottom class Game(): def __init__(self): self.gameState = 6 def makeLevel(self): if self.gameState == 1: rKey = False gKey = False bKey = False yButton = False yOn = False oButton = False oOn = False pButton = False pOn = False level = [ "WWWWWWWWWW", "WCB W E W", "WWW W W", "W BBBW", "W W", "WWWWWWWWWW"] if self.gameState == 2: rKey = False gKey = False bKey = False yButton = False yOn = False oButton = True oOn = True pButton = False pOn = False level = [ 'WWWWWWWWWWWW', 'WWW W', 'WWW W', 'WWW W', 'WC W', 'WWW WWBWW', 'WWW W WW', 'WWW W WW', 'WWW W WW', 'WWW W WW', 'WWW WWOWW', 'WWW oWEWW', 'WWWWWWWWWWWW'] if self.gameState == 3: rKey = False gKey = False bKey = True yButton = False yOn = False oButton = True oOn = True pButton = False pOn = False level = [ "WWWWWWWWWWWW", "WWWCB WoWWW", "WE BW BK WWW", "WWWO B W", "WWWWWWWWWkWW", "WWWWWWWWWWWW"] if self.gameState == 4: rKey = False gKey = False bKey = True yButton = False yOn = False oButton = True oOn = True pButton = False pOn = False level = [ 'WWWWWWWWWWWWWWWW', 'WW WWWWWWW WWW', 'WkB W WWW', 'WWOW W W W KEW', 'WW WBW W W WWW', 'WWWW C Wo WWW', 'WWWWWWWWWWWWWWWW'] if self.gameState == 5: rKey = True gKey = False bKey = True yButton = True yOn = True oButton = True oOn = True pButton = True pOn = True level = [ 'WWWWWWWWWWWWWWWW', 'WWWWWWoWWWWWWWWW', 'WWWWWW WWWWWWWWW', 'WWWWWWPWWWWWWWWW', 'W pW O W', 'W C WW BWW WWEWW', 'W WB WkWWWWW', 'WWBW W WrWWWWW', 'WWyWY K WWWWW', 'WWRWW WWWWWWWWWW', 'WW WWWWWWWWWW', 'WWWWWWWWWWWWWWWW'] if self.gameState == 6: rKey = False gKey = False bKey = False yButton = False yOn = False oButton = False oOn = False pButton = False pOn = False level = [ 'WWWWWWWWWWWWWWWW', 'WB B B W', 'W B B B B W', 'W B B B B W', 'W B B W', 'W B W', 'W C B W', 'W B W', 'W B W', 'W BB B W', 'W B B B W', 'W B B B BW', 'W B BB BEW', 'WWWWWWWWWWWWWWWW'] screen = pygame.display.set_mode((len(level[0])*16, len(level)*16)) x = y = 0 wallsize = len(walls) increment = 0 """print wallsize if wallsize !=0: while(increment<wallsize): walls.pop(increment) increment +=1 print(increment)""" walls[:]=[] boulders[:] = [] for boulder in boulders: del boulder for row in level: for col in row: if col == "C": player = Player((x,y)) if col == "W": Wall((x,y)) if col == "B": hitBoulder = Boulder((x,y)) if col == "r": redKey = pygame.Rect(x,y,16,16) if col == "R": redDoor = pygame.Rect(x,y,16,16) if col == "g": greenKey = pygame.Rect(x,y,16,16) if col == "G": greenDoor = pygame.Rect(x,y,16,16) if col == "k": blueKey = pygame.Rect(x,y,16,16) if col == "K": blueDoor = pygame.Rect(x,y,16,16) if col == "y": yellowButton = pygame.Rect(x,y,16,16) if col == "Y": yellowDoor = pygame.Rect(x,y,16,16) if col == "o": orangeButton = pygame.Rect(x,y,16,16) if col == "O": orangeDoor = pygame.Rect(x,y,16,16) if col == "p": purpleButton = pygame.Rect(x,y,16,16) if col == "P": purpleDoor = pygame.Rect(x,y,16,16) if col == "E": exit = pygame.Rect(x,y,16,16) x += 16 x = 0 y += 16 while True: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() key = pygame.key.get_pressed() if key[pygame.K_LEFT]: player.move(-2,0) horizontal = 2 if key[pygame.K_RIGHT]: player.move(2,0) horizontal = -2 if key[pygame.K_UP]: player.move(0,-2) vertical = -2 if key[pygame.K_DOWN]: player.move(0,2) vertical = 2 else: vrtical = 0 horizontal = 0 screen.fill((0,0,0)) if player.rect.colliderect(exit): self.gameState+=1 self.makeLevel() for wall in walls: screen.blit(WALL,wall.rect) for boulder in boulders: if rKey: screen.blit(RK,redKey) screen.blit(RD,redDoor) if player.rect.colliderect(redKey): rKey = False if boulder.rect.colliderect(redKey): if boulder.moveX > 0: boulder.rect.right = redKey.left if boulder.moveX < 0: boulder.rect.left = redKey.right if boulder.moveY > 0: boulder.rect.bottom = redKey.top if boulder.moveY < 0: boulder.rect.top = redKey.bottom if player.rect.colliderect(redDoor): if player.moveX > 0: player.rect.right = redDoor.left if player.moveX < 0: player.rect.left = redDoor.right if player.moveY > 0: player.rect.bottom = redDoor.top if player.moveY < 0: player.rect.top = redDoor.bottom if boulder.rect.colliderect(redDoor): if boulder.moveX > 0: boulder.rect.right = redDoor.left if boulder.moveX < 0: boulder.rect.left = redDoor.right if boulder.moveY > 0: boulder.rect.bottom = redDoor.top if boulder.moveY < 0: boulder.rect.top = redDoor.bottom if gKey: screen.blit(GK,greenKey) screen.blit(GD,greenDoor) if player.rect.colliderect(greenKey): gKey = False if boulder.rect.colliderect(greenKey): if boulder.moveX > 0: boulder.rect.right = greenKey.left if boulder.moveX < 0: boulder.rect.left = greenKey.right if boulder.moveY > 0: boulder.rect.bottom = greenKey.top if boulder.moveY < 0: boulder.rect.top = greenKey.bottom if player.rect.colliderect(greenDoor): if player.moveX > 0: player.rect.right = greenDoor.left if player.moveX < 0: player.rect.left = greenDoor.right if player.moveY > 0: player.rect.bottom = greenDoor.top if player.moveY < 0: player.rect.top = greenDoor.bottom if boulder.rect.colliderect(greenDoor): if boulder.moveX > 0: boulder.rect.right = greenDoor.left if boulder.moveX < 0: boulder.rect.left = greenDoor.right if boulder.moveY > 0: boulder.rect.bottom = greenDoor.top if boulder.moveY < 0: boulder.rect.top = greenDoor.bottom if bKey: screen.blit(BK,blueKey) screen.blit(BD, blueDoor) if player.rect.colliderect(blueKey): bKey = False if boulder.rect.colliderect(blueKey): if boulder.moveX > 0: boulder.rect.right = blueKey.left if boulder.moveX < 0: boulder.rect.left = blueKey.right if boulder.moveY > 0: boulder.rect.bottom = blueKey.top if boulder.moveY < 0: boulder.rect.top = blueKey.bottom if player.rect.colliderect(blueDoor): if player.moveX > 0: player.rect.right = blueDoor.left if player.moveX < 0: player.rect.left = blueDoor.right if player.moveY > 0: player.rect.bottom = blueDoor.top if player.moveY < 0: player.rect.top = blueDoor.bottom if boulder.rect.colliderect(blueDoor): if boulder.moveX > 0: boulder.rect.right = blueDoor.left if boulder.moveX < 0: boulder.rect.left = blueDoor.right if boulder.moveY > 0: boulder.rect.bottom = blueDoor.top if boulder.moveY < 0: boulder.rect.top = blueDoor.bottom if yOn: screen.blit(YB,yellowButton) if yButton: screen.blit(YD,yellowDoor) if player.rect.colliderect(yellowButton): yButton = False if boulder.rect.colliderect(yellowButton): yButton = False hitBoulder = boulder if player.rect.colliderect(yellowDoor): if player.moveX > 0: player.rect.right = yellowDoor.left if player.moveX < 0: player.rect.left = yellowDoor.right if player.moveY > 0: player.rect.bottom = yellowDoor.top if player.moveY < 0: player.rect.top = yellowDoor.bottom if boulder.rect.colliderect(yellowDoor): if boulder.moveX > 0: boulder.rect.right = yellowDoor.left if boulder.moveX < 0: boulder.rect.left = yellowDoor.right if boulder.moveY > 0: boulder.rect.bottom = yellowDoor.top if boulder.moveY < 0: boulder.rect.top = yellowDoor.bottom elif player.rect.colliderect(yellowButton): yButton = False elif hitBoulder.rect.colliderect(yellowButton): yButton = False else: yButton = True if oOn: screen.blit(OB,orangeButton) if oButton: screen.blit(OD,orangeDoor) if player.rect.colliderect(orangeButton): oButton = False if boulder.rect.colliderect(orangeButton): oButton = False hitBoulder = boulder if player.rect.colliderect(orangeDoor): if player.moveX > 0: player.rect.right = orangeDoor.left if player.moveX < 0: player.rect.left = orangeDoor.right if player.moveY > 0: player.rect.bottom = orangeDoor.top if player.moveY < 0: player.rect.top = orangeDoor.bottom if boulder.rect.colliderect(orangeDoor): if boulder.moveX > 0: boulder.rect.right = orangeDoor.left if boulder.moveX < 0: boulder.rect.left = orangeDoor.right if boulder.moveY > 0: boulder.rect.bottom = orangeDoor.top if boulder.moveY < 0: boulder.rect.top = orangeDoor.bottom elif player.rect.colliderect(orangeButton): oButton = False elif hitBoulder.rect.colliderect(orangeButton): oButton = False #else: # oButton = True if pOn: screen.blit(PB,purpleButton) if pButton: screen.blit(PD,purpleDoor) if player.rect.colliderect(purpleButton): pButton = False if boulder.rect.colliderect(purpleButton): pButton = False hitBoulder = boulder if player.rect.colliderect(purpleDoor): if player.moveX > 0: player.rect.right = purpleDoor.left if player.moveX < 0: player.rect.left = purpleDoor.right if player.moveY > 0: player.rect.bottom = purpleDoor.top if player.moveY < 0: player.rect.top = purpleDoor.bottom if boulder.rect.colliderect(purpleDoor): if boulder.moveX > 0: boulder.rect.right = purpleDoor.left if boulder.moveX < 0: boulder.rect.left = purpleDoor.right if boulder.moveY > 0: boulder.rect.bottom = purpleDoor.top if boulder.moveY < 0: boulder.rect.top = purpleDoor.bottom elif player.rect.colliderect(purpleButton): pButton = False elif hitBoulder.rect.colliderect(purpleButton): pButton = False else: pButton = True screen.blit(EXIT,exit) for boulder in boulders: screen.blit(BOULDER,boulder.rect) screen.blit(PLAYER,player.rect) pygame.display.flip() pygame.init() WALL = pygame.image.load('sprite/wall.png') PLAYER = pygame.image.load('sprite/player.png') BOULDER = pygame.image.load('sprite/boulder.png') RK = pygame.image.load('sprite/redkey.png') RD = pygame.image.load('sprite/reddoor.png') GK = pygame.image.load('sprite/greenkey.png') GD = pygame.image.load('sprite/greendoor.png') BK = pygame.image.load('sprite/bluekey.png') BD = pygame.image.load('sprite/bluedoor.png') YB = pygame.image.load('sprite/yellowbutton.png') YD = pygame.image.load('sprite/yellowdoor.png') OB = pygame.image.load('sprite/orangebutton.png') OD = pygame.image.load('sprite/orangedoor.png') PB = pygame.image.load('sprite/purplebutton.png') PD = pygame.image.load('sprite/purpledoor.png') EXIT = pygame.image.load('sprite/exit.png') clock = pygame.time.Clock() game = Game() walls = [] boulders = [] global player global hitBoulder global screen global rKey global gKey global bKey global yButton global yOn global oButton global oOn global pButton global pOn vertical = 0 horizontal = 0 game.makeLevel()
{ "repo_name": "ProjectToWin/Puzzle-Game", "path": "Main.py", "copies": "1", "size": "29847", "license": "unlicense", "hash": -3422282193070499000, "line_mean": 52.3935599284, "line_max": 100, "alpha_frac": 0.2957751198, "autogenerated": false, "ratio": 5.885821337014396, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.011550343880658507, "num_lines": 559 }
from pyparsing import * import random import string def aOrAn( item ): if item.desc[0] in "aeiou": return "an " + item.desc else: return "a " + item.desc def enumerateItems(l): if len(l) == 0: return "nothing" out = [] if len(l) > 1: out.append(', '.join(aOrAn(item) for item in l[:-1])) out.append('and') out.append(aOrAn(l[-1])) return " ".join(out) def enumerateDoors(l): if len(l) == 0: return "" out = [] if len(l) > 1: out.append(', '.join(l[:-1])) out.append("and") out.append(l[-1]) return " ".join(out) class Room(object): def __init__(self, desc): self.desc = desc self.inv = [] self.gameOver = False self.doors = [None,None,None,None] def __getattr__(self,attr): return \ { "n":self.doors[0], "s":self.doors[1], "e":self.doors[2], "w":self.doors[3], }[attr] def enter(self,player): if self.gameOver: player.gameOver = True def addItem(self, it): self.inv.append(it) def removeItem(self,it): self.inv.remove(it) def describe(self): print(self.desc) visibleItems = [ it for it in self.inv if it.isVisible ] if random.random() > 0.5: if len(visibleItems) > 1: is_form = "are" else: is_form = "is" print("There %s %s here." % (is_form, enumerateItems(visibleItems))) else: print("You see %s." % (enumerateItems(visibleItems))) class Exit(Room): def __init__(self): super(Exit,self).__init__("") def enter(self,player): player.gameOver = True class Item(object): items = {} def __init__(self, desc): self.desc = desc self.isDeadly = False self.isFragile = False self.isBroken = False self.isTakeable = True self.isVisible = True self.isOpenable = False self.useAction = None self.usableConditionTest = None self.cantTakeMessage = "You can't take that!" Item.items[desc] = self def __str__(self): return self.desc def breakItem(self): if not self.isBroken: print("<Crash!>") self.desc = "broken " + self.desc self.isBroken = True def isUsable(self, player, target): if self.usableConditionTest: return self.usableConditionTest( player, target ) else: return False def useItem(self, player, target): if self.useAction: self.useAction(player, self, target) class OpenableItem(Item): def __init__(self, desc, contents=None): super(OpenableItem,self).__init__(desc) self.isOpenable = True self.isOpened = False if contents is not None: if isinstance(contents, Item): self.contents = [contents,] else: self.contents = contents else: self.contents = [] def openItem(self, player): if not self.isOpened: self.isOpened = not self.isOpened if self.contents is not None: for item in self.contents: player.room.addItem( item ) self.contents = [] self.desc = "open " + self.desc def closeItem(self, player): if self.isOpened: self.isOpened = not self.isOpened if self.desc.startswith("open "): self.desc = self.desc[5:] class Command(object): "Base class for commands" def __init__(self, verb, verbProg): self.verb = verb self.verbProg = verbProg @staticmethod def helpDescription(): return "" def _doCommand(self, player): pass def __call__(self, player ): print(self.verbProg.capitalize()+"...") self._doCommand(player) class MoveCommand(Command): def __init__(self, quals): super(MoveCommand,self).__init__("MOVE", "moving") self.direction = quals.direction[0] @staticmethod def helpDescription(): return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST (can abbreviate as 'GO N' and 'GO W', or even just 'E' and 'S')""" def _doCommand(self, player): rm = player.room nextRoom = rm.doors[ { "N":0, "S":1, "E":2, "W":3, }[self.direction] ] if nextRoom: player.moveTo( nextRoom ) else: print("Can't go that way.") class TakeCommand(Command): def __init__(self, quals): super(TakeCommand,self).__init__("TAKE", "taking") self.subject = quals.item @staticmethod def helpDescription(): return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in rm.inv and subj.isVisible: if subj.isTakeable: rm.removeItem(subj) player.take(subj) else: print(subj.cantTakeMessage) else: print("There is no %s here." % subj) class DropCommand(Command): def __init__(self, quals): super(DropCommand,self).__init__("DROP", "dropping") self.subject = quals.item @staticmethod def helpDescription(): return "DROP or LEAVE - drop an object (but fragile items may break)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in player.inv: rm.addItem(subj) player.drop(subj) else: print("You don't have %s." % (aOrAn(subj))) class InventoryCommand(Command): def __init__(self, quals): super(InventoryCommand,self).__init__("INV", "taking inventory") @staticmethod def helpDescription(): return "INVENTORY or INV or I - lists what items you have" def _doCommand(self, player): print("You have %s." % enumerateItems( player.inv )) class LookCommand(Command): def __init__(self, quals): super(LookCommand,self).__init__("LOOK", "looking") @staticmethod def helpDescription(): return "LOOK or L - describes the current room and any objects in it" def _doCommand(self, player): player.room.describe() class DoorsCommand(Command): def __init__(self, quals): super(DoorsCommand,self).__init__("DOORS", "looking for doors") @staticmethod def helpDescription(): return "DOORS - display what doors are visible from this room" def _doCommand(self, player): rm = player.room numDoors = sum([1 for r in rm.doors if r is not None]) if numDoors == 0: reply = "There are no doors in any direction." else: if numDoors == 1: reply = "There is a door to the " else: reply = "There are doors to the " doorNames = [ {0:"north", 1:"south", 2:"east", 3:"west"}[i] for i,d in enumerate(rm.doors) if d is not None ] #~ print doorNames reply += enumerateDoors( doorNames ) reply += "." print(reply) class UseCommand(Command): def __init__(self, quals): super(UseCommand,self).__init__("USE", "using") self.subject = Item.items[quals.usedObj] if quals.targetObj: self.target = Item.items[quals.targetObj] else: self.target = None @staticmethod def helpDescription(): return "USE or U - use an object, optionally IN or ON another object" def _doCommand(self, player): rm = player.room availItems = rm.inv + player.inv if self.subject in availItems: if self.subject.isUsable( player, self.target ): self.subject.useItem( player, self.target ) else: print("You can't use that here.") else: print("There is no %s here to use." % self.subject) class OpenCommand(Command): def __init__(self, quals): super(OpenCommand,self).__init__("OPEN", "opening") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "OPEN or O - open an object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isOpenable: if not self.subject.isOpened: self.subject.openItem( player ) else: print("It's already open.") else: print("You can't open that.") else: print("There is no %s here to open." % self.subject) class CloseCommand(Command): def __init__(self, quals): super(CloseCommand,self).__init__("CLOSE", "closing") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "CLOSE or CL - close an object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isOpenable: if self.subject.isOpened: self.subject.closeItem( player ) else: print("You can't close that, it's not open.") else: print("You can't close that.") else: print("There is no %s here to close." % self.subject) class QuitCommand(Command): def __init__(self, quals): super(QuitCommand,self).__init__("QUIT", "quitting") @staticmethod def helpDescription(): return "QUIT or Q - ends the game" def _doCommand(self, player): print("Ok....") player.gameOver = True class HelpCommand(Command): def __init__(self, quals): super(HelpCommand,self).__init__("HELP", "helping") @staticmethod def helpDescription(): return "HELP or H or ? - displays this help message" def _doCommand(self, player): print("Enter any of the following commands (not case sensitive):") for cmd in [ InventoryCommand, DropCommand, TakeCommand, UseCommand, OpenCommand, CloseCommand, MoveCommand, LookCommand, DoorsCommand, QuitCommand, HelpCommand, ]: print(" - %s" % cmd.helpDescription()) print() class AppParseException(ParseException): pass class Parser(object): def __init__(self): self.bnf = self.makeBNF() def makeBNF(self): invVerb = oneOf("INV INVENTORY I", caseless=True) dropVerb = oneOf("DROP LEAVE", caseless=True) takeVerb = oneOf("TAKE PICKUP", caseless=True) | \ (CaselessLiteral("PICK") + CaselessLiteral("UP") ) moveVerb = oneOf("MOVE GO", caseless=True) | empty useVerb = oneOf("USE U", caseless=True) openVerb = oneOf("OPEN O", caseless=True) closeVerb = oneOf("CLOSE CL", caseless=True) quitVerb = oneOf("QUIT Q", caseless=True) lookVerb = oneOf("LOOK L", caseless=True) doorsVerb = CaselessLiteral("DOORS") helpVerb = oneOf("H HELP ?",caseless=True) itemRef = OneOrMore(Word(alphas)).setParseAction( self.validateItemName ) nDir = oneOf("N NORTH",caseless=True).setParseAction(replaceWith("N")) sDir = oneOf("S SOUTH",caseless=True).setParseAction(replaceWith("S")) eDir = oneOf("E EAST",caseless=True).setParseAction(replaceWith("E")) wDir = oneOf("W WEST",caseless=True).setParseAction(replaceWith("W")) moveDirection = nDir | sDir | eDir | wDir invCommand = invVerb dropCommand = dropVerb + itemRef("item") takeCommand = takeVerb + itemRef("item") useCommand = useVerb + itemRef("usedObj") + \ Optional(oneOf("IN ON",caseless=True)) + \ Optional(itemRef,default=None)("targetObj") openCommand = openVerb + itemRef("item") closeCommand = closeVerb + itemRef("item") moveCommand = moveVerb + moveDirection("direction") quitCommand = quitVerb lookCommand = lookVerb doorsCommand = doorsVerb helpCommand = helpVerb # attach command classes to expressions invCommand.setParseAction(InventoryCommand) dropCommand.setParseAction(DropCommand) takeCommand.setParseAction(TakeCommand) useCommand.setParseAction(UseCommand) openCommand.setParseAction(OpenCommand) closeCommand.setParseAction(CloseCommand) moveCommand.setParseAction(MoveCommand) quitCommand.setParseAction(QuitCommand) lookCommand.setParseAction(LookCommand) doorsCommand.setParseAction(DoorsCommand) helpCommand.setParseAction(HelpCommand) # define parser using all command expressions return ( invCommand | useCommand | openCommand | closeCommand | dropCommand | takeCommand | moveCommand | lookCommand | doorsCommand | helpCommand | quitCommand )("command") + LineEnd() def validateItemName(self,s,l,t): iname = " ".join(t) if iname not in Item.items: raise AppParseException(s,l,"No such item '%s'." % iname) return iname def parseCmd(self, cmdstr): try: ret = self.bnf.parseString(cmdstr) return ret except AppParseException as pe: print(pe.msg) except ParseException as pe: print(random.choice([ "Sorry, I don't understand that.", "Huh?", "Excuse me?", "???", "What?" ] )) class Player(object): def __init__(self, name): self.name = name self.gameOver = False self.inv = [] def moveTo(self, rm): self.room = rm rm.enter(self) if self.gameOver: if rm.desc: rm.describe() print("Game over!") else: rm.describe() def take(self,it): if it.isDeadly: print("Aaaagh!...., the %s killed me!" % it) self.gameOver = True else: self.inv.append(it) def drop(self,it): self.inv.remove(it) if it.isFragile: it.breakItem() def createRooms( rm ): """ create rooms, using multiline string showing map layout string contains symbols for the following: A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by reference letter -, | symbols indicate connection between rooms <, >, ^, . symbols indicate one-way connection between rooms """ # start with empty dictionary of rooms ret = {} # look for room symbols, and initialize dictionary # - exit room is always marked 'Z' for c in rm: if c in string.ascii_letters: if c != "Z": ret[c] = Room(c) else: ret[c] = Exit() # scan through input string looking for connections between rooms rows = rm.split("\n") for row,line in enumerate(rows): for col,c in enumerate(line): if c in string.ascii_letters: room = ret[c] n = None s = None e = None w = None # look in neighboring cells for connection symbols (must take # care to guard that neighboring cells exist before testing # contents) if col > 0 and line[col-1] in "<-": other = line[col-2] w = ret[other] if col < len(line)-1 and line[col+1] in "->": other = line[col+2] e = ret[other] if row > 1 and col < len(rows[row-1]) and rows[row-1][col] in '|^': other = rows[row-2][col] n = ret[other] if row < len(rows)-1 and col < len(rows[row+1]) and rows[row+1][col] in '|.': other = rows[row+2][col] s = ret[other] # set connections to neighboring rooms room.doors=[n,s,e,w] return ret # put items in rooms def putItemInRoom(i,r): if isinstance(r,str): r = rooms[r] r.addItem( Item.items[i] ) def playGame(p,startRoom): # create parser parser = Parser() p.moveTo( startRoom ) while not p.gameOver: cmdstr = input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command( p ) print() print("You ended the game with:") for i in p.inv: print(" -", aOrAn(i)) #==================== # start game definition roomMap = """ d-Z | f-c-e . | q<b | A """ rooms = createRooms( roomMap ) rooms["A"].desc = "You are standing on the front porch of a wooden shack." rooms["b"].desc = "You are in a garden." rooms["c"].desc = "You are in a kitchen." rooms["d"].desc = "You are on the back porch." rooms["e"].desc = "You are in a library." rooms["f"].desc = "You are on the patio." rooms["q"].desc = "You are sinking in quicksand. You're dead..." rooms["q"].gameOver = True # define global variables for referencing rooms frontPorch = rooms["A"] garden = rooms["b"] kitchen = rooms["c"] backPorch = rooms["d"] library = rooms["e"] patio = rooms["f"] # create items itemNames = """sword.diamond.apple.flower.coin.shovel.book.mirror.telescope.gold bar""".split(".") for itemName in itemNames: Item( itemName ) Item.items["apple"].isDeadly = True Item.items["mirror"].isFragile = True Item.items["coin"].isVisible = False Item.items["shovel"].usableConditionTest = ( lambda p,t: p.room is garden ) def useShovel(p,subj,target): coin = Item.items["coin"] if not coin.isVisible and coin in p.room.inv: coin.isVisible = True Item.items["shovel"].useAction = useShovel Item.items["telescope"].isTakeable = False def useTelescope(p,subj,target): print("You don't see anything.") Item.items["telescope"].useAction = useTelescope OpenableItem("treasure chest", Item.items["gold bar"]) Item.items["chest"] = Item.items["treasure chest"] Item.items["chest"].isTakeable = False Item.items["chest"].cantTakeMessage = "It's too heavy!" OpenableItem("mailbox") Item.items["mailbox"].isTakeable = False Item.items["mailbox"].cantTakeMessage = "It's nailed to the wall!" putItemInRoom("mailbox", frontPorch) putItemInRoom("shovel", frontPorch) putItemInRoom("coin", garden) putItemInRoom("flower", garden) putItemInRoom("apple", library) putItemInRoom("mirror", library) putItemInRoom("telescope", library) putItemInRoom("book", kitchen) putItemInRoom("diamond", backPorch) putItemInRoom("treasure chest", patio) # create player plyr = Player("Bob") plyr.take( Item.items["sword"] ) # start game playGame( plyr, frontPorch )
{ "repo_name": "nzavagli/UnrealPy", "path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/pyparsing-2.0.3/examples/adventureEngine.py", "copies": "2", "size": "19947", "license": "mit", "hash": 8128528127414193000, "line_mean": 29.7824074074, "line_max": 98, "alpha_frac": 0.5513611069, "autogenerated": false, "ratio": 3.844834232845027, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5396195339745027, "avg_score": null, "num_lines": null }
from pyparsing import * import random def aOrAn( item ): if item.desc[0] in "aeiou": return "an" else: return "a" def enumerateItems(l): if len(l) == 0: return "nothing" out = [] for item in l: if len(l)>1 and item == l[-1]: out.append("and") out.append( aOrAn( item ) ) if item == l[-1]: out.append(item.desc) else: if len(l)>2: out.append(item.desc+",") else: out.append(item.desc) return " ".join(out) def enumerateDoors(l): if len(l) == 0: return "" out = [] for item in l: if len(l)>1 and item == l[-1]: out.append("and") if item == l[-1]: out.append(item) else: if len(l)>2: out.append(item+",") else: out.append(item) return " ".join(out) class Room(object): def __init__(self, desc): self.desc = desc self.inv = [] self.gameOver = False self.doors = [None,None,None,None] def __getattr__(self,attr): return \ { "n":self.doors[0], "s":self.doors[1], "e":self.doors[2], "w":self.doors[3], }[attr] def enter(self,player): if self.gameOver: player.gameOver = True def addItem(self, it): self.inv.append(it) def removeItem(self,it): self.inv.remove(it) def describe(self): print self.desc visibleItems = [ it for it in self.inv if it.isVisible ] if len(visibleItems) > 1: print "There are %s here." % enumerateItems( visibleItems ) else: print "There is %s here." % enumerateItems( visibleItems ) class Exit(Room): def __init__(self): super(Exit,self).__init__("") def enter(self,player): player.gameOver = True class Item(object): items = {} def __init__(self, desc): self.desc = desc self.isDeadly = False self.isFragile = False self.isBroken = False self.isTakeable = True self.isVisible = True self.isOpenable = False self.useAction = None self.usableConditionTest = None Item.items[desc] = self def __str__(self): return self.desc def breakItem(self): if not self.isBroken: print "<Crash!>" self.desc = "broken " + self.desc self.isBroken = True def isUsable(self, player, target): if self.usableConditionTest: return self.usableConditionTest( player, target ) else: return False def useItem(self, player, target): if self.useAction: self.useAction(player, self, target) class OpenableItem(Item): def __init__(self, desc, contents = None): super(OpenableItem,self).__init__(desc) self.isOpenable = True self.isOpened = False self.contents = contents def openItem(self, player): if not self.isOpened: self.isOpened = True self.isOpenable = False if self.contents is not None: player.room.addItem( self.contents ) self.desc = "open " + self.desc class Command(object): "Base class for commands" def __init__(self, verb, verbProg): self.verb = verb self.verbProg = verbProg @staticmethod def helpDescription(): return "" def _doCommand(self, player): pass def __call__(self, player ): print self.verbProg.capitalize()+"..." self._doCommand(player) class MoveCommand(Command): def __init__(self, quals): super(MoveCommand,self).__init__("MOVE", "moving") self.direction = quals["direction"][0] @staticmethod def helpDescription(): return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST (can abbreviate as 'GO N' and 'GO W', or even just 'E' and 'S')""" def _doCommand(self, player): rm = player.room nextRoom = rm.doors[ { "N":0, "S":1, "E":2, "W":3, }[self.direction] ] if nextRoom: player.moveTo( nextRoom ) else: print "Can't go that way." class TakeCommand(Command): def __init__(self, quals): super(TakeCommand,self).__init__("TAKE", "taking") self.subject = quals["item"] @staticmethod def helpDescription(): return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in rm.inv and subj.isVisible: if subj.isTakeable: rm.removeItem(subj) player.take(subj) else: print "You can't take that!" else: print "There is no %s here." % subj class DropCommand(Command): def __init__(self, quals): super(DropCommand,self).__init__("DROP", "dropping") self.subject = quals["item"] @staticmethod def helpDescription(): return "DROP or LEAVE - drop an object (but fragile items may break)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in player.inv: rm.addItem(subj) player.drop(subj) else: print "You don't have %s %s." % (aOrAn(subj), subj) class InventoryCommand(Command): def __init__(self, quals): super(InventoryCommand,self).__init__("INV", "taking inventory") @staticmethod def helpDescription(): return "INVENTORY or INV or I - lists what items you have" def _doCommand(self, player): print "You have %s." % enumerateItems( player.inv ) class LookCommand(Command): def __init__(self, quals): super(LookCommand,self).__init__("LOOK", "looking") @staticmethod def helpDescription(): return "LOOK or L - describes the current room and any objects in it" def _doCommand(self, player): player.room.describe() class DoorsCommand(Command): def __init__(self, quals): super(DoorsCommand,self).__init__("DOORS", "looking for doors") @staticmethod def helpDescription(): return "DOORS - display what doors are visible from this room" def _doCommand(self, player): rm = player.room numDoors = sum([1 for r in rm.doors if r is not None]) if numDoors == 0: reply = "There are no doors in any direction." else: if numDoors == 1: reply = "There is a door to the " else: reply = "There are doors to the " doorNames = [ {0:"north", 1:"south", 2:"east", 3:"west"}[i] for i,d in enumerate(rm.doors) if d is not None ] #~ print doorNames reply += enumerateDoors( doorNames ) reply += "." print reply class UseCommand(Command): def __init__(self, quals): super(UseCommand,self).__init__("USE", "using") self.subject = Item.items[ quals["usedObj"] ] if "targetObj" in quals.keys(): self.target = Item.items[ quals["targetObj"] ] else: self.target = None @staticmethod def helpDescription(): return "USE or U - use an object, optionally IN or ON another object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isUsable( player, self.target ): self.subject.useItem( player, self.target ) else: print "You can't use that here." else: print "There is no %s here to use." % self.subject class OpenCommand(Command): def __init__(self, quals): super(OpenCommand,self).__init__("OPEN", "opening") self.subject = Item.items[ quals["item"] ] @staticmethod def helpDescription(): return "OPEN or O - open an object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isOpenable: self.subject.openItem( player ) else: print "You can't use that here." else: print "There is no %s here to use." % self.subject class QuitCommand(Command): def __init__(self, quals): super(QuitCommand,self).__init__("QUIT", "quitting") @staticmethod def helpDescription(): return "QUIT or Q - ends the game" def _doCommand(self, player): print "Ok...." player.gameOver = True class HelpCommand(Command): def __init__(self, quals): super(HelpCommand,self).__init__("HELP", "helping") @staticmethod def helpDescription(): return "HELP or H or ? - displays this help message" def _doCommand(self, player): print "Enter any of the following commands (not case sensitive):" for cmd in [ InventoryCommand, DropCommand, TakeCommand, UseCommand, OpenCommand, MoveCommand, LookCommand, DoorsCommand, QuitCommand, HelpCommand, ]: print " - %s" % cmd.helpDescription() print class AppParseException(ParseException): pass class Parser(object): def __init__(self): self.bnf = self.makeBNF() def makeCommandParseAction( self, cls ): def cmdParseAction(s,l,tokens): return cls(tokens) return cmdParseAction def makeBNF(self): invVerb = oneOf("INV INVENTORY I", caseless=True) dropVerb = oneOf("DROP LEAVE", caseless=True) takeVerb = oneOf("TAKE PICKUP", caseless=True) | \ (CaselessLiteral("PICK") + CaselessLiteral("UP") ) moveVerb = oneOf("MOVE GO", caseless=True) | empty useVerb = oneOf("USE U", caseless=True) openVerb = oneOf("OPEN O", caseless=True) quitVerb = oneOf("QUIT Q", caseless=True) lookVerb = oneOf("LOOK L", caseless=True) doorsVerb = CaselessLiteral("DOORS") helpVerb = oneOf("H HELP ?",caseless=True) itemRef = OneOrMore(Word(alphas)).setParseAction( self.validateItemName ) nDir = oneOf("N NORTH",caseless=True).setParseAction(replaceWith("N")) sDir = oneOf("S SOUTH",caseless=True).setParseAction(replaceWith("S")) eDir = oneOf("E EAST",caseless=True).setParseAction(replaceWith("E")) wDir = oneOf("W WEST",caseless=True).setParseAction(replaceWith("W")) moveDirection = nDir | sDir | eDir | wDir invCommand = invVerb dropCommand = dropVerb + itemRef.setResultsName("item") takeCommand = takeVerb + itemRef.setResultsName("item") useCommand = useVerb + itemRef.setResultsName("usedObj") + \ Optional(oneOf("IN ON",caseless=True)) + \ Optional(itemRef,default=None).setResultsName("targetObj") openCommand = openVerb + itemRef.setResultsName("item") moveCommand = moveVerb + moveDirection.setResultsName("direction") quitCommand = quitVerb lookCommand = lookVerb doorsCommand = doorsVerb helpCommand = helpVerb invCommand.setParseAction( self.makeCommandParseAction( InventoryCommand ) ) dropCommand.setParseAction( self.makeCommandParseAction( DropCommand ) ) takeCommand.setParseAction( self.makeCommandParseAction( TakeCommand ) ) useCommand.setParseAction( self.makeCommandParseAction( UseCommand ) ) openCommand.setParseAction( self.makeCommandParseAction( OpenCommand ) ) moveCommand.setParseAction( self.makeCommandParseAction( MoveCommand ) ) quitCommand.setParseAction( self.makeCommandParseAction( QuitCommand ) ) lookCommand.setParseAction( self.makeCommandParseAction( LookCommand ) ) doorsCommand.setParseAction( self.makeCommandParseAction( DoorsCommand ) ) helpCommand.setParseAction( self.makeCommandParseAction( HelpCommand ) ) return ( invCommand | useCommand | openCommand | dropCommand | takeCommand | moveCommand | lookCommand | doorsCommand | helpCommand | quitCommand ).setResultsName("command") + LineEnd() def validateItemName(self,s,l,t): iname = " ".join(t) if iname not in Item.items: raise AppParseException(s,l,"No such item '%s'." % iname) return iname def parseCmd(self, cmdstr): try: ret = self.bnf.parseString(cmdstr) return ret except AppParseException, pe: print pe.msg except ParseException, pe: print random.choice([ "Sorry, I don't understand that.", "Huh?", "Excuse me?", "???", "What?" ] ) class Player(object): def __init__(self, name): self.name = name self.gameOver = False self.inv = [] def moveTo(self, rm): self.room = rm rm.enter(self) if self.gameOver: if rm.desc: rm.describe() print "Game over!" else: rm.describe() def take(self,it): if it.isDeadly: print "Aaaagh!...., the %s killed me!" % it self.gameOver = True else: self.inv.append(it) def drop(self,it): self.inv.remove(it) if it.isFragile: it.breakItem() def createRooms( rm ): """ create rooms, using multiline string showing map layout string contains symbols for the following: A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by reference letter -, | symbols indicate connection between rooms <, >, ^, . symbols indicate one-way connection between rooms """ # start with empty dictionary of rooms ret = {} # look for room symbols, and initialize dictionary # - exit room is always marked 'Z' for c in rm: if "A" <= c <= "Z" or "a" <= c <= "z": if c != "Z": ret[c] = Room(c) else: ret[c] = Exit() # scan through input string looking for connections between rooms rows = rm.split("\n") for row,line in enumerate(rows): for col,c in enumerate(line): if "A" <= c <= "Z" or "a" <= c <= "z": room = ret[c] n = None s = None e = None w = None # look in neighboring cells for connection symbols (must take # care to guard that neighboring cells exist before testing # contents) if col > 0 and line[col-1] in "<-": other = line[col-2] w = ret[other] if col < len(line)-1 and line[col+1] in "->": other = line[col+2] e = ret[other] if row > 1 and col < len(rows[row-1]) and rows[row-1][col] in '|^': other = rows[row-2][col] n = ret[other] if row < len(rows)-1 and col < len(rows[row+1]) and rows[row+1][col] in '|.': other = rows[row+2][col] s = ret[other] # set connections to neighboring rooms room.doors=[n,s,e,w] return ret # put items in rooms def putItemInRoom(i,r): if isinstance(r,basestring): r = rooms[r] r.addItem( Item.items[i] ) def playGame(p,startRoom): # create parser parser = Parser() p.moveTo( startRoom ) while not p.gameOver: cmdstr = raw_input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command( p ) print print "You ended the game with:" for i in p.inv: print " -", aOrAn(i), i #==================== # start game definition roomMap = """ d-Z | f-c-e . | q<b | A """ rooms = createRooms( roomMap ) rooms["A"].desc = "You are standing at the front door." rooms["b"].desc = "You are in a garden." rooms["c"].desc = "You are in a kitchen." rooms["d"].desc = "You are on the back porch." rooms["e"].desc = "You are in a library." rooms["f"].desc = "You are on the patio." rooms["q"].desc = "You are sinking in quicksand. You're dead..." rooms["q"].gameOver = True # define global variables for referencing rooms frontPorch = rooms["A"] garden = rooms["b"] kitchen = rooms["c"] backPorch = rooms["d"] library = rooms["e"] patio = rooms["f"] # create items itemNames = """sword.diamond.apple.flower.coin.shovel.book.mirror.telescope.gold bar""".split(".") for itemName in itemNames: Item( itemName ) Item.items["apple"].isDeadly = True Item.items["mirror"].isFragile = True Item.items["coin"].isVisible = False Item.items["shovel"].usableConditionTest = ( lambda p,t: p.room is garden ) def useShovel(p,subj,target): coin = Item.items["coin"] if not coin.isVisible and coin in p.room.inv: coin.isVisible = True Item.items["shovel"].useAction = useShovel Item.items["telescope"].isTakeable = False def useTelescope(p,subj,target): print "You don't see anything." Item.items["telescope"].useAction = useTelescope OpenableItem("treasure chest", Item.items["gold bar"]) putItemInRoom("shovel", frontPorch) putItemInRoom("coin", garden) putItemInRoom("flower", garden) putItemInRoom("apple", library) putItemInRoom("mirror", library) putItemInRoom("telescope", library) putItemInRoom("book", kitchen) putItemInRoom("diamond", backPorch) putItemInRoom("treasure chest", patio) # create player plyr = Player("Bob") plyr.take( Item.items["sword"] ) # start game playGame( plyr, frontPorch )
{ "repo_name": "scrollback/kuma", "path": "vendor/packages/pyparsing/examples/adventureEngine.py", "copies": "16", "size": "19432", "license": "mpl-2.0", "hash": -1301176848301296400, "line_mean": 29.6998368679, "line_max": 98, "alpha_frac": 0.530671058, "autogenerated": false, "ratio": 3.9248636639062817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.018141104748513798, "num_lines": 613 }
from pyparsingOD import * import random import string def aOrAn( item ): if item.desc[0] in "aeiou": return "an " + item.desc else: return "a " + item.desc def enumerateItems(l): if len(l) == 0: return "nothing" out = [] if len(l) > 1: out.append(', '.join(aOrAn(item) for item in l[:-1])) out.append('and') out.append(aOrAn(l[-1])) return " ".join(out) def enumerateDoors(l): if len(l) == 0: return "" out = [] if len(l) > 1: out.append(', '.join(l[:-1])) out.append("and") out.append(l[-1]) return " ".join(out) class Room(object): def __init__(self, desc): self.desc = desc self.inv = [] self.gameOver = False self.doors = [None,None,None,None] def __getattr__(self,attr): return \ { "n":self.doors[0], "s":self.doors[1], "e":self.doors[2], "w":self.doors[3], }[attr] def enter(self,player): if self.gameOver: player.gameOver = True def addItem(self, it): self.inv.append(it) def removeItem(self,it): self.inv.remove(it) def describe(self): print(self.desc) visibleItems = [ it for it in self.inv if it.isVisible ] if random.random() > 0.5: if len(visibleItems) > 1: is_form = "are" else: is_form = "is" print("There %s %s here." % (is_form, enumerateItems(visibleItems))) else: print("You see %s." % (enumerateItems(visibleItems))) class Exit(Room): def __init__(self): super(Exit,self).__init__("") def enter(self,player): player.gameOver = True class Item(object): items = {} def __init__(self, desc): self.desc = desc self.isDeadly = False self.isFragile = False self.isBroken = False self.isTakeable = True self.isVisible = True self.isOpenable = False self.useAction = None self.usableConditionTest = None self.cantTakeMessage = "You can't take that!" Item.items[desc] = self def __str__(self): return self.desc def breakItem(self): if not self.isBroken: print("<Crash!>") self.desc = "broken " + self.desc self.isBroken = True def isUsable(self, player, target): if self.usableConditionTest: return self.usableConditionTest( player, target ) else: return False def useItem(self, player, target): if self.useAction: self.useAction(player, self, target) class OpenableItem(Item): def __init__(self, desc, contents=None): super(OpenableItem,self).__init__(desc) self.isOpenable = True self.isOpened = False if contents is not None: if isinstance(contents, Item): self.contents = [contents,] else: self.contents = contents else: self.contents = [] def openItem(self, player): if not self.isOpened: self.isOpened = not self.isOpened if self.contents is not None: for item in self.contents: player.room.addItem( item ) self.contents = [] self.desc = "open " + self.desc def closeItem(self, player): if self.isOpened: self.isOpened = not self.isOpened if self.desc.startswith("open "): self.desc = self.desc[5:] class Command(object): "Base class for commands" def __init__(self, verb, verbProg): self.verb = verb self.verbProg = verbProg @staticmethod def helpDescription(): return "" def _doCommand(self, player): pass def __call__(self, player ): print(self.verbProg.capitalize()+"...") self._doCommand(player) class MoveCommand(Command): def __init__(self, quals): super(MoveCommand,self).__init__("MOVE", "moving") self.direction = quals.direction[0] @staticmethod def helpDescription(): return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST (can abbreviate as 'GO N' and 'GO W', or even just 'E' and 'S')""" def _doCommand(self, player): rm = player.room nextRoom = rm.doors[ { "N":0, "S":1, "E":2, "W":3, }[self.direction] ] if nextRoom: player.moveTo( nextRoom ) else: print("Can't go that way.") class TakeCommand(Command): def __init__(self, quals): super(TakeCommand,self).__init__("TAKE", "taking") self.subject = quals.item @staticmethod def helpDescription(): return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in rm.inv and subj.isVisible: if subj.isTakeable: rm.removeItem(subj) player.take(subj) else: print(subj.cantTakeMessage) else: print("There is no %s here." % subj) class DropCommand(Command): def __init__(self, quals): super(DropCommand,self).__init__("DROP", "dropping") self.subject = quals.item @staticmethod def helpDescription(): return "DROP or LEAVE - drop an object (but fragile items may break)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in player.inv: rm.addItem(subj) player.drop(subj) else: print("You don't have %s." % (aOrAn(subj))) class InventoryCommand(Command): def __init__(self, quals): super(InventoryCommand,self).__init__("INV", "taking inventory") @staticmethod def helpDescription(): return "INVENTORY or INV or I - lists what items you have" def _doCommand(self, player): print("You have %s." % enumerateItems( player.inv )) class LookCommand(Command): def __init__(self, quals): super(LookCommand,self).__init__("LOOK", "looking") @staticmethod def helpDescription(): return "LOOK or L - describes the current room and any objects in it" def _doCommand(self, player): player.room.describe() class DoorsCommand(Command): def __init__(self, quals): super(DoorsCommand,self).__init__("DOORS", "looking for doors") @staticmethod def helpDescription(): return "DOORS - display what doors are visible from this room" def _doCommand(self, player): rm = player.room numDoors = sum([1 for r in rm.doors if r is not None]) if numDoors == 0: reply = "There are no doors in any direction." else: if numDoors == 1: reply = "There is a door to the " else: reply = "There are doors to the " doorNames = [ {0:"north", 1:"south", 2:"east", 3:"west"}[i] for i,d in enumerate(rm.doors) if d is not None ] #~ print doorNames reply += enumerateDoors( doorNames ) reply += "." print(reply) class UseCommand(Command): def __init__(self, quals): super(UseCommand,self).__init__("USE", "using") self.subject = Item.items[quals.usedObj] if quals.targetObj: self.target = Item.items[quals.targetObj] else: self.target = None @staticmethod def helpDescription(): return "USE or U - use an object, optionally IN or ON another object" def _doCommand(self, player): rm = player.room availItems = rm.inv + player.inv if self.subject in availItems: if self.subject.isUsable( player, self.target ): self.subject.useItem( player, self.target ) else: print("You can't use that here.") else: print("There is no %s here to use." % self.subject) class OpenCommand(Command): def __init__(self, quals): super(OpenCommand,self).__init__("OPEN", "opening") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "OPEN or O - open an object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isOpenable: if not self.subject.isOpened: self.subject.openItem( player ) else: print("It's already open.") else: print("You can't open that.") else: print("There is no %s here to open." % self.subject) class CloseCommand(Command): def __init__(self, quals): super(CloseCommand,self).__init__("CLOSE", "closing") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "CLOSE or CL - close an object" def _doCommand(self, player): rm = player.room availItems = rm.inv+player.inv if self.subject in availItems: if self.subject.isOpenable: if self.subject.isOpened: self.subject.closeItem( player ) else: print("You can't close that, it's not open.") else: print("You can't close that.") else: print("There is no %s here to close." % self.subject) class QuitCommand(Command): def __init__(self, quals): super(QuitCommand,self).__init__("QUIT", "quitting") @staticmethod def helpDescription(): return "QUIT or Q - ends the game" def _doCommand(self, player): print("Ok....") player.gameOver = True class HelpCommand(Command): def __init__(self, quals): super(HelpCommand,self).__init__("HELP", "helping") @staticmethod def helpDescription(): return "HELP or H or ? - displays this help message" def _doCommand(self, player): print("Enter any of the following commands (not case sensitive):") for cmd in [ InventoryCommand, DropCommand, TakeCommand, UseCommand, OpenCommand, CloseCommand, MoveCommand, LookCommand, DoorsCommand, QuitCommand, HelpCommand, ]: print(" - %s" % cmd.helpDescription()) print() class AppParseException(ParseException): pass class Parser(object): def __init__(self): self.bnf = self.makeBNF() def makeBNF(self): invVerb = oneOf("INV INVENTORY I", caseless=True) dropVerb = oneOf("DROP LEAVE", caseless=True) takeVerb = oneOf("TAKE PICKUP", caseless=True) | \ (CaselessLiteral("PICK") + CaselessLiteral("UP") ) moveVerb = oneOf("MOVE GO", caseless=True) | empty useVerb = oneOf("USE U", caseless=True) openVerb = oneOf("OPEN O", caseless=True) closeVerb = oneOf("CLOSE CL", caseless=True) quitVerb = oneOf("QUIT Q", caseless=True) lookVerb = oneOf("LOOK L", caseless=True) doorsVerb = CaselessLiteral("DOORS") helpVerb = oneOf("H HELP ?",caseless=True) itemRef = OneOrMore(Word(alphas)).setParseAction( self.validateItemName ) nDir = oneOf("N NORTH",caseless=True).setParseAction(replaceWith("N")) sDir = oneOf("S SOUTH",caseless=True).setParseAction(replaceWith("S")) eDir = oneOf("E EAST",caseless=True).setParseAction(replaceWith("E")) wDir = oneOf("W WEST",caseless=True).setParseAction(replaceWith("W")) moveDirection = nDir | sDir | eDir | wDir invCommand = invVerb dropCommand = dropVerb + itemRef("item") takeCommand = takeVerb + itemRef("item") useCommand = useVerb + itemRef("usedObj") + \ Optional(oneOf("IN ON",caseless=True)) + \ Optional(itemRef,default=None)("targetObj") openCommand = openVerb + itemRef("item") closeCommand = closeVerb + itemRef("item") moveCommand = moveVerb + moveDirection("direction") quitCommand = quitVerb lookCommand = lookVerb doorsCommand = doorsVerb helpCommand = helpVerb # attach command classes to expressions invCommand.setParseAction(InventoryCommand) dropCommand.setParseAction(DropCommand) takeCommand.setParseAction(TakeCommand) useCommand.setParseAction(UseCommand) openCommand.setParseAction(OpenCommand) closeCommand.setParseAction(CloseCommand) moveCommand.setParseAction(MoveCommand) quitCommand.setParseAction(QuitCommand) lookCommand.setParseAction(LookCommand) doorsCommand.setParseAction(DoorsCommand) helpCommand.setParseAction(HelpCommand) # define parser using all command expressions return ( invCommand | useCommand | openCommand | closeCommand | dropCommand | takeCommand | moveCommand | lookCommand | doorsCommand | helpCommand | quitCommand )("command") + LineEnd() def validateItemName(self,s,l,t): iname = " ".join(t) if iname not in Item.items: raise AppParseException(s,l,"No such item '%s'." % iname) return iname def parseCmd(self, cmdstr): try: ret = self.bnf.parseString(cmdstr) return ret except AppParseException as pe: print(pe.msg) except ParseException as pe: print(random.choice([ "Sorry, I don't understand that.", "Huh?", "Excuse me?", "???", "What?" ] )) class Player(object): def __init__(self, name): self.name = name self.gameOver = False self.inv = [] def moveTo(self, rm): self.room = rm rm.enter(self) if self.gameOver: if rm.desc: rm.describe() print("Game over!") else: rm.describe() def take(self,it): if it.isDeadly: print("Aaaagh!...., the %s killed me!" % it) self.gameOver = True else: self.inv.append(it) def drop(self,it): self.inv.remove(it) if it.isFragile: it.breakItem() def createRooms( rm ): """ create rooms, using multiline string showing map layout string contains symbols for the following: A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by reference letter -, | symbols indicate connection between rooms <, >, ^, . symbols indicate one-way connection between rooms """ # start with empty dictionary of rooms ret = {} # look for room symbols, and initialize dictionary # - exit room is always marked 'Z' for c in rm: if c in string.ascii_letters: if c != "Z": ret[c] = Room(c) else: ret[c] = Exit() # scan through input string looking for connections between rooms rows = rm.split("\n") for row,line in enumerate(rows): for col,c in enumerate(line): if c in string.ascii_letters: room = ret[c] n = None s = None e = None w = None # look in neighboring cells for connection symbols (must take # care to guard that neighboring cells exist before testing # contents) if col > 0 and line[col-1] in "<-": other = line[col-2] w = ret[other] if col < len(line)-1 and line[col+1] in "->": other = line[col+2] e = ret[other] if row > 1 and col < len(rows[row-1]) and rows[row-1][col] in '|^': other = rows[row-2][col] n = ret[other] if row < len(rows)-1 and col < len(rows[row+1]) and rows[row+1][col] in '|.': other = rows[row+2][col] s = ret[other] # set connections to neighboring rooms room.doors=[n,s,e,w] return ret # put items in rooms def putItemInRoom(i,r): if isinstance(r,str): r = rooms[r] r.addItem( Item.items[i] ) def playGame(p,startRoom): # create parser parser = Parser() p.moveTo( startRoom ) while not p.gameOver: cmdstr = input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command( p ) print() print("You ended the game with:") for i in p.inv: print(" -", aOrAn(i)) #==================== # start game definition roomMap = """ d-Z | f-c-e . | q<b | A """ rooms = createRooms( roomMap ) rooms["A"].desc = "You are standing on the front porch of a wooden shack." rooms["b"].desc = "You are in a garden." rooms["c"].desc = "You are in a kitchen." rooms["d"].desc = "You are on the back porch." rooms["e"].desc = "You are in a library." rooms["f"].desc = "You are on the patio." rooms["q"].desc = "You are sinking in quicksand. You're dead..." rooms["q"].gameOver = True # define global variables for referencing rooms frontPorch = rooms["A"] garden = rooms["b"] kitchen = rooms["c"] backPorch = rooms["d"] library = rooms["e"] patio = rooms["f"] # create items itemNames = """sword.diamond.apple.flower.coin.shovel.book.mirror.telescope.gold bar""".split(".") for itemName in itemNames: Item( itemName ) Item.items["apple"].isDeadly = True Item.items["mirror"].isFragile = True Item.items["coin"].isVisible = False Item.items["shovel"].usableConditionTest = ( lambda p,t: p.room is garden ) def useShovel(p,subj,target): coin = Item.items["coin"] if not coin.isVisible and coin in p.room.inv: coin.isVisible = True Item.items["shovel"].useAction = useShovel Item.items["telescope"].isTakeable = False def useTelescope(p,subj,target): print("You don't see anything.") Item.items["telescope"].useAction = useTelescope OpenableItem("treasure chest", Item.items["gold bar"]) Item.items["chest"] = Item.items["treasure chest"] Item.items["chest"].isTakeable = False Item.items["chest"].cantTakeMessage = "It's too heavy!" OpenableItem("mailbox") Item.items["mailbox"].isTakeable = False Item.items["mailbox"].cantTakeMessage = "It's nailed to the wall!" putItemInRoom("mailbox", frontPorch) putItemInRoom("shovel", frontPorch) putItemInRoom("coin", garden) putItemInRoom("flower", garden) putItemInRoom("apple", library) putItemInRoom("mirror", library) putItemInRoom("telescope", library) putItemInRoom("book", kitchen) putItemInRoom("diamond", backPorch) putItemInRoom("treasure chest", patio) # create player plyr = Player("Bob") plyr.take( Item.items["sword"] ) # start game playGame( plyr, frontPorch )
{ "repo_name": "schlichtanders/pyparsing-2.0.3-OrderedDict", "path": "examples/adventureEngine.py", "copies": "1", "size": "20597", "license": "mit", "hash": 4502245178500715500, "line_mean": 29.7854938272, "line_max": 98, "alpha_frac": 0.534058358, "autogenerated": false, "ratio": 3.9128039513677813, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49468623093677816, "avg_score": null, "num_lines": null }
'Adventure in Style, based on the classic game and an unusual book.' __author__ = 'Nick Montfort (based on works by Crowther, Woods, and Queneau)' __copyright__ = 'Copyright 2011 Nick Montfort' __license__ = 'ISC' __version__ = '0.5.0.0' __status__ = 'Development' from random import random, randint, choice from item_model import Actor, Door, Room, SharedThing, Substance, Thing from action_model import Behave, Configure, Modify, Sense from joker import update_spin import can discourse = { 'command_grammar': { 'CAGE ACCESSIBLE': ['cage ACCESSIBLE', '(cage in|entrap|trap) ACCESSIBLE'], 'OIL ACCESSIBLE': ['oil ACCESSIBLE', 'lubricate ACCESSIBLE'], 'UNCHAIN ACCESSIBLE': ['(unchain|unleash) ACCESSIBLE'], 'WATER ACCESSIBLE': ['water ACCESSIBLE']}, 'compass': { 'across': 'across', 'barren': 'barren', 'bed': 'bed', 'bedquilt': 'bedquilt', 'building': 'house', 'broken': 'broken', 'canyon': 'canyon', 'cavern': 'cavern', 'climb': 'climb', 'cobble': 'cobble', 'crack': 'crack', 'crawl': 'crawl', 'dark': 'dark', 'debris': 'debris', 'depression': 'depression', 'downstream': 'downstream', 'enter': 'enter', 'entrance': 'entrance', 'exit': 'leave', 'floor': 'floor', 'forest': 'forest', 'fork': 'fork', 'giant': 'giant', 'gully': 'gully', 'hall': 'hall', 'hill': 'hill', 'hole': 'hole', 'house': 'house', 'in': 'in', 'jump': 'jump', 'leave': 'leave', 'left': 'left', 'low': 'low', 'nowhere': 'nowhere', 'onward': 'onward', 'oriental': 'oriental', 'outdoors': 'outdoors', 'over': 'over', 'pit': 'pit', 'plover': 'plover', 'plugh': 'plugh', 'reservoir': 'reservoir', 'right': 'right', 'rock': 'rock', 'room': 'room', 'secret': 'secret', 'shell': 'shell', 'slab': 'slab', 'slit': 'slit', 'stair': 'stair', 'stream': 'stream', 'surface': 'surface', 'tunnel': 'tunnel', 'upstream': 'upstream', 'valley': 'valley', 'view': 'view', 'wall': 'wall', 'xyzzy': 'xyzzy', 'y2': 'y2'}, 'metadata': { 'title': 'Adventure in Style', 'headline': 'Two Great Tastes that Taste Great Together', 'people': [('by', 'Nick Montfort'), ('based on Adventure by', 'Will Crowther and Don Woods'), ('and based on Exercises in Style by', 'Raymond Queneau')], 'prologue': """Welcome to Adventure!! Note that the cave entrance is SOUTH, SOUTH, SOUTH from here."""}, 'spin': { 'commanded': '@adventurer', 'focalizer': '@adventurer', 'narratee': '@adventurer'}, 'verb_representation': { 'examine': '[agent/s] [take/v] a look at [direct/o]', 'leave': '[agent/s] [set/v] off [direction]ward', 'scare': '[agent/s] [scare/v] [direct/o] away', 'appear': '[direct/s] [appear/v]', 'block': '[direct/s] [are/not/v] able to get by [agent/o]', 'flit': '[agent/s] [flit/v] away, remaining in the general area', 'flee': '[agent/s] [flee/v], trembling (or at least wriggling)', 'blast': 'the treasure valut [blast/1/v] open -- Victory!', 'disappear': '[direct/s] [scurry/v] away out of sight', 'set_closing': 'a voice [boom/v], "The cave will be closing soon!"'}} def COMMAND_cage(agent, tokens, _): 'to confine in a cage' return Configure('cage', agent, template=('[agent/s] [put/v] [direct/o] in ' + '[indirect/o]'), direct=tokens[1], new=('in', '@cage')) def COMMAND_oil(agent, tokens, concept): 'to pour oil onto something, such as a rusty door' direct = '@cosmos' for held in concept.descendants(agent): if held[:4] == '@oil': direct = held return Configure('pour', agent, template='[agent/s] [oil/v] [indirect/o]', direct=direct, new=('on', tokens[1])) def COMMAND_turn_to(agent, tokens, concept): 'to rotate; to revolve; to make to face differently' if tokens[1] == '@lamp': tokens[1] = '@dial' try: value = int(tokens[2]) except ValueError: value = 1 if value < 1 or value > len(variation): value = 1 return Modify('turn', agent, template='[agent/s] [turn/v] [direct/o] to ' + str(value), direct=tokens[1], feature='setting', new=value) def COMMAND_unchain(agent, tokens, _): 'to free from being restrained by a chain' return Modify('unchain', agent, direct=tokens[1], feature='chained', new=False) def COMMAND_water(agent, tokens, concept): 'to pour water onto something, such as a plant' direct = '@cosmos' for held in concept.descendants(agent): if held[:6] == '@water': direct = held return Configure('pour', agent, template='[agent/s] [water/v] [indirect/o]', direct=direct, new=('on', tokens[1])) initial_actions = [ Sense('examine', '@adventurer', direct='@end_of_road', modality='sight')] all_treasures = ['@nugget', '@diamonds', '@bars', '@jewelry', '@coins', '@eggs', '@trident', '@vase', '@emerald', '@pyramid', '@pearl', '@chest', '@rug', '@spices', '@chain'] interjections = ['uh', 'uh', 'uh', 'um', 'um', 'er'] def double_template(phrases): new_phrases = [] for phrase in phrases.split(): new_phrases.append(phrase) if phrase[-3:] == '/o]': new_phrases += ['and', choice(['the radiant being', 'the majestic presence', 'the tremendous aura', 'the incredible unity', 'the solemn physicality', 'the uplifting nature', 'the full existence', 'the all-singing, all-dancing being', 'the profound air', 'the ineffable quality', 'the unbearable lightness', 'the harmonious flow', 'the powerful memory']), 'of', phrase] return ' '.join(new_phrases) def hesitant_sentence(phrases): new_phrases = phrases[:1] for original in phrases[1:]: if randint(1,6) == 1: if not new_phrases[-1][-1] in ',.:;': new_phrases.append(',') new_phrases.append(choice(interjections)) if not original[:1] in ',.:;': new_phrases.append(',') new_phrases.append(original) return new_phrases def surprise_sentence(phrases): chosen = randint(1,8) if chosen == 1: phrases = [choice(['whoa', 'dude']) + ','] + phrases elif chosen == 2: if not phrases[-1][-1] in ',.:;': phrases[-1] += ',' phrases = phrases + [choice(['man', 'dude',])] phrases[-1] = phrases[-1] + '!' return phrases def surprise_paragraph(paragraphs): chosen = randint(1,3) if chosen == 1: paragraphs = paragraphs + choice(['Amazing!', 'Wow!', 'Awesome!', 'Out of this world!', 'Incredible!']) return paragraphs def valley_sentence(phrases): new_phrases = phrases[:1] for original in phrases[1:]: if randint(1,5) == 1: if not new_phrases[-1][-1] in ',.:;': new_phrases.append(',') new_phrases.append('like') if not original in ',.:;': new_phrases.append(',') new_phrases.append(original) if len(new_phrases) > 0 and randint(1,6) == 1: if not new_phrases[-1] in ',.:;': new_phrases.append(',') new_phrases.append(choice(['totally', 'for sure'])) return new_phrases variation = [ ['typical', {}], ['memoir', {'narrator': '@adventurer', 'narratee': None, 'time': 'after'}], ['royal', {'narrator': '@adventurer', 'narratee': None, '@adventurer': [('@adventurer', 'number', 'plural')]}], # NEXT-STEPS # This '@adventurer' entry doesn't do anything now; it's an idea for now # spin files might override aspects of the simulated world to allow tellings # of this sort. ['impersonal', {'narrator': None, 'narratee': None}], ['prophecy', {'time': 'before'}], ['retrograde', {'order': 'retrograde', 'window': 7, 'room_name_headings': False, 'time_words': True}], # NEXT-STEPS # 'time-words' are baked into the Microplanner right now. It would be better # to pass in a dictionary with lists of words that can be selected from at # random, at the least -- perheps with functions that would return # appropriate words. ['flashback', {'order': 'analepsis'}], ['double entry', {'narratee': None, 'template_filter': [double_template]}], ['oriented', {'known_directions': True, 'room_name_headings': False}], ['in medias res', {'progressive': True}], ['finished by then', {'perfect': True, 'time': 'before'}], ['tell it to the lamp', {'narrator': None, 'narratee': '@lamp'}], ] class Cosmos(Actor): def __init__(self, tag, **keywords): self.closing = 0 self.lamp_controls_changed = False Actor.__init__(self, tag, **keywords) def update_spin(self, world, discourse): if world.item['@lamp'].on and self.lamp_controls_changed: discourse.spin = discourse.initial_spin.copy() _, spin = variation[world.item['@dial'].setting - 1] discourse.spin = update_spin(discourse.spin, spin) if world.item['@hesitant'].on: discourse.spin['sentence_filter'] += [hesitant_sentence] if world.item['@surprise'].on: discourse.spin['sentence_filter'] += [surprise_sentence] discourse.spin['paragraph_filter'] += [surprise_paragraph] if world.item['@valley_girl'].on: discourse.spin['sentence_filter'] += [valley_sentence] if variation[world.item['@dial'].setting - 1][0] == 'royal': world.item['@adventurer'].number = 'plural' adv_concept = world.concept['@adventurer'] adv_concept.item['@adventurer'].number = 'plural' else: world.item['@adventurer'].number = 'singular' adv_concept = world.concept['@adventurer'] adv_concept.item['@adventurer'].number = 'singular' self.lamp_controls_changed = False return discourse.spin def react(self, world, basis): actions = [] if (basis.modify and basis.direct == '@dial' and basis.feature == 'setting') or (basis.modify and basis.direct == '@lamp' and basis.feature == 'on' and basis.new_value == True): self.lamp_controls_changed = True elif (basis.modify and basis.direct in ['@hesitant', '@surprise', '@valley_girl']): self.lamp_controls_changed = True if (not world.item['@troll'].scared and not world.item['@troll'].parent == '@northeast_side_of_chasm' and basis.configure and basis.direct == '@adventurer' and basis.new_parent == '@northeast_side_of_chasm'): actions.append(Configure('appear', '@cosmos', template='[direct/s] [appear/v]', direct='@troll', new=('in', '@northeast_side_of_chasm'), salience=0.9)) actions.append(Modify('change_blocked', '@cosmos', direct='@troll', feature='blocked', new=['cross', 'over', 'southwest'], salience=0.1)) if (self.closing > 0 and world.ticks == self.closing): actions.append(Configure('appear', '@cosmos', template=('[direct/s] [appear/v] in ' + '[indirect/o]'), direct='@adventurer', new=('in', '@northeast_end'), salience=0.9)) return actions cosmos = Cosmos('@cosmos', called='creation', referring=None, allowed=can.have_any_item) class Lamp(Thing): '@lamp is the only instance.' def react(self, _, basis): 'Increase/decrease the light emitted when turned on/off.' actions = [] if (basis.modify and basis.direct == str(self) and basis.feature == 'on'): # If turned on, make it glow; otherwise, have it stop glowing. if basis.new_value: actions.append(Modify('light', basis.agent, direct=str(self), feature='glow', new=0.6, salience=0.1)) else: actions.append(Modify('extinguish', basis.agent, direct=str(self), feature='glow', new=0.0, salience=0.1)) return actions class Dial(Thing): '@dial is the only instance.' def react(self, _, basis): 'Select the appropraite word for the new variation.' actions = [] if (basis.modify and basis.direct == str(self) and basis.feature == 'setting'): (name, _) = variation[basis.new_value - 1] actions.append(Modify('select', basis.agent, template=('[agent/s] [select/v]' + ' [begin-caps]"' + name + '"'), direct=basis.direct, feature='word', new=name)) return actions class Button(Thing): '@button is the only instance.' def react(self, world, basis): 'Blast and win the game if the black rod is in place.' actions = [] if (basis.behave and hasattr(basis, 'direct') and basis.direct == str(self) and basis.force > 0.1 and str(world.room_of('@black_rod')) == '@northeast_end'): blast = Behave('blast', '@cosmos', direct='@southwest_end', force=1) # The adventurer won't sense the action unless it has something # visible, such as the room, as its direct object. blast.final = True actions.append(blast) return actions class Guardian(Thing): """There are several subclasses representing different guardians.""" def __init__(self, tag, **keywords): self.alive = True Thing.__init__(self, tag, **keywords) def prevent(self, world, basis): """Block exits.""" if (basis.behave and basis.verb == 'leave' and basis.direction in self.blocked): return True return False class Snake(Guardian): '@snake is the only instance.' def react(self, world, basis): 'Flee if the bird arrives.' actions = [] if (basis.configure and basis.direct == '@bird' and basis.new_parent == world.room_of(str(self))): actions.append(Configure('flee', '@cosmos', template='[@snake/s] [flee/v]', direct='@snake', new=('of', '@cosmos'), salience=0.9)) return actions + Guardian.react(self, world, basis) class Dragon(Guardian): '@dragon is the only instance.' def react(self, world, basis): 'Perish if struck, move off of rug, change description.' actions = [] if (basis.behave and basis.direct == str(self) and basis.force > 0.3): actions.append(Modify('kill', basis.agent, direct=str(self), feature='alive', new=False, salience=0.9)) actions.append(Configure('fall', '@cosmos', direct=str(self), new=('in', str(world.room_of(str(self)))), salience=0.1)) sight = """ [this] [is/1/v] just a huge, dead dragon, flopped on the ground""" actions.append(Modify('change_appearance', basis.agent, direct=str(self), feature='sight', new=sight, salience=0.0)) return actions + Guardian.react(self, world, basis) class Troll(Guardian): '@troll is the only instance.' def __init__(self, tag, **keywords): self.scared = False Guardian.__init__(self, tag, **keywords) def react(self, world, basis): actions = [] 'Disappear if given a treasure.' if (basis.configure and basis.new_parent == str(self) and 'treasure' in world.item[basis.direct].qualities): actions.append(Configure('disappear', '@cosmos', template='[direct/s] [disappear/v]', direct='@troll', new=('of', '@cosmos'), salience=0.9)) 'Flee if scared.' if (basis.modify and basis.direct == str(self) and basis.feature == 'scared' and basis.new_value == True): actions.append(Configure('flee', '@cosmos', template='[@troll/s] [flee/v]', direct='@troll', new=('of', '@cosmos'), salience=0.9)) return actions + Guardian.react(self, world, basis) class Bear(Actor): '@bear is the only instance.' def __init__(self, tag, **keywords): self.angry = True self.chained = True Actor.__init__(self, tag, **keywords) def act(self, command_map, concept): 'If not chained and the troll is present, scare him.' actions = [] if ((not self.chained) and '@troll' in concept.item and concept.room_of(str(self)) == concept.room_of('@troll')): actions.append(Modify('scare', str(self), template='[agent/s] [scare/v] [@troll/s]', direct='@troll', feature='scared', new=True)) return actions def prevent(self, world, basis): # No one can manipulate the chain if the bear is angry. if ((basis.configure or basis.modify) and basis.direct == '@chain' and self.angry): return True return False def react(self, world, basis): 'Food- and chain-related reactions.' actions = [] # Eat food if it is offered, calm down. if (basis.configure and basis.new_parent == str(self) and 'food' in world.item[basis.direct].qualities): actions.append(Behave('eat', str(self), direct=basis.direct)) actions.append(Modify('calm', '@cosmos', template='[direct/s] [calm/v] down', direct=str(self), feature='angry', new=False)) # If chained, follow the holder of the chain. if (self.chained and basis.configure and basis.direct == world.item['@chain'].parent): actions.append(Configure('follow', str(self), template=('[agent/s] [follow/v] [' + basis.direct + '/o]'), direct=str(self), new=(basis.new_link, basis.new_parent))) # If entering the bridge, destroy it; kill whoever is holding the chain. if (basis.configure and basis.direct == str(self) and basis.new_parent == '@bridge'): actions.append(Modify('collapse', '@cosmos', template='the bridge [collapse/1/v]', direct='@bridge', feature='connects', new=())) actions.append(Modify('die', '@cosmos', template='[direct/s] [die/1/v]', direct='@bear', feature='alive', new=False)) if self.chained: holder = world.item['@chain'].parent actions.append(Modify('die', '@cosmos', template='[direct/s] [die/1/v]', direct=holder, feature='alive', new=False)) return actions class Oyster(Thing): '@oyster is the only instance.' def prevent(self, _, basis): if (basis.modify and basis.direct == str(self) and basis.feature == 'open' and basis.new_value and (not hasattr(basis, 'indirect') or not basis.indirect == '@trident')): return True return False def react(self, _, basis): 'When opened, move the pearl to the cul-de-sac.' actions = [] if (basis.modify and basis.direct == str(self) and basis.feature == 'open' and basis.new_value and ('in', '@pearl') in self.children): sight = """ an enormous oyster, currently [open/@oyster/a]""" actions.append(Configure('fall', '@cosmos', template=('[direct/o] [fall/v] from ' + '[@oyster/o]'), direct='@pearl', new=('in', '@cul_de_sac'))) actions.append(Modify('change_sight', basis.agent, direct=str(self), feature='sight', new=sight, salience=0)) actions.append(Modify('rename', basis.agent, direct=str(self), feature='called', template="""so, at it happens, [this] actually [is/v/v] an oyster, not a clam""", new='(enormous) oyster')) return actions class Plant(Thing): '@plant is the only instance.' def __init__(self, tag, **keywords): self.size = 0 self.alive = True Thing.__init__(self, tag, **keywords) def react(self, world, basis): 'Consume water; then grow when watered, the first two times.' actions = [] if (basis.configure and basis.new_parent == str(self) and basis.direct.partition('_')[0] == '@oil'): # Consume oil actions.append(Configure('consume', '@cosmos', template=('[direct/s] [soak/v] into [' + str(self) + '/o]'), direct=basis.direct, new=('of', '@cosmos'), salience=0.1)) # And die! actions.append(Modify('die', '@cosmos', template='[@plant/s] [die/v]', direct=str(self), feature='alive', new=False)) if (basis.configure and basis.new_parent == str(self) and basis.direct.partition('_')[0] == '@water'): # Consume water actions.append(Configure('consume', '@cosmos', template=('[@plant/s] [soak/v] up ' + '[direct/o]'), direct=basis.direct, new=('of', '@cosmos'), salience=0.1)) # If not already the maximum size, grow. if self.size == 0 or self.size == 1: actions.append(Modify('grow', '@cosmos', template='[@plant/s] [grow/v]', direct=str(self), feature='size', new=(self.size + 1))) sight = ["""a twelve-foot beanstalk""", """a 25-foot beanstalk"""][self.size] actions.append(Modify('change_sight', '@cosmos', direct=str(self), feature='sight', new=sight, salience=0.0)) if self.size == 1: exits = world.item['@west_pit'].exits.copy() exits.update({'climb': '@narrow_corridor'}) actions.append(Modify('change_exits', '@cosmos', direct='@west_pit', feature='exits', new=exits, salience=0.0)) return actions class RustyDoor(Door): '@rusty_door is the only instance.' def react(self, world, basis): 'Consume oil; then unlock if not already unlocked.' actions = [] if (basis.configure and basis.new_parent == str(self) and basis.direct.partition('_')[0] == '@oil'): # Consume the oil actions.append(Configure('consume', '@cosmos', template=('[direct/s] [soak/v] into [' + str(self) + '/o]'), direct=basis.direct, new=('of', '@cosmos'), salience=0.1)) # If not already unlocked, unlock. if self.locked: actions.append(Modify('unlock', '@cosmos', template=('[' + str(self) + '/s] ' + '[come/v] loose'), direct=str(self), feature='locked', new=False, salience=0.9)) return actions class Bird(Thing): '@bird is the only instance.' def __init__(self, tag, **keywords): self.alive = True Thing.__init__(self, tag, **keywords) def prevent(self, world, basis): if (basis.configure and basis.direct == str(self) and basis.new_parent == '@cage' and basis.agent == world.item['@rusty_rod'].parent): return True return False def react(self, world, basis): 'Flee from one holding the rod; Leave all but the cage or a room.' actions = [] if (basis.configure and basis.direct == str(self) and not basis.new_parent == '@cage' and not world.item[basis.new_parent].room): room = str(world.item[str(self)].place(world)) actions.append(Configure('flit', str(self), template='[agent/s] [flit/v] off', direct=str(self), new=('in', room), salience=0.7)) return actions class Delicate(Thing): '@vase is the only instance.' def react(self, _, basis): 'Shatter if placed on anything other than the pillow.' actions = [] if (basis.configure and basis.direct == str(self)): if (not basis.new_parent in ['@pillow', '@soft_room', '@adventurer', '@cosmos']): smash = Configure('smash', basis.agent, direct=basis.direct, new=('of', '@cosmos'), salience=0.9) actions.append(smash) return actions class Wanderer(Actor): 'Not used, but could be used for the dwarves and the pirate.' def act(self, command_map, world): if random() > .2 and len(self.exits(world)) > 0: way = choice(self.exits(world).keys()) return [self.do_command('exit ' + way, command_map, world)] class OutsideArea(Room): 'Subclass for all forest/outside Rooms, with sky and sun.' def __init__(self, tag, **keywords): if 'shared' not in keywords: keywords['shared'] = [] keywords['shared'] += ['@sky', '@sun'] Room.__init__(self, tag, **keywords) class CaveRoom(Room): 'Subclass for all cave Rooms.' def __init__(self, tag, **keywords): adj, noun = '', '' if 'referring' in keywords: (adj, _, noun) = keywords['referring'].partition('|') keywords['referring'] = adj + '| cave chamber room' + noun if 'glow' not in keywords: keywords['glow'] = 0.0 Room.__init__(self, tag, **keywords) class Bridgable(CaveRoom): '@fissure_east is the only instance.' def react(self, world, basis): 'When the rod is waved, the bridge appears.' actions = [] if (basis.behave and basis.direct == '@rusty_rod' and basis.verb == 'shake' and 'west' not in self.exits): exits = self.exits.copy() exits.update({'west': '@bridge', 'over': '@bridge'}) sight = """ [*/s] [are/v] on the east bank of a fissure slicing clear across the hall the mist [is/1/v] quite thick [here], and the fissure [is/1/v] too wide to jump it [is/1/v] a good thing the fissure [is/1/v] bridged [now], and [*/s] [are/v] able to walk across it to the west """ actions.append(Modify('change_exits', '@cosmos', template='a_bridge [now] [lead/v] west', direct=str(self), feature='exits', new=exits, salience=0.9)) actions.append(Modify('change_sight', '@cosmos', direct=str(self), feature='sight', new=sight, salience=0.0)) return actions class EggSummoning(CaveRoom): '@giant_room_92 is the only instance.' def react(self, world, basis): 'Have "fee fie foe sum" summon the eggs here.' actions = [] if (basis.behave and hasattr(basis, 'utterance') and basis.utterance in ['fee fie foe foo', '"fee fie foe foo"'] and ('@eggs', 'in') not in self.children): actions.append(Configure('appear', '@cosmos', template='[direct/s] [appear/v]', direct='@eggs', new=('in', str(self)), salience=0.9)) return actions class Building(Room): '@building_3 is the only instance.' def react(self, world, basis): 'When all treasures are in place, countdown to cave closing.' actions = [] if world.item['@cosmos'].closing == 0: all_there = True for treasure in all_treasures: all_there &= (str(self) == str(world.room_of(treasure))) if all_there: actions.append(Modify('change_closing', '@cosmos', direct='@cosmos', feature='closing', new=(world.ticks + 28), salience=0)) return actions def contain_any_thing_if_open(tag, link, world): return link == 'in' and getattr(world.item['@cage'], 'open') def support_one_item(tag, link, world): return link == 'on' and len(world.item['@pillow'].children) < 2 def contain_any_treasure(tag, link, world): return link == 'in' and 'treasure' in world.item[tag].qualities def possess_any_treasure(tag, link, world): return link == 'of' and 'treasure' in world.item[tag].qualities def support_any_item_or_dragon(tag, link, world): return link == 'on' and '@dragon' not in world.item['@rug'].children def support_chain(tag, link, world): return (tag, link) == ('@chain', 'on') can.contain_any_thing_if_open = contain_any_thing_if_open can.support_one_item = support_one_item can.contain_any_treasure = contain_any_treasure can.possess_any_treasure = possess_any_treasure can.support_any_item_or_dragon = support_any_item_or_dragon can.support_chain = support_chain items = [ Substance('@water', called='water', referring='clear |', qualities=['drink', 'liquid'], consumable=True, sight='clear water', taste="nothing unpleasant"), Substance('@oil', called='oil', referring='black dark thick |', qualities=['liquid'], sight='black oil'), Actor('@adventurer in @end_of_road', article='the', called='(intrepid) adventurer', allowed=can.possess_any_thing, qualities=['person', 'man'], gender='?', sight='a nondescript adventurer'), OutsideArea('@end_of_road', article='the', called='end of the road', referring='of the | road end', exits={'hill': '@hill', 'west': '@hill', 'up': '@hill', 'enter': '@building', 'house': '@building', 'in': '@building', 'east': '@building', 'downstream': '@valley', 'gully': '@valley', 'stream': '@valley', 'south': '@valley', 'down': '@valley', 'forest': '@forest_near_road', 'north': '@forest_near_road', 'depression': '@outside_grate'}, sight=""" [*/s] [stand/ing/v] at _the_end of _a_road before _a_small_brick_building [@stream_by_road/s] [flow/v] out of _the_building and down _a_gully"""), Thing('@stream_by_road part_of @end_of_road', article='a', called='small stream', referring='| stream creek river spring', source='@water', mention=False, sight='a small stream', touch='cool water', hearing='quiet babbling'), SharedThing('@sky', article='the', called='sky', referring='blue clear | heavens', mention=False, accessible=False, sight='a blue, clear sky'), SharedThing('@sun', article='the', called='sun', mention=False, accessible=False), OutsideArea('@hill', article='the', called='hill in road', exits={'hill': '@end_of_road', 'house': '@end_of_road', 'onward': '@end_of_road', 'east': '@end_of_road', 'north': '@end_of_road', 'down': '@end_of_road', 'forest': '@forest_near_road', 'south': '@forest_near_road'}, sight=""" [*/s] [walk/ed/v] up _a_hill, still in _the_forest _the_road [slope/1/v] back down _the_other_side of _the_hill there [is/1/v] _a_building in the_distance"""), Building('@building', article='the', called="building's interior", referring='well | building house', exits={'enter': '@end_of_road', 'leave': '@end_of_road', 'outdoors': '@end_of_road', 'west': '@end_of_road', 'xyzzy': '@debris_room', 'plugh': '@y2', 'down': """the_stream [flow/1/v] out through a pair of 1 foot diameter sewer pipes, too small to enter""", 'stream': """the_stream [flow/1/v] out through a pair of 1 foot diameter sewer pipes, too small to enter"""}, sight=""" [*/s] [are/v] inside _a_building, _a_well_house for _a_large_spring"""), Thing('@keys in @building', article='some', called='(glinting) keys', referring='key of ring | key keyring ring', qualities=['device', 'metal'], number='plural', sight='ordinary keys, on a ring'), Thing('@food in @building', article='some', called='food', referring='tasty fresh edible | wrap', qualities=['food'], consumable=True, sight='a wrap, fresh and edible', smell=""" something pleasing _bacon was somehow involved in the production of [this] wrap""", taste="food that [seem/1/v] fresh and palatable"), Thing('@bottle in @building', article='a', called='(clear) (glass) bottle', open=False, transparent=True, vessel='@water', sight='a clear glass bottle, currently [open/@bottle/a]', touch="smooth glass"), Lamp('@lamp in @building', article='a', called='(shiny) (brass) (carbide) lamp', referring='| lantern light', qualities=['device', 'metal'], on=False, sight=""" a brass carbide lamp, the kind often used for illuminating caves [@lamp/s/pro] [is/v] shiny and [glow/@lamp/a] [@lamp/s/pro] [display/v] the word [word/@dial/a] and [have/v] three switches: a "HESITANT" switch, a "SURPRISE" switch, and a "VALLEY GIRL" switch [@lamp/s] also [feature/v] a dial which can range from 1 to 12 and [is/v] set to [setting/@dial/a]""", touch=""" [@lamp/s] and [@dial/s] on it, which [*/s] [sense/v] [is/1/v] set to [setting/@dial/a]"""), Dial('@dial part_of @lamp', article='the', called='dial', referring='round | dial knob', setting=2, word='memoir', mention=False, sight=""" [@dial/s] can be set to any number between 1 and 12 [@dial/pro/s] [is/v] set to [setting/@dial/a]"""), Thing('@hesitant part_of @lamp', article='the', called='"HESITANT" switch', referring='hesitant | switch', mention=False, on=False), Thing('@surprise part_of @lamp', article='the', called='"SURPRISE" switch', referring='surprise | switch', mention=False, on=False), Thing('@valley_girl part_of @lamp', article='the', called='"VALLEY GIRL" switch', referring='valley girl | switch', mention=False, on=False), OutsideArea('@valley', article='the', called='valley', exits={'upstream': '@end_of_road', 'house': '@end_of_road', 'north': '@end_of_road', 'forest': '@forest_near_road', 'east': '@forest_near_road', 'west': '@forest_near_road', 'up': '@forest_near_road', 'downstream': '@slit', 'south': '@slit', 'down': '@slit', 'depression': '@outside_grate'}, sight=""" [*/s] [are/v] in _a_valley in _the_forest beside _a_stream tumbling along _a_rocky_bed"""), Thing('@stream_in_valley part_of @valley', article='a', called='tumbling stream', referring='| stream creek river spring', qualities=['liquid'], source='@water', mention=False, sight='a tumbling stream'), OutsideArea('@forest_near_road', article='the', called='forest', exits={'valley': '@valley', 'east': '@valley', 'down': '@valley', 'forest': '@forest_near_valley', 'west': '@forest_near_road', 'south': '@forest_near_road'}, sight=""" [*/s] [are/v] in open forest, with _a_deep_valley to _one_side"""), OutsideArea('@forest_near_valley', article='the', called='forest', sight=""" [*/s] [are/v] in open forest near both _a_valley and _a_road""", exits={'hill': '@end_of_road', 'north': '@end_of_road', 'valley': '@valley', 'east': '@valley', 'west': '@valley', 'down': '@valley', 'forest': '@forest_near_road', 'south': '@forest_near_road'}), OutsideArea('@slit', article='the', called='slit in the streambed', exits={'house': '@end_of_road', 'upstream': '@valley', 'north': '@valley', 'forest': '@forest_near_road', 'east': '@forest_near_road', 'west': '@forest_near_road', 'downstream': '@outside_grate', 'rock': '@outside_grate', 'bed': '@outside_grate', 'south': '@outside_grate', 'slit': '[*/s] [fit/not/v] through a two-inch slit', 'stream': '[*/s] [fit/not/v] through a two-inch slit', 'down': '[*/s] [fit/not/v] through a two-inch slit'}, sight=""" at [*'s] feet all _the_water of _the_stream [splash/1/v] into _a_2-inch_slit in _the_rock downstream _the_streambed [is/1/v] bare rock"""), Thing('@spring_7 in @slit', article='a', called='small stream', referring='| stream creek river spring', qualities=['liquid'], source='@water', mention=False, sight='a small stream'), OutsideArea('@outside_grate', article='the', called='area outside the grate', sight=""" [*/s] [are/v] in a _20-foot_depression floored with bare dirt set into the_dirt [is/1/v] [@grate/o] mounted in _concrete _a_dry_streambed [lead/1/v] into _the_depression""", exits={'forest': '@forest_near_road', 'east': '@forest_near_road', 'west': '@forest_near_road', 'south': '@forest_near_road', 'house': '@end_of_road', 'upstream': '@slit', 'gully': '@slit', 'north': '@slit', 'enter': '@grate', 'down': '@grate'}), Door('@grate', article='a', called='(strong) (steel) grate', referring='| grating grill grille barrier', qualities=['doorway', 'metal'], allowed=can.permit_any_item, open=False, locked=True, key='@keys', transparent=True, connects=['@outside_grate', '@below_grate'], mention=False, sight=""" a grate, placed to restrict entry to the cave it [is/1/v] currently [open/@grate/a]"""), CaveRoom('@below_grate', article='the', called='area below the grate', referring='below the grate |', sight=""" [*/s] [are/v] in _a_small_chamber beneath _a_3x3_steel_grate to the surface _a_low crawl over _cobbles [lead/1/v] inward to the west""", glow=0.7, exits={'leave': '@grate', 'exit': '@grate', 'up': '@grate', 'crawl': '@cobble_crawl', 'cobble': '@cobble_crawl', 'in': '@cobble_crawl', 'west': '@cobble_crawl', 'pit': '@small_pit', 'debris': '@debris_room'}), CaveRoom('@cobble_crawl', article='the', called='cobble crawl', referring='passage', sight=""" [*/s] [crawl/ing/v] over _cobbles in _a_low_passage there [is/1/v] a dim _light at _the_east_end of _the_passage""", glow=0.5, exits={'leave': '@below_grate', 'surface': '@below_grate', 'nowhere': '@below_grate', 'east': '@below_grate', 'in': '@debris_room', 'dark': '@debris_room', 'west': '@debris_room', 'debris': '@debris_room', 'pit': '@small_pit'}), Thing('@cage in @cobble_crawl', article='a', called='wicker cage', referring='wicker | cage', allowed=can.contain_any_thing_if_open, open=True, transparent=True, sight=""" a wicker cage, about the size of a breadbasket, currently [open/@cage/a]"""), CaveRoom('@debris_room', article='the', called='debris room', sight=""" [*/s] [are/v] in _a_room filled with _debris washed in from _the_surface _a_low_wide_passage with _cobbles [become/1/v] plugged with _mud and _debris [here], but _an_awkward_canyon [lead/1/v] upward and west _a_note on the wall [say/1/v] "MAGIC WORD XYZZY\"""", exits={'entrance': '@below_grate', 'crawl': '@cobble_crawl', 'cobble': '@cobble_crawl', 'tunnel': '@cobble_crawl', 'low': '@cobble_crawl', 'east': '@cobble_crawl', 'canyon': '@awkward_canyon', 'in': '@awkward_canyon', 'up': '@awkward_canyon', 'west': '@awkward_canyon', 'xyzzy': '@building', 'pit': '@small_pit'}), Thing('@rusty_rod in @debris_room', article='a', called='black rod', referring='black iron rusty sinister | rod', sight='[this] ordinary sinister black rod, rather rusty'), CaveRoom('@awkward_canyon', article='the', called='awkward canyon', sight=""" [*/s] [are/v] in _an_awkward_sloping_east/west_canyon""", exits={'entrance': '@below_grate', 'down': '@debris_room', 'east': '@debris_room', 'debris': '@debris_room', 'in': '@bird_chamber', 'up': '@bird_chamber', 'west': '@bird_chamber', 'pit': '@small_pit'}), CaveRoom('@bird_chamber', article='the', called='bird chamber', sight=""" [*/s] [are/v] in _a_splendid_chamber thirty feet high _the_walls [are/2/v] frozen _rivers of orange _stone _an_awkward_canyon and _a_good_passage [exit/2/v] from the east and west _sides of _the_chamber""", exits={'entrance': '@below_grate', 'debris': '@debris_room', 'canyon': '@awkward_canyon', 'east': '@awkward_canyon', 'tunnel': '@small_pit', 'pit': '@small_pit', 'west': '@small_pit'}), Bird('@bird in @bird_chamber', article='a', called='little bird', referring='little cheerful | bird', sight='nothing more than a bird'), CaveRoom('@small_pit', article='the', called='top of the small pit', exits={'entrance': '@below_grate', 'debris': '@debris_room', 'tunnel': '@bird_chamber', 'east': '@bird_chamber', 'down': '@hall_of_mists', 'west': 'the crack [is/1/v] far too small to follow', 'crack': 'the crack [is/1/v] far too small to follow'}, sight=""" at [*'s] feet [is/1/v] _a_small_pit breathing traces of white _mist _an_east_passage [end/1/v] [here] except for _a_small_crack leading on"""), CaveRoom('@hall_of_mists', article='the', called='hall of mists', sight=""" [*/s] [are/v] at one _end of _a_vast_hall stretching forward out of sight to the west there [are/2/v] _openings to either _side nearby, _a_wide_stone_staircase [lead/1/v] downward _the_hall [is/1/v] filled with _wisps of white _mist swaying to and fro almost as if alive _a_cold_wind [blow/1/v] up _the_staircase there [is/1/v] _a_passage at _the_top of _a_dome behind [*/o]""", exits={'left': '@nugget_room', 'south': '@nugget_room', 'onward': '@fissure_east', 'hall': '@fissure_east', 'west': '@fissure_east', 'stair': '@hall_of_mountain_king', 'down': '@hall_of_mountain_king', 'north': '@hall_of_mountain_king', 'up': '@small_pit', 'y2': '@y2'}), Bridgable('@fissure_east', article='the', called='east bank of the fissure', referring='east of fissure | bank', sight=""" [*/s] [are/v] on _the_east_bank of _a_fissure that [slice/1/v] clear across _the_hall _the_mist [is/1/v] quite thick here, and _the_fissure [is/1/v] too wide to jump""", shared=['@fissure'], exits={'hall': '@hall_of_mists', 'east': '@hall_of_mists'}), SharedThing('@fissure', article='a', called='fissure', referring='massive |', sight='a massive fissure'), Door('@bridge', article='a', called='bridge', referring='| bridge span', allowed=can.permit_any_item, connects=['@fissure_east', '@fissure_west'], sight='[@bridge] [span/v] the chasm'), CaveRoom('@nugget_room', article='the', called='nugget of gold room', referring='nugget of gold low |', exits={'hall': '@hall_of_mists', 'leave': '@hall_of_mists', 'north': '@hall_of_mists'}, sight=""" [this] [is/1/v] _a_low_room with _a_crude_note on _the_wall _the_note [say/1/v] , "You won't get it up the steps" """), Thing('@nugget in @nugget_room', article='a', called='nugget of gold', referring='large sparkling of | nugget gold', qualities=['treasure', 'metal'], sight='a large gold nugget'), CaveRoom('@hall_of_mountain_king', article='the', called='Hall of the Mountain King', referring='of the mountain king | hall', sight=""" [*/s] [are/v] in _the_Hall_of_the_Mountain_King, with _passages off in all _directions""", exits={'stair': '@hall_of_mists', 'up': '@hall_of_mists', 'east': '@hall_of_mists', 'west': '@west_side_chamber', 'north': '@low_passage', 'south': '@south_side_chamber', 'secret': '@secret_east_west_canyon', 'southwest': '@secret_east_west_canyon'}), Snake('@snake in @hall_of_mountain_king', article='a', called='huge snake', referring='huge green fierce | snake', sight='[this] [is/1/v] just a huge snake, barring the way', smell="something like Polo cologne", blocked=['west', 'north', 'south', 'secret', 'southwest']), CaveRoom('@west_end_of_twopit_room', article='the', called='west end of twopit room', sight=""" [*/s] [are/v] at _the_west_end of _the_Twopit_Room there [is/1/v] _a_large_hole in _the_wall above _the_pit at [this] _end of _the_room""", exits={'east': '@east_end_of_twopit_room', 'across': '@east_end_of_twopit_room', 'west': '@slab_room', 'slab': '@slab_room', 'down': '@west_pit', 'pit': '@west_pit', 'hole': '@complex_junction'}), CaveRoom('@east_pit', article='the', called='east pit', referring='eastern east | pit', sight=""" [*/s] [are/v] at _the_bottom of _the_eastern_pit in _the_Twopit_Room there [is/1/v] [@pool_of_oil/o] in _one_corner of _the_pit""", exits={'up': '@east_end_of_twopit_room', 'leave': '@east_end_of_twopit_room'}), Thing('@pool_of_oil in @east_pit', article='a', called='small pool of oil', referring='small of oil | pool', qualities=['liquid'], source='@oil', sight='a small pool of oil'), CaveRoom('@west_pit', article='the', called='west pit', referring='western west | pit', sight=""" [*/s] [are/v] at _the_bottom of _the_western_pit in _the_Twopit_Room there [is/1/v] _a_large_hole in _the_wall about 25 feet above [*/o]""", exits={'up': '@west_end_of_twopit_room', 'leave': '@west_end_of_twopit_room'}), Plant('@plant in @west_pit', article='a', called='plant', referring='tiny little big tall gigantic | plant beanstalk', open=False, sight='a tiny little plant, murmuring "Water, water, ..."'), CaveRoom('@fissure_west', article='the', called='west side of fissure', referring='west of fissure | side', sight=""" [*/s] [are/v] on _the_west_side of _the_fissure in _the_Hall_of_Mists""", shared=['@fissure'], exits={'over': '@fissure_east', 'east': '@fissure_east', 'west': '@west_end_of_hall_of_mists'}), Thing('@diamonds in @fissure_west', article='some', called='diamonds', referring='| jewel jewels', qualities=['treasure'], sight='diamonds'), CaveRoom('@low_passage', article='the', called='low passage', sight=""" [*/s] [are/v] in _a_low_north/south_passage at _a_hole in _the_floor the hole [go/1/v] down to an east/west passage""", exits={'hall': '@hall_of_mountain_king', 'leave': '@hall_of_mountain_king', 'south': '@hall_of_mountain_king', 'north': '@y2', 'y2': '@y2', 'down': '@dirty_passage', 'hole': '@dirty_passage'}), Thing('@bars in @low_passage', article='the', called='bars of silver', referring='several of | bars silver', qualities=['treasure', 'metal'], number='plural', sight='several bars of silver'), CaveRoom('@south_side_chamber', article='the', called='south side chamber', sight=""" [*/s] [are/v] in the south side chamber""", exits={'hall': '@hall_of_mountain_king', 'leave': '@hall_of_mountain_king', 'north': '@hall_of_mountain_king'}), Thing('@jewelry in @south_side_chamber', article='some', called='(precious) jewelry', referring='| jewel jewels', qualities=['treasure'], sight='precious jewelry'), CaveRoom('@west_side_chamber', article='the', called='west side chamber', sight=""" [*/s] [are/v] in _the_west_side_chamber of _the_Hall_of_the_Mountain_King _a_passage continues west and up [here]""", exits={'hall': '@hall_of_mountain_king', 'leave': '@hall_of_mountain_king', 'east': '@hall_of_mountain_king', 'west': '@crossover', 'up': '@crossover'}), Thing('@coins in @west_side_chamber', article='many', called='coins', referring='shiny numerous | money', qualities=['treasure', 'metal'], number='plural', sight='numerous coins'), CaveRoom('@y2', called='Y2', sight=""" [*/s] [are/v] in _a_large_room, with _a_passage to the south, _a_passage to the west, and _a_wall of broken _rock to the east there [is/1/v] a large "Y2" on a rock in the room's center""", exits={'plugh': '@building', 'south': '@low_passage', 'east': '@jumble', 'wall': '@jumble', 'broken': '@jumble', 'west': '@window_on_pit', 'plover': '@plover_room'}), CaveRoom('@jumble', article='the', called='jumble', sight=""" [*/s] [are/v] in _a_jumble of _rock, with _cracks everywhere""", exits={'down': '@y2', 'y2': '@y2', 'up': '@hall_of_mists'}), CaveRoom('@window_on_pit', article='the', called='window on pit', sight=""" [*/s] [are/v] at _a_low_window overlooking _a_huge_pit, which extends up out of sight _a_floor [is/1/v] indistinctly visible over 50 feet below _traces of white _mist [cover/2/v] _the_floor of _the_pit, becoming thicker to the right _marks in _the_dust around _the_window [seem/2/v] to indicate that _someone [have/1/v] been [here] recently directly across _the_pit from [*/o] and 25 feet away there [is/1/v] _a_similar_window looking into _a_lighted_room _a_shadowy_figure [is/1/v] there peering back at [*/o]""", exits={'east': '@y2', 'y2': '@y2'}), CaveRoom('@dirty_passage', article='the', called='dirty passage', sight=""" [*/s] [are/v] in _a_dirty_broken_passage to the east [is/1/v] _a_crawl to the west [is/1/v] _a_large_passage above [*/o] [is/1/v] _a_hole to _another_passage""", exits={'east': '@brink_of_pit', 'crawl': '@brink_of_pit', 'up': '@low_passage', 'hole': '@low_passage', 'west': '@dusty_rock_room', 'bedquilt': '@bedquilt'}), CaveRoom('@brink_of_pit', article='the', called='brink of pit', sight=""" [*/s] [are/v] on _the_brink of _a_small_clean_climbable_pit _a_crawl [lead/1/v] west""", exits={'west': '@dirty_passage', 'crawl': '@dirty_passage', 'down': '@bottom_of_pit', 'pit': '@bottom_of_pit', 'climb': '@bottom_of_pit'}), CaveRoom('@bottom_of_pit', article='the', called='bottom of pit', sight=""" [*/s] [are/v] in the bottom of _a_small_pit with [@stream_in_pit/o], which [enter/1/v] and [exit/1/v] through _tiny_slits""", exits={'climb': '@brink_of_pit', 'up': '@brink_of_pit', 'leave': '@brink_of_pit'}), Thing('@stream_in_pit part_of @bottom_of_pit', article='a', called='little stream', referring='small | stream creek river spring', qualities=['liquid'], source='@water', mention=False, sight='a little stream'), CaveRoom('@dusty_rock_room', article='the', called='dusty rock room', sight=""" [*/s] [are/v] in _a_large_room full of _dusty_rocks there [is/1/v] _a_big_hole in _the_floor there [are/2/v] _cracks everywhere, and _a_passage leading east""", exits={'east': '@dirty_passage', 'tunnel': '@dirty_passage', 'down': '@complex_junction', 'hole': '@complex_junction', 'floor': '@complex_junction', 'bedquilt': '@bedquilt'}), CaveRoom('@west_end_of_hall_of_mists', article='the', called='west end of hall of mists', sight=""" [*/s] [are/v] at _the_west_end of _the_Hall_of_Mists _a_low_wide_crawl [continue/1/v] west and _another [go/1/v] north to the south [is/1/v] _a_little_passage 6 feet off _the_floor""", exits={'south': '@maze_1', 'up': '@maze_1', 'tunnel': '@maze_1', 'climb': '@maze_1', 'east': '@fissure_west', 'west': '@east_end_of_long_hall', 'crawl': '@east_end_of_long_hall'}), CaveRoom('@maze_1', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'up': '@west_end_of_hall_of_mists', 'north': '@maze_1', 'east': '@maze_2', 'south': '@maze_4', 'west': '@maze_11'}), CaveRoom('@maze_2', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_1', 'south': '@maze_3', 'east': '@room'}), CaveRoom('@maze_3', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'east': '@maze_2', 'down': '@dead_end_3', 'south': '@maze_6', 'north': '@dead_end_11'}), CaveRoom('@maze_4', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_1', 'north': '@maze_2', 'east': '@dead_end_1', 'south': '@dead_end_2', 'up': '@maze_14', 'down': '@maze_14'}), CaveRoom('@dead_end_1', article='the', called='dead end', referring='dead | end', exits={'west': '@maze_4', 'leave': '@maze_4'}), CaveRoom('@dead_end_2', article='the', called='dead end', referring='dead | end', sight=""" dead end""", exits={'east': '@maze_4', 'leave': '@maze_4'}), CaveRoom('@dead_end_3', article='the', called='dead end', referring='dead | end', exits={'up': '@maze_3', 'leave': '@maze_3'}), CaveRoom('@maze_5', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'east': '@maze_6', 'west': '@maze_7'}), CaveRoom('@maze_6', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'east': '@maze_3', 'west': '@maze_5', 'down': '@maze_7', 'south': '@maze_8'}), CaveRoom('@maze_7', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_5', 'up': '@maze_6', 'east': '@maze_8', 'south': '@maze_9'}), CaveRoom('@maze_8', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_6', 'east': '@maze_7', 'south': '@maze_8', 'up': '@maze_9', 'north': '@maze_10', 'down': '@dead_end_13'}), CaveRoom('@maze_9', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_7', 'north': '@maze_8', 'south': '@dead_end_4'}), CaveRoom('@dead_end_4', article='the', called='dead end', referring='dead | end', exits={'west': '@maze_9', 'leave': '@maze_9'}), CaveRoom('@maze_10', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'west': '@maze_8', 'north': '@maze_10', 'down': '@dead_end_5', 'east': '@brink_with_column'}), CaveRoom('@dead_end_5', article='the', called='dead end', referring='dead | end', exits={'up': '@maze_10', 'leave': '@maze_10'}), CaveRoom('@brink_with_column', article='the', called='brink of pit', sight=""" [*/s] [are/v] on _the_brink of _a_thirty_foot_pit with _a_massive_orange_column down _one_wall [*/s] could climb down [here] but [*/s] could not get back up _the_maze [continue/1/v] at _this_level""", exits={'down': '@bird_chamber', 'climb': '@bird_chamber', 'west': '@maze_10', 'south': '@dead_end_6', 'north': '@maze_12', 'east': '@maze_13'}), CaveRoom('@dead_end_6', article='the', called='dead end', referring='dead | end', exits={'east': '@brink_with_column', 'leave': '@brink_with_column'}), CaveRoom('@east_end_of_long_hall', article='the', called='east end of long hall', sight=""" [*/s] [are/v] at _the_east_end of _a_very_long_hall apparently without _side_chambers to the east _a_low_wide_crawl [slant/1/v] up to the north _a_round_two-foot_hole [slant/1/v] down""", exits={'east': '@west_end_of_hall_of_mists', 'up': '@west_end_of_hall_of_mists', 'crawl': '@west_end_of_hall_of_mists', 'west': '@west_end_of_long_hall', 'north': '@crossover', 'down': '@crossover', 'hole': '@crossover'}), CaveRoom('@west_end_of_long_hall', article='the', called='west end of long hall', sight=""" [*/s] [are/v] at _the_west_end of _a_very_long_featureless_hall _the_hall [join/1/v] up with _a_narrow_north/south_passage""", exits={'east': '@east_end_of_long_hall', 'north': '@crossover'}), CaveRoom('@crossover', article='the', called='crossover', sight=""" [*/s] [are/v] at _a_crossover of _a_high_north/south_passage and _a_low_east/west_one""", exits={'west': '@east_end_of_long_hall', 'north': '@dead_end_7', 'east': '@west_side_chamber', 'south': '@west_end_of_long_hall'}), CaveRoom('@dead_end_7', article='the', called='dead end', referring='dead | end', exits={'south': '@crossover', 'leave': '@crossover'}), CaveRoom('@complex_junction', article='the', called='complex junction', sight=""" [*/s] [are/v] at a_complex_junction _a_low_hands_and_knees_passage from the north [join/1/v] _a_higher_crawl from the east to make _a_walking_passage going west there [is/1/v] also _a_large_room above _the_air [is/1/v] damp [here]""", exits={'up': '@dusty_rock_room', 'climb': '@dusty_rock_room', 'room': '@dusty_rock_room', 'west': '@bedquilt', 'bedquilt': '@bedquilt', 'north': '@shell_room', 'shell': '@shell_room', 'east': '@anteroom'}), CaveRoom('@bedquilt', article='the', called='bedquilt', sight=""" [*/s] [are/v] in Bedquilt, _a_long_east/west_passage with _holes everywhere""", exits={'east': '@complex_junction', 'west': '@swiss_cheese_room', 'slab': '@slab_room', 'up': '@dusty_rock_room', 'north': '@junction_of_three_secret_canyons', 'down': '@anteroom'}), # NEXT STEPS Passages should lead off randomly, south should exist CaveRoom('@swiss_cheese_room', article='the', called='swiss cheese room', sight=""" [*/s] [are/v] in _a_room whose _walls [resemble/1/v] _Swiss_cheese _obvious_passages [go/2/v] west, east, northeast, and northwest _part of _the_room [is/1/v] occupied by _a_large_bedrock_block""", exits={'northeast': '@bedquilt', 'west': '@east_end_of_twopit_room', 'canyon': '@tall_canyon', 'south': '@tall_canyon', 'east': '@soft_room', 'oriental': '@oriental_room'}), CaveRoom('@east_end_of_twopit_room', article='the', called='east end of twopit room', exits={'east': '@swiss_cheese_room', 'west': '@west_end_of_twopit_room', 'across': '@west_end_of_twopit_room', 'down': '@east_pit', 'pit': '@east_pit'}, sight=""" [*/s] [are/v] at _the_east_end of _the_Twopit_Room _the_floor [here] [is/1/v] littered with _thin_rock_slabs, which [make/2/v] it easy to descend _the_pits there [is/1/v] _a_path [here] bypassing _the_pits to connect _passages from east and west there [are/2/v] _holes all over, but the only _big_one [is/1/v] on _the_wall directly over _the_west_pit where [*/s] [are/v] unable to get to it"""), CaveRoom('@slab_room', article='the', called='slab room', exits={'south': '@west_end_of_twopit_room', 'up': '@secret_canyon_above_room', 'climb': '@secret_canyon_above_room', 'north': '@bedquilt'}, sight=""" [*/s] [are/v] in _a_large_low_circular_chamber whose _floor [is/v] _an_immense_slab fallen from _the_ceiling east and west there once were _large_passages, but _they [are/2/v] [now] filled with _boulders _low_small_passages [go/2/v] north and south, and _the_south_one quickly [bend/1/v] west around _the_boulders"""), CaveRoom('@secret_canyon_above_room', article='the', called='secret canyon above room', sight=""" [*/s] [are/v] in _a_secret_north/south_canyon above _a_large_room""", exits={'down': '@slab_room', 'slab': '@slab_room', 'south': '@secret_canyon', 'north': '@mirror_canyon', 'reservoir': '@reservoir'}), CaveRoom('@secret_canyon_above_passage', article='the', called='secret canyon above passage', sight=""" [*/s] [are/v] in _a_secret_north/south_canyon above _a_sizable_passage""", exits={'north': '@junction_of_three_secret_canyons', 'down': '@bedquilt', 'tunnel': '@bedquilt', 'south': '@top_of_stalactite'}), CaveRoom('@junction_of_three_secret_canyons', article='the', called='junction of three secret canyons', sight=""" [*/s] [are/v] in _a_secret_canyon at _a_junction of _three_canyons, bearing north, south, and southeast _the_north_one is as tall as _the_other_two combined""", exits={'southeast': '@bedquilt', 'south': '@secret_canyon_above_passage', 'north': '@window_on_pit_redux'}), CaveRoom('@large_low_room', article='the', called='large low room', sight=""" [*/s] [are/v] in _a_large_low_room _crawls lead north, southeast, and southwest""", exits={'bedquilt': '@bedquilt', 'southwest': '@sloping_corridor', 'north': '@dead_end_8', 'southeast': '@oriental_room', 'oriental': '@oriental_room'}), CaveRoom('@dead_end_8', article='the', called='dead end crawl', referring='dead | end crawl', exits={'south': '@large_low_room', 'crawl': '@large_low_room', 'leave': '@large_low_room'}), CaveRoom('@secret_east_west_canyon', article='the', called='secret east/west canyon above tight canyon', sight=""" [*/s] [are/v] in _a_secret_canyon which [here] [run/1/v] east/west it [cross/1/v] over _a_very_tight_canyon 15 feet below if [*/s] were to go down [*/s] may not be able to get back up""", exits={'east': '@hall_of_mountain_king', 'west': '@secret_canyon', 'down': '@wide_place'}), CaveRoom('@wide_place', article='the', called='wide place', sight=""" [*/s] [are/v] at _a_wide_place in _a_very_tight_north/south_canyon""", exits={'south': '@tight_spot', 'north': '@tall_canyon'}), CaveRoom('@tight_spot', article='the', called='tight spot', sight='_the_canyon [here] [become/1/v] too tight to go further south', exits={'north': '@wide_place'}), CaveRoom('@tall_canyon', article='the', called='tall canyon', sight=""" [*/s] [are/v] in _a_tall_east/west_canyon _a_low_tight_crawl [go/1/v] three feet north and [seem/1/v] to open up""", exits={'east': '@wide_place', 'west': '@dead_end_9', 'north': '@swiss_cheese_room', 'crawl': '@swiss_cheese_room'}), CaveRoom('@dead_end_9', article='the', called='dead end', referring='dead | end', sight=""" _the_canyon runs into _a_mass_of_boulders -- [*/s] [are/v] at _a_dead_end""", exits={'south': '@tall_canyon'}), CaveRoom('@maze_11', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all alike""", exits={'north': '@maze_1', 'west': '@maze_11', 'south': '@maze_11', 'east': '@dead_end_10'}), CaveRoom('@dead_end_10', article='the', called='dead end', referring='dead | end', exits={'west': '@maze_11', 'leave': '@maze_11'}), CaveRoom('@dead_end_11', article='the', called='dead end', referring='dead | end', exits={'south': '@maze_3', 'leave': '@maze_3'}), CaveRoom('@maze_12', article='the', called='maze', sight='[*/s] [are/v] in _a_maze of _twisty_little_passages, all alike', exits={'south': '@brink_with_column', 'east': '@maze_13', 'west': '@dead_end_12'}), CaveRoom('@maze_13', article='the', called='maze', sight='[*/s] [are/v] in _a_maze of _twisty_little_passages, all alike', exits={'north': '@brink_with_column', 'west': '@maze_12', 'northwest': '@dead_end_14'}), CaveRoom('@dead_end_12', article='the', called='dead end', referring='dead | end', exits={'east': '@maze_12', 'leave': '@maze_12'}), CaveRoom('@dead_end_13', article='the', called='dead end', referring='dead | end', exits={'up': '@maze_8', 'leave': '@maze_8'}), CaveRoom('@maze_14', article='the', called='maze', sight='[*/s] [are/v] in _a_maze of _twisty_little_passages, all alike', exits={'up': '@maze_4', 'down': '@maze_4'}), CaveRoom('@narrow_corridor', article='the', called='narrow corridor', sight=""" [*/s] [are/v] in _a_long,_narrow_corridor stretching out of sight to _the_west at _the_eastern_end [is/v] _a_hole through which [*/s] [can/v] see _a_profusion of _leaves""", exits={'down': '@west_pit', 'climb': '@west_pit', 'east': '@west_pit', 'west': '@giant_room', 'giant': '@giant_room'}), CaveRoom('@steep_incline', article='the', called='steep incline above large room', sight=""" [*/s] [are/v] at _the_top of _a_steep_incline above _a_large_room [*/s] could climb down [here], but [*/s] would not be able to climb up there is _a_passage leading back to the north""", exits={'north': '@cavern_with_waterfall', 'cavern': '@cavern_with_waterfall', 'tunnel': '@cavern_with_waterfall', 'down': '@large_low_room', 'climb': '@large_low_room'}), EggSummoning('@giant_room', article='the', called='giant room', sight=""" [*/s] [are/v] in _the_Giant_Room _the_ceiling [here] [is/1/v] too high up for [*'s] lamp to show _it _cavernous_passages [lead/2/v] east, north, and south on _the_west_wall [is/1/v] scrawled _the_inscription, "FEE FIE FOE FOO" \[sic]""", exits={'south': '@narrow_corridor', 'east': '@blocked_passage', 'north': '@end_of_immense_passage'}), Thing('@eggs in @giant_room', article='some', called='golden eggs', referring='several gold golden | egg eggs', qualities=['treasure', 'metal'], number='plural', sight='several golden eggs'), CaveRoom('@blocked_passage', article='the', called='blocked passage', sight='_the_passage [here] [is/1/v] blocked by _a_recent_cave-in', exits={'south': '@giant_room', 'giant': '@giant_room', 'leave': '@giant_room'}), CaveRoom('@end_of_immense_passage', article='the', called='end of immense passage', sight='[*/s] [are/v] at _one_end of _an_immense_north/south_passage', exits={'south': '@giant_room', 'giant': '@giant_room', 'tunnel': '@giant_room', 'north': '@rusty_door'}), RustyDoor('@rusty_door', article='a', called='(massive) (rusty) (iron) door', referring='| door', qualities=['doorway', 'metal'], allowed=can.permit_any_item, open=False, locked=True, connects=['@end_of_immense_passage', '@cavern_with_waterfall'], sight=""" a door, placed to restrict passage to the north, which [is/v] [now] [open/@rusty_door/a]"""), CaveRoom('@cavern_with_waterfall', article='the', called='cavern with waterfall', sight=""" [*/s] [are/v] in _a_magnificent_cavern with _a_rushing_stream, which [cascade/1/v] over [@waterfall/o] into _a_roaring_whirlpool which [disappear/1/v] through _a_hole in _the_floor _passages [exit/2/v] to the south and west""", exits={'south': '@end_of_immense_passage', 'leave': '@end_of_immense_passage', 'giant': '@giant_room', 'west': '@steep_incline'}), Thing('@waterfall part_of @cavern_with_waterfall', article='a', called='sparkling waterfalll', referring='rushing sparkling roaring | stream creek river spring ' + 'waterfall whirlpool', qualities=['liquid'], source='@water', mention=False), Thing('@trident in @cavern_with_waterfall', article='a', called='jewel-encrusted trident', referring='jeweled | trident', qualities=['treasure', 'metal'], sight='a jewel-encrusted trident'), CaveRoom('@soft_room', article='the', called='soft room', sight=""" [*/s] [are/v] in _the_Soft_Room _the_walls [are/2/v] covered with _heavy_curtains, _the_floor with _a_thick_pile_carpet _moss [cover/1/v] _the_ceiling""", exits={'west': '@swiss_cheese_room', 'leave': '@swiss_cheese_room'}), Thing('@pillow in @soft_room', article='a', called='(small) (velvet) pillow', referring='| pillow', allowed=can.support_one_item), CaveRoom('@oriental_room', article='the', called='oriental room', sight=""" [this] [is/1/v] _the_Oriental_Room _ancient_oriental_cave_drawings [cover/2/v] _the_walls _a_gently_sloping_passage [lead/1/v] upward to the north, _another_passage [lead/1/v] southeast, and _a_hands_and_knees_crawl [lead/1/v] west""", exits={'southeast': '@swiss_cheese_room', 'west': '@large_low_room', 'crawl': '@large_low_room', 'up': '@misty_cavern', 'north': '@misty_cavern', 'cavern': '@misty_cavern'}), Delicate('@vase in @oriental_room', article='a', called='(delicate) (precious) (Ming) vase', referring='| vase', qualities=['treasure'], sight='a delicate, precious, Ming vase'), CaveRoom('@misty_cavern', article='the', called='misty cavern', sight=""" [*/s] [are/v] following _a_wide_path around _the_outer_edge of _a_large_cavern far below, through _a_heavy_white_mist, _strange_splashing_noises [are/2/v] heard _the_mist [rise/1/v] up through _a_fissure in _the_ceiling _the_path [exit/1/v] to the south and west""", exits={'south': '@oriental_room', 'oriental': '@oriental_room', 'west': '@alcove'}), CaveRoom('@alcove', article='the', called='alcove', sight=""" [*/s] [are/v] in _an_alcove _a_small_northwest_path [seem/1/v] to widen after _a_short_distance _an_extremely_tight_tunnel [lead/1/v] east it [look/1/v] like _a_very_tight_squeeze _an_eerie_light [is/1/v] seen at _the_other_end""", exits={'northwest': '@misty_cavern', 'cavern': '@misty_cavern', 'east': '@plover_room'}), CaveRoom('@plover_room', article='the', called='plover room', sight=""" [*/s] [are/v] in _a_small_chamber lit by _an_eerie_green_light _an_extremely_narrow_tunnel [exit/1/v] to the west _a_dark_corridor [lead/1/v] northeast""", glow=0.5, exits={'west': '@alcove', 'plover': '@y2', 'northeast': '@dark_room', 'dark': '@dark_room'}), Thing('@emerald in @plover_room', article='an', called='emerald', referring='| jewel egg', qualities=['treasure'], sight='an emerald the size of a plover\'s egg'), CaveRoom('@dark_room', article='the', called='dark room', sight=""" [*/s] [are/v] in _the_Dark_Room _a_corridor leading south [is/1/v] _the_only_exit""", exits={'south': '@plover_room', 'plover': '@plover_room', 'leave': '@plover_room'}), Thing('@pyramid in @dark_room', article='a', called='platinum pyramid', referring='| platinum pyramid', qualities=['treasure', 'metal'], sight='a platinum pyramid, eight inches on a side'), CaveRoom('@arched_hall', article='the', called='arched hall', sight=""" [*/s] [are/v] in an arched hall _a_coral_passage once continued up and east from [here], but [is/1/v] [now] blocked by _debris""", smell="sea water", exits={'down': '@shell_room', 'shell': '@shell_room', 'leave': '@shell_room'}), CaveRoom('@shell_room', article='the', called='shell room', referring='shell |', sight=""" [*/s] [are/v] in _a_large_room carved out of _sedimentary_rock _the_floor and _walls [are/2/v] littered with _bits of _shells embedded in _the_stone _a_shallow_passage [proceed/1/v] downward, and _a_somewhat_steeper_one [lead/1/v] up a low hands and knees passage [enter/1/v] from the south""", exits={'up': '@arched_hall', 'hall': '@arched_hall', 'down': '@long_sloping_corridor', 'south': '@complex_junction'}), Oyster('@oyster in @shell_room', article='a', called='(enormous) clam', referring='tightly closed tightly-closed | bivalve', open=False, sight='a tightly-closed and enormous bivalve'), Thing('@pearl in @oyster', article='a', called='glistening pearl', referring='| pearl', qualities=['treasure'], sight='a glistening pearl'), CaveRoom('@long_sloping_corridor', article='the', called='long sloping corridor', sight=""" [*/s] [are/v] in _a_long_sloping_corridor with _ragged_sharp_walls""", exits={'up': '@shell_room', 'shell': '@shell_room', 'down': '@cul_de_sac'}), CaveRoom('@cul_de_sac', article='the', called='cul-de-sac', sight='[*/s] [are/v] in _a_cul-de-sac about eight feet across', exits={'up': '@long_sloping_corridor', 'leave': '@long_sloping_corridor', 'shell': '@shell_room'}), CaveRoom('@anteroom', article='the', called='anteroom', sight=""" [*/s] [are/v] in _an_anteroom leading to _a_large_passage to the east _small_passages [go/2/v] west and up _the_remnants of recent digging [are/2/v] evident _a_sign in midair [here] [say/1/v]: "Cave under construction beyond this point. Proceed at own risk. \[Witt Construction Company]\"""", exits={'up': '@complex_junction', 'west': '@bedquilt', 'east': '@witts_end'}), Thing('@magazine in @anteroom', article='some', called='magazines', referring='a few recent | issues magazine magazines', number='plural', sight='a few recent issues of "Spelunker Today" magazine'), CaveRoom('@maze_15', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisty_little_passages, all different""", exits={'south': '@maze_17', 'southwest': '@maze_18', 'northeast': '@maze_19', 'southeast': '@maze_20', 'up': '@maze_21', 'northwest': '@maze_22', 'east': '@maze_23', 'west': '@maze_24', 'north': '@maze_25', 'down': '@west_end_of_long_hall'}), CaveRoom('@witts_end', called="Witt's End", sight=""" [*/s] [are/v] at _Witt's_End _passages [lead/2/v] off ... well, east and west""", exits={'east': '@anteroom', 'west': '@crossover'}), # NEXT STEPS Passages should lead off "in ALL directions", randomness CaveRoom('@mirror_canyon', article='the', called='mirror canyon', sight=""" [*/s] [are/v] in _a_north/south_canyon about 25 feet across _the_floor [is/1/v] covered by _white_mist seeping in from the north _the_walls [extend/2/v] upward for well over 100 feet suspended from _some_unseen_point far above [*/s], _an_enormous_two-sided_mirror [hang/ing/1/v] parallel to and midway between the _canyon_walls (_The_mirror [is/1/v] obviously provided for the use of _the_dwarves, who are extremely vain.) _a_small_window [is/1/v] seen in _either_wall, some fifty feet up""", exits={'south': '@secret_canyon_above_room', 'north': '@reservoir', 'reservoir': '@reservoir'}), CaveRoom('@window_on_pit_redux', article='the', called='window on pit', sight=""" [*/s] [are/v] at _a_low_window overlooking _a_huge_pit, which [extend/1/v] up out of sight _a_floor [is/1/v] indistinctly visible over 50 feet below _traces of _white_mist [cover/2/v] _the_floor of _the_pit, becoming thicker to the left _marks in _the_dust around _the_window [seem/2/v] to indicate that _someone has been [here] recently directly across _the_pit from [*/o] and 25 feet away there [is/1/v] _a_similar_window looking into _a_lighted_room _a_shadowy_figure [is/1/v] seen there peering back at [*/s]""", exits={'west': '@junction_of_three_secret_canyons'}), CaveRoom('@top_of_stalactite', article='the', called='top of stalactite', sight=""" _a_large_stalactite [extend/1/v] from _the_roof and almost [reach/1/v] _the_floor below [*/s] could climb down _it, and jump from _it to _the_floor, but having done so [*/s] would be unable to reach _it to climb back up""", exits={'north': '@secret_canyon_above_passage', 'down': '@maze_4'}), CaveRoom('@maze_16', article='the', called='maze', sight=""" [*/s] [are/v] in _a_little_maze of _twisting_passages, all different""", exits={'southwest': '@maze_17', 'north': '@maze_18', 'east': '@maze_19', 'northwest': '@maze_20', 'southeast': '@maze_21', 'northeast': '@maze_22', 'west': '@maze_23', 'down': '@maze_24', 'up': '@maze_25', 'south': '@dead_end_15'}), CaveRoom('@reservoir', article='the', called='edge of the reservoir', referring='| edge', sight=""" [*/s] [are/v] at _the_edge of _a_large_underground_reservoir _an_opaque_cloud of _white_mist [fill/1/v] _the_room and [rise/1/v] rapidly upward _the_lake [is/1/v] fed by _a_stream, which [tumble/1/v] out of _a_hole in _the_wall about 10 feet overhead and [splash/1/v] noisily into _the_water somewhere within _the_mist _the_only_passage [go/1/v] back toward the south""", exits={'south': '@mirror_canyon', 'leave': '@mirror_canyon'}), Thing('@lake part_of @reservoir', article='a', called='a large underground lake', referring='large underground | stream creek river spring lake', source='@water', mention=False), CaveRoom('@dead_end_14', article='the', called='dead end', referring='dead | end', exits={'southeast': '@maze_13'}), Thing('@chest in @dead_end_14', article='the', called="(pirate's) treasure chest", referring='| chest', qualities=['treasure'], sight="the pirate's treasure chest", allowed=can.contain_any_treasure), CaveRoom('@northeast_end', article='the', called='northeast end', sight=""" [*/s] [are/v] at _the_northeast_end of _an_immense_room, even larger than _the_giant_room it [appear/1/v] to be _a_repository for _the_"ADVENTURE"_program _massive_torches far overhead [bathe/2/v] _the_room with _smoky_yellow_light scattered about [*/s] [see/v] _a_pile_of_bottles (all of them empty), _a_nursery of _young_beanstalks murmuring quietly, _a_bed of _oysters, _a_bundle of _black_rods with _rusty_stars on _their_ends, and _a_collection_of_brass_lanterns off to _one_side a_great_many_dwarves [sleep/ing/2/v] on _the_floor, snoring loudly _a_sign nearby [read/1/v]: "Do not disturb the dwarves!" _an_immense_mirror [hang/ing/v] against _one_wall, and [stretch/1/v] to _the_other_end of _the_room, where _various_other_sundry_objects [are/2/v] glimpsed dimly in the distance""", exits={'southwest': '@southwest_end'}), CaveRoom('@southwest_end', article='the', called='southwest end', sight=""" [*/s] [are/v] at _the_southwest end of _the_repository to _one_side [is/1/v] _a_pit full of _fierce_green_snakes on _the_other_side [is/1/v] _a_row of _small_wicker_cages, each of which [contain/1/v] _a_little_sulking_bird in _one_corner [is/1/v] _a_bundle of _black_rods with _rusty_marks on _their_ends _a_large_number of _velvet_pillows [are/2/v] scattered about on _the_floor _a_vast_mirror [stretch/1/v] off to the northeast at [*'s] _feet [is/1/v] _a_large_steel_grate, next to which [is/1/v] _a_sign which [read/1/v], "Treasure vault. Keys in Main Office\"""", exits={'northeast': '@northeast_end'}), Thing('@black_rod in @southwest_end', article='a', called='small black rod', referring='small black | rod', sight='a small black rod'), Button('@button in @southwest_end', article='a', called='button', referring='red | button', sight='just a red button'), CaveRoom('@southwest_side_of_chasm', article='the', called='southwest side of chasm', sight=""" [*/s] [are/v] on _one_side of _a_large,_deep_chasm _a_heavy_white_mist rising up from below [obscure/1/v] _all_view of _the_far_side _a_southwest_path [lead/1/v] away from _the_chasm into _a_winding_corridor""", exits={'southwest': '@sloping_corridor', 'over': '@northeast_side_of_chasm', 'cross': '@northeast_side_of_chasm', 'northeast': '@northeast_side_of_chasm'}), Troll('@troll in @southwest_side_of_chasm', article='a', called='(burly) troll', referring=' | monster guardian', sight='[this] [is/1/v] just a burly troll, barring the way', allowed=can.possess_any_treasure, blocked=['northeast', 'over', 'cross']), CaveRoom('@sloping_corridor', article='the', called='sloping corridor', sight=""" [*/s] [are/v] in _a_long_winding_corridor sloping out of sight in both directions""", exits={'down': '@large_low_room', 'up': '@southwest_side_of_chasm'}), CaveRoom('@secret_canyon', article='the', called='secret canyon', sight=""" [*/s] [are/v] in _a_secret_canyon which [exit/1/v] to the north and east""", exits={'north': '@secret_canyon_above_room', 'east': '@secret_east_west_canyon'}), Thing('@rug in @secret_canyon', article='a', called='(Persian) rug', referring='persian | rug', qualities=['treasure'], allowed=can.support_any_item_or_dragon, sight='a Persian rug'), Dragon('@dragon on @rug', article='a', called='huge dragon', referring='huge green fierce | dragon', sight='[this] [is/1/v] just a huge dragon, barring the way', blocked=['north', 'onward']), CaveRoom('@northeast_side_of_chasm', article='the', called='northeast side of chasm', sight=""" [*/s] [are/v] on _the_far_side of _the_chasm _a_northeast_path [lead/1/v] away from _the_chasm on [this] side""", exits={'northeast': '@corridor', 'over': '@southwest_side_of_chasm', 'fork': '@fork_in_path', 'view': '@breath_taking_view', 'barren': '@front_of_barren_room', 'southwest': '@southwest_side_of_chasm', 'cross': '@southwest_side_of_chasm'}), CaveRoom('@corridor', article='the', called='corridor', sight=""" [*/s] [are/v] in a long east/west corridor _a_faint_rumbling_noise [is/1/v] heard in the distance""", exits={'west': '@northeast_side_of_chasm', 'east': '@fork_in_path', 'fork': '@fork_in_path', 'view': '@breath_taking_view', 'barren': '@front_of_barren_room'}), CaveRoom('@fork_in_path', article='the', called='fork in path', sight=""" _the_path [fork/1/v] [here] _the_left_fork [lead/1/v] northeast _a_dull_rumbling [seem/1/v] to get louder in that direction _the_right_fork [lead/1/v] southeast down _a_gentle_slope _the_main_corridor [enter/1/v] from the west""", exits={'west': '@corridor', 'northeast': '@junction_with_warm_walls', 'left': '@junction_with_warm_walls', 'southeast': '@limestone_passage', 'right': '@limestone_passage', 'down': '@limestone_passage', 'view': '@breath_taking_view', 'barren': '@front_of_barren_room'}), CaveRoom('@junction_with_warm_walls', article='the', called='junction with warm walls', sight=""" _the_walls [are/2/v] quite warm here from the north [*/s] [hear/v] _a_steady_roar, so loud that _the_entire_cave [seem/1/v] to be trembling _another_passage [lead/1/v] south, and _a_low_crawl [go/1/v] east""", exits={'south': '@fork_in_path', 'fork': '@fork_in_path', 'north': '@breath_taking_view', 'view': '@breath_taking_view', 'east': '@chamber_of_boulders', 'crawl': '@chamber_of_boulders'}), CaveRoom('@breath_taking_view', article='the', called='breath-taking view', sight=""" [*/s] [are/v] on _the_edge of _a_breath-taking_view far below [*/s] [is/1/v] _an_active_volcano, from which _great_gouts of _molten_lava [come/2/v] surging out, cascading back down into _the_depths _the_glowing_rock [fill/1/v] _the_farthest_reaches of _the_cavern with _a_blood-red_glare, giving _everything _an_eerie,_macabre_appearance _the_air [is/1/v] filled with flickering sparks of ash _the_walls [are/2/v] hot to the touch, and _the_thundering of _the_volcano [drown/1/v] out all other sounds embedded in _the_jagged_roof far overhead [are/1/v] _myriad_twisted_formations composed of _pure_white_alabaster, which scatter _the_murky_light into _sinister_apparitions upon _the_walls to _one_side [is/1/v] _a_deep_gorge, filled with _a_bizarre_chaos of _tortured_rock which seems to have been crafted by _the_devil _himself _an_immense_river of _fire [crash/1/v] out from _the_depths of _the_volcano, [burn/1/v] its way through _the_gorge, and [plummet/1/v] into _a_bottomless_pit far off to [*'s] left to _the_right, _an_immense_geyser of _blistering_steam [erupt/1/v] continuously from _a_barren_island in _the_center of _a_sulfurous_lake, which bubbles ominously _the_far_right_wall [is/1/v] aflame with _an_incandescence of its own, which [lend/1/v] _an_additional_infernal_splendor to _the_already_hellish_scene _a_dark,_foreboding_passage [exit/1/v] to the south""", smell="a heavy smell of brimstone", exits={'south': '@junction_with_warm_walls', 'tunnel': '@junction_with_warm_walls', 'leave': '@junction_with_warm_walls', 'fork': '@fork_in_path', 'down': '@west_end_of_long_hall', 'jump': '@west_end_of_long_hall'}), CaveRoom('@chamber_of_boulders', article='the', called='chamber of boulders', sight=""" [*/s] [are/v] in _a_small_chamber filled with _large_boulders _the_walls [are/2/v] very warm, causing _the_air in _the_room to be almost stifling from _the_heat _the_only_exit [is/1/v] _a_crawl heading west, through which [is/1/v] coming _a_low_rumbling""", exits={'west': '@junction_with_warm_walls', 'leave': '@junction_with_warm_walls', 'crawl': '@junction_with_warm_walls', 'fork': '@fork_in_path', 'view': '@breath_taking_view'}), Thing('@spices in @chamber_of_boulders', article='some', called='rare spices', referring='rare | spice spices', qualities=['treasure'], sight='rare spices'), CaveRoom('@limestone_passage', article='the', called='limestone passage', sight=""" [*/s] [are/v] walking along _a_gently_sloping_north/south_passage lined with _oddly_shaped_limestone_formations""", exits={'north': '@fork_in_path', 'up': '@fork_in_path', 'fork': '@fork_in_path', 'south': '@front_of_barren_room', 'down': '@front_of_barren_room', 'barren': '@front_of_barren_room', 'view': '@breath_taking_view'}), CaveRoom('@front_of_barren_room', article='the', called='front of barren room', sight=""" [*/s] [stand/ing/v] at _the_entrance to _a_large,_barren_room _a_sign posted above _the_entrance [read/1/v]: "Caution! Bear in room!\"""", exits={'west': '@limestone_passage', 'up': '@limestone_passage', 'fork': '@fork_in_path', 'east': '@barren_room', 'in': '@barren_room', 'barren': '@barren_room', 'enter': '@barren_room', 'view': '@breath_taking_view'}), CaveRoom('@barren_room', article='the', called='barren room', sight=""" [*/s] [are/v] inside _a_barren_room _the_center of _the_room [is/1/v] completely empty except for _some_dust marks in _the_dust [lead/2/v] away toward _the_far_end of _the_room the only exit [is/1/v] the way you came in""", exits={'west': '@front_of_barren_room', 'leave': '@front_of_barren_room', 'fork': '@fork_in_path', 'view': '@breath_taking_view'}), Bear('@bear in @barren_room', article='a', called='(ferocious) (cave) bear', referring=' | animal creature', sight='a ferocious cave bear, currently [angry/@bear/a]', allowed=can.possess_any_thing), Thing('@hook part_of @barren_room', article='a', called='(small) hook', referring='| peg', qualities=['metal'], allowed=can.support_chain, sight='a small metal hook, somehow affixed to the cave wall'), Thing('@chain on @hook', article='a', called='(golden) chain', referring='gold | leash', qualities=['treasure', 'metal'], sight='just an ordinary golden chain'), CaveRoom('@maze_17', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _twisting_little_passages, all different""", exits={'west': '@maze_15', 'southeast': '@maze_18', 'northwest': '@maze_19', 'southwest': '@maze_20', 'northeast': '@maze_21', 'up': '@maze_22', 'down': '@maze_23', 'north': '@maze_24', 'south': '@maze_25', 'east': '@maze_16'}), CaveRoom('@maze_18', article='the', called='maze', sight=""" [*/s] [are/v] in _a_little_maze of _twisty_passages, all different""", exits={'northwest': '@maze_15', 'up': '@maze_17', 'north': '@maze_19', 'south': '@maze_20', 'west': '@maze_21', 'southwest': '@maze_22', 'northeast': '@maze_23', 'east': '@maze_24', 'down': '@maze_25', 'southeast': '@maze_16'}), CaveRoom('@maze_19', article='the', called='maze', sight=""" [*/s] [are/v] in _a_twisting_maze of _little_passages, all different""", exits={'up': '@maze_15', 'down': '@maze_17', 'west': '@maze_18', 'northeast': '@maze_20', 'southwest': '@maze_21', 'east': '@maze_22', 'north': '@maze_23', 'northwest': '@maze_24', 'southeast': '@maze_25', 'south': '@maze_16'}), CaveRoom('@maze_20', article='the', called='maze', sight=""" [*/s] [are/v] in _a_twisting_little_maze of _passages, all different""", exits={'northeast': '@maze_15', 'north': '@maze_17', 'northwest': '@maze_18', 'southeast': '@maze_19', 'east': '@maze_21', 'down': '@maze_22', 'south': '@maze_23', 'up': '@maze_24', 'west': '@maze_25', 'southwest': '@maze_16'}), CaveRoom('@maze_21', article='the', called='maze', sight=""" [*/s] [are/v] in _a_twisty_little_maze of _passages, all different""", exits={'north': '@maze_15', 'southeast': '@maze_17', 'down': '@maze_18', 'south': '@maze_19', 'east': '@maze_20', 'west': '@maze_22', 'southwest': '@maze_23', 'northeast': '@maze_24', 'northwest': '@maze_25', 'up': '@maze_16'}), CaveRoom('@maze_22', article='the', called='maze', sight=""" [*/s] [are/v] in _a_twisty_maze of _little_passages, all different""", exits={'east': '@maze_15', 'west': '@maze_17', 'up': '@maze_18', 'southwest': '@maze_19', 'down': '@maze_20', 'south': '@maze_21', 'northwest': '@maze_23', 'southeast': '@maze_24', 'northeast': '@maze_25', 'north': '@maze_16'}), CaveRoom('@maze_23', article='the', called='maze', sight=""" [*/s] [are/v] in _a_little_twisty_maze of _passages, all different""", exits={'southeast': '@maze_15', 'northeast': '@maze_17', 'south': '@maze_18', 'down': '@maze_19', 'up': '@maze_20', 'northwest': '@maze_21', 'north': '@maze_22', 'southwest': '@maze_24', 'east': '@maze_25', 'west': '@maze_16'}), CaveRoom('@maze_24', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _little_twisting_passages, all different""", exits={'down': '@maze_15', 'east': '@maze_17', 'northeast': '@maze_18', 'up': '@maze_19', 'west': '@maze_20', 'north': '@maze_21', 'south': '@maze_22', 'southeast': '@maze_23', 'southwest': '@maze_25', 'northwest': '@maze_16'}), CaveRoom('@maze_25', article='the', called='maze', sight=""" [*/s] [are/v] in _a_maze of _little_twisty_passages, all different""", exits={'southwest': '@maze_15', 'northwest': '@maze_17', 'east': '@maze_18', 'west': '@maze_19', 'north': '@maze_20', 'down': '@maze_21', 'southeast': '@maze_22', 'up': '@maze_23', 'south': '@maze_24', 'northeast': '@maze_16'}), CaveRoom('@dead_end_15', article='the', called='dead end', referring='dead | end', exits={'north': '@maze_16', 'leave': '@maze_16'})]
{ "repo_name": "lucidbard/curveship", "path": "fiction/adventure.py", "copies": "3", "size": "103671", "license": "isc", "hash": -5825600230400938000, "line_mean": 34.9718945177, "line_max": 80, "alpha_frac": 0.5156311794, "autogenerated": false, "ratio": 3.352986836572981, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.011169326850143792, "num_lines": 2882 }
"""adventurelookup URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from adventures.urls import router as adventures_router urlpatterns = [ url(settings.BASE_URL_PATTERN + r'/auth/', include('rest_framework.urls', namespace='rest_framework')), url(settings.BASE_URL_PATTERN + r'/signups', include('signups.urls')), url(settings.BASE_URL_PATTERN + r'/admin/', admin.site.urls), url(settings.BASE_URL_PATTERN + '/', include(adventures_router.urls)), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
{ "repo_name": "petertrotman/adventurelookup", "path": "server/adventurelookup/urls.py", "copies": "1", "size": "1298", "license": "mit", "hash": 864285639290445200, "line_mean": 39.5625, "line_max": 79, "alpha_frac": 0.7203389831, "autogenerated": false, "ratio": 3.625698324022346, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4846037307122346, "avg_score": null, "num_lines": null }
# Adversarial autoencoder from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import tensorflow as tf import matplotlib.pyplot as plt import time from tfutil_deprecated import LayerManager flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('max_steps', 100000, 'Number of steps to run trainer.') flags.DEFINE_float('learning_rate', 0.0003, 'Initial learning rate.') flags.DEFINE_string('data_dir', '/tmp/data', 'Directory for storing data') flags.DEFINE_string('summaries_dir', '/tmp/aae/logs', 'Summaries directory') flags.DEFINE_string('train_dir', '/tmp/aae/save', 'Saves directory') TRAIN_SIZE = 60000 TEST_SIZE = 10000 SIG_LEN = 256 NUM_COMPONENTS = 3 BATCH_SIZE = 64 PRIOR_BATCH_SIZE = 5 PRETRAIN = False TRAIN = True LATENT_DIM = 20 NUM_HIDDEN_LAYERS = 3 HIDDEN_LAYER_SIZE = 200 def log(s): print('[%s] ' % time.asctime() + s) def rand_periodic(num_components, num_signals, signal_length): time = numpy.arange(signal_length, dtype=numpy.float32).reshape(1, signal_length) period = numpy.random.rand(num_signals, 1) * 80 + 40 counter = 2*numpy.pi*time / period sin_coeff = numpy.random.randn(num_components, num_signals) cos_coeff = numpy.random.randn(num_components, num_signals) arg = numpy.arange(1, num_components + 1).reshape(num_components, 1, 1) * counter return numpy.einsum('ij,ijk->jk', sin_coeff, numpy.sin(arg)) + numpy.einsum('ij,ijk->jk', cos_coeff, numpy.cos(arg)) def train(): # Import data log('simulating data') numpy.random.seed(3737) test_data = rand_periodic(NUM_COMPONENTS, TEST_SIZE, SIG_LEN) if TRAIN: train_data = rand_periodic(NUM_COMPONENTS, TRAIN_SIZE, SIG_LEN) else: # Don't waste time computing training data train_data = numpy.zeros((TRAIN_SIZE, SIG_LEN)) log('done simulating') lm_ae = LayerManager() lm_disc = LayerManager() with tf.name_scope('input'): all_train_data_initializer = tf.placeholder(tf.float32, [TRAIN_SIZE, SIG_LEN]) all_train_data = tf.Variable(all_train_data_initializer, trainable=False, collections=[]) random_training_example = tf.train.slice_input_producer([all_train_data]) training_batch = tf.train.batch([random_training_example], batch_size=BATCH_SIZE, enqueue_many=True) fed_input_data = tf.placeholder(tf.float32, [None, SIG_LEN]) def log_std_act(log_std): return tf.clip_by_value(log_std, -4.0, 4.0) def id_act(z): return z def double_relu(z): return [tf.nn.relu(z), tf.nn.relu(-z)] def encoder(data): last = data for i in range(NUM_HIDDEN_LAYERS): last = lm_ae.nn_layer(last, HIDDEN_LAYER_SIZE, 'encoder/hidden{}'.format(i), act=double_relu) with tf.variable_scope('latent'): latent_mean = lm_ae.nn_layer(last, LATENT_DIM, 'mean', act=id_act) latent_log_std = lm_ae.nn_layer(last, LATENT_DIM, 'log_std', act=log_std_act) return latent_mean, latent_log_std def decoder(code): last = code for i in range(NUM_HIDDEN_LAYERS): last = lm_ae.nn_layer(last, HIDDEN_LAYER_SIZE, 'decoder/hidden{}'.format(i), act=double_relu) output_mean = lm_ae.nn_layer(last, SIG_LEN, 'output/mean', act=id_act) output_log_std = lm_ae.nn_layer(last, SIG_LEN, 'output/log_std', act=log_std_act) return output_mean, output_log_std def discriminator(latent): last = latent for i in range(1): last = lm_disc.nn_layer(last, 20, 'discriminator/hidden{}'.format(i), act=double_relu) output_logit = lm_disc.nn_layer(last, 1, 'discrimator/prediction', act=id_act) return output_logit def full_model(data): latent_mean, latent_log_std = encoder(data) #latent_sample = lm_ae.reparam_normal_sample(latent_mean, latent_log_std, 'sample') latent_sample = latent_mean output_mean, output_log_std = decoder(latent_sample) disc_neg_logit = discriminator(latent_sample) tf.get_variable_scope().reuse_variables() latent_prior_sample = tf.random_normal(tf.shape(latent_mean)) latent_prior_sample.set_shape(latent_mean.get_shape().as_list()) disc_pos_logit = discriminator(latent_prior_sample) reconstruction_error = tf.reduce_sum( -0.5 * numpy.log(2 * numpy.pi) - output_log_std - 0.5 * tf.square(output_mean - data) / tf.exp( 2.0 * output_log_std), reduction_indices=[1]) disc_cross_entropy = 0.5*tf.nn.sigmoid_cross_entropy_with_logits(disc_neg_logit, tf.zeros(tf.shape(disc_neg_logit))) \ + 0.5*tf.nn.sigmoid_cross_entropy_with_logits(disc_pos_logit, tf.ones( tf.shape(disc_pos_logit))) num_copies = 85 image = tf.reshape( tf.tile(tf.expand_dims(tf.transpose(tf.pack([data, output_mean, data - output_mean]), perm=[1, 0, 2]), 2), [1, 1, num_copies, 1]), [-1, 3 * num_copies, SIG_LEN]) lm_ae.summaries.image_summary('posterior_sample', tf.expand_dims(image, -1), 5) rough_error = tf.reduce_mean(tf.square(tf.reduce_mean(tf.square(output_mean), reduction_indices=[1]) - tf.reduce_mean(tf.square(data), reduction_indices=[1]))) return output_mean, tf.reduce_mean(reconstruction_error), tf.reduce_mean(disc_cross_entropy), rough_error def prior_model(): latent_sample = tf.random_normal((PRIOR_BATCH_SIZE, LATENT_DIM)) output_mean, output_log_std = decoder(latent_sample) num_copies = 255 image = tf.tile(tf.expand_dims(output_mean, 1), [1, num_copies, 1]) sample_image = lm_ae.summaries.image_summary('prior_sample', tf.expand_dims(image, -1), 5) return output_mean, sample_image with tf.name_scope('posterior'): posterior_mean, reconstruction_error, disc_cross_entropy, rough_error = full_model(training_batch) training_merged = lm_ae.summaries.merge_all_summaries() tf.get_variable_scope().reuse_variables() with tf.name_scope('prior'): prior_mean, prior_sample = prior_model() lm_ae.summaries.reset() with tf.name_scope('test'): test_posterior_mean, test_reconstruction_error, test_dist_cross_entropy, _ = full_model(fed_input_data) test_merged = lm_ae.summaries.merge_all_summaries() saver = tf.train.Saver(tf.trainable_variables()) batch = tf.Variable(0) learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, batch, 5000, 0.8, staircase=True) pretrain_step = tf.train.AdamOptimizer(0.03).minimize(rough_error, var_list=lm_ae.scale_factory.variables) ae_train_step = tf.train.AdamOptimizer(learning_rate).minimize(-reconstruction_error, global_step=batch, var_list=lm_ae.weight_factory.variables + lm_ae.bias_factory.variables) ae_fool_disc_train_step = tf.train.AdamOptimizer(learning_rate/3.0).minimize(-disc_cross_entropy, global_step=batch, var_list=lm_ae.weight_factory.variables + lm_ae.bias_factory.variables) disc_train_step = tf.train.AdamOptimizer(learning_rate/3.0).minimize(disc_cross_entropy, global_step=batch, var_list=lm_disc.weight_factory.variables + lm_disc.bias_factory.variables) def feed_dict(mode): """Make a TensorFlow feed_dict: maps data onto Tensor placeholders.""" if mode == 'test': return {fed_input_data: test_data} else: return {} def validate(i, write_summary=True): summary, ce, re = sess.run([test_merged, test_dist_cross_entropy, test_reconstruction_error], feed_dict=feed_dict('test')) log('batch %s: Test set cross entropy = %s, test set reconstruction error = %s' % (i, ce, re)) if write_summary: test_writer.add_summary(summary, i) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) sess.run(all_train_data.initializer, feed_dict={all_train_data_initializer: train_data}) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) if TRAIN: train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train', sess.graph) test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test') try: if PRETRAIN: log('starting pre-training') for i in range(3000): err, _ = sess.run([rough_error, pretrain_step], feed_dict=feed_dict('train')) if i % 100 == 99: log('batch %s: single training batch rough error = %s' % (i, err)) #validate(0, write_summary=False) log('initializing ae') for i in range(5000): re, _ = sess.run([reconstruction_error, ae_train_step], feed_dict=feed_dict('train')) if i % 1000 == 999: log('batch %s: single training batch reconstruction error = %s' % (i, re)) # #validate(0, write_summary=False) # log('initializing discriminator') # for i in range(5000): # ce, _ = sess.run([disc_cross_entropy, disc_train_step], feed_dict('train')) # if i % 1000 == 999: # log('batch %s: single training batch cross entropy = %s' % (i, ce)) #validate(0, write_summary=False) log('starting training') for i in range(FLAGS.max_steps): if i % 1000 == 999: # Do test set validate(i) # if i % 10 == 0: # sess.run([disc_train_step], feed_dict('train')) if i % 100 == 99: # Record a summary run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, prior_sample_summary, _ = sess.run([training_merged, prior_sample, ae_train_step], feed_dict=feed_dict('train'), options=run_options, run_metadata=run_metadata) train_writer.add_summary(summary, i) train_writer.add_summary(prior_sample_summary, i) train_writer.add_run_metadata(run_metadata, 'batch%d' % i) else: # sess.run([disc_train_step], feed_dict=feed_dict('train')) # sess.run([ae_fool_disc_train_step], feed_dict=feed_dict('train')) # sess.run([ae_train_step], feed_dict=feed_dict('train')) sess.run([ae_train_step, ae_fool_disc_train_step, disc_train_step], feed_dict=feed_dict('train')) finally: log('saving') saver.save(sess, FLAGS.train_dir, global_step=batch) log('done') else: log('restoring') saver.restore(sess, FLAGS.train_dir + '-' + str(FLAGS.max_steps)) fig = plt.figure() ax = fig.add_subplot(111) def plot_prior(_): prior_means, = sess.run([prior_mean], feed_dict=feed_dict('prior')) plt.cla() ax.plot(prior_means[0, :]) plt.draw() plot_prior(None) cid = fig.canvas.mpl_connect('button_press_event', plot_prior) plt.show() fig.canvas.mpl_disconnect(cid) coord.request_stop() coord.join(threads) sess.close() def main(_): if tf.gfile.Exists(FLAGS.summaries_dir): tf.gfile.DeleteRecursively(FLAGS.summaries_dir) tf.gfile.MakeDirs(FLAGS.summaries_dir) train() if __name__ == '__main__': tf.app.run()
{ "repo_name": "NoahDStein/NeuralNetSandbox", "path": "aae.py", "copies": "1", "size": "11967", "license": "apache-2.0", "hash": 8229987379316187000, "line_mean": 45.5642023346, "line_max": 192, "alpha_frac": 0.6002339768, "autogenerated": false, "ratio": 3.4676905244856564, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4567924501285656, "avg_score": null, "num_lines": null }
'''Adversarial autoencoder ''' from cortex.plugins import ModelPlugin, register_model from cortex.built_ins.models.gan import (SimpleDiscriminator, GradientPenalty, generator_loss) from cortex.built_ins.models.vae import ImageDecoder, ImageEncoder class AdversarialAutoencoder(ModelPlugin): '''Adversarial Autoencoder Autoencoder with a GAN loss on the latent space. ''' defaults = dict( data=dict(batch_size=dict(train=64, test=640), inputs=dict(inputs='images')), optimizer=dict(optimizer='Adam', learning_rate=1e-4), train=dict(epochs=500, archive_every=10) ) def __init__(self): super().__init__() encoder_contract = dict(kwargs=dict(dim_out='dim_z')) decoder_contract = dict(kwargs=dict(dim_in='dim_z')) disc_contract = dict(kwargs=dict(dim_in='dim_z')) penalty_contract = dict(nets=dict(network='discriminator')) self.encoder = ImageEncoder(contract=encoder_contract) self.decoder = ImageDecoder(contract=decoder_contract) self.discriminator = SimpleDiscriminator(contract=disc_contract) self.penalty = GradientPenalty(contract=penalty_contract) def build(self, noise_type='normal', dim_z=64): ''' Args: noise_type: Prior noise distribution. dim_z: Dimensionality of latent space. ''' self.add_noise('Z', dist=noise_type, size=dim_z) self.encoder.build() self.decoder.build() self.discriminator.build() def routine(self, inputs, Z, encoder_loss_type='non-saturating', measure=None, beta=1.0): ''' Args: encoder_loss_type: Adversarial loss type for the encoder. beta: Amount of adversarial loss for the encoder. ''' Z_Q = self.encoder.encode(inputs) self.decoder.routine(inputs, Z_Q) E_pos, E_neg, P_samples, Q_samples = self.discriminator.score( Z, Z_Q, measure) adversarial_loss = generator_loss( Q_samples, measure, loss_type=encoder_loss_type) self.losses.encoder = self.losses.decoder + beta * adversarial_loss self.results.adversarial_loss = adversarial_loss.item() def train_step(self, n_discriminator_updates=1): ''' Args: n_discriminator_updates: Number of discriminator updates per step. ''' for _ in range(n_discriminator_updates): self.data.next() inputs, Z = self.inputs('inputs', 'Z') Z_Q = self.encoder.encode(inputs) self.discriminator.routine(Z, Z_Q) self.optimizer_step() self.penalty.routine(Z) self.optimizer_step() self.routine(auto_input=True) self.optimizer_step() def eval_step(self): self.data.next() inputs, Z = self.inputs('inputs', 'Z') Z_Q = self.encoder.encode(inputs) self.discriminator.routine(Z, Z_Q) self.penalty.routine(Z) self.routine(auto_input=True) def visualize(self, inputs, Z, targets): self.decoder.visualize(Z) self.encoder.visualize(inputs, targets) Z_Q = self.encoder.encode(inputs) R = self.decoder.decode(Z_Q) self.add_image(inputs, name='ground truth') self.add_image(R, name='reconstructed') register_model(AdversarialAutoencoder)
{ "repo_name": "rdevon/cortex", "path": "cortex/built_ins/models/adversarial_autoencoder.py", "copies": "1", "size": "3471", "license": "bsd-3-clause", "hash": -7032006892946175000, "line_mean": 30.2702702703, "line_max": 78, "alpha_frac": 0.6113511956, "autogenerated": false, "ratio": 3.712299465240642, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48236506608406415, "avg_score": null, "num_lines": null }
'''Adversarially learned inference and Bi-GAN Currently noise encoder is not implemented. ''' __author__ = 'R Devon Hjelm and Samuel Lavoie' __author_email__ = 'erroneus@gmail.com' from cortex.plugins import register_plugin, ModelPlugin from cortex.built_ins.models.gan import ( get_positive_expectation, get_negative_expectation, GradientPenalty) from cortex.built_ins.models.vae import ImageDecoder, ImageEncoder from cortex.built_ins.networks.fully_connected import FullyConnectedNet import torch import torch.nn as nn class ALIDiscriminatorModule(nn.Module): '''ALI discriminator model. ''' def __init__(self, x_encoder, z_encoder, topnet): super(ALIDiscriminatorModule, self).__init__() self.x_encoder = x_encoder self.z_encoder = z_encoder self.topnet = topnet def forward(self, x, z, nonlinearity=None): w = self.x_encoder(x) if len(w.size()) == 4: w = w.view(-1, w.size(1) * w.size(2) * w.size(3)) if self.z_encoder is None: v = z else: v = self.z_encoder(z) v = torch.cat([v, w], dim=1) y = self.topnet(v) return y class BidirectionalModel(ModelPlugin): def __init__(self, discriminator, **kwargs): super().__init__(**kwargs) self.discriminator = discriminator encoder_contract = dict(kwargs=dict(dim_out='dim_z')) decoder_contract = dict(kwargs=dict(dim_in='dim_z')) self.decoder = ImageDecoder(contract=decoder_contract) self.encoder = ImageEncoder(contract=encoder_contract) def build(self): self.decoder.build() self.encoder.build() def routine(self, inputs, Z, measure=None): decoder = self.nets.decoder encoder = self.nets.encoder X_P, Z_Q = inputs, Z X_Q = decoder(Z_Q) Z_P = encoder(X_P) E_pos, E_neg, _, _ = self.discriminator.score( X_P, X_Q, Z_P, Z_Q, measure) self.losses.decoder = -E_neg self.losses.encoder = E_pos def visualize(self): self.decoder.visualize(auto_input=True) self.encoder.visualize(auto_input=True) class ALIDiscriminator(ModelPlugin): def build(self, topnet_args=dict(dim_h=[512, 128], batch_norm=False), dim_int=256, dim_z=None): ''' Args: topnet_args: Keyword arguments for the top network. dim_int: Intermediate layer size for discriminator. ''' x_encoder = self.nets.x_encoder try: z_encoder = self.nets.z_encoder except KeyError: z_encoder = None if z_encoder is not None: z_encoder_out = list( z_encoder.models[-1].parameters())[-1].size()[0] dim_in = dim_int + z_encoder_out else: dim_in = dim_int + dim_z topnet = FullyConnectedNet(dim_in, 1, **topnet_args) discriminator = ALIDiscriminatorModule(x_encoder, z_encoder, topnet) self.nets.discriminator = discriminator def routine(self, X_real, X_fake, Z_real, Z_fake, measure='GAN'): ''' Args: measure: GAN measure. {GAN, JSD, KL, RKL (reverse KL), X2 (Chi^2), H2 (squared Hellinger), DV (Donsker Varahdan KL), W1 (IPM)} ''' X_P, Z_P = X_real, Z_real X_Q, Z_Q = X_fake, Z_fake E_pos, E_neg, P_samples, Q_samples = self.score( X_P, X_Q, Z_P, Z_Q, measure) difference = E_pos - E_neg self.losses.discriminator = -difference self.results.update(Scores=dict(Ep=P_samples.mean().item(), Eq=Q_samples.mean().item())) self.results['{} distance'.format(measure)] = difference.item() def score(self, X_P, X_Q, Z_P, Z_Q, measure): discriminator = self.nets.discriminator P_samples = discriminator(X_P, Z_P) Q_samples = discriminator(X_Q, Z_Q) E_pos = get_positive_expectation(P_samples, measure) E_neg = get_negative_expectation(Q_samples, measure) return E_pos, E_neg, P_samples, Q_samples def visualize(self, X_real, X_fake, Z_real, Z_fake, targets): discriminator = self.nets.discriminator X_P, Z_P = X_real, Z_real X_Q, Z_Q = X_fake, Z_fake P_samples = discriminator(X_P, Z_P) Q_samples = discriminator(X_Q, Z_Q) self.add_histogram(dict(fake=Q_samples.view(-1).data, real=P_samples.view(-1).data), name='discriminator output') self.add_scatter(Z_P, labels=targets.data, name='latent values') class ALI(ModelPlugin): '''Adversarially learned inference. a.k.a. BiGAN Note: Currently noisy encoder not supported. ''' defaults = dict( data=dict(batch_size=dict(train=64, test=640), inputs=dict(inputs='images')), optimizer=dict(optimizer='Adam', learning_rate=1e-4), train=dict(epochs=500, save_on_lowest='losses.generator') ) def __init__(self): super().__init__() self.discriminator = ALIDiscriminator() self.bidirectional_model = BidirectionalModel( discriminator=self.discriminator) encoder_contract = dict(nets=dict(encoder='x_encoder'), kwargs=dict(dim_out='dim_int')) self.encoder = ImageEncoder(contract=encoder_contract) penalty_contract = dict(nets=dict(network='discriminator')) self.penalty = GradientPenalty(contract=penalty_contract) def build(self, dim_z=None, dim_int=None, use_z_encoder=False, z_encoder_args=dict(dim_h=256, batch_norm=True), noise_type='normal'): ''' Args: use_z_encoder: Use a neural network for Z pathway in discriminator. z_encoder_args: Arguments for the Z pathway encoder. ''' self.add_noise('Z', dist=noise_type, size=dim_z) if use_z_encoder: encoder = FullyConnectedNet(dim_z, dim_int, **z_encoder_args) self.nets.z_encoder = encoder self.encoder.build() self.discriminator.build() self.bidirectional_model.build() def train_step(self, discriminator_updates=1): ''' Args: generator_updates: Number of generator updates per step. discriminator_updates: Number of discriminator updates per step. ''' for _ in range(discriminator_updates): self.data.next() inputs, Z = self.inputs('inputs', 'Z') generated = self.bidirectional_model.decoder.decode(Z) inferred = self.bidirectional_model.encoder.encode(inputs) self.discriminator.routine( inputs, generated.detach(), inferred.detach(), Z) self.optimizer_step() self.penalty.routine((inputs, inferred)) self.optimizer_step() self.bidirectional_model.train_step() def eval_step(self): self.data.next() inputs, Z = self.inputs('inputs', 'Z') generated = self.bidirectional_model.decoder.decode(Z) inferred = self.bidirectional_model.encoder.encode(inputs) self.discriminator.routine(inputs, generated, inferred, Z) self.bidirectional_model.eval_step() def visualize(self, inputs, Z, targets): generated = self.bidirectional_model.decoder.decode(Z) inferred = self.bidirectional_model.encoder.encode(inputs) self.bidirectional_model.visualize() self.discriminator.visualize(inputs, generated, inferred, Z, targets) register_plugin(ALI)
{ "repo_name": "rdevon/cortex", "path": "cortex/built_ins/models/ali.py", "copies": "1", "size": "7744", "license": "bsd-3-clause", "hash": 4475384260665485300, "line_mean": 29.976, "line_max": 79, "alpha_frac": 0.5947830579, "autogenerated": false, "ratio": 3.5736040609137056, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9668387118813706, "avg_score": 0, "num_lines": 250 }
advertClicks = [ { "url": "b.example.com", "date": "2015-11-22 11:11:11" }, { "url": "c.example.com", "date": "2015-11-22 11:11:11" }, { "url": "a.example.com", "date": "2015-11-22 11:11:11" }, { "url": "a.example.com", "date": "2015-11-22 22:22:22" }, { "url": "a.example.com", "date": "2015-12-22 11:11:11" }, { "url": "a.example.com", "date": "2015-12-22 22:22:22" } ] days = {} for item in advertClicks: date = item["date"].split(" ")[0] if date not in days: days[date] = {} day = days[date] if item["url"] not in day: day[item["url"]] = {"clicks": 0} properties = day[item["url"]] properties["clicks"] = properties["clicks"] + 1 output = [] for dayKey, dayObject in days.iteritems(): for urlKey, properties in dayObject.iteritems(): output.append(dayKey + " " + urlKey + " " + str(properties["clicks"])) print "<br>\n".join(output) # the last iteration's "properties.clicks", # from inside the center of the for loop, # is equivalent to: #print(days["2015-11-22"]["c.example.com"]["clicks"]) # Which would be preferable if we knew they keys in advance.
{ "repo_name": "bobbybabra/pcg2015_kel", "path": "site/impress2Kev.py", "copies": "1", "size": "1276", "license": "mit", "hash": 1592854173122256100, "line_mean": 24.52, "line_max": 119, "alpha_frac": 0.5219435737, "autogenerated": false, "ratio": 3.030878859857482, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9041898520514003, "avg_score": 0.0021847826086956517, "num_lines": 50 }