def tf_solve(self, fn_x, x_init, base_value, target_value, estimated_improvement=None):

return super(LineSearch, self).tf_solve(fn_x, x_init, base_value, target_value, estimated_improvement)<EOL>

Iteratively optimizes $f(x)$ for $x$ on the line between $x'$ and $x_0$.

Args:
    fn_x: A callable returning the value $f(x)$ at $x$.
    x_init: Initial solution guess $x_0$.
    base_value: Value $f(x')$ at $x = x'$.
    target_value: Value $f(x_0)$ at $x = x_0$.
    estimated_improvement: Estimated improvement for $x = x_0$, $f(x')$ if None.

Returns:
    A solution $x$ to the problem as given by the solver.


def tf_initialize(self, x_init, base_value, target_value, estimated_improvement):

self.base_value = base_value<EOL>if estimated_improvement is None:  <EOL><INDENT>estimated_improvement = tf.abs(x=base_value)<EOL><DEDENT>first_step = super(LineSearch, self).tf_initialize(x_init)<EOL>improvement = tf.divide(<EOL>x=(target_value - self.base_value),<EOL>y=tf.maximum(x=estimated_improvement, y=util.epsilon)<EOL>)<EOL>last_improvement = improvement - <NUM_LIT:1.0><EOL>if self.mode == '<STR_LIT>':<EOL><INDENT>deltas = [-t * self.parameter for t in x_init]<EOL>self.estimated_incr = -estimated_improvement * self.parameter<EOL><DEDENT>elif self.mode == '<STR_LIT>':<EOL><INDENT>deltas = [-t * self.parameter for t in x_init]<EOL><DEDENT>return first_step + (deltas, improvement, last_improvement, estimated_improvement)<EOL>

Initialization step preparing the arguments for the first iteration of the loop body.

Args:
    x_init: Initial solution guess $x_0$.
    base_value: Value $f(x')$ at $x = x'$.
    target_value: Value $f(x_0)$ at $x = x_0$.
    estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None.

Returns:
    Initial arguments for tf_step.


def tf_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):

x, next_iteration, deltas, improvement, last_improvement, estimated_improvement = super(LineSearch, self).tf_step(<EOL>x, iteration, deltas, improvement, last_improvement, estimated_improvement<EOL>)<EOL>next_x = [t + delta for t, delta in zip(x, deltas)]<EOL>if self.mode == '<STR_LIT>':<EOL><INDENT>next_deltas = deltas<EOL>next_estimated_improvement = estimated_improvement + self.estimated_incr<EOL><DEDENT>elif self.mode == '<STR_LIT>':<EOL><INDENT>next_deltas = [delta * self.parameter for delta in deltas]<EOL>next_estimated_improvement = estimated_improvement * self.parameter<EOL><DEDENT>target_value = self.fn_x(next_deltas)<EOL>next_improvement = tf.divide(<EOL>x=(target_value - self.base_value),<EOL>y=tf.maximum(x=next_estimated_improvement, y=util.epsilon)<EOL>)<EOL>return next_x, next_iteration, next_deltas, next_improvement, improvement, next_estimated_improvement<EOL>

Iteration loop body of the line search algorithm.

Args:
    x: Current solution estimate $x_t$.
    iteration: Current iteration counter $t$.
    deltas: Current difference $x_t - x'$.
    improvement: Current improvement $(f(x_t) - f(x')) / v'$.
    last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.
    estimated_improvement: Current estimated value $v'$.

Returns:
    Updated arguments for next iteration.


def tf_next_step(self, x, iteration, deltas, improvement, last_improvement, estimated_improvement):

next_step = super(LineSearch, self).tf_next_step(<EOL>x, iteration, deltas, improvement, last_improvement, estimated_improvement<EOL>)<EOL>def undo_deltas():<EOL><INDENT>value = self.fn_x([-delta for delta in deltas])<EOL>with tf.control_dependencies(control_inputs=(value,)):<EOL><INDENT>return tf.less(x=value, y=value)  <EOL><DEDENT><DEDENT>improved = tf.cond(<EOL>pred=(improvement > last_improvement),<EOL>true_fn=(lambda: True),<EOL>false_fn=undo_deltas<EOL>)<EOL>next_step = tf.logical_and(x=next_step, y=improved)<EOL>next_step = tf.logical_and(x=next_step, y=(improvement < self.accept_ratio))<EOL>return tf.logical_and(x=next_step, y=(estimated_improvement > util.epsilon))<EOL>

Termination condition: max number of iterations, or no improvement for last step, or
improvement less than acceptable ratio, or estimated value not positive.

Args:
    x: Current solution estimate $x_t$.
    iteration: Current iteration counter $t$.
    deltas: Current difference $x_t - x'$.
    improvement: Current improvement $(f(x_t) - f(x')) / v'$.
    last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.
    estimated_improvement: Current estimated value $v'$.

Returns:
    True if another iteration should be performed.


def __init__(self, max_iterations, unroll_loop=False):

assert max_iterations >= <NUM_LIT:0><EOL>self.max_iterations = max_iterations<EOL>assert isinstance(unroll_loop, bool)<EOL>self.unroll_loop = unroll_loop<EOL>super(Iterative, self).__init__()<EOL>self.initialize = tf.make_template(name_='<STR_LIT>', func_=self.tf_initialize)<EOL>self.step = tf.make_template(name_='<STR_LIT>', func_=self.tf_step)<EOL>self.next_step = tf.make_template(name_='<STR_LIT>', func_=self.tf_next_step)<EOL>

Creates a new iterative solver instance.

Args:
    max_iterations: Maximum number of iterations before termination.
    unroll_loop: Unrolls the TensorFlow while loop if true.


def tf_solve(self, fn_x, x_init, *args):

self.fn_x = fn_x<EOL>args = self.initialize(x_init, *args)<EOL>if self.unroll_loop:<EOL><INDENT>for _ in range(self.max_iterations):<EOL><INDENT>next_step = self.next_step(*args)<EOL>step = (lambda: self.step(*args))<EOL>do_nothing = (lambda: args)<EOL>args = tf.cond(pred=next_step, true_fn=step, false_fn=do_nothing)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>args = tf.while_loop(cond=self.next_step, body=self.step, loop_vars=args)<EOL><DEDENT>return args[<NUM_LIT:0>]<EOL>

Iteratively solves an equation/optimization for $x$ involving an expression $f(x)$.

Args:
    fn_x: A callable returning an expression $f(x)$ given $x$.
    x_init: Initial solution guess $x_0$.
    *args: Additional solver-specific arguments.

Returns:
    A solution $x$ to the problem as given by the solver.


return x_init, <NUM_LIT:0><EOL>

Initialization step preparing the arguments for the first iteration of the loop body
(default: initial solution guess and iteration counter).

Args:
    x_init: Initial solution guess $x_0$.
    *args: Additional solver-specific arguments.

Returns:
    Initial arguments for tf_step.


return (x, iteration + <NUM_LIT:1>) + args<EOL>

Iteration loop body of the iterative solver (default: increment iteration step). The
first two loop arguments have to be the current solution estimate and the iteration step.

Args:
    x: Current solution estimate.
    iteration: Current iteration counter.
    *args: Additional solver-specific arguments.

Returns:
    Updated arguments for next iteration.


def tf_next_step(self, x, iteration, *args):

return iteration < self.max_iterations<EOL>

Termination condition (default: max number of iterations).

Args:
    x: Current solution estimate.
    iteration: Current iteration counter.
    *args: Additional solver-specific arguments.

Returns:
    True if another iteration should be performed.


<EOL>self.solve = tf.make_template(name_='<STR_LIT>', func_=self.tf_solve)<EOL>


raise NotImplementedError<EOL>

Solves an equation/optimization for $x$ involving an expression $f(x)$.

Args:
    fn_x: A callable returning an expression $f(x)$ given $x$.
    *args: Additional solver-specific arguments.

Returns:
    A solution $x$ to the problem as given by the solver.


return util.get_object(<EOL>obj=config,<EOL>predefined=tensorforce.core.optimizers.solvers.solvers,<EOL>kwargs=kwargs<EOL>)<EOL>

Creates a solver from a specification dict.


def __init__(self, max_iterations, damping, unroll_loop=False):

assert damping >= <NUM_LIT:0.0><EOL>self.damping = damping<EOL>super(ConjugateGradient, self).__init__(max_iterations=max_iterations, unroll_loop=unroll_loop)<EOL>

Creates a new conjugate gradient solver instance.

Args:
    max_iterations: Maximum number of iterations before termination.
    damping: Damping factor.
    unroll_loop: Unrolls the TensorFlow while loop if true.


return super(ConjugateGradient, self).tf_solve(fn_x, x_init, b)<EOL>

Iteratively solves the system of linear equations $A x = b$.

Args:
    fn_x: A callable returning the left-hand side $A x$ of the system of linear equations.
    x_init: Initial solution guess $x_0$, zero vector if None.
    b: The right-hand side $b$ of the system of linear equations.

Returns:
    A solution $x$ to the problem as given by the solver.


if x_init is None:<EOL><INDENT>x_init = [tf.zeros(shape=util.shape(t)) for t in b]<EOL><DEDENT>initial_args = super(ConjugateGradient, self).tf_initialize(x_init)<EOL>conjugate = residual = [t - fx for t, fx in zip(b, self.fn_x(x_init))]<EOL>squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in residual])<EOL>return initial_args + (conjugate, residual, squared_residual)<EOL>

Initialization step preparing the arguments for the first iteration of the loop body:
$x_0, 0, p_0, r_0, r_0^2$.

Args:
    x_init: Initial solution guess $x_0$, zero vector if None.
    b: The right-hand side $b$ of the system of linear equations.

Returns:
    Initial arguments for tf_step.


def tf_step(self, x, iteration, conjugate, residual, squared_residual):

x, next_iteration, conjugate, residual, squared_residual = super(ConjugateGradient, self).tf_step(<EOL>x, iteration, conjugate, residual, squared_residual<EOL>)<EOL>A_conjugate = self.fn_x(conjugate)<EOL>if self.damping > <NUM_LIT:0.0>:<EOL><INDENT>A_conjugate = [A_conj + self.damping * conj for A_conj, conj in zip(A_conjugate, conjugate)]<EOL><DEDENT>conjugate_A_conjugate = tf.add_n(<EOL>inputs=[tf.reduce_sum(input_tensor=(conj * A_conj)) for conj, A_conj in zip(conjugate, A_conjugate)]<EOL>)<EOL>alpha = squared_residual / tf.maximum(x=conjugate_A_conjugate, y=util.epsilon)<EOL>next_x = [t + alpha * conj for t, conj in zip(x, conjugate)]<EOL>next_residual = [res - alpha * A_conj for res, A_conj in zip(residual, A_conjugate)]<EOL>next_squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in next_residual])<EOL>beta = next_squared_residual / tf.maximum(x=squared_residual, y=util.epsilon)<EOL>next_conjugate = [res + beta * conj for res, conj in zip(next_residual, conjugate)]<EOL>return next_x, next_iteration, next_conjugate, next_residual, next_squared_residual<EOL>

Iteration loop body of the conjugate gradient algorithm.

Args:
    x: Current solution estimate $x_t$.
    iteration: Current iteration counter $t$.
    conjugate: Current conjugate $c_t$.
    residual: Current residual $r_t$.
    squared_residual: Current squared residual $r_t^2$.

Returns:
    Updated arguments for next iteration.


def tf_next_step(self, x, iteration, conjugate, residual, squared_residual):

next_step = super(ConjugateGradient, self).tf_next_step(x, iteration, conjugate, residual, squared_residual)<EOL>return tf.logical_and(x=next_step, y=(squared_residual >= util.epsilon))<EOL>

Termination condition: max number of iterations, or residual sufficiently small.

Args:
    x: Current solution estimate $x_t$.
    iteration: Current iteration counter $t$.
    conjugate: Current conjugate $c_t$.
    residual: Current residual $r_t$.
    squared_residual: Current squared residual $r_t^2$.

Returns:
    True if another iteration should be performed.


if not self._isfull():<EOL><INDENT>self._memory.append(None)<EOL><DEDENT>position = self._next_position_then_increment()<EOL>old_priority = <NUM_LIT:0> if self._memory[position] is Noneelse (self._memory[position].priority or <NUM_LIT:0>)<EOL>row = _SumRow(item, priority)<EOL>self._memory[position] = row<EOL>self._update_internal_nodes(<EOL>position, (row.priority or <NUM_LIT:0>) - old_priority)<EOL>

Stores a transition in replay memory.

If the memory is full, the oldest entry is replaced.


def move(self, external_index, new_priority):

index = external_index + (self._capacity - <NUM_LIT:1>)<EOL>return self._move(index, new_priority)<EOL>


item, old_priority = self._memory[index]<EOL>old_priority = old_priority or <NUM_LIT:0><EOL>self._memory[index] = _SumRow(item, new_priority)<EOL>self._update_internal_nodes(index, new_priority - old_priority)<EOL>


def _update_internal_nodes(self, index, delta):

<EOL>while index > <NUM_LIT:0>:<EOL><INDENT>index = (index - <NUM_LIT:1>) // <NUM_LIT:2><EOL>self._memory[index] += delta<EOL><DEDENT>

Update internal priority sums when leaf priority has been changed.
Args:
    index: leaf node index
    delta: change in priority


start = self._capacity - <NUM_LIT:1><EOL>position = start + self._position<EOL>self._position = (self._position + <NUM_LIT:1>) % self._capacity<EOL>return position<EOL>


parent = <NUM_LIT:0><EOL>while True:<EOL><INDENT>left = <NUM_LIT:2> * parent + <NUM_LIT:1><EOL>if left >= len(self._memory):<EOL><INDENT>return parent<EOL><DEDENT>left_p = self._memory[left] if left < self._capacity - <NUM_LIT:1>else (self._memory[left].priority or <NUM_LIT:0>)<EOL>if p <= left_p:<EOL><INDENT>parent = left<EOL><DEDENT>else:<EOL><INDENT>if left + <NUM_LIT:1> >= len(self._memory):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>p -= left_p<EOL>parent = left + <NUM_LIT:1><EOL><DEDENT><DEDENT>

Sample random element with priority greater than p.


pool_size = len(self)<EOL>if pool_size == <NUM_LIT:0>:<EOL><INDENT>return []<EOL><DEDENT>delta_p = self._memory[<NUM_LIT:0>] / batch_size<EOL>chosen_idx = []<EOL>if abs(self._memory[<NUM_LIT:0>]) < util.epsilon:<EOL><INDENT>chosen_idx = np.random.randint(self._capacity - <NUM_LIT:1>, self._capacity - <NUM_LIT:1> + len(self), size=batch_size).tolist()<EOL><DEDENT>else:<EOL><INDENT>for i in xrange(batch_size):<EOL><INDENT>lower = max(i * delta_p, <NUM_LIT:0>)<EOL>upper = min((i + <NUM_LIT:1>) * delta_p, self._memory[<NUM_LIT:0>])<EOL>p = random.uniform(lower, upper)<EOL>chosen_idx.append(self._sample_with_priority(p))<EOL><DEDENT><DEDENT>return [(i, self._memory[i]) for i in chosen_idx]<EOL>


return len(self._memory) - (self._capacity - <NUM_LIT:1>)<EOL>

Return the current number of transitions.


def get_batch(self, batch_size, next_states=False):

if batch_size > len(self.observations):<EOL><INDENT>raise TensorForceError(<EOL>"<STR_LIT>")<EOL><DEDENT>states = {name: np.zeros((batch_size,) + tuple(state['<STR_LIT>']), dtype=util.np_dtype(<EOL>state['<STR_LIT:type>'])) for name, state in self.states_spec.items()}<EOL>internals = [np.zeros((batch_size,) + shape, dtype)<EOL>for shape, dtype in self.internals_spec]<EOL>actions = {name: np.zeros((batch_size,) + tuple(action['<STR_LIT>']), dtype=util.np_dtype(action['<STR_LIT:type>'])) for name, action in self.actions_spec.items()}<EOL>terminal = np.zeros((batch_size,), dtype=util.np_dtype('<STR_LIT:bool>'))<EOL>reward = np.zeros((batch_size,), dtype=util.np_dtype('<STR_LIT:float>'))<EOL>if next_states:<EOL><INDENT>next_states = {name: np.zeros((batch_size,) + tuple(state['<STR_LIT>']), dtype=util.np_dtype(<EOL>state['<STR_LIT:type>'])) for name, state in self.states_spec.items()}<EOL>next_internals = [np.zeros((batch_size,) + shape, dtype)<EOL>for shape, dtype in self.internals_spec]<EOL><DEDENT>unseen_indices = list(xrange(<EOL>self.none_priority_index + self.observations._capacity - <NUM_LIT:1>,<EOL>len(self.observations) + self.observations._capacity - <NUM_LIT:1>)<EOL>)<EOL>self.batch_indices = unseen_indices[:batch_size]<EOL>remaining = batch_size - len(self.batch_indices)<EOL>if remaining:<EOL><INDENT>samples = self.observations.sample_minibatch(remaining)<EOL>sample_indices = [i for i, o in samples]<EOL>self.batch_indices += sample_indices<EOL><DEDENT>np.random.shuffle(self.batch_indices)<EOL>for n, index in enumerate(self.batch_indices):<EOL><INDENT>observation, _ = self.observations._memory[index]<EOL>for name, state in states.items():<EOL><INDENT>state[n] = observation[<NUM_LIT:0>][name]<EOL><DEDENT>for k, internal in enumerate(internals):<EOL><INDENT>internal[n] = observation[<NUM_LIT:1>][k]<EOL><DEDENT>for name, action in actions.items():<EOL><INDENT>action[n] = observation[<NUM_LIT:2>][name]<EOL><DEDENT>terminal[n] = observation[<NUM_LIT:3>]<EOL>reward[n] = observation[<NUM_LIT:4>]<EOL>if next_states:<EOL><INDENT>for name, next_state in next_states.items():<EOL><INDENT>next_state[n] = observation[<NUM_LIT:5>][name]<EOL><DEDENT>for k, next_internal in enumerate(next_internals):<EOL><INDENT>next_internal[n] = observation[<NUM_LIT:6>][k]<EOL><DEDENT><DEDENT><DEDENT>if next_states:<EOL><INDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward,<EOL>next_states=next_states,<EOL>next_internals=next_internals<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward<EOL>)<EOL><DEDENT>

Samples a batch of the specified size according to priority.

Args:
    batch_size: The batch size
    next_states: A boolean flag indicating whether 'next_states' values should be included

Returns: A dict containing states, actions, rewards, terminals, internal states (and next states)


if self.batch_indices is None:<EOL><INDENT>raise TensorForceError("<STR_LIT>")<EOL><DEDENT>for index, loss in zip(self.batch_indices, loss_per_instance):<EOL><INDENT>new_priority = (np.abs(loss) + self.prioritization_constant) ** self.prioritization_weight<EOL>self.observations._move(index, new_priority)<EOL>self.none_priority_index += <NUM_LIT:1><EOL><DEDENT>

Computes priorities according to loss.

Args:
    loss_per_instance:


def __init__(self, states, internals, actions, include_next_states, capacity, scope='<STR_LIT>', summary_labels=None):

self.capacity = capacity<EOL>self.scope = scope<EOL>self.states_memory = dict()  <EOL>self.internals_memory = dict()  <EOL>self.actions_memory = dict()  <EOL>self.terminal_memory = None  <EOL>self.reward_memory = None  <EOL>self.memory_index = None  <EOL>self.episode_indices = None  <EOL>self.episode_count = None  <EOL>self.retrieve_indices = None<EOL>super(Queue, self).__init__(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>include_next_states=include_next_states,<EOL>scope=scope,<EOL>summary_labels=summary_labels<EOL>)<EOL>

Queue memory.

Args:
    capacity: Memory capacity.


states = dict()<EOL>for name in sorted(self.states_memory):<EOL><INDENT>states[name] = tf.gather(params=self.states_memory[name], indices=indices)<EOL><DEDENT>internals = dict()<EOL>for name in sorted(self.internals_memory):<EOL><INDENT>internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)<EOL><DEDENT>actions = dict()<EOL>for name in sorted(self.actions_memory):<EOL><INDENT>actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)<EOL><DEDENT>terminal = tf.gather(params=self.terminal_memory, indices=indices)<EOL>reward = tf.gather(params=self.reward_memory, indices=indices)<EOL>if self.include_next_states:<EOL><INDENT>assert util.rank(indices) == <NUM_LIT:1><EOL>next_indices = (indices + <NUM_LIT:1>) % self.capacity<EOL>next_states = dict()<EOL>for name in sorted(self.states_memory):<EOL><INDENT>next_states[name] = tf.gather(params=self.states_memory[name], indices=next_indices)<EOL><DEDENT>next_internals = dict()<EOL>for name in sorted(self.internals_memory):<EOL><INDENT>next_internals[name] = tf.gather(params=self.internals_memory[name], indices=next_indices)<EOL><DEDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward,<EOL>next_states=next_states,<EOL>next_internals=next_internals<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward<EOL>)<EOL><DEDENT>

Fetches experiences for given indices.

Args:
    indices: Index tensor

Returns: Batch of experiences


Replay memory.

Args:
    states (dict): States specification.
    internals (dict): Internal states specification.
    actions (dict): Actions specification.
    include_next_states (bool): Include subsequent state if true.
    capacity (int): Memory capacity (number of state/internals/action/(next-state)? records).


def __init__(self, states, internals, actions, include_next_states, scope='<STR_LIT>', summary_labels=None):

self.states_spec = states<EOL>self.internals_spec = internals<EOL>self.actions_spec = actions<EOL>self.include_next_states = include_next_states<EOL>self.scope = scope<EOL>self.summary_labels = set(summary_labels or ())<EOL>self.variables = dict()<EOL>self.initialize = None  <EOL>self.store = None<EOL>self.retrieve_timesteps = None<EOL>self.retrieve_episodes = None<EOL>self.retrieve_sequences = None<EOL>self.update_batch = None<EOL>self.setup_template_funcs()<EOL>

Args:
    states (dict): States specification.
    internals (dict): Internal states specification.
    actions (dict): Actions specification.
    include_next_states (bool): Include subsequent state if true.
    scope (str): The tf variable scope to use when creating variables for this memory.
    summary_labels (list): List of summary labels.


raise NotImplementedError<EOL>

Initializes the memory. Called by a memory-model in its own tf_initialize method.


def tf_store(self, states, internals, actions, terminal, reward):

raise NotImplementedError<EOL>

Stores experiences, i.e. a batch of timesteps.

Args:
    states: Dict of state tensors.
    internals: List of prior internal state tensors.
    actions: Dict of action tensors.
    terminal: Terminal boolean tensor.
    reward: Reward tensor.


raise NotImplementedError<EOL>

Retrieves a given number of timesteps from the stored experiences.

Args:
    n: Number of timesteps to retrieve.

Returns:
    Dicts containing the retrieved experiences.


raise NotImplementedError<EOL>

Retrieves a given number of episodes from the stored experiences.

Args:
    n: Number of episodes to retrieve.

Returns:
    Dicts containing the retrieved experiences.


def tf_retrieve_sequences(self, n, sequence_length):

raise NotImplementedError<EOL>

Retrieves a given number of temporally consistent timestep sequences from the stored
experiences.

Args:
    n: Number of sequences to retrieve.
    sequence_length: Length of timestep sequences.

Returns:
    Dicts containing the retrieved experiences.


return tf.no_op()<EOL>

Updates the internal information of the latest batch instances based on their loss.

Args:
    loss_per_instance: Loss per instance tensor.


return [self.variables[key] for key in sorted(self.variables)]<EOL>

Returns the TensorFlow variables used by the memory.

Returns:
    List of variables.


memory = util.get_object(<EOL>obj=spec,<EOL>predefined_objects=tensorforce.core.memories.memories,<EOL>kwargs=kwargs<EOL>)<EOL>assert isinstance(memory, Memory)<EOL>return memory<EOL>

Creates a memory from a specification dict.


self.capacity = capacity<EOL>self.buffer_size = buffer_size<EOL>self.prioritization_weight = prioritization_weight<EOL>self.retrieve_indices = None<EOL>self.states_memory = dict()<EOL>self.internals_memory = dict()<EOL>self.actions_memory = dict()<EOL>self.terminal_memory = None<EOL>self.reward_memory = None<EOL>self.memory_index = None<EOL>self.priorities = None<EOL>self.buffer_index = None<EOL>self.states_buffer = dict()<EOL>self.internals_buffer = dict()<EOL>self.actions_buffer = dict()<EOL>self.terminal_buffer = None<EOL>self.reward_buffer = None<EOL>self.batch_indices = None<EOL>self.last_batch_buffer_elems = None<EOL>self.memory_size = None<EOL>super(PrioritizedReplay, self).__init__(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>include_next_states=include_next_states,<EOL>scope=scope,<EOL>summary_labels=summary_labels<EOL>)<EOL>

Prioritized experience replay.

Args:
    states: States specification.
    internals: Internal states specification.
    actions: Actions specification.
    include_next_states: Include subsequent state if true.
    capacity: Memory capacity.
    prioritization_weight: Prioritization weight.
    buffer_size: Buffer size. The buffer is used to insert experiences before experiences
        have been computed via updates. Note that if the buffer is to small in comparison
        to the frequency with which updates are performed, old experiences from the buffer
        will be overwritten before they are moved to the main memory.


def tf_retrieve_indices(self, buffer_elements, priority_indices):

states = dict()<EOL>buffer_start = self.buffer_index - buffer_elements<EOL>buffer_end = self.buffer_index<EOL>for name in sorted(self.states_memory):<EOL><INDENT>buffer_state_memory = self.states_buffer[name]<EOL>buffer_states = buffer_state_memory[buffer_start:buffer_end]<EOL>memory_states = tf.gather(params=self.states_memory[name], indices=priority_indices)<EOL>states[name] = tf.concat(values=(buffer_states, memory_states), axis=<NUM_LIT:0>)<EOL><DEDENT>internals = dict()<EOL>for name in sorted(self.internals_memory):<EOL><INDENT>internal_buffer_memory = self.internals_buffer[name]<EOL>buffer_internals = internal_buffer_memory[buffer_start:buffer_end]<EOL>memory_internals = tf.gather(params=self.internals_memory[name], indices=priority_indices)<EOL>internals[name] = tf.concat(values=(buffer_internals, memory_internals), axis=<NUM_LIT:0>)<EOL><DEDENT>actions = dict()<EOL>for name in sorted(self.actions_memory):<EOL><INDENT>action_buffer_memory = self.actions_buffer[name]<EOL>buffer_action = action_buffer_memory[buffer_start:buffer_end]<EOL>memory_action = tf.gather(params=self.actions_memory[name], indices=priority_indices)<EOL>actions[name] = tf.concat(values=(buffer_action, memory_action), axis=<NUM_LIT:0>)<EOL><DEDENT>buffer_terminal = self.terminal_buffer[buffer_start:buffer_end]<EOL>priority_terminal = tf.gather(params=self.terminal_memory, indices=priority_indices)<EOL>terminal = tf.concat(values=(buffer_terminal, priority_terminal), axis=<NUM_LIT:0>)<EOL>buffer_reward = self.reward_buffer[buffer_start:buffer_end]<EOL>priority_reward = tf.gather(params=self.reward_memory, indices=priority_indices)<EOL>reward = tf.concat(values=(buffer_reward, priority_reward), axis=<NUM_LIT:0>)<EOL>if self.include_next_states:<EOL><INDENT>assert util.rank(priority_indices) == <NUM_LIT:1><EOL>next_priority_indices = (priority_indices + <NUM_LIT:1>) % self.capacity<EOL>next_buffer_start = (buffer_start + <NUM_LIT:1>) % self.buffer_size<EOL>next_buffer_end = (buffer_end + <NUM_LIT:1>) % self.buffer_size<EOL>next_states = dict()<EOL>for name in sorted(self.states_memory):<EOL><INDENT>buffer_state_memory = self.states_buffer[name]<EOL>buffer_next_states = buffer_state_memory[next_buffer_start:next_buffer_end]<EOL>memory_next_states = tf.gather(params=self.states_memory[name], indices=next_priority_indices)<EOL>next_states[name] = tf.concat(values=(buffer_next_states, memory_next_states), axis=<NUM_LIT:0>)<EOL><DEDENT>next_internals = dict()<EOL>for name in sorted(self.internals_memory):<EOL><INDENT>buffer_internal_memory = self.internals_buffer[name]<EOL>buffer_next_internals = buffer_internal_memory[next_buffer_start:next_buffer_end]<EOL>memory_next_internals = tf.gather(params=self.internals_memory[name], indices=next_priority_indices)<EOL>next_internals[name] = tf.concat(values=(buffer_next_internals, memory_next_internals), axis=<NUM_LIT:0>)<EOL><DEDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward,<EOL>next_states=next_states,<EOL>next_internals=next_internals<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return dict(<EOL>states=states,<EOL>internals=internals,<EOL>actions=actions,<EOL>terminal=terminal,<EOL>reward=reward<EOL>)<EOL><DEDENT>

Fetches experiences for given indices by combining entries from buffer
which have no priorities, and entries from priority memory.

Args:
    buffer_elements: Number of buffer elements to retrieve
    priority_indices: Index tensor for priority memory

Returns: Batch of experiences


<EOL>mask = tf.not_equal(<EOL>x=self.batch_indices,<EOL>y=tf.zeros(shape=tf.shape(input=self.batch_indices), dtype=tf.int32)<EOL>)<EOL>priority_indices = tf.reshape(tensor=tf.where(condition=mask), shape=[-<NUM_LIT:1>])<EOL>sampled_buffer_batch = self.tf_retrieve_indices(<EOL>buffer_elements=self.last_batch_buffer_elems,<EOL>priority_indices=priority_indices<EOL>)<EOL>states = sampled_buffer_batch['<STR_LIT>']<EOL>internals = sampled_buffer_batch['<STR_LIT>']<EOL>actions = sampled_buffer_batch['<STR_LIT>']<EOL>terminal = sampled_buffer_batch['<STR_LIT>']<EOL>reward = sampled_buffer_batch['<STR_LIT>']<EOL>priorities = loss_per_instance ** self.prioritization_weight<EOL>assignments = list()<EOL>memory_end_index = self.memory_index + self.last_batch_buffer_elems<EOL>memory_insert_indices = tf.range(<EOL>start=self.memory_index,<EOL>limit=memory_end_index<EOL>) % self.capacity<EOL>for name in sorted(states):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.states_memory[name],<EOL>indices=memory_insert_indices,<EOL>updates=states[name][<NUM_LIT:0>:self.last_batch_buffer_elems])<EOL>)<EOL><DEDENT>for name in sorted(internals):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.internals_buffer[name],<EOL>indices=memory_insert_indices,<EOL>updates=internals[name][<NUM_LIT:0>:self.last_batch_buffer_elems]<EOL>))<EOL><DEDENT>assignments.append(tf.scatter_update(<EOL>ref=self.priorities,<EOL>indices=memory_insert_indices,<EOL>updates=priorities[<NUM_LIT:0>:self.last_batch_buffer_elems]<EOL>))<EOL>assignments.append(tf.scatter_update(<EOL>ref=self.terminal_memory,<EOL>indices=memory_insert_indices,<EOL>updates=terminal[<NUM_LIT:0>:self.last_batch_buffer_elems])<EOL>)<EOL>assignments.append(tf.scatter_update(<EOL>ref=self.reward_memory,<EOL>indices=memory_insert_indices,<EOL>updates=reward[<NUM_LIT:0>:self.last_batch_buffer_elems])<EOL>)<EOL>for name in sorted(actions):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.actions_memory[name],<EOL>indices=memory_insert_indices,<EOL>updates=actions[name][<NUM_LIT:0>:self.last_batch_buffer_elems]<EOL>))<EOL><DEDENT>main_memory_priorities = priorities[self.last_batch_buffer_elems:]<EOL>main_memory_priorities = main_memory_priorities[<NUM_LIT:0>:tf.shape(priority_indices)[<NUM_LIT:0>]]<EOL>assignments.append(tf.scatter_update(<EOL>ref=self.priorities,<EOL>indices=priority_indices,<EOL>updates=main_memory_priorities<EOL>))<EOL>with tf.control_dependencies(control_inputs=assignments):<EOL><INDENT>assignments = list()<EOL>sorted_priorities, sorted_indices = tf.nn.top_k(<EOL>input=self.priorities,<EOL>k=self.capacity,<EOL>sorted=True<EOL>)<EOL>assignments.append(tf.assign(ref=self.priorities, value=sorted_priorities))<EOL>assignments.append(tf.scatter_update(<EOL>ref=self.terminal_memory,<EOL>indices=sorted_indices,<EOL>updates=self.terminal_memory<EOL>))<EOL>for name in sorted(self.states_memory):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.states_memory[name],<EOL>indices=sorted_indices,<EOL>updates=self.states_memory[name]<EOL>))<EOL><DEDENT>for name in sorted(self.actions_memory):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.actions_memory[name],<EOL>indices=sorted_indices,<EOL>updates=self.actions_memory[name]<EOL>))<EOL><DEDENT>for name in sorted(self.internals_memory):<EOL><INDENT>assignments.append(tf.scatter_update(<EOL>ref=self.internals_memory[name],<EOL>indices=sorted_indices,<EOL>updates=self.internals_memory[name]<EOL>))<EOL><DEDENT>assignments.append(tf.scatter_update(<EOL>ref=self.reward_memory,<EOL>indices=sorted_indices,<EOL>updates=self.reward_memory<EOL>))<EOL><DEDENT>with tf.control_dependencies(control_inputs=assignments):<EOL><INDENT>assignments = list()<EOL>assignments.append(tf.assign_sub(ref=self.buffer_index, value=self.last_batch_buffer_elems))<EOL>total_inserted_elements = self.memory_size + self.last_batch_buffer_elems<EOL>assignments.append(tf.assign(<EOL>ref=self.memory_size,<EOL>value=tf.minimum(x=total_inserted_elements, y=self.capacity))<EOL>)<EOL>assignments.append(tf.assign(ref=self.memory_index, value=memory_end_index))<EOL>assignments.append(tf.assign(<EOL>ref=self.batch_indices,<EOL>value=tf.zeros(shape=tf.shape(self.batch_indices), dtype=tf.int32)<EOL>))<EOL><DEDENT>with tf.control_dependencies(control_inputs=assignments):<EOL><INDENT>return tf.no_op()<EOL><DEDENT>

Updates priority memory by performing the following steps:

1. Use saved indices from prior retrieval to reconstruct the batch
elements which will have their priorities updated.
2. Compute priorities for these elements.
3. Insert buffer elements to memory, potentially overwriting existing elements.
4. Update priorities of existing memory elements
5. Resort memory.
6. Update buffer insertion index.

Note that this implementation could be made more efficient by maintaining
a sorted version via sum trees.

:param loss_per_instance: Losses from recent batch to perform priority update


self.ignore_unknown_dtypes = False<EOL>self.meta_params = dict()<EOL>self.method_calling = inspect.getframeinfo(current_frame)[<NUM_LIT:2>]<EOL>_, _, __, self.vals_current = inspect.getargvalues(current_frame)<EOL>if '<STR_LIT>' in self.vals_current:<EOL><INDENT>self.recorded_class_type = self.vals_current['<STR_LIT>']<EOL>self.meta_params['<STR_LIT>'] = str(self.vals_current['<STR_LIT>'])<EOL><DEDENT>frame_list = inspect.getouterframes(current_frame)<EOL>for frame in frame_list:<EOL><INDENT>args, varargs, keywords, vals = inspect.getargvalues(frame[<NUM_LIT:0>])<EOL>if '<STR_LIT>' in vals:<EOL><INDENT>if self.recorded_class_type == vals['<STR_LIT>']:<EOL><INDENT>for i in args:<EOL><INDENT>self.meta_params[i] = vals[i]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>del self.meta_params['<STR_LIT>']<EOL>

Init the MetaPrameterRecord with "Agent" parameters by passing inspect.currentframe() from Agent Class.

The Init will search back to find the parent class to capture all passed parameters and store
them in "self.meta_params".

NOTE: Currently only optimized for TensorBoard output.

TODO: Add JSON Export, TEXT EXPORT

Args:
    current_frame: Frame value from class to obtain metaparameters[= inspect.currentframe()]


ops = []<EOL>self.ignore_unknown_dtypes = True<EOL>for key in sorted(self.meta_params):<EOL><INDENT>value = self.convert_data_to_string(self.meta_params[key])<EOL>if len(value) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>ops.append(tf.contrib.summary.generic(name=key, tensor=tf.convert_to_tensor(str(value))))<EOL><DEDENT>else:<EOL><INDENT>ops.append(tf.contrib.summary.generic(name=key, tensor=tf.as_string(tf.convert_to_tensor(value))))<EOL><DEDENT><DEDENT>return ops<EOL>

Convert MetaParams into TF Summary Format and create summary_op.

Returns:
    Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication.


return ascii_art.ascii_art_to_game(<EOL>GAME_ART, what_lies_beneath='<STR_LIT:U+0020>',<EOL>sprites=dict(<EOL>[('<STR_LIT:P>', PlayerSprite)] +<EOL>[(c, UpwardLaserBoltSprite) for c in UPWARD_BOLT_CHARS] +<EOL>[(c, DownwardLaserBoltSprite) for c in DOWNWARD_BOLT_CHARS]),<EOL>drapes=dict(X=MarauderDrape,<EOL>B=BunkerDrape),<EOL>update_schedule=['<STR_LIT:P>', '<STR_LIT:B>', '<STR_LIT:X>'] + list(_ALL_BOLT_CHARS))<EOL>

Builds and returns an Extraterrestrial Marauders game.


def __init__(self, corner, position, character):

super(PlayerSprite, self).__init__(<EOL>corner, position, character, impassable='<STR_LIT>', confined_to_board=True)<EOL>

Simply indicates to the superclass that we can't walk off the board.


super(UpwardLaserBoltSprite, self).__init__(<EOL>corner, position, character, impassable='<STR_LIT>')<EOL>self._teleport((-<NUM_LIT:1>, -<NUM_LIT:1>))<EOL>

Starts the Sprite in a hidden position off of the board.


def _fly(self, board, layers, things, the_plot):

<EOL>if (self.character in the_plot['<STR_LIT>'] or<EOL>self.character in the_plot['<STR_LIT>']):<EOL><INDENT>return self._teleport((-<NUM_LIT:1>, -<NUM_LIT:1>))<EOL><DEDENT>self._north(board, the_plot)<EOL>

Handles the behaviour of visible bolts flying toward Marauders.


def _fire(self, layers, things, the_plot):

<EOL>if the_plot.get('<STR_LIT>') == the_plot.frame: return<EOL>the_plot['<STR_LIT>'] = the_plot.frame<EOL>row, col = things['<STR_LIT:P>'].position<EOL>self._teleport((row-<NUM_LIT:1>, col))<EOL>


super(DownwardLaserBoltSprite, self).__init__(<EOL>corner, position, character, impassable='<STR_LIT>')<EOL>self._teleport((-<NUM_LIT:1>, -<NUM_LIT:1>))<EOL>


<EOL>if self.character in the_plot['<STR_LIT>']:<EOL><INDENT>return self._teleport((-<NUM_LIT:1>, -<NUM_LIT:1>))<EOL><DEDENT>if self.position == things['<STR_LIT:P>'].position: the_plot.terminate_episode()<EOL>self._south(board, the_plot)<EOL>

Handles the behaviour of visible bolts flying toward the player.


<EOL>if the_plot.get('<STR_LIT>') == the_plot.frame: return<EOL>the_plot['<STR_LIT>'] = the_plot.frame<EOL>col = np.random.choice(np.nonzero(layers['<STR_LIT:X>'].sum(axis=<NUM_LIT:0>))[<NUM_LIT:0>])<EOL>row = np.nonzero(layers['<STR_LIT:X>'][:, col])[<NUM_LIT:0>][-<NUM_LIT:1>] + <NUM_LIT:1><EOL>self._teleport((row, col))<EOL>

Launches a new bolt from a random Marauder.


def escape(text, quote=False, smart_amp=True):

if smart_amp:<EOL><INDENT>text = _escape_pattern.sub('<STR_LIT>', text)<EOL><DEDENT>else:<EOL><INDENT>text = text.replace('<STR_LIT:&>', '<STR_LIT>')<EOL><DEDENT>text = text.replace('<STR_LIT:<>', '<STR_LIT>')<EOL>text = text.replace('<STR_LIT:>>', '<STR_LIT>')<EOL>if quote:<EOL><INDENT>text = text.replace('<STR_LIT:">', '<STR_LIT>')<EOL>text = text.replace("<STR_LIT:'>", '<STR_LIT>')<EOL><DEDENT>return text<EOL>

Replace special characters "&", "<" and ">" to HTML-safe sequences.

    The original cgi.escape will always escape "&", but you can control
    this one for a smart escape amp.

    :param quote: if set to True, " and ' will be escaped.
    :param smart_amp: if set to False, & will always be escaped.


lower_url = url.lower().strip('<STR_LIT>')<EOL>for scheme in _scheme_blacklist:<EOL><INDENT>if lower_url.startswith(scheme):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>return escape(url, quote=True, smart_amp=False)<EOL>

Remove dangerous URL schemes like javascript: and escape afterwards.


def markdown(text, escape=True, **kwargs):

return Markdown(escape=escape, **kwargs)(text)<EOL>

Render markdown formatted text to html.

    :param text: markdown formatted text content.
    :param escape: if set to False, all html tags will not be escaped.
    :param use_xhtml: output with xhtml tags.
    :param hard_wrap: if set to True, it will use the GFM line breaks feature.
    :param parse_block_html: parse text only in block level html.
    :param parse_inline_html: parse text only in inline level html.


self.tokens.append({<EOL>'<STR_LIT:type>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT:1> if m.group(<NUM_LIT:2>) == '<STR_LIT:=>' else <NUM_LIT:2>,<EOL>'<STR_LIT:text>': m.group(<NUM_LIT:1>),<EOL>})<EOL>


self.linebreak = re.compile(r'<STR_LIT>')<EOL>self.text = re.compile(<EOL>r'<STR_LIT>'<EOL>)<EOL>

Grammar for hard wrap linebreak. You don't need to add two
        spaces at the end of a line.


return '<STR_LIT>'<EOL>

Returns the default, empty output value for the renderer.

        All renderer methods use the '+=' operator to append to this value.
        Default is a string so rendering HTML can build up a result string with
        the rendered Markdown.

        Can be overridden by Renderer subclasses to be types like an empty
        list, allowing the renderer to create a tree-like structure to
        represent the document (which can then be reprocessed later into a
        separate format like docx or pdf).


code = code.rstrip('<STR_LIT:\n>')<EOL>if not lang:<EOL><INDENT>code = escape(code, smart_amp=False)<EOL>return '<STR_LIT>' % code<EOL><DEDENT>code = escape(code, quote=True, smart_amp=False)<EOL>return '<STR_LIT>' % (lang, code)<EOL>

Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.


return '<STR_LIT>' % text.rstrip('<STR_LIT:\n>')<EOL>

Rendering <blockquote> with the given text.

        :param text: text content of the blockquote.


if self.options.get('<STR_LIT>') andhtml.lower().startswith('<STR_LIT>'):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if self.options.get('<STR_LIT>'):<EOL><INDENT>return escape(html)<EOL><DEDENT>return html<EOL>

Rendering block level pure html content.

        :param html: text content of the html snippet.


def header(self, text, level, raw=None):

return '<STR_LIT>' % (level, text, level)<EOL>

Rendering header/heading tags like ``<h1>`` ``<h2>``.

        :param text: rendered text content for the header.
        :param level: a number for the header level, for example: 1.
        :param raw: raw text content of the header.


if self.options.get('<STR_LIT>'):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'<EOL>


tag = '<STR_LIT>'<EOL>if ordered:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>' % (tag, body, tag)<EOL>

Rendering list tags like ``<ul>`` and ``<ol>``.

        :param body: body contents of the list.
        :param ordered: whether this list is ordered or not.


return '<STR_LIT>' % text<EOL>

Rendering list item snippet. Like ``<li>``.


return '<STR_LIT>' % text.strip('<STR_LIT:U+0020>')<EOL>


return (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) % (header, body)<EOL>

Rendering table element. Wrap header and body in it.

        :param header: header part of the table.
        :param body: body part of the table.


return '<STR_LIT>' % content<EOL>

Rendering a table row. Like ``<tr>``.

        :param content: content of current table row.


if flags['<STR_LIT>']:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>align = flags['<STR_LIT>']<EOL>if not align:<EOL><INDENT>return '<STR_LIT>' % (tag, content, tag)<EOL><DEDENT>return '<STR_LIT>' % (<EOL>tag, align, content, tag<EOL>)<EOL>

Rendering a table cell. Like ``<th>`` ``<td>``.

        :param content: content of current table cell.
        :param header: whether this is header or not.
        :param align: align of current table cell.


return '<STR_LIT>' % text<EOL>

Rendering **strong** text.

        :param text: text content for emphasis.


return '<STR_LIT>' % text<EOL>

Rendering *emphasis* text.

        :param text: text content for emphasis.


text = escape(text.rstrip(), smart_amp=False)<EOL>return '<STR_LIT>' % text<EOL>

Rendering inline `code` text.

        :param text: text content for inline code.


return '<STR_LIT>' % text<EOL>

Rendering ~~strikethrough~~ text.

        :param text: text content for strikethrough.


if self.options.get('<STR_LIT>'):<EOL><INDENT>return text<EOL><DEDENT>return escape(text)<EOL>

Rendering unformatted text.

        :param text: text content.


return escape(text)<EOL>

Rendering escape sequence.

        :param text: text content.


def autolink(self, link, is_email=False):

text = link = escape(link)<EOL>if is_email:<EOL><INDENT>link = '<STR_LIT>' % link<EOL><DEDENT>return '<STR_LIT>' % (link, text)<EOL>

Rendering a given link or email address.

        :param link: link content or email address.
        :param is_email: whether this is an email or not.


link = escape_link(link)<EOL>if not title:<EOL><INDENT>return '<STR_LIT>' % (link, text)<EOL><DEDENT>title = escape(title, quote=True)<EOL>return '<STR_LIT>' % (link, title, text)<EOL>

Rendering a given link with content and title.

        :param link: href link for ``<a>`` tag.
        :param title: title content for `title` attribute.
        :param text: text content for description.


src = escape_link(src)<EOL>text = escape(text, quote=True)<EOL>if title:<EOL><INDENT>title = escape(title, quote=True)<EOL>html = '<STR_LIT>' % (src, text, title)<EOL><DEDENT>else:<EOL><INDENT>html = '<STR_LIT>' % (src, text)<EOL><DEDENT>if self.options.get('<STR_LIT>'):<EOL><INDENT>return '<STR_LIT>' % html<EOL><DEDENT>return '<STR_LIT>' % html<EOL>

Rendering a image with title and text.

        :param src: source link of the image.
        :param title: title text of the image.
        :param text: alt text of the image.


if self.options.get('<STR_LIT>'):<EOL><INDENT>return escape(html)<EOL><DEDENT>return html<EOL>

Rendering span level pure html content.

        :param html: text content of the html snippet.


return '<STR_LIT>'<EOL>


html = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) % (escape(key), escape(key), index)<EOL>return html<EOL>

Rendering the ref anchor of a footnote.

        :param key: identity key for the footnote.
        :param index: the index count of current footnote.


back = (<EOL>'<STR_LIT>'<EOL>) % escape(key)<EOL>text = text.rstrip()<EOL>if text.endswith('<STR_LIT>'):<EOL><INDENT>text = re.sub(r'<STR_LIT>', r'<STR_LIT>' % back, text)<EOL><DEDENT>else:<EOL><INDENT>text = '<STR_LIT>' % (text, back)<EOL><DEDENT>html = '<STR_LIT>' % (escape(key), text)<EOL>return html<EOL>

Rendering a footnote item.

        :param key: identity key for the footnote.
        :param text: text content of the footnote.


html = '<STR_LIT>'<EOL>return html % (self.hrule(), text)<EOL>

Wrapper for all footnotes.

        :param text: contents of all footnotes.


return self.parse(text)<EOL>

Render the Markdown text.

        :param text: markdown formatted text content.


def process_docstring(app, what, name, obj, options, lines):

markdown = "<STR_LIT:\n>".join(lines)<EOL>rest = m2r(markdown)<EOL>rest.replace("<STR_LIT:\r\n>", "<STR_LIT:\n>")<EOL>del lines[:]<EOL>lines.extend(rest.split("<STR_LIT:\n>"))<EOL>


global _is_sphinx<EOL>_is_sphinx = True<EOL>app.add_config_value('<STR_LIT>', False, '<STR_LIT>')<EOL>app.add_source_parser('<STR_LIT>', M2RParser)<EOL>app.add_directive('<STR_LIT>', MdInclude)<EOL>


return self.renderer.image_link(<EOL>m.group('<STR_LIT:url>'), m.group('<STR_LIT:target>'), m.group('<STR_LIT>'))<EOL>


return self.renderer.rest_role(m.group(<NUM_LIT:0>))<EOL>


return self.renderer.rest_link(m.group(<NUM_LIT:0>))<EOL>


return self.renderer.inline_math(m.group(<NUM_LIT:1>))<EOL>


marker = '<STR_LIT::>' if m.group(<NUM_LIT:1>) is None else '<STR_LIT>'<EOL>return self.renderer.eol_literal_marker(marker)<EOL>


return '<STR_LIT>' + self._indent_block(html) + '<STR_LIT>'<EOL>

Rendering block level pure html content.

        :param html: text content of the html snippet.


return '<STR_LIT>'.format(text, self.hmarks[level] * len(text))<EOL>

Rendering header/heading tags like ``<h1>`` ``<h2>``.

        :param text: rendered text content for the header.
        :param level: a number for the header level, for example: 1.
        :param raw: raw text content of the header.


mark = '<STR_LIT>' if ordered else '<STR_LIT>'<EOL>lines = body.splitlines()<EOL>for i, line in enumerate(lines):<EOL><INDENT>if line and not line.startswith(self.list_marker):<EOL><INDENT>lines[i] = '<STR_LIT:U+0020>' * len(mark) + line<EOL><DEDENT><DEDENT>return '<STR_LIT>'.format(<EOL>'<STR_LIT:\n>'.join(lines)).replace(self.list_marker, mark)<EOL>

Rendering list tags like ``<ul>`` and ``<ol>``.

        :param body: body contents of the list.
        :param ordered: whether this list is ordered or not.


return '<STR_LIT:\n>' + self.list_marker + text<EOL>

Rendering list item snippet. Like ``<li>``.


return '<STR_LIT:\n>' + text + '<STR_LIT:\n>'<EOL>


table = '<STR_LIT>'<EOL>if header and not header.isspace():<EOL><INDENT>table = (table + self.indent + '<STR_LIT>' +<EOL>self._indent_block(header) + '<STR_LIT:\n>')<EOL><DEDENT>else:<EOL><INDENT>table = table + '<STR_LIT:\n>'<EOL><DEDENT>table = table + self._indent_block(body) + '<STR_LIT>'<EOL>return table<EOL>

Rendering table element. Wrap header and body in it.

        :param header: header part of the table.
        :param body: body part of the table.


contents = content.splitlines()<EOL>if not contents:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>clist = ['<STR_LIT>' + contents[<NUM_LIT:0>]]<EOL>if len(contents) > <NUM_LIT:1>:<EOL><INDENT>for c in contents[<NUM_LIT:1>:]:<EOL><INDENT>clist.append('<STR_LIT:U+0020>' + c)<EOL><DEDENT><DEDENT>return '<STR_LIT:\n>'.join(clist) + '<STR_LIT:\n>'<EOL>

Rendering a table row. Like ``<tr>``.

        :param content: content of current table row.


return '<STR_LIT>' + content + '<STR_LIT:\n>'<EOL>

Rendering a table cell. Like ``<th>`` ``<td>``.

        :param content: content of current table cell.
        :param header: whether this is header or not.
        :param align: align of current table cell.


return '<STR_LIT>'.format(text)<EOL>

Rendering **strong** text.

        :param text: text content for emphasis.


return '<STR_LIT>'.format(text)<EOL>

Rendering *emphasis* text.

        :param text: text content for emphasis.


if '<STR_LIT>' not in text:<EOL><INDENT>return '<STR_LIT>'.format(text)<EOL><DEDENT>else:<EOL><INDENT>return self._raw_html(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(text.replace('<STR_LIT>', '<STR_LIT>')))<EOL><DEDENT>

Rendering inline `code` text.

        :param text: text content for inline code.


if self.options.get('<STR_LIT>'):<EOL><INDENT>return self._raw_html('<STR_LIT>') + '<STR_LIT:\n>'<EOL><DEDENT>return self._raw_html('<STR_LIT>') + '<STR_LIT:\n>'<EOL>


return self._raw_html('<STR_LIT>'.format(text))<EOL>

Rendering ~~strikethrough~~ text.

        :param text: text content for strikethrough.


return text<EOL>

Rendering unformatted text.

        :param text: text content.


return link<EOL>

Rendering a given link or email address.

        :param link: link content or email address.
        :param is_email: whether this is an email or not.


if title:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>return '<STR_LIT>'.format(target=link, text=text)<EOL>

Rendering a given link with content and title.

        :param link: href link for ``<a>`` tag.
        :param title: title content for `title` attribute.
        :param text: text content for description.


<EOL>return '<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(src),<EOL>'<STR_LIT>'.format(src),<EOL>'<STR_LIT>'.format(text),<EOL>'<STR_LIT>',<EOL>])<EOL>

Rendering a image with title and text.

        :param src: source link of the image.
        :param title: title text of the image.
        :param text: alt text of the image.


return self._raw_html(html)<EOL>

Rendering span level pure html content.

        :param html: text content of the html snippet.


return '<STR_LIT>'<EOL>


return '<STR_LIT>'.format(key)<EOL>

Rendering the ref anchor of a footnote.

        :param key: identity key for the footnote.
        :param index: the index count of current footnote.


return '<STR_LIT>'.format(key, text.strip())<EOL>

Rendering a footnote item.

        :param key: identity key for the footnote.
        :param text: text content of the footnote.


if text:<EOL><INDENT>return '<STR_LIT>' + text<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>

Wrapper for all footnotes.

        :param text: contents of all footnotes.


return '<STR_LIT>'.format(math)<EOL>


return marker<EOL>


if not self.state.document.settings.file_insertion_enabled:<EOL><INDENT>raise self.warning('<STR_LIT>' % self.name)<EOL><DEDENT>source = self.state_machine.input_lines.source(<EOL>self.lineno - self.state_machine.input_offset - <NUM_LIT:1>)<EOL>source_dir = os.path.dirname(os.path.abspath(source))<EOL>path = rst.directives.path(self.arguments[<NUM_LIT:0>])<EOL>path = os.path.normpath(os.path.join(source_dir, path))<EOL>path = utils.relative_path(None, path)<EOL>path = nodes.reprunicode(path)<EOL>encoding = self.options.get(<EOL>'<STR_LIT>', self.state.document.settings.input_encoding)<EOL>e_handler = self.state.document.settings.input_encoding_error_handler<EOL>tab_width = self.options.get(<EOL>'<STR_LIT>', self.state.document.settings.tab_width)<EOL>try:<EOL><INDENT>self.state.document.settings.record_dependencies.add(path)<EOL>include_file = io.FileInput(source_path=path,<EOL>encoding=encoding,<EOL>error_handler=e_handler)<EOL><DEDENT>except UnicodeEncodeError as error:<EOL><INDENT>raise self.severe('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(self.name, SafeString(path)))<EOL><DEDENT>except IOError as error:<EOL><INDENT>raise self.severe('<STR_LIT>' %<EOL>(self.name, ErrorString(error)))<EOL><DEDENT>try:<EOL><INDENT>rawtext = include_file.read()<EOL><DEDENT>except UnicodeError as error:<EOL><INDENT>raise self.severe('<STR_LIT>' %<EOL>(self.name, ErrorString(error)))<EOL><DEDENT>config = self.state.document.settings.env.config<EOL>converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis)<EOL>include_lines = statemachine.string2lines(converter(rawtext),<EOL>tab_width,<EOL>convert_whitespace=True)<EOL>self.state_machine.insert_input(include_lines, path)<EOL>return []<EOL>

Most of this method is from ``docutils.parser.rst.Directive``.

        docutils version: 0.12


def validate(self, filename, module, classname, ignore):

with open(os.path.normpath(os.path.join('<STR_LIT>', '<STR_LIT>', filename))) as f:<EOL><INDENT>docs = f.read()<EOL><DEDENT>module = module_loading.import_module(module)<EOL>methods = re.findall(r'<STR_LIT>', docs, flags=re.M)<EOL>attributes = re.findall(r'<STR_LIT>', docs, flags=re.M)<EOL>documented = set(filter(lambda x: x.startswith(classname), [a for a in methods] + attributes))<EOL>implemented = set(classname + '<STR_LIT:.>' + x for x in dir(getattr(module, classname))<EOL>if not x.startswith('<STR_LIT:_>') or x == '<STR_LIT>')<EOL>print(implemented)<EOL>ignored = set(classname + '<STR_LIT:.>' + x for x in ignore)<EOL>self.assertSetEqual(implemented - documented - ignored, set(), msg='<STR_LIT>')<EOL>self.assertSetEqual(documented - implemented - ignored, set(), msg='<STR_LIT>')<EOL>

Finds all automethod and autoattribute statements in an rst file
comparing them to the attributes found in the actual class


return os.path.join(__name__.split('<STR_LIT:.>')[-<NUM_LIT:2>], path)<EOL>

Prepend the effect package name to a path so resources
can still be loaded when copied into a new effect package.


@property<EOL><INDENT>def ctx(self) -> moderngl.Context:<DEDENT>

return context.ctx()<EOL>


@classmethod<EOL><INDENT>def from_single(cls, meta: ProgramDescription, source: str):<DEDENT>

instance = cls(meta)<EOL>instance.vertex_source = ShaderSource(<EOL>VERTEX_SHADER,<EOL>meta.path or meta.vertex_shader,<EOL>source<EOL>)<EOL>if GEOMETRY_SHADER in source:<EOL><INDENT>instance.geometry_source = ShaderSource(<EOL>GEOMETRY_SHADER,<EOL>meta.path or meta.geometry_shader,<EOL>source,<EOL>)<EOL><DEDENT>if FRAGMENT_SHADER in source:<EOL><INDENT>instance.fragment_source = ShaderSource(<EOL>FRAGMENT_SHADER,<EOL>meta.path or meta.fragment_shader,<EOL>source,<EOL>)<EOL><DEDENT>if TESS_CONTROL_SHADER in source:<EOL><INDENT>instance.tess_control_source = ShaderSource(<EOL>TESS_CONTROL_SHADER,<EOL>meta.path or meta.tess_control_shader,<EOL>source,<EOL>)<EOL><DEDENT>if TESS_EVALUATION_SHADER in source:<EOL><INDENT>instance.tess_evaluation_source = ShaderSource(<EOL>TESS_EVALUATION_SHADER,<EOL>meta.path or meta.tess_evaluation_shader,<EOL>source,<EOL>)<EOL><DEDENT>return instance<EOL>

Initialize a single glsl string containing all shaders


@classmethod<EOL><INDENT>def from_separate(cls, meta: ProgramDescription, vertex_source, geometry_source=None, fragment_source=None,<EOL>tess_control_source=None, tess_evaluation_source=None):<DEDENT>

instance = cls(meta)<EOL>instance.vertex_source = ShaderSource(<EOL>VERTEX_SHADER,<EOL>meta.path or meta.vertex_shader,<EOL>vertex_source,<EOL>)<EOL>if geometry_source:<EOL><INDENT>instance.geometry_source = ShaderSource(<EOL>GEOMETRY_SHADER,<EOL>meta.path or meta.geometry_shader,<EOL>geometry_source,<EOL>)<EOL><DEDENT>if fragment_source:<EOL><INDENT>instance.fragment_source = ShaderSource(<EOL>FRAGMENT_SHADER,<EOL>meta.path or meta.fragment_shader,<EOL>fragment_source,<EOL>)<EOL><DEDENT>if tess_control_source:<EOL><INDENT>instance.tess_control_source = ShaderSource(<EOL>TESS_CONTROL_SHADER,<EOL>meta.path or meta.tess_control_shader,<EOL>tess_control_source,<EOL>)<EOL><DEDENT>if tess_evaluation_source:<EOL><INDENT>instance.tess_evaluation_source = ShaderSource(<EOL>TESS_EVALUATION_SHADER,<EOL>meta.path or meta.tess_control_shader,<EOL>tess_evaluation_source,<EOL>)<EOL><DEDENT>return instance<EOL>


<EOL>out_attribs = []<EOL>if not self.fragment_source:<EOL><INDENT>if self.geometry_source:<EOL><INDENT>out_attribs = self.geometry_source.find_out_attribs()<EOL><DEDENT>else:<EOL><INDENT>out_attribs = self.vertex_source.find_out_attribs()<EOL><DEDENT><DEDENT>program = self.ctx.program(<EOL>vertex_shader=self.vertex_source.source,<EOL>geometry_shader=self.geometry_source.source if self.geometry_source else None,<EOL>fragment_shader=self.fragment_source.source if self.fragment_source else None,<EOL>tess_control_shader=self.tess_control_source.source if self.tess_control_source else None,<EOL>tess_evaluation_shader=self.tess_evaluation_source.source if self.tess_evaluation_source else None,<EOL>varyings=out_attribs,<EOL>)<EOL>program.extra = {'<STR_LIT>': self.meta}<EOL>return program<EOL>

Creates a shader program.

Returns:
    ModernGL Program instance


names = []<EOL>for line in self.lines:<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>names.append(line.split()[<NUM_LIT:2>].replace('<STR_LIT:;>', '<STR_LIT>'))<EOL><DEDENT><DEDENT>return names<EOL>

Get all out attributes in the shader source.

:return: List of attribute names


print("<STR_LIT>".format(self.name))<EOL>for i, line in enumerate(self.lines):<EOL><INDENT>print("<STR_LIT>".format(str(i).zfill(<NUM_LIT:3>), line))<EOL><DEDENT>print("<STR_LIT>".format(self.name))<EOL>


def __init__(self, meta: ProgramDescription, program: moderngl.Program):

self.program = program<EOL>self.meta = meta<EOL>

Create a shader using either a file path or a name
:param meta: The ProgramMeta
:param program: The program instance


return self.program.mglo<EOL>


@property<EOL><INDENT>def glo(self) -> int:<DEDENT>

return self.program.glo<EOL>

int: The internal OpenGL object.
This values is provided for debug purposes only.


@property<EOL><INDENT>def subroutines(self) -> Tuple[str, ...]:<DEDENT>

return self.program.subroutines<EOL>


@property<EOL><INDENT>def geometry_input(self) -> int:<DEDENT>

return self.program.geometry_input<EOL>

int: The geometry input primitive.
The GeometryShader's input primitive if the GeometryShader exists.
The geometry input primitive will be used for validation.


@property<EOL><INDENT>def geometry_output(self) -> int:<DEDENT>

return self.program.geometry_output<EOL>

int: The geometry output primitive.
The GeometryShader's output primitive if the GeometryShader exists.


@property<EOL><INDENT>def geometry_vertices(self) -> int:<DEDENT>

return self.program.geometry_vertices<EOL>

int: The maximum number of vertices that
the geometry shader will output.


def __init__(self, buffer: moderngl.Buffer, buffer_format: str, attributes=None, per_instance=False):

self.buffer = buffer<EOL>self.attrib_formats = types.parse_attribute_formats(buffer_format)<EOL>self.attributes = attributes<EOL>self.per_instance = per_instance<EOL>if self.buffer.size % self.vertex_size != <NUM_LIT:0>:<EOL><INDENT>raise VAOError("<STR_LIT>".format(<EOL>buffer_format, self.vertex_size, self.buffer.size % self.vertex_size<EOL>))<EOL><DEDENT>self.vertices = self.buffer.size // self.vertex_size<EOL>

:param buffer: The vbo object
:param format: The format of the buffer


def content(self, attributes: List[str]):

formats = []<EOL>attrs = []<EOL>for attrib_format, attrib in zip(self.attrib_formats, self.attributes):<EOL><INDENT>if attrib not in attributes:<EOL><INDENT>formats.append(attrib_format.pad_str())<EOL>continue<EOL><DEDENT>formats.append(attrib_format.format)<EOL>attrs.append(attrib)<EOL>attributes.remove(attrib)<EOL><DEDENT>if not attrs:<EOL><INDENT>return None<EOL><DEDENT>return (<EOL>self.buffer,<EOL>"<STR_LIT>".format("<STR_LIT:U+0020>".join(formats), '<STR_LIT>' if self.per_instance else '<STR_LIT>'),<EOL>*attrs<EOL>)<EOL>


def __init__(self, name="<STR_LIT>", mode=moderngl.TRIANGLES):

self.ctx = context.ctx()<EOL>self.name = name<EOL>self.mode = mode<EOL>try:<EOL><INDENT>DRAW_MODES[self.mode]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise VAOError("<STR_LIT>".format(DRAW_MODES.values()))<EOL><DEDENT>self.buffers = []<EOL>self._index_buffer = None<EOL>self._index_element_size = None<EOL>self.vertex_count = <NUM_LIT:0><EOL>self.vaos = {}<EOL>

Create and empty VAO

Keyword Args:
    name (str): The name for debug purposes
    mode (int): Default draw mode


def render(self, program: moderngl.Program, mode=None, vertices=-<NUM_LIT:1>, first=<NUM_LIT:0>, instances=<NUM_LIT:1>):

vao = self.instance(program)<EOL>if mode is None:<EOL><INDENT>mode = self.mode<EOL><DEDENT>vao.render(mode, vertices=vertices, first=first, instances=instances)<EOL>

Render the VAO.

Args:
    program: The ``moderngl.Program``

Keyword Args:
    mode: Override the draw mode (``TRIANGLES`` etc)
    vertices (int): The number of vertices to transform
    first (int): The index of the first vertex to start with
    instances (int): The number of instances


def render_indirect(self, program: moderngl.Program, buffer, mode=None, count=-<NUM_LIT:1>, *, first=<NUM_LIT:0>):

vao = self.instance(program)<EOL>if mode is None:<EOL><INDENT>mode = self.mode<EOL><DEDENT>vao.render_indirect(buffer, mode=mode, count=count, first=first)<EOL>

The render primitive (mode) must be the same as the input primitive of the GeometryShader.
The draw commands are 5 integers: (count, instanceCount, firstIndex, baseVertex, baseInstance).

Args:
    program: The ``moderngl.Program``
    buffer: The ``moderngl.Buffer`` containing indirect draw commands

Keyword Args:
    mode (int): By default :py:data:`TRIANGLES` will be used.
    count (int): The number of draws.
    first (int): The index of the first indirect draw command.


def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,<EOL>mode=None, vertices=-<NUM_LIT:1>, first=<NUM_LIT:0>, instances=<NUM_LIT:1>):

vao = self.instance(program)<EOL>if mode is None:<EOL><INDENT>mode = self.mode<EOL><DEDENT>vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)<EOL>

Transform vertices. Stores the output in a single buffer.

Args:
    program: The ``moderngl.Program``
    buffer: The ``moderngl.buffer`` to store the output

Keyword Args:
    mode: Draw mode (for example ``moderngl.POINTS``)
    vertices (int): The number of vertices to transform
    first (int): The index of the first vertex to start with
    instances (int): The number of instances


def buffer(self, buffer, buffer_format: str, attribute_names, per_instance=False):

if not isinstance(attribute_names, list):<EOL><INDENT>attribute_names = [attribute_names, ]<EOL><DEDENT>if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]:<EOL><INDENT>raise VAOError(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(type(buffer))<EOL>)<EOL>)<EOL><DEDENT>if isinstance(buffer, numpy.ndarray):<EOL><INDENT>buffer = self.ctx.buffer(buffer.tobytes())<EOL><DEDENT>if isinstance(buffer, bytes):<EOL><INDENT>buffer = self.ctx.buffer(data=buffer)<EOL><DEDENT>formats = buffer_format.split()<EOL>if len(formats) != len(attribute_names):<EOL><INDENT>raise VAOError("<STR_LIT>".format(buffer_format, attribute_names))<EOL><DEDENT>self.buffers.append(BufferInfo(buffer, buffer_format, attribute_names, per_instance=per_instance))<EOL>self.vertex_count = self.buffers[-<NUM_LIT:1>].vertices<EOL>return buffer<EOL>

Register a buffer/vbo for the VAO. This can be called multiple times.
adding multiple buffers (interleaved or not)

Args:
    buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`` or ``bytes``.
    buffer_format (str): The format of the buffer. (eg. ``3f 3f`` for interleaved positions and normals).
    attribute_names: A list of attribute names this buffer should map to.

Keyword Args:
    per_instance (bool): Is this buffer per instance data for instanced rendering?

Returns:
    The ``moderngl.Buffer`` instance object. This is handy when providing ``bytes`` and ``numpy.array``.


def index_buffer(self, buffer, index_element_size=<NUM_LIT:4>):

if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]:<EOL><INDENT>raise VAOError("<STR_LIT>")<EOL><DEDENT>if isinstance(buffer, numpy.ndarray):<EOL><INDENT>buffer = self.ctx.buffer(buffer.tobytes())<EOL><DEDENT>if isinstance(buffer, bytes):<EOL><INDENT>buffer = self.ctx.buffer(data=buffer)<EOL><DEDENT>self._index_buffer = buffer<EOL>self._index_element_size = index_element_size<EOL>

Set the index buffer for this VAO

Args:
    buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``

Keyword Args:
    index_element_size (int): Byte size of each element. 1, 2 or 4


def instance(self, program: moderngl.Program) -> moderngl.VertexArray:

vao = self.vaos.get(program.glo)<EOL>if vao:<EOL><INDENT>return vao<EOL><DEDENT>program_attributes = [name for name, attr in program._members.items() if isinstance(attr, moderngl.Attribute)]<EOL>for attrib_name in program_attributes:<EOL><INDENT>if attrib_name.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>if not sum(buffer.has_attribute(attrib_name) for buffer in self.buffers):<EOL><INDENT>raise VAOError("<STR_LIT>".format(<EOL>self.name, attrib_name, program.name))<EOL><DEDENT><DEDENT>vao_content = []<EOL>for buffer in self.buffers:<EOL><INDENT>content = buffer.content(program_attributes)<EOL>if content:<EOL><INDENT>vao_content.append(content)<EOL><DEDENT><DEDENT>if program_attributes:<EOL><INDENT>for attrib_name in program_attributes:<EOL><INDENT>if attrib_name.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>raise VAOError("<STR_LIT>".format([n for n in program_attributes]))<EOL><DEDENT><DEDENT>if self._index_buffer:<EOL><INDENT>vao = context.ctx().vertex_array(program, vao_content,<EOL>self._index_buffer, self._index_element_size)<EOL><DEDENT>else:<EOL><INDENT>vao = context.ctx().vertex_array(program, vao_content)<EOL><DEDENT>self.vaos[program.glo] = vao<EOL>return vao<EOL>

Obtain the ``moderngl.VertexArray`` instance for the program.
The instance is only created once and cached internally.

Returns: ``moderngl.VertexArray`` instance


for key, vao in self.vaos:<EOL><INDENT>vao.release()<EOL><DEDENT>if buffer:<EOL><INDENT>for buff in self.buffers:<EOL><INDENT>buff.buffer.release()<EOL><DEDENT>if self._index_buffer:<EOL><INDENT>self._index_buffer.release()<EOL><DEDENT><DEDENT>

Destroy the vao object

Keyword Args:
    buffers (bool): also release buffers


def buffer_format(frmt: str) -> BufferFormat:

try:<EOL><INDENT>return BUFFER_FORMATS[frmt]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>frmt, BUFFER_FORMATS.keys()<EOL>))<EOL><DEDENT>

Look up info about a buffer format
:param frmt: format string such as 'f', 'i' and 'u'
:return: BufferFormat instance


def attribute_format(frmt: str) -> BufferFormat:

try:<EOL><INDENT>return ATTRIBUTE_FORMATS[frmt]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>frmt, ATTRIBUTE_FORMATS.keys()<EOL>))<EOL><DEDENT>

Look up info about an attribute format
:param frmt: Format of an
:return: BufferFormat instance


def __init__(self, format_string: str, components: int, bytes_per_component: int):

self.format = format_string<EOL>self.components = components<EOL>self.bytes_per_component = bytes_per_component<EOL>

:param format_string: moderngl format string
:param components: components
:param byte_size: byte per component


return "<STR_LIT>".format(self.components, self.bytes_per_component)<EOL>

Padding string used my moderngl in interleaved buffers


def update(self, aspect_ratio=None, fov=None, near=None, far=None):

self.aspect_ratio = aspect_ratio or self.aspect_ratio<EOL>self.fov = fov or self.fov<EOL>self.near = near or self.near<EOL>self.far = far or self.far<EOL>self.matrix = Matrix44.perspective_projection(self.fov, self.aspect_ratio, self.near, self.far)<EOL>

Update the internal projection matrix based on current values
or values passed in if specified.

:param aspect_ratio: New aspect ratio
:param fov: New field of view
:param near: New near value
:param far: New far value


return self.far / (self.far - self.near), (self.far * self.near) / (self.near - self.far)<EOL>

Returns the (x, y) projection constants for the current projection.
:return: x, y tuple projection constants


def draw(self, texture, pos=(<NUM_LIT:0.0>, <NUM_LIT:0.0>), scale=(<NUM_LIT:1.0>, <NUM_LIT:1.0>)):

if not self.initialized:<EOL><INDENT>self.init()<EOL><DEDENT>self._texture2d_shader["<STR_LIT>"].value = (pos[<NUM_LIT:0>] - <NUM_LIT:1.0>, pos[<NUM_LIT:1>] - <NUM_LIT:1.0>)<EOL>self._texture2d_shader["<STR_LIT>"].value = (scale[<NUM_LIT:0>], scale[<NUM_LIT:1>])<EOL>texture.use(location=<NUM_LIT:0>)<EOL>self._texture2d_sampler.use(location=<NUM_LIT:0>)<EOL>self._texture2d_shader["<STR_LIT>"].value = <NUM_LIT:0><EOL>self._quad.render(self._texture2d_shader)<EOL>self._texture2d_sampler.clear(location=<NUM_LIT:0>)<EOL>

Draw texture using a fullscreen quad.
By default this will conver the entire screen.

:param pos: (tuple) offset x, y
:param scale: (tuple) scale x, y


def draw_depth(self, texture, near, far, pos=(<NUM_LIT:0.0>, <NUM_LIT:0.0>), scale=(<NUM_LIT:1.0>, <NUM_LIT:1.0>)):

if not self.initialized:<EOL><INDENT>self.init()<EOL><DEDENT>self._depth_shader["<STR_LIT>"].value = (pos[<NUM_LIT:0>] - <NUM_LIT:1.0>, pos[<NUM_LIT:1>] - <NUM_LIT:1.0>)<EOL>self._depth_shader["<STR_LIT>"].value = (scale[<NUM_LIT:0>], scale[<NUM_LIT:1>])<EOL>self._depth_shader["<STR_LIT>"].value = near<EOL>self._depth_shader["<STR_LIT>"].value = far<EOL>self._depth_sampler.use(location=<NUM_LIT:0>)<EOL>texture.use(location=<NUM_LIT:0>)<EOL>self._depth_shader["<STR_LIT>"].value = <NUM_LIT:0><EOL>self._quad.render(self._depth_shader)<EOL>self._depth_sampler.clear(location=<NUM_LIT:0>)<EOL>

Draw depth buffer linearized.
By default this will draw the texture as a full screen quad.
A sampler will be used to ensure the right conditions to draw the depth buffer.

:param near: Near plane in projection
:param far: Far plane in projection
:param pos: (tuple) offset x, y
:param scale: (tuple) scale x, y


if not TextureHelper._quad:<EOL><INDENT>TextureHelper._quad = geometry.quad_fs()<EOL><DEDENT>TextureHelper._texture2d_shader = context.ctx().program(<EOL>vertex_shader="""<STR_LIT>""",<EOL>fragment_shader="""<STR_LIT>"""<EOL>)<EOL>TextureHelper._texture2d_sampler = self.ctx.sampler(<EOL>filter=(moderngl.LINEAR, moderngl.LINEAR),<EOL>)<EOL>

Initialize geometry and shader for drawing FBO layers


from demosys import geometry<EOL>if not TextureHelper._quad:<EOL><INDENT>TextureHelper._quad = geometry.quad_fs()<EOL><DEDENT>TextureHelper._depth_shader = context.ctx().program(<EOL>vertex_shader="""<STR_LIT>""",<EOL>fragment_shader="""<STR_LIT>"""<EOL>)<EOL>TextureHelper._depth_sampler = self.ctx.sampler(<EOL>filter=(moderngl.LINEAR, moderngl.LINEAR),<EOL>compare_func='<STR_LIT>',<EOL>)<EOL>


Finder = import_string(import_path)<EOL>if not issubclass(Finder, BaseFileSystemFinder):<EOL><INDENT>raise ImproperlyConfigured('<STR_LIT>'.format(import_path))<EOL><DEDENT>return Finder()<EOL>

Get a finder class from an import path.
Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
This function uses an lru cache.

:param import_path: string representing an import path
:return: An instance of the finder


<EOL>if getattr(self, '<STR_LIT>', None):<EOL><INDENT>self.paths = getattr(settings, self.settings_attr)<EOL><DEDENT>path_found = None<EOL>for entry in self.paths:<EOL><INDENT>abspath = entry / path<EOL>if abspath.exists():<EOL><INDENT>path_found = abspath<EOL><DEDENT><DEDENT>return path_found<EOL>

Find a file in the path. The file may exist in multiple
paths. The last found file will be returned.

:param path: The path to find
:return: The absolute path to the file or None if not found


def init(window=None, project=None, timeline=None):

from demosys.effects.registry import Effect<EOL>from demosys.scene import camera<EOL>window.timeline = timeline<EOL>setattr(Effect, '<STR_LIT>', window)<EOL>setattr(Effect, '<STR_LIT>', window.ctx)<EOL>setattr(Effect, '<STR_LIT>', project)<EOL>window.sys_camera = camera.SystemCamera(aspect=window.aspect_ratio, fov=<NUM_LIT>, near=<NUM_LIT:1>, far=<NUM_LIT:1000>)<EOL>setattr(Effect, '<STR_LIT>', window.sys_camera)<EOL>print("<STR_LIT>", time.time())<EOL>project.load()<EOL>timer_cls = import_string(settings.TIMER)<EOL>window.timer = timer_cls()<EOL>window.timer.start()<EOL>

Initialize, load and run

:param manager: The effect manager to use


dest = "<STR_LIT>"<EOL>if settings.SCREENSHOT_PATH:<EOL><INDENT>if not os.path.exists(settings.SCREENSHOT_PATH):<EOL><INDENT>print("<STR_LIT>".format(settings.SCREENSHOT_PATH))<EOL>os.makedirs(settings.SCREENSHOT_PATH)<EOL><DEDENT>dest = settings.SCREENSHOT_PATH<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if not Config.target:<EOL><INDENT>Config.target = context.window().fbo<EOL><DEDENT>image = Image.frombytes(<EOL>"<STR_LIT>",<EOL>(Config.target.viewport[<NUM_LIT:2>], Config.target.viewport[<NUM_LIT:3>]),<EOL>Config.target.read(viewport=Config.target.viewport, alignment=Config.alignment),<EOL>)<EOL>image = image.transpose(Image.FLIP_TOP_BOTTOM)<EOL>if not name:<EOL><INDENT>name = "<STR_LIT>".format(datetime.now().strftime("<STR_LIT>"), file_format)<EOL><DEDENT>dest = os.path.join(dest, name)<EOL>print("<STR_LIT>", dest)<EOL>image.save(dest, format=file_format)<EOL>

Create a screenshot
:param file_format: formats supported by PIL (png, jpeg etc)


def __init__(self, fov=<NUM_LIT>, aspect=<NUM_LIT:1.0>, near=<NUM_LIT:1>, far=<NUM_LIT:100>):

self.position = Vector3([<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>])<EOL>self.up = Vector3([<NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT:0.0>])<EOL>self.right = Vector3([<NUM_LIT:1.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>])<EOL>self.dir = Vector3([<NUM_LIT:0.0>, <NUM_LIT:0.0>, -<NUM_LIT:1.0>])<EOL>self.yaw = -<NUM_LIT><EOL>self.pitch = <NUM_LIT:0.0><EOL>self._up = Vector3([<NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT:0.0>])<EOL>self.projection = Projection(aspect, fov, near, far)<EOL>

Initialize camera using a specific projection

:param fov: Field of view
:param aspect: Aspect ratio
:param near: Near plane
:param far: Far plane


self.position = Vector3([x, y, z])<EOL>

Set the 3D position of the camera

:param x: float
:param y: float
:param z: float


self._update_yaw_and_pitch()<EOL>return self._gl_look_at(self.position, self.position + self.dir, self._up)<EOL>

:return: The current view matrix for the camera


front = Vector3([<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>])<EOL>front.x = cos(radians(self.yaw)) * cos(radians(self.pitch))<EOL>front.y = sin(radians(self.pitch))<EOL>front.z = sin(radians(self.yaw)) * cos(radians(self.pitch))<EOL>self.dir = vector.normalise(front)<EOL>self.right = vector.normalise(vector3.cross(self.dir, self._up))<EOL>self.up = vector.normalise(vector3.cross(self.right, self.dir))<EOL>

Updates the camera vectors based on the current yaw and pitch


if pos is None:<EOL><INDENT>vec = Vector3(pos)<EOL><DEDENT>if vec is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return self._gl_look_at(self.position, vec, self._up)<EOL>

Look at a specific point

:param vec: Vector3 position
:param pos: python list [x, y, x]
:return: Camera matrix


z = vector.normalise(pos - target)<EOL>x = vector.normalise(vector3.cross(vector.normalise(up), z))<EOL>y = vector3.cross(z, x)<EOL>translate = matrix44.create_identity()<EOL>translate[<NUM_LIT:3>][<NUM_LIT:0>] = -pos.x<EOL>translate[<NUM_LIT:3>][<NUM_LIT:1>] = -pos.y<EOL>translate[<NUM_LIT:3>][<NUM_LIT:2>] = -pos.z<EOL>rotate = matrix44.create_identity()<EOL>rotate[<NUM_LIT:0>][<NUM_LIT:0>] = x[<NUM_LIT:0>]  <EOL>rotate[<NUM_LIT:1>][<NUM_LIT:0>] = x[<NUM_LIT:1>]<EOL>rotate[<NUM_LIT:2>][<NUM_LIT:0>] = x[<NUM_LIT:2>]<EOL>rotate[<NUM_LIT:0>][<NUM_LIT:1>] = y[<NUM_LIT:0>]  <EOL>rotate[<NUM_LIT:1>][<NUM_LIT:1>] = y[<NUM_LIT:1>]<EOL>rotate[<NUM_LIT:2>][<NUM_LIT:1>] = y[<NUM_LIT:2>]<EOL>rotate[<NUM_LIT:0>][<NUM_LIT:2>] = z[<NUM_LIT:0>]  <EOL>rotate[<NUM_LIT:1>][<NUM_LIT:2>] = z[<NUM_LIT:1>]<EOL>rotate[<NUM_LIT:2>][<NUM_LIT:2>] = z[<NUM_LIT:2>]<EOL>return matrix44.multiply(translate, rotate)<EOL>

The standard lookAt method

:param pos: current position
:param target: target position to look at
:param up: direction up


def move_state(self, direction, activate):

if direction == RIGHT:<EOL><INDENT>self._xdir = POSITIVE if activate else STILL<EOL><DEDENT>elif direction == LEFT:<EOL><INDENT>self._xdir = NEGATIVE if activate else STILL<EOL><DEDENT>elif direction == FORWARD:<EOL><INDENT>self._zdir = NEGATIVE if activate else STILL<EOL><DEDENT>elif direction == BACKWARD:<EOL><INDENT>self._zdir = POSITIVE if activate else STILL<EOL><DEDENT>elif direction == UP:<EOL><INDENT>self._ydir = POSITIVE if activate else STILL<EOL><DEDENT>elif direction == DOWN:<EOL><INDENT>self._ydir = NEGATIVE if activate else STILL<EOL><DEDENT>

Set the camera position move state

:param direction: What direction to update
:param activate: Start or stop moving in the direction


if self.last_x is None:<EOL><INDENT>self.last_x = x<EOL><DEDENT>if self.last_y is None:<EOL><INDENT>self.last_y = y<EOL><DEDENT>x_offset = self.last_x - x<EOL>y_offset = self.last_y - y<EOL>self.last_x = x<EOL>self.last_y = y<EOL>x_offset *= self.mouse_sensitivity<EOL>y_offset *= self.mouse_sensitivity<EOL>self.yaw -= x_offset<EOL>self.pitch += y_offset<EOL>if self.pitch > <NUM_LIT>:<EOL><INDENT>self.pitch = <NUM_LIT><EOL><DEDENT>if self.pitch < -<NUM_LIT>:<EOL><INDENT>self.pitch = -<NUM_LIT><EOL><DEDENT>self._update_yaw_and_pitch()<EOL>

Set the rotation state of the camera

:param x: viewport x pos
:param y: viewport y pos


<EOL>now = time.time()<EOL>t = max(now - self._last_time, <NUM_LIT:0>)<EOL>self._last_time = now<EOL>if self._xdir == POSITIVE:<EOL><INDENT>self.position += self.right * self.velocity * t<EOL><DEDENT>elif self._xdir == NEGATIVE:<EOL><INDENT>self.position -= self.right * self.velocity * t<EOL><DEDENT>if self._zdir == NEGATIVE:<EOL><INDENT>self.position += self.dir * self.velocity * t<EOL><DEDENT>elif self._zdir == POSITIVE:<EOL><INDENT>self.position -= self.dir * self.velocity * t<EOL><DEDENT>if self._ydir == POSITIVE:<EOL><INDENT>self.position += self.up * self.velocity * t<EOL><DEDENT>elif self._ydir == NEGATIVE:<EOL><INDENT>self.position -= self.up * self.velocity * t<EOL><DEDENT>return self._gl_look_at(self.position, self.position + self.dir, self._up)<EOL>


def __init__(self, name, vao=None, material=None, attributes=None, bbox_min=None, bbox_max=None):

self.name = name<EOL>self.vao = vao<EOL>self.material = material<EOL>self.attributes = attributes or {}<EOL>self.bbox_min = bbox_min<EOL>self.bbox_max = bbox_max<EOL>self.mesh_program = None<EOL>

:param name: Name of the mesh
:param vao: VAO
:param material: Material
:param attributes: Details info about each mesh attribute (dict)
    {
        "NORMAL": {"name": "in_normal", "components": 3, "type": GL_FLOAT},
        "POSITION": {"name": "in_position", "components": 3, "type": GL_FLOAT}
    }


def draw(self, projection_matrix=None, view_matrix=None, camera_matrix=None, time=<NUM_LIT:0>):

Draw the mesh using the assigned mesh program

:param projection_matrix: projection_matrix (bytes)
:param view_matrix: view_matrix (bytes)
:param camera_matrix: camera_matrix (bytes)


def add_attribute(self, attr_type, name, components):

self.attributes[attr_type] = {"<STR_LIT:name>": name, "<STR_LIT>": components}<EOL>

Add metadata about the mesh
:param attr_type: POSITION, NORMAL etc
:param name: The attribute name used in the program
:param components: Number of floats


def __init__(self, name, mesh_programs=None, **kwargs):

self.name = name<EOL>self.root_nodes = []<EOL>self.nodes = []<EOL>self.materials = []<EOL>self.meshes = []<EOL>self.cameras = []<EOL>self.bbox_min = None<EOL>self.bbox_max = None<EOL>self.diagonal_size = <NUM_LIT:1.0><EOL>self.bbox_vao = geometry.bbox()<EOL>self.bbox_program = programs.load(ProgramDescription(<EOL>label='<STR_LIT>',<EOL>path='<STR_LIT>'))<EOL>self._view_matrix = matrix44.create_identity()<EOL>

:param name: Unique name or path for the scene
:param mesh_programs: List of MeshPrograms to apply to the scene
:param loader: Loader class for the scene if relevant


def draw(self, projection_matrix=None, camera_matrix=None, time=<NUM_LIT:0>):

projection_matrix = projection_matrix.astype('<STR_LIT>').tobytes()<EOL>camera_matrix = camera_matrix.astype('<STR_LIT>').tobytes()<EOL>for node in self.root_nodes:<EOL><INDENT>node.draw(<EOL>projection_matrix=projection_matrix,<EOL>camera_matrix=camera_matrix,<EOL>time=time,<EOL>)<EOL><DEDENT>self.ctx.clear_samplers(<NUM_LIT:0>, <NUM_LIT:4>)<EOL>

Draw all the nodes in the scene

:param projection_matrix: projection matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
:param time: The current time


def draw_bbox(self, projection_matrix=None, camera_matrix=None, all=True):

projection_matrix = projection_matrix.astype('<STR_LIT>').tobytes()<EOL>camera_matrix = camera_matrix.astype('<STR_LIT>').tobytes()<EOL>self.bbox_program["<STR_LIT>"].write(projection_matrix)<EOL>self.bbox_program["<STR_LIT>"].write(self._view_matrix.astype('<STR_LIT>').tobytes())<EOL>self.bbox_program["<STR_LIT>"].write(camera_matrix)<EOL>self.bbox_program["<STR_LIT>"].write(self.bbox_min.astype('<STR_LIT>').tobytes())<EOL>self.bbox_program["<STR_LIT>"].write(self.bbox_max.astype('<STR_LIT>').tobytes())<EOL>self.bbox_program["<STR_LIT>"].value = (<NUM_LIT:1.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL>self.bbox_vao.render(self.bbox_program)<EOL>if not all:<EOL><INDENT>return<EOL><DEDENT>for node in self.root_nodes:<EOL><INDENT>node.draw_bbox(projection_matrix, camera_matrix, self.bbox_program, self.bbox_vao)<EOL><DEDENT>


if not mesh_programs:<EOL><INDENT>mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()]<EOL><DEDENT>for mesh in self.meshes:<EOL><INDENT>for mp in mesh_programs:<EOL><INDENT>instance = mp.apply(mesh)<EOL>if instance is not None:<EOL><INDENT>if isinstance(instance, MeshProgram):<EOL><INDENT>mesh.mesh_program = mp<EOL>break<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(type(instance)))<EOL><DEDENT><DEDENT><DEDENT>if not mesh.mesh_program:<EOL><INDENT>print("<STR_LIT>".format(mesh.name))<EOL><DEDENT><DEDENT>


bbox_min, bbox_max = None, None<EOL>for node in self.root_nodes:<EOL><INDENT>bbox_min, bbox_max = node.calc_global_bbox(<EOL>matrix44.create_identity(),<EOL>bbox_min,<EOL>bbox_max<EOL>)<EOL><DEDENT>self.bbox_min = bbox_min<EOL>self.bbox_max = bbox_max<EOL>self.diagonal_size = vector3.length(self.bbox_max - self.bbox_min)<EOL>


for mesh in self.meshes:<EOL><INDENT>mesh.vao.release()<EOL><DEDENT>

Destroy the scene data and deallocate buffers


def draw(self, mesh, projection_matrix=None, view_matrix=None, camera_matrix=None, time=<NUM_LIT:0>):

self.program["<STR_LIT>"].write(projection_matrix)<EOL>self.program["<STR_LIT>"].write(view_matrix)<EOL>mesh.vao.render(self.program)<EOL>

Draw code for the mesh. Should be overriden.

:param projection_matrix: projection_matrix (bytes)
:param view_matrix: view_matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
:param time: The current time


raise NotImplementedError("<STR_LIT>")<EOL>

Determine if this MeshProgram should be applied to the mesh
Can return self or some MeshProgram instance to support dynamic MeshProgram creation

:param mesh: The mesh to inspect


Draw node and children

:param projection_matrix: projection matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
:param time: The current time


def calc_global_bbox(self, view_matrix, bbox_min, bbox_max):

if self.matrix is not None:<EOL><INDENT>view_matrix = matrix44.multiply(self.matrix, view_matrix)<EOL><DEDENT>if self.mesh:<EOL><INDENT>bbox_min, bbox_max = self.mesh.calc_global_bbox(view_matrix, bbox_min, bbox_max)<EOL><DEDENT>for child in self.children:<EOL><INDENT>bbox_min, bbox_max = child.calc_global_bbox(view_matrix, bbox_min, bbox_max)<EOL><DEDENT>return bbox_min, bbox_max<EOL>


if self.initialized:<EOL><INDENT>mixer.music.unpause()<EOL><DEDENT>else:<EOL><INDENT>mixer.music.play()<EOL>mixer.music.play()<EOL>self.initialized = True<EOL><DEDENT>self.paused = False<EOL>


mixer.music.pause()<EOL>self.pause_time = self.get_time()<EOL>self.paused = True<EOL>


if self.paused:<EOL><INDENT>self.start()<EOL><DEDENT>else:<EOL><INDENT>self.pause()<EOL><DEDENT>


mixer.music.stop()<EOL>return self.get_time()<EOL>

Stop the music

Returns:
    The current location in the music


if self.paused:<EOL><INDENT>return self.pause_time<EOL><DEDENT>return mixer.music.get_pos() / <NUM_LIT><EOL>

Get the current position in the music in seconds


if value < <NUM_LIT:0>:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>mixer.music.set_pos(value)<EOL>

Set the current time in the music in seconds causing the player
to seek to this location in the file.


if self.start_time is None:<EOL><INDENT>self.start_time = time.time()<EOL><DEDENT>else:<EOL><INDENT>pause_duration = time.time() - self.pause_time<EOL>self.offset += pause_duration<EOL>self.pause_time = None<EOL><DEDENT>

Start the timer by recoding the current ``time.time()``
preparing to report the number of seconds since this timestamp.


self.pause_time = time.time()<EOL>

Pause the timer by setting the internal pause time using ``time.time()``


if self.pause_time:<EOL><INDENT>self.start()<EOL><DEDENT>else:<EOL><INDENT>self.pause()<EOL><DEDENT>


self.stop_time = time.time()<EOL>return self.stop_time - self.start_time - self.offset<EOL>

Stop the timer

Returns:
    The time the timer was stopped


if self.pause_time is not None:<EOL><INDENT>curr_time = self.pause_time - self.offset - self.start_time<EOL>return curr_time<EOL><DEDENT>curr_time = time.time()<EOL>return curr_time - self.start_time - self.offset<EOL>

Get the current time in seconds

Returns:
    The current time in seconds


if value < <NUM_LIT:0>:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>self.offset += self.get_time() - value<EOL>

Set the current time. This can be used to jump in the timeline.

Args:
    value (float): The new time


raise NotImplementedError()<EOL>

Start the timer initially or resume after pause

Raises:
    NotImplementedError


raise NotImplementedError()<EOL>

Pause the timer

Raises:
    NotImplementedError


raise NotImplementedError()<EOL>

Toggle pause state

Raises:
    NotImplementedError


raise NotImplementedError()<EOL>

Stop the timer. Should only be called once when stopping the timer.

Returns:
    The time the timer was stopped

Raises:
    NotImplementedError


raise NotImplementedError()<EOL>

Get the current time in seconds

Returns:
    The current time in seconds

Raises:
    NotImplementedError


raise NotImplementedError()<EOL>

Set the current time in seconds.

Args:
    value (float): The new time

Raises:
    NotImplementedError


config = getattr(settings, '<STR_LIT>', None)<EOL>if config is None:<EOL><INDENT>config = {}<EOL><DEDENT>self.mode = config.get('<STR_LIT>') or '<STR_LIT>'<EOL>self.files = config.get('<STR_LIT>') or '<STR_LIT>'<EOL>self.project = config.get('<STR_LIT>') or '<STR_LIT>'<EOL>self.rps = config.get('<STR_LIT>', <NUM_LIT>)<EOL>self.start_paused = False<EOL>self.controller = TimeController(self.rps)<EOL>if self.mode == '<STR_LIT>':<EOL><INDENT>self.rocket = Rocket.from_socket(self.controller, track_path=self.files)<EOL>self.start_paused = True<EOL><DEDENT>elif self.mode == '<STR_LIT>':<EOL><INDENT>self.rocket = Rocket.from_project_file(self.controller, self.project)<EOL><DEDENT>elif self.mode == '<STR_LIT>':<EOL><INDENT>self.rocket = Rocket.from_files(self.controller, self.files)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(self.mode))<EOL><DEDENT>for track in tracks.tacks:<EOL><INDENT>self.rocket.tracks.add(track)<EOL><DEDENT>for track in tracks.tacks:<EOL><INDENT>self.rocket.track(track.name)<EOL><DEDENT>self.rocket.update()<EOL>super().__init__(**kwargs)<EOL>

Initialize the rocket timer using values from settings


if not self.start_paused:<EOL><INDENT>self.rocket.start()<EOL><DEDENT>


self.rocket.update()<EOL>return self.rocket.time<EOL>


if value < <NUM_LIT:0>:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>self.controller.row = self.rps * value<EOL>

Set the current time jumping in the timeline.

Args:
    value (float): The new time


self.controller.playing = False<EOL>


self.controller.playing = not self.controller.playing<EOL>


return self.rocket.time<EOL>

Stop the timer

Returns:
    The current time.


self.player.play()<EOL>self.paused = False<EOL>


self.pause_time = self.get_time()<EOL>self.paused = True<EOL>self.player.pause()<EOL>


self.player.stop()<EOL>return self.get_time()<EOL>

Stop the music

Returns:
    The current time in seconds


if self.paused:<EOL><INDENT>return self.pause_time<EOL><DEDENT>return self.player.get_time() / <NUM_LIT><EOL>


self.music.start()<EOL>if not self.start_paused:<EOL><INDENT>self.rocket.start()<EOL><DEDENT>


self.rocket.update()<EOL>return self.music.get_time()<EOL>


Set the current time jumping in the timeline

Args:
    value (float): The new time value


self.controller.playing = False<EOL>self.music.pause()<EOL>


self.controller.playing = not self.controller.playing<EOL>self.music.toggle_pause()<EOL>


return self.rocket.time<EOL>

Stop the timer

Returns:
    The current time


self.ctx.disable(moderngl.DEPTH_TEST)<EOL>helper.draw(self.gbuffer.color_attachments[<NUM_LIT:0>], pos=(<NUM_LIT:0.0>, <NUM_LIT:0.0>), scale=(<NUM_LIT>, <NUM_LIT>))<EOL>helper.draw(self.gbuffer.color_attachments[<NUM_LIT:1>], pos=(<NUM_LIT:0.5>, <NUM_LIT:0.0>), scale=(<NUM_LIT>, <NUM_LIT>))<EOL>helper.draw_depth(self.gbuffer.depth_attachment, near, far, pos=(<NUM_LIT:1.0>, <NUM_LIT:0.0>), scale=(<NUM_LIT>, <NUM_LIT>))<EOL>helper.draw(self.lightbuffer.color_attachments[<NUM_LIT:0>], pos=(<NUM_LIT>, <NUM_LIT:0.0>), scale=(<NUM_LIT>, <NUM_LIT>))<EOL>

Draw framebuffers for debug purposes.
We need to supply near and far plane so the depth buffer can be linearized when visualizing.

:param near: Projection near value
:param far: Projection far value


def add_point_light(self, position, radius):

self.point_lights.append(PointLight(position, radius))<EOL>


def render_lights(self, camera_matrix, projection):

<EOL>self.ctx.front_face = '<STR_LIT>'<EOL>self.ctx.blend_func = moderngl.ONE, moderngl.ONE<EOL>helper._depth_sampler.use(location=<NUM_LIT:1>)<EOL>with self.lightbuffer_scope:<EOL><INDENT>for light in self.point_lights:<EOL><INDENT>light_size = light.radius<EOL>m_light = matrix44.multiply(light.matrix, camera_matrix)<EOL>self.point_light_shader["<STR_LIT>"].write(projection.tobytes())<EOL>self.point_light_shader["<STR_LIT>"].write(m_light.astype('<STR_LIT>').tobytes())<EOL>self.gbuffer.color_attachments[<NUM_LIT:1>].use(location=<NUM_LIT:0>)<EOL>self.point_light_shader["<STR_LIT>"].value = <NUM_LIT:0><EOL>self.gbuffer.depth_attachment.use(location=<NUM_LIT:1>)<EOL>self.point_light_shader["<STR_LIT>"].value = <NUM_LIT:1><EOL>self.point_light_shader["<STR_LIT>"].value = (self.width, self.height)<EOL>self.point_light_shader["<STR_LIT>"].value = projection.projection_constants<EOL>self.point_light_shader["<STR_LIT>"].value = light_size<EOL>self.unit_cube.render(self.point_light_shader)<EOL><DEDENT><DEDENT>helper._depth_sampler.clear(location=<NUM_LIT:1>)<EOL>


def render_lights_debug(self, camera_matrix, projection):

self.ctx.enable(moderngl.BLEND)<EOL>self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA<EOL>for light in self.point_lights:<EOL><INDENT>m_mv = matrix44.multiply(light.matrix, camera_matrix)<EOL>light_size = light.radius<EOL>self.debug_shader["<STR_LIT>"].write(projection.tobytes())<EOL>self.debug_shader["<STR_LIT>"].write(m_mv.astype('<STR_LIT>').tobytes())<EOL>self.debug_shader["<STR_LIT:size>"].value = light_size<EOL>self.unit_cube.render(self.debug_shader, mode=moderngl.LINE_STRIP)<EOL><DEDENT>self.ctx.disable(moderngl.BLEND)<EOL>


self.gbuffer.clear()<EOL>self.lightbuffer.clear()<EOL>


pass<EOL>

Implement the initialize when extending the class.
This method is responsible for fetching or creating resources
and doing genereal initalization of the effect.

The effect initializer is called when all resources are loaded
(with the exception of resources you manually load in the
the initializer).

If your effect requires arguments during initialiation you
are free to add positional and keyword arguments.

You **do not** have to call the superclass initializer though ``super()``

Example::

    def __init__(self):
        # Fetch reference to resource by their label
        self.program = self.get_program('simple_textured')
        self.texture = self.get_texture('bricks')
        # .. create a cube etc ..


pass<EOL>

Called after all effects are initialized before drawing starts.
Some initialization may be neccessary to do here such as
interaction with other effects.

This method does nothing unless implemented.


@property<EOL><INDENT>def name(self) -> str:<DEDENT>

return self._name<EOL>


@property<EOL><INDENT>def label(self) -> str:<DEDENT>

return self._label<EOL>

The label assigned to this effect instance


@property<EOL><INDENT>def window(self) -> BaseWindow:<DEDENT>

return self._window<EOL>


@property<EOL><INDENT>def ctx(self) -> moderngl.Context:<DEDENT>

return self._ctx<EOL>


@property<EOL><INDENT>def sys_camera(self) -> camera.SystemCamera:<DEDENT>

return self._sys_camera<EOL>


def draw(self, time: float, frametime: float, target: moderngl.Framebuffer):

raise NotImplementedError("<STR_LIT>")<EOL>

Draw function called by the system every frame when the effect is active.
This method raises ``NotImplementedError`` unless implemented.

Args:
    time (float): The current time in seconds.
    frametime (float): The time the previous frame used to render in seconds.
    target (``moderngl.Framebuffer``): The target FBO for the effect.


def get_program(self, label: str) -> moderngl.Program:

return self._project.get_program(label)<EOL>

Get a program by its label

Args:
    label (str): The label for the program

Returns: py:class:`moderngl.Program` instance


def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray,<EOL>moderngl.Texture3D, moderngl.TextureCube]:

return self._project.get_texture(label)<EOL>

Get a texture by its label

Args:
    label (str): The Label for the texture

Returns:
    The py:class:`moderngl.Texture` instance


def get_track(self, name: str) -> Track:

return resources.tracks.get(name)<EOL>

Gets or creates a rocket track.
Only avaiable when using a Rocket timer.

Args:
    name (str): The rocket track name

Returns:
    The :py:class:`rocket.Track` instance


def get_scene(self, label: str) -> Scene:

return self._project.get_scene(label)<EOL>

Get a scene by its label

Args:
    label (str): The label for the scene

Returns: The :py:class:`Scene` instance


return self._project.get_data(label)<EOL>

Get a data instance by its label

Args:
    label (str): Label for the data instance

Returns:
    Contents of the data file


def get_effect(self, label: str) -> '<STR_LIT>':

return self._project.get_effect(label)<EOL>

Get an effect instance by label.

Args:
    label (str): Label for the data file

Returns: The :py:class:`Effect` instance


def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['<STR_LIT>']:

return self._project.get_effect_class(effect_name, package_name=package_name)<EOL>

Get an effect class by the class name

Args:
    effect_name (str): Name of the effect class

Keyword Args:
    package_name (str): The package the effect belongs to. This is optional and only
                        needed when effect class names are not unique.

Returns:
    :py:class:`Effect` class


def create_projection(self, fov: float = <NUM_LIT>, near: float = <NUM_LIT:1.0>, far: float = <NUM_LIT>, aspect_ratio: float = None):

return matrix44.create_perspective_projection_matrix(<EOL>fov,<EOL>aspect_ratio or self.window.aspect_ratio,<EOL>near,<EOL>far,<EOL>dtype='<STR_LIT>',<EOL>)<EOL>

Create a projection matrix with the following parameters.
When ``aspect_ratio`` is not provided the configured aspect
ratio for the window will be used.

Args:
    fov (float): Field of view (float)
    near (float): Camera near value
    far (float): Camrea far value

Keyword Args:
    aspect_ratio (float): Aspect ratio of the viewport

Returns:
    The projection matrix as a float32 :py:class:`numpy.array`


def create_transformation(self, rotation=None, translation=None):

mat = None<EOL>if rotation is not None:<EOL><INDENT>mat = Matrix44.from_eulers(Vector3(rotation))<EOL><DEDENT>if translation is not None:<EOL><INDENT>trans = matrix44.create_from_translation(Vector3(translation))<EOL>if mat is None:<EOL><INDENT>mat = trans<EOL><DEDENT>else:<EOL><INDENT>mat = matrix44.multiply(mat, trans)<EOL><DEDENT><DEDENT>return mat<EOL>

Creates a transformation matrix woth rotations and translation.

Args:
    rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`
    translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`

Returns:
    A 4x4 matrix as a :py:class:`numpy.array`


normal_m = Matrix33.from_matrix44(modelview)<EOL>normal_m = normal_m.inverse<EOL>normal_m = normal_m.transpose()<EOL>return normal_m<EOL>

Creates a normal matrix from modelview matrix

Args:
    modelview: The modelview matrix

Returns:
    A 3x3 Normal matrix as a :py:class:`numpy.array`


parts = path.split('<STR_LIT:.>')<EOL>if parts[-<NUM_LIT:1>][<NUM_LIT:0>].isupper():<EOL><INDENT>return "<STR_LIT:.>".join(parts[:-<NUM_LIT:1>]), parts[-<NUM_LIT:1>]<EOL><DEDENT>return path, "<STR_LIT>"<EOL>

Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.

Examples::

    # Path to effect pacakge
    examples.cubes

    # Path to effect class
    examples.cubes.Cubes

Args:
    path: python path to effect package. May also include effect class name.

Returns:
    tuple: (package_path, effect_class)


for package in self.packages:<EOL><INDENT>yield os.path.join(package.path, '<STR_LIT>')<EOL><DEDENT>

Get all effect directories for registered effects.


def get_effect_resources(self) -> List[Any]:

resources = []<EOL>for package in self.packages:<EOL><INDENT>resources.extend(package.resources)<EOL><DEDENT>return resources<EOL>

Get all resources registed in effect packages.
These are typically located in ``resources.py``


for package in package_list:<EOL><INDENT>self.add_package(package)<EOL><DEDENT>

Polulate the registry with effect packages.

:param module_list: List of effect module paths


name, cls_name = parse_package_string(name)<EOL>if name in self.package_map:<EOL><INDENT>return<EOL><DEDENT>package = EffectPackage(name)<EOL>package.load()<EOL>self.packages.append(package)<EOL>self.package_map[package.name] = package<EOL>self.polulate(package.effect_packages)<EOL>

Registers a single package

:param name: (str) The effect package to add