<commit_before>import logging

import numpy
import sdl2
from OpenGL.GL import *
from sdl2 import video

from mgl2d.math.matrix4 import Matrix4
from mgl2d.math.rect import Rect

logger = logging.getLogger(__name__)

class Screen(object):
    def __init__(self, width, height, title='Window', gl_major=4, gl_minor=1):
        self._width = width
        self._height = height
        self._aspect_ratio = float(width) / float(height)
        self._viewport = Rect(0, 0, width, height)

        # Create the window
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())

        self._window = sdl2.SDL_CreateWindow(str.encode(title),
                                             sdl2.SDL_WINDOWPOS_UNDEFINED,
                                             sdl2.SDL_WINDOWPOS_UNDEFINED, width, height,
                                             sdl2.SDL_WINDOW_OPENGL)
        if not self._window:
            print(sdl2.SDL_GetError())
            return

        # Set up OpenGL
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, gl_major)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, gl_minor)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE)
        self._context = sdl2.SDL_GL_CreateContext(self._window)
        self._projection_matrix = self._ortho_projection()

        # Post processing steps
        self._pp_steps = []

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def is_opened(self):
        return self._window is not None

    @property
    def projection_matrix(self):
        return self._projection_matrix

    def _ortho_projection(self):
        z_far = 1.0
        z_near = -1.0

        m = numpy.zeros((4, 4), dtype=numpy.float32)
        m[0, 0] = + 2.0 / self._width
        m[3, 0] = - 1.0
        m[1, 1] = - 2.0 / self._height
        m[3, 1] = + 1.0
        m[2, 2] = - 2.0 / (z_far - z_near)
        m[3, 2] = (z_far + z_near) / (z_near - z_far)
        m[3, 3] = + 1.0

        return Matrix4(m)

    def close(self):
        sdl2.SDL_GL_DeleteContext(self._context)
        self._context = None
        sdl2.SDL_DestroyWindow(self._window)
        self._window = None

    def begin_update(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        if len(self._pp_steps) > 0:
            self._pp_steps[0].fbo.bind()

    def end_update(self):
        if len(self._pp_steps) > 0:
            if len(self._pp_steps) > 1:
                for x in range(1, len(self._pp_steps)):
                    self._pp_steps[x].fbo.bind()
                    self._pp_steps[x - 1].draw(self)

            self._pp_steps[-1].fbo.unbind()
            self._pp_steps[-1].draw(self)

        sdl2.SDL_GL_SwapWindow(self._window)

    def add_postprocessing_step(self, step):
        self._pp_steps.append(step)

    def print_info(self):
        logger.info('%dx%d ratio: %.2f' % (self._width, self._height, self._aspect_ratio))
        logger.info('Rendeer: %s (%s)' % (glGetString(GL_RENDERER), glGetString(GL_VENDOR)))
        logger.info('OpenGL: %s GLSL: %s' % (glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)))
<commit_msg>Enable basic alpha blending by default<commit_after>import logging

import numpy
import sdl2
from OpenGL.GL import *
from sdl2 import video

from mgl2d.math.matrix4 import Matrix4
from mgl2d.math.rect import Rect

logger = logging.getLogger(__name__)

class Screen(object):
    def __init__(self, width, height, title='Window', alpha_blending=True, gl_major=4, gl_minor=1):
        self._width = width
        self._height = height
        self._aspect_ratio = float(width) / float(height)
        self._viewport = Rect(0, 0, width, height)

        # Create the window
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())

        self._window = sdl2.SDL_CreateWindow(str.encode(title),
                                             sdl2.SDL_WINDOWPOS_UNDEFINED,
                                             sdl2.SDL_WINDOWPOS_UNDEFINED, width, height,
                                             sdl2.SDL_WINDOW_OPENGL)
        if not self._window:
            print(sdl2.SDL_GetError())
            return

        # Set up OpenGL
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, gl_major)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, gl_minor)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE)
        self._context = sdl2.SDL_GL_CreateContext(self._window)
        self._projection_matrix = self._ortho_projection()

        if alpha_blending:
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        # Post processing steps
        self._pp_steps = []

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def is_opened(self):
        return self._window is not None

    @property
    def projection_matrix(self):
        return self._projection_matrix

    def _ortho_projection(self):
        z_far = 1.0
        z_near = -1.0

        m = numpy.zeros((4, 4), dtype=numpy.float32)
        m[0, 0] = + 2.0 / self._width
        m[3, 0] = - 1.0
        m[1, 1] = - 2.0 / self._height
        m[3, 1] = + 1.0
        m[2, 2] = - 2.0 / (z_far - z_near)
        m[3, 2] = (z_far + z_near) / (z_near - z_far)
        m[3, 3] = + 1.0

        return Matrix4(m)

    def close(self):
        sdl2.SDL_GL_DeleteContext(self._context)
        self._context = None
        sdl2.SDL_DestroyWindow(self._window)
        self._window = None

    def begin_update(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        if len(self._pp_steps) > 0:
            self._pp_steps[0].fbo.bind()

    def end_update(self):
        if len(self._pp_steps) > 0:
            if len(self._pp_steps) > 1:
                for x in range(1, len(self._pp_steps)):
                    self._pp_steps[x].fbo.bind()
                    self._pp_steps[x - 1].draw(self)

            self._pp_steps[-1].fbo.unbind()
            self._pp_steps[-1].draw(self)

        sdl2.SDL_GL_SwapWindow(self._window)

    def add_postprocessing_step(self, step):
        self._pp_steps.append(step)

    def print_info(self):
        logger.info('%dx%d ratio: %.2f' % (self._width, self._height, self._aspect_ratio))
        logger.info('Rendeer: %s (%s)' % (glGetString(GL_RENDERER), glGetString(GL_VENDOR)))
        logger.info('OpenGL: %s GLSL: %s' % (glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)))
<|endoftext|>


<commit_before>import os
import pytest
from rhcephpkg import Clone
from rhcephpkg.tests.util import CallRecorder

class CheckCallRecorder(CallRecorder):

    def __call__(self, cmd):
        """ Store cmd, in order to verify it later. """
        self.called += 1
        if cmd[:2] == ['git', 'clone']:
            self.fake_git_clone(*cmd[2:])
        self.args = cmd
        return 0

    def fake_git_clone(self, *args):
        """ Just make a directory in cwd. """
        try:
            dirname = args[1]
        except IndexError:
            dirname = os.path.basename(args[0])
        os.mkdir(dirname)

class TestClone(object):

    def test_basic_clone(self, tmpdir, monkeypatch):
        recorder = CheckCallRecorder()
        monkeypatch.setattr('subprocess.check_call', recorder)
        monkeypatch.chdir(tmpdir)
        clone = Clone([])
        clone._run('mypkg')
        assert recorder.args == ['git', 'clone',
                                 'ssh://kdreyer@git.example.com/ubuntu/mypkg']

    def test_already_exists(self, tmpdir, monkeypatch):
        tmpdir.mkdir('mypkg')
        monkeypatch.chdir(tmpdir)
        clone = Clone([])
        with pytest.raises(SystemExit) as e:
            clone._run('mypkg')
        expected = 'mypkg already exists in current working directory.'
        assert str(e.value) == expected
<commit_msg>tests: assert dir exists after clone operation<commit_after>import os
import pytest
from rhcephpkg import Clone
from rhcephpkg.tests.util import CallRecorder

class CheckCallRecorder(CallRecorder):

    def __call__(self, cmd):
        """ Store cmd, in order to verify it later. """
        self.called += 1
        if cmd[:2] == ['git', 'clone']:
            self.fake_git_clone(*cmd[2:])
        self.args = cmd
        return 0

    def fake_git_clone(self, *args):
        """ Just make a directory in cwd. """
        try:
            dirname = args[1]
        except IndexError:
            dirname = os.path.basename(args[0])
        os.mkdir(dirname)

class TestClone(object):

    def test_basic_clone(self, tmpdir, monkeypatch):
        recorder = CheckCallRecorder()
        monkeypatch.setattr('subprocess.check_call', recorder)
        monkeypatch.chdir(tmpdir)
        clone = Clone([])
        clone._run('mypkg')
        assert recorder.args == ['git', 'clone',
                                 'ssh://kdreyer@git.example.com/ubuntu/mypkg']
        assert tmpdir.join('mypkg').check(dir=1)

    def test_already_exists(self, tmpdir, monkeypatch):
        tmpdir.mkdir('mypkg')
        monkeypatch.chdir(tmpdir)
        clone = Clone([])
        with pytest.raises(SystemExit) as e:
            clone._run('mypkg')
        expected = 'mypkg already exists in current working directory.'
        assert str(e.value) == expected
<|endoftext|>


<commit_before>"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import datetime

from django.db import models

class RnaPrecomputed(models.Model):
    id = models.CharField(max_length=22, primary_key=True)
    upi = models.ForeignKey('Rna', db_column='upi', to_field='upi', related_name='precomputed')
    taxid = models.IntegerField(db_index=True, null=True)
    description = models.CharField(max_length=250)
    rna_type = models.CharField(max_length=250)
    rfam_problems = models.TextField(default='')
    update_date = models.DateField(null=False, default=datetime.date(1970, 1, 1))

    class Meta:
        db_table = 'rnc_rna_precomputed'
<commit_msg> #330 Some missing documentation lines in RnaPrecomputed.<commit_after>"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import datetime

from django.db import models

class RnaPrecomputed(models.Model):
    """
    Contains 2 types of entries: species-specific (taxid != Null) and non-species-specific (taxid == Null).

    For every Rna there should be 1 entry in RnaPrecomputed, where taxid = Null and some species-specific.
    """
    id = models.CharField(max_length=22, primary_key=True)  # id = upi + taxid if taxid != Null else upi
    upi = models.ForeignKey('Rna', db_column='upi', to_field='upi', related_name='precomputed')
    taxid = models.IntegerField(db_index=True, null=True)
    description = models.CharField(max_length=250)
    rna_type = models.CharField(max_length=250)
    rfam_problems = models.TextField(default='')
    update_date = models.DateField(null=False, default=datetime.date(1970, 1, 1))

    class Meta:
        db_table = 'rnc_rna_precomputed'
<|endoftext|>


<commit_before>import json

from tastypie.test import ResourceTestCase
from django.contrib.auth.models import User
from setup_helpers import TestSetupHelpers
from pandas import read_csv, notnull, to_datetime
from rhizome.models import *
from pandas import read_csv, notnull, to_datetime, DataFrame, Series
from rhizome.cache_meta import minify_geo_json, LocationTreeCache

class GeoResourceTest(ResourceTestCase):
    def setUp(self):
      #   super(GeoResourceTest, self).setUp()

        self.ts = TestSetupHelpers()
        self.lt = LocationType.objects.create(name='Province',admin_level=2)
        self.o = self.ts.create_arbitrary_office()
        location_df_from_csv= read_csv('rhizome/tests/_data/locations_nimroz.csv')
        locations = self.ts.model_df_to_data(location_df_from_csv,Location)

        ## override location type attribute from file so that these locations ##
        ## are provinces ##
        for loc in locations:
            loc.location_type_id = self.lt.id
            loc.save()

        geo_json_df = read_csv('rhizome/tests/_data/geo_json.txt',delimiter = "|")
        location_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','location_code')),columns=['location_id','location_code'])
        location_tree_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','parent_location_id')),columns=['location_id','parent_location_id'])
        location_tree_df['lvl'] = Series(1, index=location_tree_df.index)
        location_tree = self.ts.model_df_to_data(location_tree_df, LocationTree)
        merged_df = location_df.merge(geo_json_df)[['location_id','geo_json']]
        self.ts.model_df_to_data(merged_df, LocationPolygon)
        minify_geo_json()
        LocationPermission.objects.create(user_id = self.ts.user.id,\
            top_lvl_location_id = 1)

    def test_get_geo_tree_lvl(self):
        get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        resp = self.ts.get(self, '/api/v1/geo/', get_data)
        self.assertHttpOK(resp)
        self.assertEqual(len(self.deserialize(resp)['features']), 5)

    # make sure that the api returns the parent location

    def test_check_parent_location(self):
        get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        resp = self.ts.get(self, '/api/v1/geo/', get_data)
        self.assertHttpOK(resp)
        resp_data = self.deserialize(resp)
        self.assertEqual(int(resp_data['parent_location_id__in']), 6)
<commit_msg>mock return true<commit_after>import json

from tastypie.test import ResourceTestCase
from django.contrib.auth.models import User
from setup_helpers import TestSetupHelpers
from pandas import read_csv, notnull, to_datetime
from rhizome.models import *
from pandas import read_csv, notnull, to_datetime, DataFrame, Series
from rhizome.cache_meta import minify_geo_json, LocationTreeCache

class GeoResourceTest(ResourceTestCase):
    def setUp(self):
      #   super(GeoResourceTest, self).setUp()

        self.ts = TestSetupHelpers()
        self.lt = LocationType.objects.create(name='Province',admin_level=2)
        self.o = self.ts.create_arbitrary_office()
        location_df_from_csv= read_csv('rhizome/tests/_data/locations_nimroz.csv')
        locations = self.ts.model_df_to_data(location_df_from_csv,Location)

        ## override location type attribute from file so that these locations ##
        ## are provinces ##
        for loc in locations:
            loc.location_type_id = self.lt.id
            loc.save()

        geo_json_df = read_csv('rhizome/tests/_data/geo_json.txt',delimiter = "|")
        location_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','location_code')),columns=['location_id','location_code'])
        location_tree_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','parent_location_id')),columns=['location_id','parent_location_id'])
        location_tree_df['lvl'] = Series(1, index=location_tree_df.index)
        location_tree = self.ts.model_df_to_data(location_tree_df, LocationTree)
        merged_df = location_df.merge(geo_json_df)[['location_id','geo_json']]
        self.ts.model_df_to_data(merged_df, LocationPolygon)
        minify_geo_json()
        LocationPermission.objects.create(user_id = self.ts.user.id,\
            top_lvl_location_id = 1)

    def test_get_geo_tree_lvl(self):
        get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        resp = self.ts.get(self, '/api/v1/geo/', get_data)
        self.assertHttpOK(resp)
        self.assertEqual(len(self.deserialize(resp)['features']), 5)

    # make sure that the api returns the parent location

    def test_check_parent_location(self):
        get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        resp = self.ts.get(self, '/api/v1/geo/', get_data)
        self.assertHttpOK(resp)
        resp_data = self.deserialize(resp)
        self.assertEqual(int(resp_data['parent_location_id__in']), 6)
<|endoftext|>


<commit_before>__author__ = 'Pharylon'

import time
import RPi.GPIO as GPIO
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-w", "--wait", type=float, default=0.001, help="Time to wait (in seconds) between steps. Default time is 0.001")
parser.add_argument("-cc", "--counterclockwise", help="Turn stepper counterclockwise", action="store_true")
args = parser.parse_args()

#We will be using GPIO pin numbers instead
#of phyisical pin numbers.
GPIO.setmode(GPIO.BCM)

#These are the four GPIO pins we will
#use to drive the stepper motor, in the order
#they are plugged into the controller board. So,
#GPIO 17 is plugged into Pin 1 on the stepper motor.
GpioPins = [17, 18, 27, 22]

for pin in GpioPins:
    GPIO.setup(pin,GPIO.OUT)
    GPIO.output(pin, False)

#These steps are defined in datasheet at
#http://www.bitsbox.co.uk/data/motor/Stepper.pdf
#Each step is a list containing GPIO pins that should be set the High
StepSequence = range(0, 8)
StepSequence[0] = [GpioPins[0]]
StepSequence[1] = [GpioPins[0], GpioPins[1]]
StepSequence[2] = [GpioPins[1]]
StepSequence[3] = [GpioPins[1], GpioPins[2]]
StepSequence[4] = [GpioPins[2]]
StepSequence[5] = [GpioPins[2], GpioPins[3]]
StepSequence[6] = [GpioPins[3]]
StepSequence[7] = [GpioPins[3], GpioPins[0]]

#if we want the motor to run in "reverse" we flip the sequence order.
if args.counterclockwise:
    rev = range(0, 8)
    revPos = 7
    for s in StepSequence:
        rev[revPos] = s
        revPos -= 1
    StepSequence = rev

while True:
    for pinList in StepSequence:
	print "New Step"
        for pin in GpioPins:
            if pin in pinList:
		print "Enabling pin %i" % pin
                GPIO.output(pin, True)
            else:
		print "Disabling pin %i" % pin
                GPIO.output(pin, False)
    	time.sleep(args.wait)
<commit_msg>More args makes it more driver-y!<commit_after>__author__ = 'Pharylon'

import time
import RPi.GPIO as GPIO
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-w", "--wait", type=float, default=0.001, help="Time to wait (in seconds) between steps. Default time is 0.001")
parser.add_argument("-s", "--steps", type=int, default=500, help="Number of steps to take. Default is 500, which is roughtly one revolution.")
parser.add_argument("-cc", "--counterclockwise", help="Turn stepper counterclockwise", action="store_true")
parser.add_argument("-v", "--verbose", help="Write pin actions", default=False, action="store_true")
args = parser.parse_args()

#We will be using GPIO pin numbers instead
#of phyisical pin numbers.
GPIO.setmode(GPIO.BCM)

#These are the four GPIO pins we will
#use to drive the stepper motor, in the order
#they are plugged into the controller board. So,
#GPIO 17 is plugged into Pin 1 on the stepper motor.
#If you change the pin hookup on the Pi, this is
#the only part of the code you should need to change.
GpioPins = [17, 18, 27, 22]

for pin in GpioPins:
    GPIO.setup(pin,GPIO.OUT)
    GPIO.output(pin, False)

#These steps are defined in datasheet at
#http://www.bitsbox.co.uk/data/motor/Stepper.pdf
#Each step is a list containing GPIO pins that should be set the High
StepSequence = range(0, 8)
StepSequence[0] = [GpioPins[0]]
StepSequence[1] = [GpioPins[0], GpioPins[1]]
StepSequence[2] = [GpioPins[1]]
StepSequence[3] = [GpioPins[1], GpioPins[2]]
StepSequence[4] = [GpioPins[2]]
StepSequence[5] = [GpioPins[2], GpioPins[3]]
StepSequence[6] = [GpioPins[3]]
StepSequence[7] = [GpioPins[3], GpioPins[0]]

#if we want the motor to run in "reverse" we flip the sequence order.
if args.counterclockwise:
    rev = range(0, 8)
    revPos = 7
    for s in StepSequence:
        rev[revPos] = s
        revPos -= 1
    StepSequence = rev

curserSpin = ["/","-","|","\\","|"]
spinPosition = 0

def PrintCursorSpin():
	global curserSpin
	global spinPosition
	print "%s\r" % curserSpin[spinPosition],
	spinPosition += 1
	if spinPosition > 4:
		spinPosition = 0

def PrintStatus(enabledPins):
	if args.verbose:
		print "New Step:"
		for pin in GpioPins:
			if pin in enabledPins:
				print "Enabling Pin %i" % pin
			else:
				print "Disabling Pin %i" % pin
	else:
		PrintCursorSpin()

stepsRemaining = args.steps
while stepsRemaining > 0:
    for pinList in StepSequence:
        for pin in GpioPins:
            if pin in pinList:
				GPIO.output(pin, True)
            else:
                GPIO.output(pin, False)
		PrintStatus(pinList)
    	time.sleep(args.wait)
    stepsRemaining -= 1

<|endoftext|>


<commit_before>r'''
SAM Parser
=====================

SAM stores input query sequences that have mapped to a reference [#]_.
The SAM format has a header section, where each line is denoted by @.
This header contains information about the program used to generate the
genbank file.

Each line following the header lines encodes information for a single read.
Each line is structured as follows.

    +--------------------------------+----------------------------------+
    | QNAME - Query template NAME    | (begins each entry; 1 per entry) |
    +--------------------------------+----------------------------------+
    | FLAG  - Bitwise FLAGs          | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | RNAME - Reference sequence     | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | POS - 1-based position         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | MAPQ - mapping quality         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | CIGAR - CIGAR string           | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | RNEXT - next alignment name    | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | PNEXT - next alignment position| 1 per entry                      |
    +--------------------------------+----------------------------------+
    | TLEN - signed observed length  | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | SEQ - segment sequence         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | QUAL - base quality            | 1 per entry                      |
    +--------------------------------+----------------------------------+

The line can be followed by optional fields.

Format Support
--------------
**Has Sniffer: Yes**

+------+------+---------------------------------------------------------------+
|Reader|Writer|                          Object Class                         |
+======+======+===============================================================+
|Yes   |No    |:mod:`skbio.sequence.Sequence`                                 |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.DNA`                                      |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.RNA`                                      |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.Protein`                                  |
+------+------+---------------------------------------------------------------+
|Yes   |No    |generator of :mod:`skbio.sequence.Sequence` objects            |
+------+------+---------------------------------------------------------------+

Reference
---------
.. [#] https://samtools.github.io/hts-specs/SAMv1.pdf
'''
from skbio.util._misc import merge_dicts
from skbio.io import create_format, FileFormatError
from skbio.sequence import Sequence, DNA, RNA, Protein
from skbio.io.format._base import (
    _line_generator, _get_nth_sequence, _too_many_blanks)

class SAMFormatError(FileFormatError):
    pass

sam = create_format('sam')

# File headers
_HEADERS = ['HD',      # The header line
            'SQ',      # Reference sequence dictionary
            'RG',      # Read group
            'PG',      # Program
            'CO'       # one-line text comment
            ]

# Alignment headers
_ALIGNMENT_HEADERS = [
          'QNAME',   # Query template NAME.
          'FLAG',    # Combination of bitwise FLAGs
          'RNAME',   # Reference sequence NAME of the alignment
          'POS',     # 1-based leftmost mapping position of the first base
          'MAPQ',    # Mapping quality. -10log10(P_err).
          'CIGAR',   # CIGAR string
          'RNEXT',   # Reference sequence name of the primary alignment of NEXT
          'PNEXT',   # Position of the primary alignment of the NEXT read
          'TLEN',    # signed observed template length
          # 'SEQ',     # segment sequence
          'QUAL',    # ASCII of base quality
]

@sam.sniffer()
def _sam_sniffer(fh):
    # check the 1st real line is a valid ID line
    if _too_many_blanks(fh, 5):
        return False, {}

    try:
        line = next(_line_generator(fh, skip_blanks=True, strip=False))
    except StopIteration:
        return False, {}

    try:
        assert line.startswith('@HD')
    except SAMFormatError:
        return False, {}
    return True, {}

def _is_float(input):
    try:
        float(input)
    except ValueError:
        return False
    return True

def parse_optional(s):
    _field, _type, _val = s.split(':')
    if _type == 'i':
        return {_field: int(_val)}
    elif _type == 'f':
        return {_field: float(_val)}
    else:
        return {_field: _val}

def parse_required(s):
    if s.isdigit():
        return int(s)
    elif _is_float(s):
        return float(s)
    else:
        return s

def _construct(record, constructor=None, **kwargs):
    seq, md = record
    if constructor is None:
        constructor = Sequence
    if constructor == RNA:
        return DNA(
            seq, metadata=md, **kwargs).transcribe()
    else:
        return constructor(
            seq, metadata=md, **kwargs)

@sam.reader(None)
def _sam_to_generator(fh, constructor=None, **kwargs):
    for record in _parse_records(fh):
        yield _construct(record, constructor, **kwargs)

@sam.reader(Sequence)
def _sam_to_sequence(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, Protein, **kwargs)

@sam.reader(Protein)
def _sam_to_protein(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, Protein, **kwargs)

@sam.reader(DNA)
def _sam_to_DNA(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, DNA, **kwargs)

@sam.reader(RNA)
def _sam_to_RNA(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, RNA, **kwargs)

def _parse_records(fh, constructor=None, **kwargs):
    metadata = {}
    optional_headers = []
    headers = _ALIGNMENT_HEADERS
    for line in _line_generator(fh, skip_blanks=True, strip=True):
        # parse the header (would be nice to abstract this pattern out)
        if line.startswith('@'):
            tabs = line.split('\t')
            key = tabs[0][1:]
            # FIXME:  The vals variable needs to be explicitly tested
            vals = tabs[1:]
            if key == 'CO':
                val = vals[0]
                optional_headers = val.split(',')
                headers = _ALIGNMENT_HEADERS + optional_headers
                headers = headers[:9] + headers[10:]
            else:
                vals = tabs[1:]
                if len(vals) > 1:
                    metadata[key] = vals
                else:
                    metadata[key] = vals[0]

        # parse the actual sequences
        else:
            tabs = line.split('\t')

            # extract sequence
            seq = tabs[9]
            tabs = tabs[:9] + tabs[10:]

            req = list(map(parse_required, tabs[:10]))
            opt = list(map(parse_optional, tabs[10:]))
            req = dict(zip(_ALIGNMENT_HEADERS, req))

            md = merge_dicts(metadata, req, *opt)
            yield seq, md
<commit_msg>fix sniffer and parser<commit_after>r'''
SAM Parser
==========

SAM stores input query sequences that have mapped to a reference [#]_.
The SAM format has a header section, where each line is denoted by @.

Each line following the header lines encodes information for a single read.
Each line is structured as follows.

    +--------------------------------+----------------------------------+
    | QNAME - Query template NAME    | (begins each entry; 1 per entry) |
    +--------------------------------+----------------------------------+
    | FLAG  - Bitwise FLAGs          | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | RNAME - Reference sequence     | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | POS - 1-based position         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | MAPQ - mapping quality         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | CIGAR - CIGAR string           | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | RNEXT - next alignment name    | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | PNEXT - next alignment position| 1 per entry                      |
    +--------------------------------+----------------------------------+
    | TLEN - signed observed length  | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | SEQ - segment sequence         | 1 per entry                      |
    +--------------------------------+----------------------------------+
    | QUAL - base quality            | 1 per entry                      |
    +--------------------------------+----------------------------------+

The line can be followed by optional fields.

Format Support
--------------
**Has Sniffer: Yes**

+------+------+---------------------------------------------------------------+
|Reader|Writer|                          Object Class                         |
+======+======+===============================================================+
|Yes   |No    |:mod:`skbio.sequence.Sequence`                                 |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.DNA`                                      |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.RNA`                                      |
+------+------+---------------------------------------------------------------+
|Yes   |No    |:mod:`skbio.sequence.Protein`                                  |
+------+------+---------------------------------------------------------------+
|Yes   |No    |generator of :mod:`skbio.sequence.Sequence` objects            |
+------+------+---------------------------------------------------------------+

Reference
---------
.. [#] https://samtools.github.io/hts-specs/SAMv1.pdf
'''
from skbio.util._misc import merge_dicts
from skbio.io import create_format, FileFormatError
from skbio.sequence import Sequence, DNA, RNA, Protein
from skbio.io.format._base import (
    _line_generator, _get_nth_sequence, _too_many_blanks)

class SAMFormatError(FileFormatError):
    pass

sam = create_format('sam')

# File headers
_HEADERS = ['HD',      # The header line
            'SQ',      # Reference sequence dictionary
            'RG',      # Read group
            'PG',      # Program
            'CO'       # one-line text comment
            ]

# Alignment headers
_ALIGNMENT_HEADERS = [
          'QNAME',   # Query template NAME.
          'FLAG',    # Combination of bitwise FLAGs
          'RNAME',   # Reference sequence NAME of the alignment
          'POS',     # 1-based leftmost mapping position of the first base
          'MAPQ',    # Mapping quality. -10log10(P_err).
          'CIGAR',   # CIGAR string
          'RNEXT',   # Reference sequence name of the primary alignment of NEXT
          'PNEXT',   # Position of the primary alignment of the NEXT read
          'TLEN',    # signed observed template length
          # 'SEQ',     # segment sequence
          'QUAL',    # ASCII of base quality
]

@sam.sniffer()
def _sam_sniffer(fh):
    # check the 1st real line is a valid ID line
    if _too_many_blanks(fh, 5):
        return False, {}

    try:
        line = next(_line_generator(fh, skip_blanks=True, strip=False))
    except StopIteration:
        return False, {}

    if line.startswith('@HD'):
        return True, {}
    else:
        return False, {}

def _is_float(input):
    try:
        float(input)
    except ValueError:
        return False
    return True

def parse_optional(s):
    _field, _type, _val = s.split(':')
    if _type == 'i':
        return {_field: int(_val)}
    elif _type == 'f':
        return {_field: float(_val)}
    else:
        return {_field: _val}

def parse_required(s):
    if s.isdigit():
        return int(s)
    elif _is_float(s):
        return float(s)
    else:
        return s

def _construct(record, constructor=None, **kwargs):
    seq, md = record
    if constructor is None:
        constructor = Sequence
    if constructor == RNA:
        return DNA(
            seq, metadata=md, **kwargs).transcribe()
    else:
        return constructor(
            seq, metadata=md, **kwargs)

@sam.reader(None)
def _sam_to_generator(fh, constructor=None, **kwargs):
    for record in _parse_records(fh):
        yield _construct(record, constructor, **kwargs)

@sam.reader(Sequence)
def _sam_to_sequence(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, Protein, **kwargs)

@sam.reader(Protein)
def _sam_to_protein(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, Protein, **kwargs)

@sam.reader(DNA)
def _sam_to_DNA(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, DNA, **kwargs)

@sam.reader(RNA)
def _sam_to_RNA(fh, seq_num=1, **kwargs):
    record = _get_nth_sequence(_parse_records(fh), seq_num)
    return _construct(record, RNA, **kwargs)

def _parse_records(fh, constructor=None, **kwargs):
    metadata = {}
    optional_headers = []
    headers = _ALIGNMENT_HEADERS
    for line in _line_generator(fh, skip_blanks=True, strip=True):
        # parse the header (would be nice to abstract this pattern out)
        if line.startswith('@'):
            tabs = line.split('\t')
            key = tabs[0][1:]
            # FIXME:  The vals variable needs to be explicitly tested
            vals = tabs[1:]
            if key == 'CO':
                val = vals[0]
                optional_headers = val.split(',')
                headers = _ALIGNMENT_HEADERS + optional_headers
                headers = headers[:9] + headers[10:]
            else:
                vals = tabs[1:]
                if len(vals) > 1:
                    metadata[key] = vals
                else:
                    metadata[key] = vals[0]

        # parse the actual sequences
        else:
            tabs = line.split('\t')

            # extract sequence
            seq = tabs[9]
            tabs = tabs[:9] + tabs[10:]

            req = list(map(parse_required, tabs[:10]))
            opt = list(map(parse_optional, tabs[10:]))
            req = dict(zip(_ALIGNMENT_HEADERS, req))

            md = merge_dicts(metadata, req, *opt)
            yield seq, md
<|endoftext|>


<commit_before># Sound works, make sure your volume is up.
import slither

sound = slither.slitherSound.loadSound('assets/boom.wav')
sound.play()
<commit_msg>Update soundtest.py<commit_after># Sound works, make sure your volume is up.
from slither import *

sound = slither.slitherSound.loadSound('assets/boom.wav')
sound.play()
<|endoftext|>


<commit_before>import json

from tastypie.test import ResourceTestCase
from django.contrib.auth.models import User
from setup_helpers import TestSetupHelpers
from pandas import read_csv, notnull, to_datetime
from rhizome.models import *
from pandas import read_csv, notnull, to_datetime, DataFrame, Series
from rhizome.cache_meta import minify_geo_json, LocationTreeCache

class GeoResourceTest(ResourceTestCase):
    def setUp(self):
      #   super(GeoResourceTest, self).setUp()

        self.ts = TestSetupHelpers()
        self.lt = LocationType.objects.create(name='Province',admin_level=2)
        self.o = self.ts.create_arbitrary_office()
        location_df_from_csv= read_csv('rhizome/tests/_data/locations_nimroz.csv')
        locations = self.ts.model_df_to_data(location_df_from_csv,Location)

        ## override location type attribute from file so that these locations ##
        ## are provinces ##
        for loc in locations:
            loc.location_type_id = self.lt.id
            loc.save()

        geo_json_df = read_csv('rhizome/tests/_data/geo_json.txt',delimiter = "|")
        location_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','location_code')),columns=['location_id','location_code'])
        location_tree_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','parent_location_id')),columns=['location_id','parent_location_id'])
        location_tree_df['lvl'] = Series(1, index=location_tree_df.index)
        location_tree = self.ts.model_df_to_data(location_tree_df, LocationTree)
        merged_df = location_df.merge(geo_json_df)[['location_id','geo_json']]
        self.ts.model_df_to_data(merged_df, LocationPolygon)
        minify_geo_json()
        LocationPermission.objects.create(user_id = self.ts.user.id,\
            top_lvl_location_id = 1)

    def test_get_geo_tree_lvl(self):
        # get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        # resp = self.ts.get(self, '/api/v1/geo/', get_data)
        # self.assertHttpOK(resp)
        # self.assertEqual(len(self.deserialize(resp)['features']), 5)
        return True
<commit_msg>comment out tests<commit_after>import json

from tastypie.test import ResourceTestCase
from django.contrib.auth.models import User
from setup_helpers import TestSetupHelpers
from pandas import read_csv, notnull, to_datetime
from rhizome.models import *
from pandas import read_csv, notnull, to_datetime, DataFrame, Series
from rhizome.cache_meta import minify_geo_json, LocationTreeCache

class GeoResourceTest(ResourceTestCase):
    def setUp(self):
      #   super(GeoResourceTest, self).setUp()

        self.ts = TestSetupHelpers()
        self.lt = LocationType.objects.create(name='Province',admin_level=2)
        self.o = self.ts.create_arbitrary_office()
        location_df_from_csv= read_csv('rhizome/tests/_data/locations_nimroz.csv')
        locations = self.ts.model_df_to_data(location_df_from_csv,Location)

        ## override location type attribute from file so that these locations ##
        ## are provinces ##
        for loc in locations:
            loc.location_type_id = self.lt.id
            loc.save()

        geo_json_df = read_csv('rhizome/tests/_data/geo_json.txt',delimiter = "|")
        location_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','location_code')),columns=['location_id','location_code'])
        location_tree_df = DataFrame(list(Location.objects.all()\
		    .values_list('id','parent_location_id')),columns=['location_id','parent_location_id'])
        location_tree_df['lvl'] = Series(1, index=location_tree_df.index)
        location_tree = self.ts.model_df_to_data(location_tree_df, LocationTree)
        merged_df = location_df.merge(geo_json_df)[['location_id','geo_json']]
        self.ts.model_df_to_data(merged_df, LocationPolygon)
        minify_geo_json()
        LocationPermission.objects.create(user_id = self.ts.user.id,\
            top_lvl_location_id = 1)

    def _get_geo_tree_lvl(self):
        get_data ={'parent_location_id__in':6, 'tree_lvl':1}
        resp = self.ts.get(self, '/api/v1/geo/', get_data)
        self.assertHttpOK(resp)
        self.assertEqual(len(self.deserialize(resp)['features']), 5)
<|endoftext|>


<commit_before>frames = None

def get_frames():
    global frames
    return frames

def load_frames():
    global frames

    import copy

    from rocketleaguereplayanalysis.data.data_loader import get_data
    from rocketleaguereplayanalysis.data.object_numbers import \
        get_player_info, get_game_event_num, team0, team1
    from rocketleaguereplayanalysis.parser.frame_data import \
        update_game_data, update_car_data, update_player_data, \
        update_ball_data, update_boost_data

    data = get_data()

    current_ball_object = None
    current_car_objects = {}
    current_boost_objects = {}
    player_info = get_player_info()
    game_event_num = get_game_event_num()

    frames = [len(data['Frames'])]
    frames[0] = {
        'time': {
            'replay_time': data['Frames'][0]['Delta'],
            'server_time': data['Frames'][0]['Time'],
            'game_time': 300,
            'game_minutes': int(300 / 60),
            'game_seconds': 300 % 60,
            'replay_delta': data['Frames'][0]['Delta'],
            'server_delta': data['Frames'][0]['Delta'],
            'real_replay_time': 0,
            'real_replay_delta': data['Frames'][0]['Delta']
        },
        'scoreboard': {
            'team0': 0,
            'team1': 0
        },
        'ball': {'loc': {'x': 0, 'y': 0, 'z': 0},
                 'rot': {'x': 0, 'y': 0, 'z': 0},
                 'sleep': True,
                 'last_hit': None},
        'cars': {}
    }

    for player_id in player_info.keys():
        current_car_objects[player_id] = None
        frames[0]['cars'][player_id] = {
            'loc': {'x': None, 'y': None, 'z': None},
            'rot': {'x': 0, 'y': 0, 'z': 0},
            'ang_vel': {'x': 0, 'y': 0, 'z': 0},
            'lin_vel': {'x': 0, 'y': 0, 'z': 0},
            'throttle': .5,
            'steer': .5,
            'ping': 0,
            'boost': 0,
            'boosting': False,
            'sleep': True,
            'drift': False,
            '2nd_cam': False,
            'driving': False,
            'scoreboard': {
                'score': 0,
                'goals': 0,
                'assists': 0,
                'saves': 0,
                'shots': 0
            }
        }

    for i in range(0, len(data['Frames'])):

        if i > 0:
            frames.append(copy.deepcopy(frames[i - 1]))

        server_time = data['Frames'][i]['Time']
        replay_time = frames[i - 1]['time']['replay_time'] + \
                      data['Frames'][i]['Delta']
        game_time = frames[i - 1]['time']['game_time']
        server_delta = data['Frames'][i]['Time'] - \
                       data['Frames'][i - 1]['Time']
        replay_delta = data['Frames'][i]['Delta']

        if replay_delta == 0:
            # There seems to have been a goal here.
            real_replay_delta = replay_delta
            real_replay_time = (frames[i]['time']['real_replay_time'] +
                                replay_delta)
        else:
            real_replay_delta = server_delta
            real_replay_time = (frames[i]['time']['real_replay_time'] +
                                server_delta)

        frames[i]['time'] = {
            'replay_time': replay_time,
            'server_time': server_time,
            'game_time': game_time,
            'game_minutes': int(game_time / 60),
            'game_seconds': game_time % 60,
            'replay_delta': replay_delta,
            'server_delta': server_delta,
            'real_replay_time': real_replay_time,
            'real_replay_delta': real_replay_delta
        }

        for update in data['Frames'][i]['ActorUpdates']:
            actor_id = update['Id']

            # Update ball object number
            if 'ClassName' in update and \
                    ('TAGame.Ball_TA' in update['ClassName']):
                current_ball_object = actor_id

            # Update car numbers
            if 'ClassName' in update and \
                    ('TAGame.Car_TA' in update['ClassName']):
                player = update['Engine.Pawn:PlayerReplicationInfo']['ActorId']
                current_car_objects[player] = update['Id']

            update_boost_data(update, frames, current_car_objects,
                              current_boost_objects, i)

            # Update ball data
            if actor_id == current_ball_object:
                update_ball_data(update, frames, i)
            # Update player info
            elif actor_id in player_info.keys():
                update_player_data(update, frames, i, actor_id)
            # Update game data
            elif actor_id == game_event_num:
                update_game_data(update, frames, i)
            # Update team 0 score
            elif actor_id == team0:
                if 'Engine.TeamInfo:Score' in update:
                    frames[i]['scoreboard']['team0'] = \
                        update['Engine.TeamInfo:Score']
            # Update team 1 score
            elif actor_id == team1:
                if 'Engine.TeamInfo:Score' in update:
                    frames[i]['scoreboard']['team1'] = \
                        update['Engine.TeamInfo:Score']
            else:
                # update car data
                for player_id in current_car_objects:
                    if actor_id == current_car_objects[player_id]:
                        update_car_data(update, frames, i, player_id)

        # Check for deleted actors
        for actor_id in data['Frames'][i]['DeletedActorIds']:
            if actor_id == current_ball_object:
                frames[i]['ball'] = {'loc': {'x': 0, 'y': 0, 'z': 0},
                                     'rot': {'x': 0, 'y': 0, 'z': 0},
                                     'sleep': True}
            else:
                for player_id in current_car_objects:
                    if actor_id == current_car_objects[player_id]:
                        current_car_objects[player_id] = None
                        frames[i]['cars'][player_id]['loc'] = {'x': None,
                                                               'y': None,
                                                               'z': None}
                        frames[i]['cars'][player_id]['rot'] = {'x': 0,
                                                               'y': 0,
                                                               'z': 0}
                        frames[i]['cars'][player_id]['ang_vel'] = {'x': 0,
                                                                   'y': 0,
                                                                   'z': 0}
                        frames[i]['cars'][player_id]['lin_vel'] = {'x': 0,
                                                                   'y': 0,
                                                                   'z': 0}
                        frames[i]['cars'][player_id]['throttle'] = .5
                        frames[i]['cars'][player_id]['steer'] = .5
                        frames[i]['cars'][player_id]['ping'] = 0
                        frames[i]['cars'][player_id]['boost'] = 0
                        frames[i]['cars'][player_id]['boosting'] = False
                        frames[i]['cars'][player_id]['sleep'] = True
                        frames[i]['cars'][player_id]['drift'] = False
                        frames[i]['cars'][player_id]['2nd_cam'] = False
                        frames[i]['cars'][player_id]['driving'] = False

        # Deplete Boost
        for player_id in current_car_objects:
            if frames[i]['cars'][player_id]['boosting']:
                frames[i]['cars'][player_id]['boost'] -= \
                    real_replay_delta * 85 / 255
                frames[i]['cars'][player_id]['boost'] = \
                    max(0, frames[i]['cars'][player_id]['boost'])
<commit_msg>Fix the issue with renders not working due to incorrect times.<commit_after>frames = None

def get_frames():
    global frames
    return frames

def load_frames():
    global frames

    import copy

    from rocketleaguereplayanalysis.data.data_loader import get_data
    from rocketleaguereplayanalysis.data.object_numbers import \
        get_player_info, get_game_event_num, team0, team1
    from rocketleaguereplayanalysis.parser.frame_data import \
        update_game_data, update_car_data, update_player_data, \
        update_ball_data, update_boost_data

    data = get_data()

    current_ball_object = None
    current_car_objects = {}
    current_boost_objects = {}
    player_info = get_player_info()
    game_event_num = get_game_event_num()

    frames = [len(data['Frames'])]
    frames[0] = {
        'time': {
            'replay_time': data['Frames'][0]['Delta'],
            'server_time': data['Frames'][0]['Time'],
            'game_time': 300,
            'game_minutes': int(300 / 60),
            'game_seconds': 300 % 60,
            'replay_delta': data['Frames'][0]['Delta'],
            'server_delta': data['Frames'][0]['Delta'],
            'real_replay_time': 0,
            'real_replay_delta': data['Frames'][0]['Delta']
        },
        'scoreboard': {
            'team0': 0,
            'team1': 0
        },
        'ball': {'loc': {'x': 0, 'y': 0, 'z': 0},
                 'rot': {'x': 0, 'y': 0, 'z': 0},
                 'sleep': True,
                 'last_hit': None},
        'cars': {}
    }

    for player_id in player_info.keys():
        current_car_objects[player_id] = None
        frames[0]['cars'][player_id] = {
            'loc': {'x': None, 'y': None, 'z': None},
            'rot': {'x': 0, 'y': 0, 'z': 0},
            'ang_vel': {'x': 0, 'y': 0, 'z': 0},
            'lin_vel': {'x': 0, 'y': 0, 'z': 0},
            'throttle': .5,
            'steer': .5,
            'ping': 0,
            'boost': 0,
            'boosting': False,
            'sleep': True,
            'drift': False,
            '2nd_cam': False,
            'driving': False,
            'scoreboard': {
                'score': 0,
                'goals': 0,
                'assists': 0,
                'saves': 0,
                'shots': 0
            }
        }

    for i in range(0, len(data['Frames'])):

        if i > 0:
            frames.append(copy.deepcopy(frames[i - 1]))

            server_time = data['Frames'][i]['Time']
            replay_time = (frames[i - 1]['time']['replay_time'] +
                           data['Frames'][i]['Delta'])
            game_time = frames[i - 1]['time']['game_time']
            server_delta = (data['Frames'][i]['Time'] -
                            data['Frames'][i - 1]['Time'])
            replay_delta = data['Frames'][i]['Delta']
        else:
            server_time = data['Frames'][0]['Time']
            replay_time = data['Frames'][0]['Delta']
            game_time = 300
            server_delta = data['Frames'][0]['Delta']
            replay_delta = data['Frames'][0]['Delta']

        if replay_delta == 0:
            # There seems to have been a goal here.
            real_replay_delta = replay_delta
            real_replay_time = (frames[i]['time']['real_replay_time'] +
                                replay_delta)
        else:
            real_replay_delta = server_delta
            real_replay_time = (frames[i]['time']['real_replay_time'] +
                                server_delta)

        frames[i]['time'] = {
            'replay_time': replay_time,
            'server_time': server_time,
            'game_time': game_time,
            'game_minutes': int(game_time / 60),
            'game_seconds': game_time % 60,
            'replay_delta': replay_delta,
            'server_delta': server_delta,
            'real_replay_time': real_replay_time,
            'real_replay_delta': real_replay_delta
        }

        for update in data['Frames'][i]['ActorUpdates']:
            actor_id = update['Id']

            # Update ball object number
            if 'ClassName' in update and \
                    ('TAGame.Ball_TA' in update['ClassName']):
                current_ball_object = actor_id

            # Update car numbers
            if 'ClassName' in update and \
                    ('TAGame.Car_TA' in update['ClassName']):
                player = update['Engine.Pawn:PlayerReplicationInfo']['ActorId']
                current_car_objects[player] = update['Id']

            update_boost_data(update, frames, current_car_objects,
                              current_boost_objects, i)

            # Update ball data
            if actor_id == current_ball_object:
                update_ball_data(update, frames, i)
            # Update player info
            elif actor_id in player_info.keys():
                update_player_data(update, frames, i, actor_id)
            # Update game data
            elif actor_id == game_event_num:
                update_game_data(update, frames, i)
            # Update team 0 score
            elif actor_id == team0:
                if 'Engine.TeamInfo:Score' in update:
                    frames[i]['scoreboard']['team0'] = \
                        update['Engine.TeamInfo:Score']
            # Update team 1 score
            elif actor_id == team1:
                if 'Engine.TeamInfo:Score' in update:
                    frames[i]['scoreboard']['team1'] = \
                        update['Engine.TeamInfo:Score']
            else:
                # update car data
                for player_id in current_car_objects:
                    if actor_id == current_car_objects[player_id]:
                        update_car_data(update, frames, i, player_id)

        # Check for deleted actors
        for actor_id in data['Frames'][i]['DeletedActorIds']:
            if actor_id == current_ball_object:
                frames[i]['ball'] = {'loc': {'x': 0, 'y': 0, 'z': 0},
                                     'rot': {'x': 0, 'y': 0, 'z': 0},
                                     'sleep': True}
            else:
                for player_id in current_car_objects:
                    if actor_id == current_car_objects[player_id]:
                        current_car_objects[player_id] = None
                        frames[i]['cars'][player_id]['loc'] = {'x': None,
                                                               'y': None,
                                                               'z': None}
                        frames[i]['cars'][player_id]['rot'] = {'x': 0,
                                                               'y': 0,
                                                               'z': 0}
                        frames[i]['cars'][player_id]['ang_vel'] = {'x': 0,
                                                                   'y': 0,
                                                                   'z': 0}
                        frames[i]['cars'][player_id]['lin_vel'] = {'x': 0,
                                                                   'y': 0,
                                                                   'z': 0}
                        frames[i]['cars'][player_id]['throttle'] = .5
                        frames[i]['cars'][player_id]['steer'] = .5
                        frames[i]['cars'][player_id]['ping'] = 0
                        frames[i]['cars'][player_id]['boost'] = 0
                        frames[i]['cars'][player_id]['boosting'] = False
                        frames[i]['cars'][player_id]['sleep'] = True
                        frames[i]['cars'][player_id]['drift'] = False
                        frames[i]['cars'][player_id]['2nd_cam'] = False
                        frames[i]['cars'][player_id]['driving'] = False

        # Deplete Boost
        for player_id in current_car_objects:
            if frames[i]['cars'][player_id]['boosting']:
                frames[i]['cars'][player_id]['boost'] -= \
                    real_replay_delta * 85 / 255
                frames[i]['cars'][player_id]['boost'] = \
                    max(0, frames[i]['cars'][player_id]['boost'])
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2012, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from openquake.engine.db import routers
from openquake.engine.db import models as oq

class OQRouterTestCase(unittest.TestCase):
    '''
    Tests for the :py:class:`openquake.engine.db.routers.OQRouter` class.
    '''
    def setUp(self):
        self.router = routers.OQRouter()

    def _db_for_read_helper(self, classes, expected_db):
        '''
        Common test logic
        '''
        for cls in classes:
            self.assertEqual(expected_db, self.router.db_for_read(cls()))

    def _db_for_write_helper(self, classes, expected_db):
        '''
        Common test logic
        '''
        for cls in classes:
            self.assertEqual(expected_db, self.router.db_for_write(cls()))

    def test_admin_correct_read_db(self):
        '''
        For each model in the 'admin' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.Organization, oq.OqUser, oq.RevisionInfo]
        expected_db = 'admin'

        self._db_for_read_helper(classes, expected_db)

    def test_admin_correct_write_db(self):
        '''
        For each model in the 'admin' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.Organization, oq.OqUser, oq.RevisionInfo]
        expected_db = 'admin'

        self._db_for_write_helper(classes, expected_db)

    def test_hzrdi_read_schema(self):
        '''
        For each model in the 'hzrdi' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.ParsedSource, oq.SiteModel]
        expected_db = 'job_init'

        self._db_for_read_helper(classes, expected_db)

    def test_hzrdi_write_schema(self):
        '''
        For each model in the 'hzrdi' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.ParsedSource, oq.SiteModel]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)

    def test_uiapi_read_schema(self):
        '''
        For each model in the 'uiapi' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.Input, oq.OqJob, oq.Output, oq.ErrorMsg]
        expected_db = 'job_init'

        self._db_for_read_helper(classes, expected_db)

    def test_uiapi_write_schema(self):
        '''
        For each model in the 'uiapi' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.Input, oq.OqJob, oq.ErrorMsg]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)
        self._db_for_write_helper([oq.Output], 'reslt_writer')

    def test_hzrdr_read_schema(self):
        '''
        For each model in the 'hzrdr' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.HazardMap, oq.HazardCurve, oq.HazardCurveData,
                   oq.GmfData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_hzrdr_write_schema(self):
        '''
        For each model in the 'hzrdr' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.HazardMap, oq.HazardCurve, oq.HazardCurveData,
                   oq.GmfData]

        expected_db = 'reslt_writer'

        self._db_for_write_helper(classes, expected_db)

    def test_riskr_read_schema(self):
        '''
        For each model in the 'riskr' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.LossMap, oq.LossMapData, oq.LossCurve, oq.LossCurveData,
                   oq.AggregateLossCurveData, oq.BCRDistribution,
                   oq.BCRDistributionData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_riskr_write_schema(self):
        '''
        For each model in the 'riskr' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.LossMap, oq.LossMapData, oq.LossCurve, oq.LossCurveData,
                   oq.AggregateLossCurveData, oq.BCRDistribution,
                   oq.BCRDistributionData]
        expected_db = 'reslt_writer'

        self._db_for_write_helper(classes, expected_db)

    def test_oqmif_correct_read_db(self):
        '''
        For each model in the 'oqmif' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.ExposureModel, oq.ExposureData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_oqmif_correct_write_db(self):
        '''
        For each model in the 'oqmif' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.ExposureModel, oq.ExposureData]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)
<commit_msg>tests/db/routers_test:<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2012, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from openquake.engine.db import routers
from openquake.engine.db import models as oq

class OQRouterTestCase(unittest.TestCase):
    '''
    Tests for the :py:class:`openquake.engine.db.routers.OQRouter` class.
    '''
    def setUp(self):
        self.router = routers.OQRouter()

    def _db_for_read_helper(self, classes, expected_db):
        '''
        Common test logic
        '''
        for cls in classes:
            self.assertEqual(expected_db, self.router.db_for_read(cls()))

    def _db_for_write_helper(self, classes, expected_db):
        '''
        Common test logic
        '''
        for cls in classes:
            self.assertEqual(expected_db, self.router.db_for_write(cls()))

    def test_admin_correct_read_db(self):
        '''
        For each model in the 'admin' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.Organization, oq.OqUser, oq.RevisionInfo]
        expected_db = 'admin'

        self._db_for_read_helper(classes, expected_db)

    def test_admin_correct_write_db(self):
        '''
        For each model in the 'admin' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.Organization, oq.OqUser, oq.RevisionInfo]
        expected_db = 'admin'

        self._db_for_write_helper(classes, expected_db)

    def test_hzrdi_read_schema(self):
        '''
        For each model in the 'hzrdi' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.ParsedSource, oq.SiteModel]
        expected_db = 'job_init'

        self._db_for_read_helper(classes, expected_db)

    def test_hzrdi_write_schema(self):
        '''
        For each model in the 'hzrdi' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.ParsedSource, oq.SiteModel]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)

    def test_uiapi_read_schema(self):
        '''
        For each model in the 'uiapi' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.Input, oq.OqJob, oq.Output, oq.ErrorMsg]
        expected_db = 'job_init'

        self._db_for_read_helper(classes, expected_db)

    def test_uiapi_write_schema(self):
        '''
        For each model in the 'uiapi' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.Input, oq.OqJob, oq.ErrorMsg]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)
        self._db_for_write_helper([oq.Output], 'reslt_writer')

    def test_hzrdr_read_schema(self):
        '''
        For each model in the 'hzrdr' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.HazardMap, oq.HazardCurve, oq.HazardCurveData,
                   oq.GmfData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_hzrdr_write_schema(self):
        '''
        For each model in the 'hzrdr' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.HazardMap, oq.HazardCurve, oq.HazardCurveData,
                   oq.GmfData]

        expected_db = 'reslt_writer'

        self._db_for_write_helper(classes, expected_db)

    def test_riskr_read_schema(self):
        '''
        For each model in the 'riskr' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.LossMap, oq.LossMapData, oq.LossCurve, oq.LossCurveData,
                   oq.AggregateLossCurveData, oq.BCRDistribution,
                   oq.BCRDistributionData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_riskr_write_schema(self):
        '''
        For each model in the 'riskr' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.LossMap, oq.LossMapData, oq.LossCurve, oq.LossCurveData,
                   oq.AggregateLossCurveData, oq.BCRDistribution,
                   oq.BCRDistributionData]
        expected_db = 'reslt_writer'

        self._db_for_write_helper(classes, expected_db)

    def test_riski_correct_read_db(self):
        '''
        For each model in the 'riski' schema, test for proper db routing
        for read operations.
        '''
        classes = [oq.ExposureModel, oq.ExposureData]
        expected_db = 'reslt_writer'

        self._db_for_read_helper(classes, expected_db)

    def test_riski_correct_write_db(self):
        '''
        For each model in the 'riski' schema, test for proper db routing
        for write operations.
        '''
        classes = [oq.ExposureModel, oq.ExposureData]
        expected_db = 'job_init'

        self._db_for_write_helper(classes, expected_db)
<|endoftext|>


<commit_before>#!/bin/env python

#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================

"""
forcefield_utils.py

Utilities relating to OpenMM ForceField replacement using SMIRKS-based matching.

AUTHORS

David L. Mobley <dmobley@mobleylab.org>

Based loosely on code from github.com/choderalab/openmoltools, and especially
parts from John Chodera and Kyle Beauchamp.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================

import os
import smarty
from smarty import ForceField
from smarty.forcefield_labeler import ForceField_labeler
from smarty.utils import get_data_filename
import simtk.openmm
from simtk.openmm import app
import simtk.openmm as mm
from simtk.openmm.app import element as elem
from simtk.openmm.app import Topology
import numpy as np
from openmoltools import system_checker
import copy

import openeye.oechem
import openeye.oeomega
import openeye.oequacpac
from openeye import oechem

from simtk import openmm, unit

#=============================================================================
# UTILITY FUNCTIONS
#=============================================================================

def create_system_from_amber( prmtop_filename, crd_filename, verbose = False ):
    """Utility function. Create and return an OpenMM System given a prmtop and
       crd, AMBER format files.

    Parameters
    ----------
    prmtop_filename : str (filename)
        Filename of input AMBER format prmtop file
    crd_filename : str (filename)
        Filename of input AMBER format crd file

    Returns
    _______
    topology : OpenMM Topology
    system : OpenMM System
    positions : initial atomic positions (OpenMM)
"""

    # Create System object
    prmtop = app.AmberPrmtopFile(prmtop_filename)
    topology = prmtop.topology
    system = prmtop.createSystem(nonbondedMethod = app.NoCutoff, constraints = None, implicitSolvent = None )

    # Read coordinates
    crd = app.AmberInpcrdFile( crd_filename )
    positions = crd.getPositions()

    return (topology, system, positions)

def create_system_from_molecule(forcefield, mol, verbose=False):
    """
    Generate a System from the given OEMol and SMIRFF forcefield, return the resulting System.

    Parameters
    ----------
    forcefield : smarty.ForceField
        SMIRFF forcefield
    mol : oechem.OEMol
        Molecule to test (must have coordinates)

    Returns
    ----------
    topology : OpenMM Topology
    system : OpenMM System
    positions : initial atomic positions (OpenMM)
    """
    # Create system
    from smarty.forcefield import generateTopologyFromOEMol
    topology = generateTopologyFromOEMol(mol)
    system = forcefield.createSystem(topology, [mol], verbose=verbose)

    # Get positions
    coordinates = mol.GetCoords()
    natoms = len(coordinates)
    positions = np.zeros([natoms,3], np.float32)
    for index in range(natoms):
        (x,y,z) = coordinates[index]
        positions[index,0] = x
        positions[index,1] = y
        positions[index,2] = z
    positions = unit.Quantity(positions, unit.angstroms)

    return topology, system, positions

def compare_system_energies( topology0, topology1, system0, system1, positions0, positions1=None, label0="AMBER system", label1 = "SMIRFF system", verbose = True ):
    """
    Given two OpenMM systems, check that their energies and component-wise
    energies are consistent, and return these. The same positions will be used
    for both systems unless a second set of positions is provided.

    Parameters
    ----------
    topology0 : OpenMM Topology
        Topology of first system
    topology1 : OpenMM Topology
        Topology of second system
    system0 : OpenMM System
        First system for comparison (usually from AMBER)
    system1 : OpenMM System
        Second system for comparison (usually from SMIRFF)
    positions0 : simtk.unit.Quantity wrapped
        Positions to use for energy evaluation comparison
    positions1 (optional) : simtk.unit.Quantity wrapped (optional)
        Positions to use for second OpenMM system; original positions are used
        if this is not provided
    label0 (optional) : str
        String labeling system0 for output. Default, "AMBER system"
    label1 (optional) : str
        String labeling system1 for output. Default, "SMIRFF system"
    verbose (optional) : bool
        Print out info on energies, True/False (default True)

    Returns
    ----------
        groups0 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the first simulation object
        groups1 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the second simulation object
        energy0 : simtk.unit.Quantity
            Energy of first system
        energy1 : simtk.unit.Quantity
            Energy of second system

    TO DO:
        Allow energy extraction/comparison of terms specified by particular
        SMARTS queries i.e. for specific bond, angle, or torsional terms.
    """

    # Create integrator
    timestep = 1.0 * unit.femtoseconds
    integrator0 = simtk.openmm.VerletIntegrator( timestep )
    integrator1 = simtk.openmm.VerletIntegrator( timestep )

    # Grab second positions
    if positions1 == None:
        positions1 = copy.deepcopy( positions0 )

    # Create simulations
    platform = simtk.openmm.Platform.getPlatformByName("Reference")
    simulation0 = app.Simulation( topology0, system0, integrator0, platform = platform )
    simulation0.context.setPositions(positions0)
    simulation1 = app.Simulation( topology1, system1, integrator1, platform = platform )
    simulation1.context.setPositions(positions1)

    # Print what torsions were found if verbose
    if verbose:
        # Build list of atoms for debugging info
        atoms0 = [ atom for atom in simulation0.topology.atoms() ]
        atoms1 = [ atom for atom in simulation1.topology.atoms() ]
        # Loop over first system and print torsion info
        for force in simulation0.system.getForces():
            if type(force) == mm.PeriodicTorsionForce:
                print("Num (type) \t Num (type) \t Num (type) \t Num (type) \t per \t phase \t k0")
                for k in range(force.getNumTorsions()):
                    i0, i1, i2, i3, per, phase, k0 = force.getTorsionParameters(k)
                    print("%3s (%3s)- %3s (%3s)- \t %s (%3s)- \t %3s (%3s)- \t %f \t %f \t %f " % (i0, atoms0[i0].name, i1, atoms0[i1].name, i2, atoms0[i2].name, i3, atoms0[i3].name, per, phase/unit.degree, k0/unit.kilojoule_per_mole) )
        for force in simulation1.system.getForces():
            if type(force) == mm.PeriodicTorsionForce:
                print("Num (type) \t Num (type) \t Num (type) \t Num (type) \t per \t phase \t k0")
                for k in range(force.getNumTorsions()):
                    i0, i1, i2, i3, per, phase, k0 = force.getTorsionParameters(k)
                    print("%3s (%3s)- %3s (%3s)- %3s (%3s)- %3s (%3s) - %f \t %f \t %f " % (i0, atoms1[i0].name, i1, atoms1[i1].name, i2, atoms1[i2].name, i3, atoms1[i3].name, per, phase/unit.degree, k0/unit.kilojoule_per_mole) )

    # Do energy comparison, print info if desired
    syscheck = system_checker.SystemChecker( simulation0, simulation1 )
    syscheck.check_force_parameters()
    groups0, groups1 = syscheck.check_energy_groups()
    energy0, energy1 = syscheck.check_energies()
    if verbose:
        print("Energy of %s: " % label0, energy0 )
        print("Energy of %s: " % label1, energy1 )
        print("\nComponents of %s:" % label0 )
        for key in groups0.keys():
            print("%s: " % key, groups0[key] )
        print("\nComponents of %s:" % label1 )
        for key in groups1.keys():
            print("%s: " % key, groups1[key] )

    # Return
    return groups0, groups1, energy0, energy1

def compare_molecule_energies( prmtop, crd, forcefield, mol, verbose = True ):
    """
    Compare energies for OpenMM Systems/topologies created from an AMBER prmtop
    and crd versus from a SMIRFF forcefield file and OEMol which should
    parameterize the same system with same parameters.

    Parameters
    ----------
    prmtop_filename : str (filename)
        Filename of input AMBER format prmtop file
    crd_filename : str (filename)
        Filename of input AMBER format crd file
    forcefield : smarty.ForceField
        SMIRFF forcefield
    mol : oechem.OEMol
        Molecule to test
    verbose (optional): Bool
        Print out info. Default: True

    Returns
    --------
        groups0 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the first simulation object
        groups1 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the second simulation object
        energy0 : simtk.unit.Quantity
            Energy of first system
        energy1 : simtk.unit.Quantity
            Energy of second system
    """

    ambertop, ambersys, amberpos = create_system_from_amber( prmtop, crd )
    smirfftop, smirffsys, smirffpos = create_system_from_molecule(forcefield, mol, verbose = verbose)

    groups0, groups1, energy0, energy1 = compare_system_energies( ambertop,
               smirfftop, ambersys, smirffsys, amberpos, verbose = verbose )

    return groups0, groups1, energy0, energy1

def get_molecule_parameterIDs( oemols, ffxml):
    """Process a list of oemols with a specified SMIRFF ffxml file and determine which parameters are used by which molecules, returning collated results.

    Parameters
    ----------
    oemols : list
        List of OpenEye OEChem molecules to parse; must have explicit hydrogens.

    Returns
    -------
    parameters_by_molecule : dict
        Parameter IDs used in each molecule, keyed by isomeric SMILES
        generated from provided OEMols. Each entry in the dict is a list
        which does not necessarily have unique entries; i.e. parameter IDs
        which are used more than once will occur multiple times.

    parameters_by_ID : dict
        Molecules in which each parameter ID occur, keyed by parameter ID.
        Each entry in the dict is a set of isomeric SMILES for molecules
        in which that parameter occurs. No frequency information is stored.

    """

    # Create storage
    parameters_by_molecule = {}
    parameters_by_ID = {}

    # Generate isomeric SMILES
    isosmiles = list()
    for mol in oemols:
        smi = oechem.OECreateIsoSmiString(mol)
        if not smi in isosmiles:
            isosmiles.append(smi)
        # If the molecule is already here, raise exception
        else:
            raise ValueError("Error: get_molecule_parameterIDs has been provided a list of oemols which contains the same molecule, having isomeric smiles %s, more than once." % smi )
    # Label molecules
    labeler = ForceField_labeler( ffxml )
    labels = labeler.labelMolecules( oemols )

    # Organize labels into output dictionary by looping over all molecules/smiles
    for idx in range(len(isosmiles)):
        # Pull smiles, initialize storage
        smi = isosmiles[idx]
        parameters_by_molecule[smi] = []

        # Organize data for this molecule
        data = labels[idx]
        for force_type in data.keys():
            for (atom_indices, pid, smirks) in data[force_type]:
                # Store pid to molecule
                parameters_by_molecule[smi].append(pid)

                # Store which molecule this pid occurred in
                if not parameters_by_ID.has_key( pid ):
                    parameters_by_ID[pid] = set()
                    parameters_by_ID[pid].add(smi)
                else:
                    parameters_by_ID[pid].add(smi)

    return parameters_by_molecule, parameters_by_ID
<commit_msg>Fix yet more non-py3-compliant code<commit_after>#!/bin/env python

#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================

"""
forcefield_utils.py

Utilities relating to OpenMM ForceField replacement using SMIRKS-based matching.

AUTHORS

David L. Mobley <dmobley@mobleylab.org>

Based loosely on code from github.com/choderalab/openmoltools, and especially
parts from John Chodera and Kyle Beauchamp.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================

import os
import smarty
from smarty import ForceField
from smarty.forcefield_labeler import ForceField_labeler
from smarty.utils import get_data_filename
import simtk.openmm
from simtk.openmm import app
import simtk.openmm as mm
from simtk.openmm.app import element as elem
from simtk.openmm.app import Topology
import numpy as np
from openmoltools import system_checker
import copy

import openeye.oechem
import openeye.oeomega
import openeye.oequacpac
from openeye import oechem

from simtk import openmm, unit

#=============================================================================
# UTILITY FUNCTIONS
#=============================================================================

def create_system_from_amber( prmtop_filename, crd_filename, verbose = False ):
    """Utility function. Create and return an OpenMM System given a prmtop and
       crd, AMBER format files.

    Parameters
    ----------
    prmtop_filename : str (filename)
        Filename of input AMBER format prmtop file
    crd_filename : str (filename)
        Filename of input AMBER format crd file

    Returns
    _______
    topology : OpenMM Topology
    system : OpenMM System
    positions : initial atomic positions (OpenMM)
"""

    # Create System object
    prmtop = app.AmberPrmtopFile(prmtop_filename)
    topology = prmtop.topology
    system = prmtop.createSystem(nonbondedMethod = app.NoCutoff, constraints = None, implicitSolvent = None )

    # Read coordinates
    crd = app.AmberInpcrdFile( crd_filename )
    positions = crd.getPositions()

    return (topology, system, positions)

def create_system_from_molecule(forcefield, mol, verbose=False):
    """
    Generate a System from the given OEMol and SMIRFF forcefield, return the resulting System.

    Parameters
    ----------
    forcefield : smarty.ForceField
        SMIRFF forcefield
    mol : oechem.OEMol
        Molecule to test (must have coordinates)

    Returns
    ----------
    topology : OpenMM Topology
    system : OpenMM System
    positions : initial atomic positions (OpenMM)
    """
    # Create system
    from smarty.forcefield import generateTopologyFromOEMol
    topology = generateTopologyFromOEMol(mol)
    system = forcefield.createSystem(topology, [mol], verbose=verbose)

    # Get positions
    coordinates = mol.GetCoords()
    natoms = len(coordinates)
    positions = np.zeros([natoms,3], np.float32)
    for index in range(natoms):
        (x,y,z) = coordinates[index]
        positions[index,0] = x
        positions[index,1] = y
        positions[index,2] = z
    positions = unit.Quantity(positions, unit.angstroms)

    return topology, system, positions

def compare_system_energies( topology0, topology1, system0, system1, positions0, positions1=None, label0="AMBER system", label1 = "SMIRFF system", verbose = True ):
    """
    Given two OpenMM systems, check that their energies and component-wise
    energies are consistent, and return these. The same positions will be used
    for both systems unless a second set of positions is provided.

    Parameters
    ----------
    topology0 : OpenMM Topology
        Topology of first system
    topology1 : OpenMM Topology
        Topology of second system
    system0 : OpenMM System
        First system for comparison (usually from AMBER)
    system1 : OpenMM System
        Second system for comparison (usually from SMIRFF)
    positions0 : simtk.unit.Quantity wrapped
        Positions to use for energy evaluation comparison
    positions1 (optional) : simtk.unit.Quantity wrapped (optional)
        Positions to use for second OpenMM system; original positions are used
        if this is not provided
    label0 (optional) : str
        String labeling system0 for output. Default, "AMBER system"
    label1 (optional) : str
        String labeling system1 for output. Default, "SMIRFF system"
    verbose (optional) : bool
        Print out info on energies, True/False (default True)

    Returns
    ----------
        groups0 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the first simulation object
        groups1 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the second simulation object
        energy0 : simtk.unit.Quantity
            Energy of first system
        energy1 : simtk.unit.Quantity
            Energy of second system

    TO DO:
        Allow energy extraction/comparison of terms specified by particular
        SMARTS queries i.e. for specific bond, angle, or torsional terms.
    """

    # Create integrator
    timestep = 1.0 * unit.femtoseconds
    integrator0 = simtk.openmm.VerletIntegrator( timestep )
    integrator1 = simtk.openmm.VerletIntegrator( timestep )

    # Grab second positions
    if positions1 == None:
        positions1 = copy.deepcopy( positions0 )

    # Create simulations
    platform = simtk.openmm.Platform.getPlatformByName("Reference")
    simulation0 = app.Simulation( topology0, system0, integrator0, platform = platform )
    simulation0.context.setPositions(positions0)
    simulation1 = app.Simulation( topology1, system1, integrator1, platform = platform )
    simulation1.context.setPositions(positions1)

    # Print what torsions were found if verbose
    if verbose:
        # Build list of atoms for debugging info
        atoms0 = [ atom for atom in simulation0.topology.atoms() ]
        atoms1 = [ atom for atom in simulation1.topology.atoms() ]
        # Loop over first system and print torsion info
        for force in simulation0.system.getForces():
            if type(force) == mm.PeriodicTorsionForce:
                print("Num (type) \t Num (type) \t Num (type) \t Num (type) \t per \t phase \t k0")
                for k in range(force.getNumTorsions()):
                    i0, i1, i2, i3, per, phase, k0 = force.getTorsionParameters(k)
                    print("%3s (%3s)- %3s (%3s)- \t %s (%3s)- \t %3s (%3s)- \t %f \t %f \t %f " % (i0, atoms0[i0].name, i1, atoms0[i1].name, i2, atoms0[i2].name, i3, atoms0[i3].name, per, phase/unit.degree, k0/unit.kilojoule_per_mole) )
        for force in simulation1.system.getForces():
            if type(force) == mm.PeriodicTorsionForce:
                print("Num (type) \t Num (type) \t Num (type) \t Num (type) \t per \t phase \t k0")
                for k in range(force.getNumTorsions()):
                    i0, i1, i2, i3, per, phase, k0 = force.getTorsionParameters(k)
                    print("%3s (%3s)- %3s (%3s)- %3s (%3s)- %3s (%3s) - %f \t %f \t %f " % (i0, atoms1[i0].name, i1, atoms1[i1].name, i2, atoms1[i2].name, i3, atoms1[i3].name, per, phase/unit.degree, k0/unit.kilojoule_per_mole) )

    # Do energy comparison, print info if desired
    syscheck = system_checker.SystemChecker( simulation0, simulation1 )
    syscheck.check_force_parameters()
    groups0, groups1 = syscheck.check_energy_groups()
    energy0, energy1 = syscheck.check_energies()
    if verbose:
        print("Energy of %s: " % label0, energy0 )
        print("Energy of %s: " % label1, energy1 )
        print("\nComponents of %s:" % label0 )
        for key in groups0.keys():
            print("%s: " % key, groups0[key] )
        print("\nComponents of %s:" % label1 )
        for key in groups1.keys():
            print("%s: " % key, groups1[key] )

    # Return
    return groups0, groups1, energy0, energy1

def compare_molecule_energies( prmtop, crd, forcefield, mol, verbose = True ):
    """
    Compare energies for OpenMM Systems/topologies created from an AMBER prmtop
    and crd versus from a SMIRFF forcefield file and OEMol which should
    parameterize the same system with same parameters.

    Parameters
    ----------
    prmtop_filename : str (filename)
        Filename of input AMBER format prmtop file
    crd_filename : str (filename)
        Filename of input AMBER format crd file
    forcefield : smarty.ForceField
        SMIRFF forcefield
    mol : oechem.OEMol
        Molecule to test
    verbose (optional): Bool
        Print out info. Default: True

    Returns
    --------
        groups0 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the first simulation object
        groups1 : dict
            As returned by openmoltools.system_checker.check_energy_groups,
            a dictionary with keys "bond", "angle", "nb", "torsion" and values
            corresponding to the energies of these components for the second simulation object
        energy0 : simtk.unit.Quantity
            Energy of first system
        energy1 : simtk.unit.Quantity
            Energy of second system
    """

    ambertop, ambersys, amberpos = create_system_from_amber( prmtop, crd )
    smirfftop, smirffsys, smirffpos = create_system_from_molecule(forcefield, mol, verbose = verbose)

    groups0, groups1, energy0, energy1 = compare_system_energies( ambertop,
               smirfftop, ambersys, smirffsys, amberpos, verbose = verbose )

    return groups0, groups1, energy0, energy1

def get_molecule_parameterIDs( oemols, ffxml):
    """Process a list of oemols with a specified SMIRFF ffxml file and determine which parameters are used by which molecules, returning collated results.

    Parameters
    ----------
    oemols : list
        List of OpenEye OEChem molecules to parse; must have explicit hydrogens.

    Returns
    -------
    parameters_by_molecule : dict
        Parameter IDs used in each molecule, keyed by isomeric SMILES
        generated from provided OEMols. Each entry in the dict is a list
        which does not necessarily have unique entries; i.e. parameter IDs
        which are used more than once will occur multiple times.

    parameters_by_ID : dict
        Molecules in which each parameter ID occur, keyed by parameter ID.
        Each entry in the dict is a set of isomeric SMILES for molecules
        in which that parameter occurs. No frequency information is stored.

    """

    # Create storage
    parameters_by_molecule = {}
    parameters_by_ID = {}

    # Generate isomeric SMILES
    isosmiles = list()
    for mol in oemols:
        smi = oechem.OECreateIsoSmiString(mol)
        if not smi in isosmiles:
            isosmiles.append(smi)
        # If the molecule is already here, raise exception
        else:
            raise ValueError("Error: get_molecule_parameterIDs has been provided a list of oemols which contains the same molecule, having isomeric smiles %s, more than once." % smi )
    # Label molecules
    labeler = ForceField_labeler( ffxml )
    labels = labeler.labelMolecules( oemols )

    # Organize labels into output dictionary by looping over all molecules/smiles
    for idx in range(len(isosmiles)):
        # Pull smiles, initialize storage
        smi = isosmiles[idx]
        parameters_by_molecule[smi] = []

        # Organize data for this molecule
        data = labels[idx]
        for force_type in data.keys():
            for (atom_indices, pid, smirks) in data[force_type]:
                # Store pid to molecule
                parameters_by_molecule[smi].append(pid)

                # Store which molecule this pid occurred in
                if pid not in parameters_by_ID:
                    parameters_by_ID[pid] = set()
                    parameters_by_ID[pid].add(smi)
                else:
                    parameters_by_ID[pid].add(smi)

    return parameters_by_molecule, parameters_by_ID
<|endoftext|>


<commit_before>musketeersName = 'Tom Dick Harry'
print 'Three musketeers are', musketeersName

musketeer_1 = musketeersName[0:3]
print 'First musketeer :', musketeer_1

musketeer_2 = musketeersName[4:8]
print 'Second musketeer :', musketeer_2

musketeer_3 = musketeersName[9:14]

print 'Third musketeer :', musketeer_3
print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n"
musketeer_3 = musketeersName[9:20]
print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3

print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n"

firstTwoChars = musketeersName[:2]
print 'First Two characters of the string :', firstTwoChars

lastTwoChars = musketeersName[12:]
print 'First Two characters of the string :', lastTwoChars

allChars = musketeersName[:]
print 'All characters of the string :', allChars
<commit_msg>Update the put put text<commit_after>musketeersName = 'Tom Dick Harry'
print 'Three musketeers are', musketeersName

musketeer_1 = musketeersName[0:3]
print 'First musketeer :', musketeer_1

musketeer_2 = musketeersName[4:8]
print 'Second musketeer :', musketeer_2

musketeer_3 = musketeersName[9:14]

print 'Third musketeer :', musketeer_3
print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n"
musketeer_3 = musketeersName[9:20]
print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3

print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n"

firstTwoChars = musketeersName[:2]
print 'First Two characters of the string :', firstTwoChars

lastTwoChars = musketeersName[12:]
print 'Last Two characters of the string :', lastTwoChars

allChars = musketeersName[:]
print 'All characters of the string :', allChars
<|endoftext|>