<commit_before>import h5py
import matplotlib.pyplot as plt
import numpy as np
import os
import os.path
import tensorflow as tf
from keras.callbacks import ModelCheckpoint

from keras.layers.normalization import BatchNormalization
from keras.backend import floatx
from keras.layers import Conv2D, Conv3D, Dense, Dropout
from keras.layers.core import Flatten
from keras.models import load_model, Sequential
from keras import optimizers
from scipy import io, signal
from sys import argv, exit

tf.logging.set_verbosity(tf.logging.WARN)
tf.logging.set_verbosity(tf.logging.INFO)
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

######################################################

def main():

	# file names to change as necessary
	model_file = 'model_100k_specA2.h5'
	sets_file = '100k_data2_sets.h5'
  #sets_file = 'sets_ball_specA.h5'

	if os.path.isfile(model_file):
		print "loading model..."
		path = os.getcwd()+'/'
		with h5py.File(path+sets_file, 'r') as sets:
			x_test = normalize(sets['test_specs'][:])
			y_test = np.log(1+sets['test_depths'][:].reshape(-1, 192))
		model = load_model(model_file, custom_objects={'adjusted_mse':adjusted_mse})
                model.summary()
	else:
		print "building model..."
		path = os.getcwd()+'/'
		with h5py.File(path+sets_file, 'r') as sets:
			x_train = normalize(sets['train_specs'][:])
			y_train = np.log(1+sets['train_depths'][:].reshape(-1, 192))

			indices = np.random.permutation(x_train.shape[0])
			np.take(x_train,indices,axis=0,out=x_train)
			np.take(y_train,indices,axis=0,out=y_train)

			x_test = normalize(sets['test_specs'][:])
			y_test = np.log(1+sets['test_depths'][:].reshape(-1, 192))
		model = build_and_train_model(x_train, y_train, model_file)
                model.summary()

	loss = run_model(model, x_test, y_test)

######################################################
######################################################

def build_and_train_model(x_train, y_train, model_file):
	net = Sequential()
	net.add(Conv2D(128, (5,5),
			strides=(1,1),
			activation='relu',
			data_format='channels_last',
			input_shape=x_train.shape[1:]))
	net.add(BatchNormalization())
	net.add(Conv2D(128, (5,5), strides=(2,2), activation='relu'))
	net.add(BatchNormalization())
	net.add(Conv2D(32, (3,3), strides=(1,1), activation='relu'))
	net.add(Flatten())
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(192, activation='linear'))
	net.compile(optimizer='adam', loss=adjusted_mse)
	print "finished compiling"

	# checkpoint
	filepath= model_file[:-3] + '.{epoch:02d}.h5'
	checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=0, save_best_only=False,save_weights_only=False, mode='auto', period=25)
	callbacks_list=[checkpoint]

	hist = net.fit(x_train, y_train, validation_split=0.1, epochs=100, batch_size=64, callbacks=callbacks_list)

	with h5py.File(model_file[:-3]+'_loss_history.h5', 'w') as lh:
		lh.create_dataset('losses', data=hist.history['loss'])
		print "loss history saved as '"+model_file[:-3]+"_loss_history.h5'"
	net.save(model_file)
	print "model saved as '%s'" %model_file
	return net

######################################################

def run_model(net, x_test, y_test):
	loss = net.evaluate(x_test, y_test)
	print "\nLOSS:", loss
	predictions = net.predict(x_test)
	view_average_error(np.exp(y_test)-1, np.exp(predictions)-1)
	for i in range(100, 2000, 110):
		view_depth_maps(100, net, np.exp(y_test)-1, np.exp(predictions)-1)

#####################################################

def adjusted_mse(y_true, y_pred):
	ok_entries = np.all(y_true)
	ok_entries = tf.cast(ok_entries, bool)
	safe_targets = tf.where(ok_entries, y_true, y_pred)
	sqr = tf.square(y_pred - safe_targets)
	valid = tf.cast(ok_entries, floatx())
	num_ok = tf.reduce_sum(valid, axis=-1) # count OK entries
	num_ok = tf.maximum(num_ok, tf.ones_like(num_ok)) # avoid divide by zero
	return tf.reduce_sum(sqr, axis=-1) / num_ok

#####################################################

def view_average_error(ytrue, ypred):
	error = np.reshape(ypred-ytrue, (-1,12,16))
	avg_error = np.mean(error, axis=0)
	stdev = np.std(avg_error)
	avg_val = np.mean(avg_error)
	rng = (avg_val-(3*stdev), avg_val+(3*stdev))
	error_map = plt.imshow(avg_error, clim=rng, cmap="Greys", interpolation='none')
	plt.title("Absolute Average Error")
	plt.show()

####################################################

def view_depth_maps(index, model, ytrue, ypred):
	all_error = ypred-ytrue
	avg_error = np.mean(all_error)
	stdev = np.std(all_error)
	rng = (avg_error-(3*stdev), avg_error+(3*stdev))
	for i in range(0, ytrue.shape[0], 50):
		for j in range(10):
			index = i  + j
			true = np.reshape(ytrue[index], (12,16))
			pred = np.reshape(ypred[index], (12,16))
			error = pred - true

			ax1 = plt.subplot(10,3,j*3 + 1)
			true_map = plt.imshow(true, clim=(500, 2000), interpolation='none')
			ax1.set_title("True Depth")

			ax2 = plt.subplot(10,3,j*3 + 2)
			pred_map = plt.imshow(pred, clim=(500, 2000), interpolation='none')
			ax2.set_title("Predicted Depth")

			ax3 = plt.subplot(10,3,j*3 + 3)
			error_map = plt.imshow(error, clim=rng, cmap="Greys", interpolation='none')
			ax3.set_title("Squared Error Map")

		plt.show()

####################################################

def normalize(x_set):
	log = np.log(1+x_set)
	minX = np.min(log)
	maxX = np.max(log)
	diff = float(maxX-minX)
	norm = ((log-minX)/diff)-0.5
	return norm

####################################################

main()

####################################################
####################################################
'''x1 = np.reshape(x[index+800], (29,178))
true1 = np.reshape(ytrue[index+800], (12,16))
pred1 = np.reshape(ypred[index+800], (12,16))
x2 = np.reshape(x[index+600], (29,178))
true2 = np.reshape(ytrue[index+600], (12,16))
pred2 = np.reshape(ypred[index+600], (12,16))
x3 = np.reshape(x[index+1900], (29,178))
true3 = np.reshape(ytrue[index+1900], (12,16))
pred3 = np.reshape(ypred[index+1900], (12,16))

ax1 = plt.subplot(3,3,1)
true_map1 = plt.imshow(x1)
ax1.set_title("Spectrogram 1")

ax2 = plt.subplot(3,3,2)
true_map1 = plt.imshow(true1, clim=(500,4000), interpolation='none')
ax2.set_title("True Depth 1")

ax3 = plt.subplot(3,3,3)
true_map1 = plt.imshow(pred1, clim=(500,4000), interpolation='none')
ax3.set_title("Predicted Depth 1")

ax4 = plt.subplot(3,3,4)
pred_map1 = plt.imshow(x2)
ax4.set_title("Spectrogram 2")

ax5 = plt.subplot(3,3,5)
true_map2 = plt.imshow(true2, clim=(500,4000), interpolation='none')
ax5.set_title("True Depth 2")

ax6 = plt.subplot(3,3,6)
pred_map2 = plt.imshow(pred2, clim=(500,4000), interpolation='none')
ax6.set_title("Predicted Depth 2")

ax7 = plt.subplot(3,3,7)
true_map3 = plt.imshow(x3)
ax7.set_title("Spectrogram 3")

ax8 = plt.subplot(3,3,8)
pred_map3 = plt.imshow(true3, clim=(500,4000), interpolation='none')
ax8.set_title("True Depth 3")

ax9 = plt.subplot(3,3,9)
true_map1 = plt.imshow(pred3, clim=(500,4000), interpolation='none')
ax9.set_title("Predicted Depth 3")

plt.show()'''
<commit_msg>divide by 20<commit_after>import h5py
import matplotlib.pyplot as plt
import numpy as np
import os
import os.path
import tensorflow as tf
from keras.callbacks import ModelCheckpoint

from keras.layers.normalization import BatchNormalization
from keras.backend import floatx
from keras.layers import Conv2D, Conv3D, Dense, Dropout
from keras.layers.core import Flatten
from keras.models import load_model, Sequential
from keras import optimizers
from scipy import io, signal
from sys import argv, exit

tf.logging.set_verbosity(tf.logging.WARN)
tf.logging.set_verbosity(tf.logging.INFO)
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

######################################################

def main():

	# file names to change as necessary
	model_file = 'model_100k_specA2X.h5'
	sets_file = '100k_data2_sets.h5'
  #sets_file = 'sets_ball_specA.h5'

	if os.path.isfile(model_file):
		print "loading model..."
		path = os.getcwd()+'/'
		with h5py.File(path+sets_file, 'r') as sets:
			x_test = (sets['test_specs'][:])/20 - 0.5
			y_test = np.log(1+sets['test_depths'][:].reshape(-1, 192))
		model = load_model(model_file, custom_objects={'adjusted_mse':adjusted_mse})
                model.summary()
	else:
		print "building model..."
		path = os.getcwd()+'/'
		with h5py.File(path+sets_file, 'r') as sets:
			x_train = (sets['train_specs'][:])/20 - 0.5
			y_train = np.log(1+sets['train_depths'][:].reshape(-1, 192))

			indices = np.random.permutation(x_train.shape[0])
			np.take(x_train,indices,axis=0,out=x_train)
			np.take(y_train,indices,axis=0,out=y_train)

			x_test = (sets['test_specs'][:])/20 - 0.5
			y_test = np.log(1+sets['test_depths'][:].reshape(-1, 192))
		model = build_and_train_model(x_train, y_train, model_file)
                model.summary()

	loss = run_model(model, x_test, y_test)

######################################################
######################################################

def build_and_train_model(x_train, y_train, model_file):
	net = Sequential()
	net.add(Conv2D(128, (5,5),
			strides=(1,1),
			activation='relu',
			data_format='channels_last',
			input_shape=x_train.shape[1:]))
	net.add(BatchNormalization())
	net.add(Conv2D(128, (5,5), strides=(2,2), activation='relu'))
	net.add(BatchNormalization())
	net.add(Conv2D(32, (3,3), strides=(1,1), activation='relu'))
	net.add(Flatten())
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(600, activation='relu'))
	net.add(BatchNormalization())
	net.add(Dense(192, activation='linear'))
	net.compile(optimizer='adam', loss=adjusted_mse)
	print "finished compiling"

	# checkpoint
	filepath= model_file[:-3] + '.{epoch:02d}.h5'
	checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=0, save_best_only=False,save_weights_only=False, mode='auto', period=25)
	callbacks_list=[checkpoint]

	hist = net.fit(x_train, y_train, validation_split=0.1, epochs=100, batch_size=64, callbacks=callbacks_list)

	with h5py.File(model_file[:-3]+'_loss_history.h5', 'w') as lh:
		lh.create_dataset('losses', data=hist.history['loss'])
		print "loss history saved as '"+model_file[:-3]+"_loss_history.h5'"
	net.save(model_file)
	print "model saved as '%s'" %model_file
	return net

######################################################

def run_model(net, x_test, y_test):
	loss = net.evaluate(x_test, y_test)
	print "\nLOSS:", loss
	predictions = net.predict(x_test)
	view_average_error(np.exp(y_test)-1, np.exp(predictions)-1)
	for i in range(100, 2000, 110):
		view_depth_maps(100, net, np.exp(y_test)-1, np.exp(predictions)-1)

#####################################################

def adjusted_mse(y_true, y_pred):
	ok_entries = np.all(y_true)
	ok_entries = tf.cast(ok_entries, bool)
	safe_targets = tf.where(ok_entries, y_true, y_pred)
	sqr = tf.square(y_pred - safe_targets)
	valid = tf.cast(ok_entries, floatx())
	num_ok = tf.reduce_sum(valid, axis=-1) # count OK entries
	num_ok = tf.maximum(num_ok, tf.ones_like(num_ok)) # avoid divide by zero
	return tf.reduce_sum(sqr, axis=-1) / num_ok

#####################################################
def view_average_error(ytrue, ypred):
	error = np.reshape(ypred-ytrue, (-1,12,16))
	avg_error = np.mean(error, axis=0)
	stdev = np.std(avg_error)
	avg_val = np.mean(avg_error)
	rng = (avg_val-(3*stdev), avg_val+(3*stdev))
	error_map = plt.imshow(avg_error, clim=rng, cmap="Greys", interpolation='none')
	plt.title("Absolute Average Error")
	plt.show()

####################################################

def view_depth_maps(index, model, ytrue, ypred):
	all_error = ypred-ytrue
	avg_error = np.mean(all_error)
	stdev = np.std(all_error)
	rng = (avg_error-(3*stdev), avg_error+(3*stdev))
	for i in range(0, ytrue.shape[0], 50):
		for j in range(10):
			index = i  + j
			true = np.reshape(ytrue[index], (12,16))
			pred = np.reshape(ypred[index], (12,16))
			error = pred - true

			ax1 = plt.subplot(10,3,j*3 + 1)
			true_map = plt.imshow(true, clim=(500, 2000), interpolation='none')
			ax1.set_title("True Depth")

			ax2 = plt.subplot(10,3,j*3 + 2)
			pred_map = plt.imshow(pred, clim=(500, 2000), interpolation='none')
			ax2.set_title("Predicted Depth")

			ax3 = plt.subplot(10,3,j*3 + 3)
			error_map = plt.imshow(error, clim=rng, cmap="Greys", interpolation='none')
			ax3.set_title("Squared Error Map")

		plt.show()

####################################################

def normalize(x_set):
	log = np.log(1+x_set)
	minX = np.min(log)
	maxX = np.max(log)
	diff = float(maxX-minX)
	norm = ((log-minX)/diff)-0.5
	return norm

####################################################

main()
<|endoftext|>


<commit_before>"""
SOAP Service Resource for OpenNSA.

Author: Henrik Thostrup Jensen <htj@nordu.net>
Copyright: NORDUnet (2011-2016)
"""

from twisted.python import log
from twisted.internet import defer
from twisted.web import resource, server

from opennsa.shared.requestinfo import RequestInfo
from opennsa.protocols.shared import minisoap

LOG_SYSTEM = 'protocol.SOAPResource'

class SOAPFault(Exception):

    def __init__(self, fault_string, detail_element=None):
        self.fault_string = fault_string
        self.detail_element = detail_element

    def createPayload(self):

        return minisoap.createSoapFault(self.fault_string, self.detail_element)

class SOAPResource(resource.Resource):

    isLeaf = True

    def __init__(self, allowed_hosts=None):
        resource.Resource.__init__(self)
        self.soap_actions = {}
        self.allowed_hosts = allowed_hosts # certificate dns

    def registerDecoder(self, soap_action, decoder):

        self.soap_actions[soap_action] = decoder

    def render_POST(self, request):

        if self.allowed_hosts is not None:
            if not request.isSecure():
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, not secure (no ssl/tls)', system=LOG_SYSTEM)
                return 'Insecure requests not allowed for this resource\r\n'

            cert = request.transport.getPeerCertificate()
            if not cert:
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, no client certificate presented', system=LOG_SYSTEM)
                return 'Requests without client certificate not allowed\r\n'

            cert_subject = cert.get_subject()
            log.msg('Certificate subject %s' % cert.get_subject(), system=LOG_SYSTEM)
            host_dn = cert.get_subject().get_components()[-1][1]
            log.msg('Host DN: %s' % host_dn, system=LOG_SYSTEM)

            if not host_dn in self.allowed_hosts:
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, certificate host dn does not match allowed hosts', system=LOG_SYSTEM)
                return 'Requests without certificate not allowed\r\n'

            request_info = RequestInfo(str(cert_subject), host_dn)

        elif request.isSecure():
            # log certificate subject
            cert = request.transport.getPeerCertificate()
            if cert:
                log.msg('Certificate subject %s' % cert.get_subject(), system=LOG_SYSTEM)

            host_dn = cert.get_subject().get_components()[-1][1]
            request_info = RequestInfo(str(cert.get_subject()), host_dn)

        else:
            request_info = RequestInfo()

        soap_action = request.requestHeaders.getRawHeaders('soapaction',[None])[0]

        soap_data = request.content.read()
        log.msg(' -- Received payload --', system=LOG_SYSTEM, payload=True)
        log.msg(soap_data, system=LOG_SYSTEM, payload=True)
        log.msg(' -- END --', system=LOG_SYSTEM, payload=True)

        if not soap_action in self.soap_actions:
            log.msg('Got request with unknown SOAP action: %s' % soap_action, system=LOG_SYSTEM)
            request.setResponseCode(406) # Not acceptable
            return 'Invalid SOAP Action for this resource\r\n'

        log.msg('Received SOAP request. Action: %s. Length: %i' % (soap_action, len(soap_data)), system=LOG_SYSTEM, debug=True)

        def reply(reply_data):

            if type(reply_data) is SOAPFault:
                reply_data = reply_data.createPayload()
                request.setResponseCode(500) # Internal server error

            if reply_data is None or len(reply_data) == 0:
                log.msg('None/empty reply data supplied for SOAPResource. This is probably wrong', system=LOG_SYSTEM)
            else:
                log.msg(' -- Sending response --', system=LOG_SYSTEM, payload=True)
                log.msg(reply_data, system=LOG_SYSTEM, payload=True)
                log.msg('-- END --', system=LOG_SYSTEM, payload=True)

            request.setHeader('Content-Type', 'text/xml') # Keeps some SOAP implementations happy
            request.write(reply_data)
            request.finish()

        def errorReply(err, soap_data):

            log.msg('Failure during SOAP decoding/dispatch: %s' % err.getErrorMessage(), system=LOG_SYSTEM)
            log.err(err)
            log.msg('SOAP Payload that caused error:')
            log.msg(soap_data)
            error_payload = SOAPFault(err.getErrorMessage()).createPayload()

            log.msg(" -- Sending response (fault) --\n%s\n -- END: Sending response (fault) --" % error_payload, system=LOG_SYSTEM, payload=True)

            request.setResponseCode(500) # Internal server error
            request.setHeader('Content-Type', 'text/xml')
            request.write(error_payload)
            request.finish()

        decoder = self.soap_actions[soap_action]
        d = defer.maybeDeferred(decoder, soap_data, request_info)
        d.addCallbacks(reply, errorReply, errbackArgs=(soap_data,))

        return server.NOT_DONE_YET

def setupSOAPResource(top_resource, resource_name, subpath=None, allowed_hosts=None):

    assert type(resource_name) is bytes, 'Resource name must be bytes'
    if subpath is not None:
        for sp in subpath:
            assert type(sp) is bytes, 'Subpath must by of type bytes'

    # Default path: NSI/services/{resource_name}
    if subpath is None:
        subpath = [b'NSI', b'services' ]

    ir = top_resource

    for path in subpath:
        if path in ir.children:
            ir = ir.children[path]
        else:
            nr = resource.Resource()
            ir.putChild(path, nr)
            ir = nr

    if resource_name in ir.children:
        raise AssertionError('Cannot insert several SOAP resources in same leaf.')

    soap_resource = SOAPResource(allowed_hosts=allowed_hosts)
    ir.putChild(resource_name, soap_resource)
    return soap_resource

<commit_msg>slightly better error message if clashing soap resources occur<commit_after>"""
SOAP Service Resource for OpenNSA.

Author: Henrik Thostrup Jensen <htj@nordu.net>
Copyright: NORDUnet (2011-2016)
"""

from twisted.python import log
from twisted.internet import defer
from twisted.web import resource, server

from opennsa.shared.requestinfo import RequestInfo
from opennsa.protocols.shared import minisoap

LOG_SYSTEM = 'protocol.SOAPResource'

class SOAPFault(Exception):

    def __init__(self, fault_string, detail_element=None):
        self.fault_string = fault_string
        self.detail_element = detail_element

    def createPayload(self):

        return minisoap.createSoapFault(self.fault_string, self.detail_element)

class SOAPResource(resource.Resource):

    isLeaf = True

    def __init__(self, allowed_hosts=None):
        resource.Resource.__init__(self)
        self.soap_actions = {}
        self.allowed_hosts = allowed_hosts # certificate dns

    def registerDecoder(self, soap_action, decoder):

        self.soap_actions[soap_action] = decoder

    def render_POST(self, request):

        if self.allowed_hosts is not None:
            if not request.isSecure():
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, not secure (no ssl/tls)', system=LOG_SYSTEM)
                return 'Insecure requests not allowed for this resource\r\n'

            cert = request.transport.getPeerCertificate()
            if not cert:
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, no client certificate presented', system=LOG_SYSTEM)
                return 'Requests without client certificate not allowed\r\n'

            cert_subject = cert.get_subject()
            log.msg('Certificate subject %s' % cert.get_subject(), system=LOG_SYSTEM)
            host_dn = cert.get_subject().get_components()[-1][1]
            log.msg('Host DN: %s' % host_dn, system=LOG_SYSTEM)

            if not host_dn in self.allowed_hosts:
                request.setResponseCode(401) # Not Authorized
                log.msg('Rejecting request, certificate host dn does not match allowed hosts', system=LOG_SYSTEM)
                return 'Requests without certificate not allowed\r\n'

            request_info = RequestInfo(str(cert_subject), host_dn)

        elif request.isSecure():
            # log certificate subject
            cert = request.transport.getPeerCertificate()
            if cert:
                log.msg('Certificate subject %s' % cert.get_subject(), system=LOG_SYSTEM)

            host_dn = cert.get_subject().get_components()[-1][1]
            request_info = RequestInfo(str(cert.get_subject()), host_dn)

        else:
            request_info = RequestInfo()

        soap_action = request.requestHeaders.getRawHeaders('soapaction',[None])[0]

        soap_data = request.content.read()
        log.msg(' -- Received payload --', system=LOG_SYSTEM, payload=True)
        log.msg(soap_data, system=LOG_SYSTEM, payload=True)
        log.msg(' -- END --', system=LOG_SYSTEM, payload=True)

        if not soap_action in self.soap_actions:
            log.msg('Got request with unknown SOAP action: %s' % soap_action, system=LOG_SYSTEM)
            request.setResponseCode(406) # Not acceptable
            return 'Invalid SOAP Action for this resource\r\n'

        log.msg('Received SOAP request. Action: %s. Length: %i' % (soap_action, len(soap_data)), system=LOG_SYSTEM, debug=True)

        def reply(reply_data):

            if type(reply_data) is SOAPFault:
                reply_data = reply_data.createPayload()
                request.setResponseCode(500) # Internal server error

            if reply_data is None or len(reply_data) == 0:
                log.msg('None/empty reply data supplied for SOAPResource. This is probably wrong', system=LOG_SYSTEM)
            else:
                log.msg(' -- Sending response --', system=LOG_SYSTEM, payload=True)
                log.msg(reply_data, system=LOG_SYSTEM, payload=True)
                log.msg('-- END --', system=LOG_SYSTEM, payload=True)

            request.setHeader('Content-Type', 'text/xml') # Keeps some SOAP implementations happy
            request.write(reply_data)
            request.finish()

        def errorReply(err, soap_data):

            log.msg('Failure during SOAP decoding/dispatch: %s' % err.getErrorMessage(), system=LOG_SYSTEM)
            log.err(err)
            log.msg('SOAP Payload that caused error:')
            log.msg(soap_data)
            error_payload = SOAPFault(err.getErrorMessage()).createPayload()

            log.msg(" -- Sending response (fault) --\n%s\n -- END: Sending response (fault) --" % error_payload, system=LOG_SYSTEM, payload=True)

            request.setResponseCode(500) # Internal server error
            request.setHeader('Content-Type', 'text/xml')
            request.write(error_payload)
            request.finish()

        decoder = self.soap_actions[soap_action]
        d = defer.maybeDeferred(decoder, soap_data, request_info)
        d.addCallbacks(reply, errorReply, errbackArgs=(soap_data,))

        return server.NOT_DONE_YET

def setupSOAPResource(top_resource, resource_name, subpath=None, allowed_hosts=None):

    assert type(resource_name) is bytes, 'Resource name must be bytes'
    if subpath is not None:
        for sp in subpath:
            assert type(sp) is bytes, 'Subpath must by of type bytes'

    # Default path: NSI/services/{resource_name}
    if subpath is None:
        subpath = [b'NSI', b'services' ]

    ir = top_resource

    for path in subpath:
        if path in ir.children:
            ir = ir.children[path]
        else:
            nr = resource.Resource()
            ir.putChild(path, nr)
            ir = nr

    if resource_name in ir.children:
        raise AssertionError('Duplicate SOAP resources detected, cannot insert resource (name {}).'.format(resource_name))

    soap_resource = SOAPResource(allowed_hosts=allowed_hosts)
    ir.putChild(resource_name, soap_resource)
    return soap_resource

<|endoftext|>


<commit_before>#!/usr/bin/env python

import random, os, sys, time, math, pygame
from vector2 import Vector2
from pygame.locals import *

SPACESWARM_VERSION = (0, 2, 0)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

WINDOWWIDTH, WINDOWHEIGHT = 800, 600
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40

random.seed()
pygame.init()
pygame.mouse.set_visible(False) # we blit the mouse instead
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Swarm!')

def load_image(name):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname)
    if image.get_alpha is None:
        image = image.convert()
    else:
        image = image.convert_alpha()
    return image

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer: return NoneSound()
    fullname=os.path.join('data', name)
    return pygame.mixer.Sound(fullname)

def terminate():
    pygame.quit()
    sys.exit()

def wait_for_player():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
                return

def get_n_points_on_circle(center, radius, n=10):
    alpha = math.pi * 2. / n
    points = list(range(n))
    for i in points:
        theta = alpha * i
        point_on_circle = Vector2(math.cos(theta) * radius,
                                  math.sin(theta) * radius)
        points[i] = center + point_on_circle
    return points

def draw_text(text, font, surface, x, y, color=TEXTCOLOR):
    text = font.render(text, 1, color)
    rect = text.get_rect()
    rect.topleft = (x, y)
    surface.blit(text, rect)

class GameObject(object):
    def __init__(self, image, location, destination=None):
        self._image = image
        self.location = location
        self.destination = destination

    def render(self, surface):
        surface.blit(self._image, self.location)

    def move(self, time_passed_seconds, speed):
        dv = Vector2(self.destination)
        lv = Vector2(self.location.x, self.location.y)
        heading = Vector2.from_points(lv, dv)
        heading.normalize()
        new_position = lv + heading * time_passed_seconds * speed
        self.location.x = new_position.x
        self.location.y = new_position.y

class Explosion(GameObject):
    image = load_image("explosion.png")

    def __init__(self, location):
        GameObject.__init__(self, Explosion.image, location)
        self._ttl = 5 # number of frames explosion should be visible

    def move(self):
        raise

    def render(self, surface):
        super(Explosion, self).render(surface)
        self._ttl -= 1

    def is_finished(self):
        return self._ttl == 0

class Alien(GameObject):
    image = load_image("alien.png")
    width, height = image.get_size()

    def __init__(self, speed=100, img=None):
        if img is None: img = Alien.image
        GameObject.__init__(self, img,
                            self._random_spawn_location(),
                            (WINDOWWIDTH/2, WINDOWHEIGHT/2))
        self._speed = speed

    def speed(self):
        """ Gives a slight random variation in speed for every alien """
        return self._speed + random.randint(-5, 5)

    def _random_spawn_location(self):
        """
        Figures out where the alien should be spawned, which should be somewhere
        along the edges of the screen.
        """
        spawn_loc = random.randint(0, 3)
        x,y = 0,0
        if spawn_loc == 0: # top
            x = random.randint(0, WINDOWWIDTH)
            y = 0
        elif spawn_loc == 1: # right
            x = WINDOWWIDTH
            y = random.randint(0, WINDOWHEIGHT)
        elif spawn_loc == 2: # bottom
            x = random.randint(0, WINDOWWIDTH)
            y = WINDOWHEIGHT
        elif spawn_loc == 3: # left
            x = 0
            y = random.randint(0, WINDOWHEIGHT)

        return pygame.Rect(x, y, Alien.width, Alien.height)

    def move(self, time_passed_seconds):
        super(Alien, self).move(time_passed_seconds, self.speed())

class SmartAlien(Alien):
    image = load_image("smart_alien.png")
    width, height = image.get_size()

    def __init__(self, speed=100):
        Alien.__init__(self, speed, SmartAlien.image)
        self._true_destination = self.destination
        self._new_destination()

    def _new_destination(self):
        lv = Vector2(self.location.x, self.location.y)
        candidates = get_n_points_on_circle(lv, 75)
        random.shuffle(candidates)
        for i in candidates:
            # find first point that is closer
            if i.get_distance_to(self._true_destination) < \
                   lv.get_distance_to(self._true_destination):
                self.destination = (i.x, i.y)
                break

    def move(self, time_passed_seconds):
        super(Alien, self).move(time_passed_seconds, self.speed())
        lv = Vector2(self.location.x, self.location.y)
        dv = Vector2(self.destination)
        if lv.get_distance_to(dv) < 2:
            self._new_destination()

class Bullet(GameObject):
    image = load_image("bullet.png")
    width, height = image.get_size()

    def __init__(self, location):
        GameObject.__init__(self, Bullet.image,
                            pygame.Rect(WINDOWWIDTH/2, WINDOWHEIGHT/2,
                                        Bullet.width, Bullet.height),
                            self._calculate_destination(location))

    def _calculate_destination(self, mouse_pos):
        """
        Figure out the destination coords for the bullet, starting from the
        center of the screen through the point the player click, to the edge
        of the screen.
        """
        dx,dy = mouse_pos

        step = Vector2.from_points((WINDOWWIDTH/2,WINDOWHEIGHT/2),
                                   (dx,dy)) * 0.1
        while True:
            if dx > WINDOWWIDTH or dy > WINDOWHEIGHT or dx < 0 or dy < 0:
                break
            dx += step.x
            dy += step.y

        return (dx, dy)

# Level definitions
LEVELS = {
    1: { 'aliens': [Alien(110) for x in range(4)],
         'spawn_rate': 50, 'multiplier': 1 },
    2: { 'aliens': [Alien(115) for x in range(6)],
         'spawn_rate': 45, 'multiplier': 1 },
    3: { 'aliens': [Alien(125) for x in range(10)],
         'spawn_rate': 40, 'multiplier': 1 },
    4: { 'aliens': [Alien(135) for x in range(14)],
         'spawn_rate': 30, 'multiplier': 1 },
    5: { 'aliens': [Alien(100) for x in range(14)],
         'spawn_rate': 25, 'multiplier': 2 },
    6: { 'aliens': [Alien(100) for x in range(20)],
         'spawn_rate': 30, 'multiplier': 2 },
    7: { 'aliens': [Alien(60) for x in range(26)],
         'spawn_rate': 40, 'multiplier': 3 },
    8: { 'aliens': [SmartAlien(120) for x in range(10)] +
         [Alien(155) for x in range(10)],
         'spawn_rate': 30, 'multiplier': 2 },
    9: { 'aliens': [SmartAlien(random.randint(90,140)) for x in range(20)] +
        [Alien(160) for x in range(10)],
        'spawn_rate': 35, 'multiplier': 2 },
    10: { 'aliens': [SmartAlien(random.randint(100,160)) for x in range(40)] +
          [Alien(65) for x in range(30)],
          'spawn_rate': 55, 'multiplier': 4 },
    }

bg = load_image("bg.jpg")
clock = pygame.time.Clock()
bullet_speed = 400

# Fonts
title_font = pygame.font.SysFont(None, 48)
font = pygame.font.SysFont(None, 32)

# Load resources
player_image = load_image("player.png")
scope_image = load_image("scope.png")
weapon_sound = load_sound("weapon.wav")
alien_killed_sound = load_sound("alienkilled.wav")
game_over_sound = load_sound("gameover.wav")
levelup_sound = load_sound("levelup.wav")
pygame.mixer.music.load("data/background.mid")

# show the "Start" screen
screen.blit(bg, (0,0))
draw_text('Space Swarm!', title_font, screen, 20,
         20, RED)
draw_text('To defend Earth, fend off the aliens with your missiles.',
         font, screen, 20, 60)
draw_text('Press any key to start.', font, screen, 20, 90)
draw_text("v"+".".join([str(x) for x in SPACESWARM_VERSION]), font, screen,
          20, WINDOWHEIGHT-40)
pygame.display.update()
wait_for_player()

# Place player in origo
player = pygame.Rect(WINDOWWIDTH / 2, WINDOWHEIGHT / 2, 50, 50)
screen.blit(player_image, player)

while True:
    # setup
    game_over, game_finished = False, False
    aliens, bullets, explosions = [], [], []
    aliens.append(Alien())
    aliens_killed = 0
    alien_spawn_timer = 0
    score = 0
    level = 1
    level_dict = LEVELS[level]
    pygame.mixer.music.play(-1, 0.0)

    while True: # Game loop
        for event in pygame.event.get():
            if event.type is MOUSEBUTTONDOWN: # weapon fired
                weapon_sound.play()
                score -= 5 * level # each bullet costs score
                if score < 0: score = 0
                bullets.append(Bullet(pygame.mouse.get_pos()))
            elif event.type is KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
            elif event.type is QUIT:
                terminate()

        alien_spawn_timer += 1
        if alien_spawn_timer == level_dict['spawn_rate']: # spawning time!
            alien_spawn_timer = 0
            if level_dict['aliens']:
                for i in range(level_dict['multiplier']):
                    aliens.append(level_dict['aliens'].pop())
                    if not level_dict['aliens']: break

        time_passed = clock.tick(FPS)
        time_passed_seconds = clock.tick(FPS) / 1000.

        for a in aliens: # move all aliens closer towards player
            a.move(time_passed_seconds)
            if player.colliderect(a.location):
                game_over = True
                break
        if game_over: break

        for b in bullets:
            b.move(time_passed_seconds, bullet_speed)

            for a in aliens:
                if b.location.colliderect(a.location): # alien shot down!
                    aliens_killed += 1
                    score += 10 * level # increase kill score as we progress
                    alien_killed_sound.play()
                    aliens.remove(a)
                    explosions.append(Explosion(a.location))
                    if b in bullets: bullets.remove(b)
                    if len(level_dict['aliens']) == 0 and len(aliens) == 0:
                        levelup_sound.play()
                        level += 1
                        if not level in LEVELS.keys():
                            game_finished = True
                        else:
                            level_dict = LEVELS[level]
                            alien_spawn_timer = 0

            if not screen.get_rect().contains(b.location) and b in bullets:
                bullets.remove(b)

        if game_finished: break
        # Redraw screen
        screen.blit(bg, (0,0))
        draw_text('Level: %s' % (level), font, screen, 0, 0)
        draw_text('Remaining aliens: %s' % (len(level_dict['aliens'])),
                 font, screen, 0, 20)
        draw_text('Aliens killed: %s' % (aliens_killed),
                 font, screen, WINDOWWIDTH/2, 0)
        draw_text('Score: %s' % (score), font, screen, WINDOWWIDTH/2, 20)

        for b in bullets: b.render(screen)
        for a in aliens: a.render(screen)
        for e in explosions:
            if e.is_finished():
                explosions.remove(e)
            else:
                e.render(screen)
        screen.blit(player_image, player)
        screen.blit(scope_image, pygame.mouse.get_pos())
        pygame.display.update()

    # broken out of game loop
    pygame.mixer.music.stop()
    if game_over:
        game_over_sound.play()
        draw_text('GAME OVER', title_font, screen, (WINDOWWIDTH / 3),
                 (WINDOWHEIGHT / 3), RED)
        draw_text('Press any key to play again, or Esc to quit.', font,
             screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    else:
        # TODO game won sound
        draw_text('CONGRATULATIONS!', title_font, screen,
                  (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3), BLUE)
        draw_text('You have saved Earth!', title_font, screen,
                  (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3) + 100, GREEN)
        draw_text('Press any key to play again, or Esc to quit.', font,
             screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 150)
    pygame.display.update()
    wait_for_player()
<commit_msg>Fixed critical bug which caused no aliens to spawn when playing again after defeat<commit_after>#!/usr/bin/env python

import random, os, sys, time, math, pygame
from vector2 import Vector2
from pygame.locals import *

SPACESWARM_VERSION = (0, 2, 0)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

WINDOWWIDTH, WINDOWHEIGHT = 800, 600
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40

random.seed()
pygame.init()
pygame.mouse.set_visible(False) # we blit the mouse instead
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Swarm!')

def load_image(name):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname)
    if image.get_alpha is None:
        image = image.convert()
    else:
        image = image.convert_alpha()
    return image

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer: return NoneSound()
    fullname=os.path.join('data', name)
    return pygame.mixer.Sound(fullname)

def terminate():
    pygame.quit()
    sys.exit()

def wait_for_player():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
                return

def get_n_points_on_circle(center, radius, n=10):
    alpha = math.pi * 2. / n
    points = list(range(n))
    for i in points:
        theta = alpha * i
        point_on_circle = Vector2(math.cos(theta) * radius,
                                  math.sin(theta) * radius)
        points[i] = center + point_on_circle
    return points

def draw_text(text, font, surface, x, y, color=TEXTCOLOR):
    text = font.render(text, 1, color)
    rect = text.get_rect()
    rect.topleft = (x, y)
    surface.blit(text, rect)

class GameObject(object):
    def __init__(self, image, location, destination=None):
        self._image = image
        self.location = location
        self.destination = destination

    def render(self, surface):
        surface.blit(self._image, self.location)

    def move(self, time_passed_seconds, speed):
        dv = Vector2(self.destination)
        lv = Vector2(self.location.x, self.location.y)
        heading = Vector2.from_points(lv, dv)
        heading.normalize()
        new_position = lv + heading * time_passed_seconds * speed
        self.location.x = new_position.x
        self.location.y = new_position.y

class Explosion(GameObject):
    image = load_image("explosion.png")

    def __init__(self, location):
        GameObject.__init__(self, Explosion.image, location)
        self._ttl = 5 # number of frames explosion should be visible

    def move(self):
        raise

    def render(self, surface):
        super(Explosion, self).render(surface)
        self._ttl -= 1

    def is_finished(self):
        return self._ttl == 0

class Alien(GameObject):
    image = load_image("alien.png")
    width, height = image.get_size()

    def __init__(self, speed=100, img=None):
        if img is None: img = Alien.image
        GameObject.__init__(self, img,
                            self._random_spawn_location(),
                            (WINDOWWIDTH/2, WINDOWHEIGHT/2))
        self._speed = speed

    def speed(self):
        """ Gives a slight random variation in speed for every alien """
        return self._speed + random.randint(-5, 5)

    def _random_spawn_location(self):
        """
        Figures out where the alien should be spawned, which should be somewhere
        along the edges of the screen.
        """
        spawn_loc = random.randint(0, 3)
        x,y = 0,0
        if spawn_loc == 0: # top
            x = random.randint(0, WINDOWWIDTH)
            y = 0
        elif spawn_loc == 1: # right
            x = WINDOWWIDTH
            y = random.randint(0, WINDOWHEIGHT)
        elif spawn_loc == 2: # bottom
            x = random.randint(0, WINDOWWIDTH)
            y = WINDOWHEIGHT
        elif spawn_loc == 3: # left
            x = 0
            y = random.randint(0, WINDOWHEIGHT)

        return pygame.Rect(x, y, Alien.width, Alien.height)

    def move(self, time_passed_seconds):
        super(Alien, self).move(time_passed_seconds, self.speed())

class SmartAlien(Alien):
    image = load_image("smart_alien.png")
    width, height = image.get_size()

    def __init__(self, speed=100):
        Alien.__init__(self, speed, SmartAlien.image)
        self._true_destination = self.destination
        self._new_destination()

    def _new_destination(self):
        lv = Vector2(self.location.x, self.location.y)
        candidates = get_n_points_on_circle(lv, 75)
        random.shuffle(candidates)
        for i in candidates:
            # find first point that is closer
            if i.get_distance_to(self._true_destination) < \
                   lv.get_distance_to(self._true_destination):
                self.destination = (i.x, i.y)
                break

    def move(self, time_passed_seconds):
        super(Alien, self).move(time_passed_seconds, self.speed())
        lv = Vector2(self.location.x, self.location.y)
        dv = Vector2(self.destination)
        if lv.get_distance_to(dv) < 2:
            self._new_destination()

class Bullet(GameObject):
    image = load_image("bullet.png")
    width, height = image.get_size()

    def __init__(self, location):
        GameObject.__init__(self, Bullet.image,
                            pygame.Rect(WINDOWWIDTH/2, WINDOWHEIGHT/2,
                                        Bullet.width, Bullet.height),
                            self._calculate_destination(location))

    def _calculate_destination(self, mouse_pos):
        """
        Figure out the destination coords for the bullet, starting from the
        center of the screen through the point the player click, to the edge
        of the screen.
        """
        dx,dy = mouse_pos

        step = Vector2.from_points((WINDOWWIDTH/2,WINDOWHEIGHT/2),
                                   (dx,dy)) * 0.1
        while True:
            if dx > WINDOWWIDTH or dy > WINDOWHEIGHT or dx < 0 or dy < 0:
                break
            dx += step.x
            dy += step.y

        return (dx, dy)

# Level definitions
# TODO refactor all the level logic into a class
def instanciate_levels():
    return {
        1: { 'aliens': [Alien(110) for x in range(4)],
         'spawn_rate': 50, 'multiplier': 1 },
        2: { 'aliens': [Alien(115) for x in range(6)],
             'spawn_rate': 45, 'multiplier': 1 },
        3: { 'aliens': [Alien(125) for x in range(10)],
             'spawn_rate': 40, 'multiplier': 1 },
        4: { 'aliens': [Alien(135) for x in range(14)],
             'spawn_rate': 30, 'multiplier': 1 },
        5: { 'aliens': [Alien(100) for x in range(14)],
             'spawn_rate': 25, 'multiplier': 2 },
        6: { 'aliens': [Alien(100) for x in range(20)],
             'spawn_rate': 30, 'multiplier': 2 },
        7: { 'aliens': [Alien(60) for x in range(26)],
             'spawn_rate': 40, 'multiplier': 3 },
        8: { 'aliens': [SmartAlien(120) for x in range(10)] +
             [Alien(155) for x in range(10)],
             'spawn_rate': 30, 'multiplier': 2 },
        9: { 'aliens': [SmartAlien(random.randint(90,140)) for x in range(20)] +
            [Alien(160) for x in range(10)],
            'spawn_rate': 35, 'multiplier': 2 },
        10: { 'aliens': [SmartAlien(random.randint(100,160)) for x in range(40)] +
              [Alien(65) for x in range(30)],
              'spawn_rate': 55, 'multiplier': 4 },
    }

bg = load_image("bg.jpg")
clock = pygame.time.Clock()
bullet_speed = 400

# Fonts
title_font = pygame.font.SysFont(None, 48)
font = pygame.font.SysFont(None, 32)

# Load resources
player_image = load_image("player.png")
scope_image = load_image("scope.png")
weapon_sound = load_sound("weapon.wav")
alien_killed_sound = load_sound("alienkilled.wav")
game_over_sound = load_sound("gameover.wav")
levelup_sound = load_sound("levelup.wav")
pygame.mixer.music.load("data/background.mid")

# show the "Start" screen
screen.blit(bg, (0,0))
draw_text('Space Swarm!', title_font, screen, 20,
         20, RED)
draw_text('To defend Earth, fend off the aliens with your missiles.',
         font, screen, 20, 60)
draw_text('Press any key to start.', font, screen, 20, 90)
draw_text("v"+".".join([str(x) for x in SPACESWARM_VERSION]), font, screen,
          20, WINDOWHEIGHT-40)
pygame.display.update()
wait_for_player()

# Place player in origo
player = pygame.Rect(WINDOWWIDTH / 2, WINDOWHEIGHT / 2, 50, 50)
screen.blit(player_image, player)

while True:
    # setup
    game_over, game_finished = False, False
    aliens, bullets, explosions = [], [], []
    aliens.append(Alien())
    aliens_killed = 0
    alien_spawn_timer = 0
    score = 0
    level = 1
    levels = instanciate_levels()
    level_dict = levels[level]
    pygame.mixer.music.play(-1, 0.0)

    while True: # Game loop
        for event in pygame.event.get():
            if event.type is MOUSEBUTTONDOWN: # weapon fired
                weapon_sound.play()
                score -= 5 * level # each bullet costs score
                if score < 0: score = 0
                bullets.append(Bullet(pygame.mouse.get_pos()))
            elif event.type is KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
            elif event.type is QUIT:
                terminate()

        alien_spawn_timer += 1
        if alien_spawn_timer == level_dict['spawn_rate']: # spawning time!
            alien_spawn_timer = 0
            if level_dict['aliens']:
                for i in range(level_dict['multiplier']):
                    aliens.append(level_dict['aliens'].pop())
                    if not level_dict['aliens']: break

        time_passed = clock.tick(FPS)
        time_passed_seconds = clock.tick(FPS) / 1000.

        for a in aliens: # move all aliens closer towards player
            a.move(time_passed_seconds)
            if player.colliderect(a.location):
                game_over = True
                break
        if game_over: break

        for b in bullets:
            b.move(time_passed_seconds, bullet_speed)

            for a in aliens:
                if b.location.colliderect(a.location): # alien shot down!
                    aliens_killed += 1
                    score += 10 * level # increase kill score as we progress
                    alien_killed_sound.play()
                    aliens.remove(a)
                    explosions.append(Explosion(a.location))
                    if b in bullets: bullets.remove(b)
                    if len(level_dict['aliens']) == 0 and len(aliens) == 0:
                        levelup_sound.play()
                        level += 1
                        if not level in levels.keys():
                            game_finished = True
                        else:
                            level_dict = levels[level]
                            alien_spawn_timer = 0

            if not screen.get_rect().contains(b.location) and b in bullets:
                bullets.remove(b)

        if game_finished: break
        # Redraw screen
        screen.blit(bg, (0,0))
        draw_text('Level: %s' % (level), font, screen, 0, 0)
        draw_text('Remaining aliens: %s' % (len(level_dict['aliens'])),
                 font, screen, 0, 20)
        draw_text('Aliens killed: %s' % (aliens_killed),
                 font, screen, WINDOWWIDTH/2, 0)
        draw_text('Score: %s' % (score), font, screen, WINDOWWIDTH/2, 20)

        for b in bullets: b.render(screen)
        for a in aliens: a.render(screen)
        for e in explosions:
            if e.is_finished():
                explosions.remove(e)
            else:
                e.render(screen)
        screen.blit(player_image, player)
        screen.blit(scope_image, pygame.mouse.get_pos())
        pygame.display.update()

    # broken out of game loop
    pygame.mixer.music.stop()
    if game_over:
        game_over_sound.play()
        draw_text('GAME OVER', title_font, screen, (WINDOWWIDTH / 3),
                 (WINDOWHEIGHT / 3), RED)
        draw_text('Press any key to play again, or Esc to quit.', font,
             screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    else:
        # TODO game won sound
        draw_text('CONGRATULATIONS!', title_font, screen,
                  (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3), BLUE)
        draw_text('You have saved Earth!', title_font, screen,
                  (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3) + 100, GREEN)
        draw_text('Press any key to play again, or Esc to quit.', font,
             screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 150)
    pygame.display.update()
    wait_for_player()
<|endoftext|>


<commit_before>from model.organism import Organism
from pyglet.gl import *
from util.draw import circle
from util.vec import Vec

class Predator(Organism):

    top_speed = 100
    lifespan_increase = 0.4
    increase_limit = 3

    def __init__(self, x, y):
        super(Predator, self).__init__(x, y)
        self.lifespan = 3
        self.reproduction_chance = 0.002

    def draw(self):
        glColor3f(0.2, 0.4, 0.5)
        circle(self.p, 10)

    def pathfind(self, prey):
        if prey:
            direction = prey.p - self.p
            absolute = direction.abs()

            if absolute != 0:
                self.v = Vec(
                    (self.top_speed * direction.x) / absolute,
                    (self.top_speed * direction.y) / absolute
                )
            else:
                self.v = Vec(0, 0)
        else:
            self.v = Vec(0, 0)

    def eat(self):
        if self.age - self.lifespan < self.increase_limit:
            self.lifespan += self.lifespan_increase
<commit_msg>Added max lifespan for predators<commit_after>from model.organism import Organism
from pyglet.gl import *
from util.draw import circle
from util.vec import Vec

class Predator(Organism):

    top_speed = 100
    max_lifespan = 100
    lifespan_increase = 0.4
    increase_limit = 3

    def __init__(self, x, y):
        super(Predator, self).__init__(x, y)
        self.lifespan = 3
        self.reproduction_chance = 0.002

    def draw(self):
        glColor3f(0.2, 0.4, 0.5)
        circle(self.p, 10)

    def pathfind(self, prey):
        if prey:
            direction = prey.p - self.p
            absolute = direction.abs()

            if absolute != 0:
                self.v = Vec(
                    (self.top_speed * direction.x) / absolute,
                    (self.top_speed * direction.y) / absolute
                )
            else:
                self.v = Vec(0, 0)
        else:
            self.v = Vec(0, 0)

    def eat(self):
        if (self.age - self.lifespan < self.increase_limit and
            self.lifespan < self.max_lifespan):
            self.lifespan += self.lifespan_increase
<|endoftext|>


<commit_before>"""
Task:
Python Implementation of the SparseDTW Algorithm by Ghazi Al-Naymat,
Sanjay Chawla and Javid Taheri.

http://arxiv.org/abs/1201.2969
"""

# Import Built-Ins
import argparse
# Import Third-Party
import numpy as np
from scipy.sparse import lil_matrix

# Import Homebrew

class SparseDTW:

    def __init__(self, s, q, res=.5):

        self.n, self.m = len(s), len(q)
        self.res = res
        self.s = s
        self.q = q
        self.SM = lil_matrix((self.n, self.m), dtype=np.float64)

    def quantize(self, series):
        return [(series[i] - min(series)) / (max(series) - min(series))
                for i in range(len(series))]

    def euc_distance(self, x, y):
        return np.abs(x - y) ** 2

    def lower_neighbors(self, x, y):
        if x == 0 and y == 0:
            return []
        else:
            coord_a = (x-1, y) if x-1 >= 0 and y >= 0 else None
            coord_b = (x-1, y-1) if x-1 >= 0 and y-1 >= 0 else None
            coord_c = (x, y-1)if x >= 0 and y-1 >= 0 else None
            return [neighbor for neighbor in (coord_a, coord_b, coord_c)
                    if neighbor is not None]

    def upper_neighbors(self, x, y):
        if x == self.n-1 and y == self.m-1:
            return []
        else:
            coord_a = (x+1, y) if x+1 < self.n and y < self.m else None
            coord_b = (x+1, y+1) if x+1 < self.n and y+1 < self.m else None
            coord_c = (x, y+1) if x < self.n and y+1 < self.m else None
            return [neighbor for neighbor in (coord_a, coord_b, coord_c)
                    if neighbor is not None]

    def unblock_upper_neighbors(self, x, y):
        coords = self.upper_neighbors(x, y)
        if coords:
            for coord in coords:
                x, y = coord
                try:
                    self.SM[coord] = self.euc_distance(self.s[x], self.q[y])
                except IndexError:
                    continue

    def populate_warp(self):
        S = self.quantize(self.s)
        Q = self.quantize(self.q)

        lower_bound = 0
        upper_bound = self.res
        while 0 <= lower_bound <= 1 - self.res / 2:
            idxS = [i for i in range(self.n) if (lower_bound <= S[i] <= upper_bound)]
            idxQ = [i for i in range(self.m) if (lower_bound <= Q[i] <= upper_bound)]

            # update bounds
            lower_bound += + self.res / 2
            upper_bound = lower_bound + self.res

            # For indices, calculate euclidic distances and add to warp matrix SM
            for i in idxS:
                for j in idxQ:
                    euc_d = self.euc_distance(S[i], Q[j])
                    if euc_d == 0:
                        self.SM[(i, j)] = -1
                    else:
                        self.SM[(i, j)] += euc_d

    def calculate_warp_costs(self):

        for i in range(self.n):
            for j in range(self.m):
                if self.SM[i,j]:
                    lower_n = [self.SM[x,y] for x,y in self.lower_neighbors(i, j)
                               if self.SM[x,y] != 0]

                    if lower_n:
                        min_cost = min(lower_n)
                        min_cost = 0 if min_cost == -1 else min_cost
                    else:
                        min_cost = 0
                    self.SM[i, j] += min_cost

                    # check upper neighbors
                    upper_n = self.upper_neighbors(i, j)
                    if upper_n and not any(self.SM[x,y] != 0 for x,y in upper_n):
                        self.unblock_upper_neighbors(i, j)
                    else:
                        continue

    def calculate_warp_path(self):
        hop = self.n-1, self.m-1
        warping_path = [hop]
        while hop != (0, 0):

            lower_n = [c for c in self.lower_neighbors(*hop) if self.SM[c] != 0]
            lowest = lower_n[0] if lower_n else (0, 0)
            if len(lower_n) > 1:
                for next_n in lower_n[1:]:
                    lowest = next_n if self.SM[lowest] > self.SM[next_n] else lowest
            else:
                pass

            hop = lowest
            warping_path.append(hop)

        warp_path = []
        for coord in sorted(warping_path):
            warp_path.append((coord, self.SM[coord]))

        return warp_path

    def __call__(self, *args, **kwargs):
        self.populate_warp()
        self.calculate_warp_costs()

        return self.calculate_warp_path()

    def as_arr(self):
        return self.SM.toarray()

if __name__ == '__main__':

        parser = argparse.ArgumentParser()
        parser.add_argument('series', nargs=2,
                            help='paths to two time series to time warp; input '
                                 'as file names; columns required. seperator is'
                                 ' tab, last column must be values')
        parser.add_argument('--resistance', '-r', required=False, default=0.5,
                            help='Resistance to use for calculation; defaults '
                                 'to 0.5')
        args = parser.parse_args()

        a = None
        b = None

        with open(args.series[0], 'r') as f:
            a = []
            for line in f:
                a.append(np.float64(line.split('\t')[-1]))

        with open(args.series[1], 'r') as f:
            b = []
            for line in f:
                b.append(np.float64(line.split('\t')[-1]))

        dtw = SparseDTW(a, b, res=args.resistance)

        for coord, value in dtw():
            print(coord, '\t', value)

<commit_msg>fixed an issue where adding values to -1<commit_after>"""
Task:
Python Implementation of the SparseDTW Algorithm by Ghazi Al-Naymat,
Sanjay Chawla and Javid Taheri.

http://arxiv.org/abs/1201.2969
"""

# Import Built-Ins
import argparse
# Import Third-Party
import numpy as np
from scipy.sparse import lil_matrix

# Import Homebrew

class SparseDTW:

    def __init__(self, s, q, res=.5):

        self.n, self.m = len(s), len(q)
        self.res = res
        self.s = s
        self.q = q
        self.SM = lil_matrix((self.n, self.m), dtype=np.float64)

    def quantize(self, series):
        return [(series[i] - min(series)) / (max(series) - min(series))
                for i in range(len(series))]

    def euc_distance(self, x, y):
        return np.abs(x - y) ** 2

    def lower_neighbors(self, x, y):
        if x == 0 and y == 0:
            return []
        else:
            coord_a = (x-1, y) if x-1 >= 0 and y >= 0 else None
            coord_b = (x-1, y-1) if x-1 >= 0 and y-1 >= 0 else None
            coord_c = (x, y-1)if x >= 0 and y-1 >= 0 else None
            return [neighbor for neighbor in (coord_a, coord_b, coord_c)
                    if neighbor is not None]

    def upper_neighbors(self, x, y):
        if x == self.n-1 and y == self.m-1:
            return []
        else:
            coord_a = (x+1, y) if x+1 < self.n and y < self.m else None
            coord_b = (x+1, y+1) if x+1 < self.n and y+1 < self.m else None
            coord_c = (x, y+1) if x < self.n and y+1 < self.m else None
            return [neighbor for neighbor in (coord_a, coord_b, coord_c)
                    if neighbor is not None]

    def unblock_upper_neighbors(self, x, y):
        coords = self.upper_neighbors(x, y)
        if coords:
            for coord in coords:
                x, y = coord
                try:
                    self.SM[coord] = self.euc_distance(self.s[x], self.q[y])
                except IndexError:
                    continue

    def populate_warp(self):
        S = self.quantize(self.s)
        Q = self.quantize(self.q)

        lower_bound = 0
        upper_bound = self.res
        while 0 <= lower_bound <= 1 - self.res / 2:
            idxS = [i for i in range(self.n) if (lower_bound <= S[i] <= upper_bound)]
            idxQ = [i for i in range(self.m) if (lower_bound <= Q[i] <= upper_bound)]

            # update bounds
            lower_bound += + self.res / 2
            upper_bound = lower_bound + self.res

            # For indices, calculate euclidic distances and add to warp matrix SM
            for i in idxS:
                for j in idxQ:
                    euc_d = self.euc_distance(S[i], Q[j])
                    if euc_d == 0:
                        self.SM[(i, j)] = -1
                    else:
                        self.SM[(i, j)] += euc_d

    def calculate_warp_costs(self):

        for i in range(self.n):
            for j in range(self.m):
                if self.SM[i,j]:
                    lower_n = [self.SM[x,y] for x,y in self.lower_neighbors(i, j)
                               if self.SM[x,y] != 0]

                    if lower_n:
                        min_cost = min(lower_n)
                        min_cost = 0 if min_cost == -1 else min_cost
                    else:
                        min_cost = 0
                    self.SM[i, j] = self.SM[i, j] + min_cost if self.SM[i, j] != -1 else 0 + min_cost

                    # check upper neighbors
                    upper_n = self.upper_neighbors(i, j)
                    if upper_n and not any(self.SM[x,y] != 0 for x,y in upper_n):
                        self.unblock_upper_neighbors(i, j)
                    else:
                        continue

    def calculate_warp_path(self):
        hop = self.n-1, self.m-1
        warping_path = [hop]
        while hop != (0, 0):

            lower_n = [c for c in self.lower_neighbors(*hop) if self.SM[c] != 0]
            lowest = lower_n[0] if lower_n else (0, 0)
            if len(lower_n) > 1:
                for next_n in lower_n[1:]:
                    lowest = next_n if self.SM[lowest] > self.SM[next_n] else lowest
            else:
                pass

            hop = lowest
            warping_path.append(hop)

        warp_path = []
        for coord in sorted(warping_path):
            warp_path.append((coord, self.SM[coord]))

        return warp_path

    def __call__(self, *args, **kwargs):
        self.populate_warp()
        self.calculate_warp_costs()

        return self.calculate_warp_path()

    def as_arr(self):
        return self.SM.toarray()

if __name__ == '__main__':

        parser = argparse.ArgumentParser()
        parser.add_argument('series', nargs=2,
                            help='paths to two time series to time warp; input '
                                 'as file names; columns required. seperator is'
                                 ' tab, last column must be values')
        parser.add_argument('--resistance', '-r', required=False, default=0.5,
                            help='Resistance to use for calculation; defaults '
                                 'to 0.5')
        args = parser.parse_args()

        a = None
        b = None

        with open(args.series[0], 'r') as f:
            a = []
            for line in f:
                a.append(np.float64(line.split('\t')[-1]))

        with open(args.series[1], 'r') as f:
            b = []
            for line in f:
                b.append(np.float64(line.split('\t')[-1]))

        dtw = SparseDTW(a, b, res=args.resistance)

        for coord, value in dtw():
            print(coord, '\t', value)

<|endoftext|>


<commit_before>from django.core.management.base import BaseCommand, CommandError

from odekro import data

class Command(BaseCommand):
    """Read in an info page file and either create or update existing info"""

    help = 'Add MPs data'
    args = '<file>'

    def handle(self, *args, **options):
        # file = open(args[])
        if len(args) != 1:
            raise CommandError

        path = args[0]
        content = open(path, 'r').read()
        data.add_mps_from_json(content)
<commit_msg>Update a docstring to match the upstream odekro branch<commit_after>from django.core.management.base import BaseCommand, CommandError

from odekro import data

class Command(BaseCommand):
    """Read in mps data and either create or update existing info"""

    help = 'Add MPs data'
    args = '<file>'

    def handle(self, *args, **options):
        # file = open(args[])
        if len(args) != 1:
            raise CommandError

        path = args[0]
        content = open(path, 'r').read()
        data.add_mps_from_json(content)
<|endoftext|>


<commit_before>
from . import gridregion

#from astropy.io import fits

def grid_SerAqu():
    print("You will image the GBT Ammonia Survey data for Serpens_Aquila")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='Serpens_Aquila'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_NGC1333():
    print("You will image the GBT Ammonia Survey data for NGC1333")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='NGC1333'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_L1455():
    print("You will image the GBT Ammonia Survey data for L1455")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='L1455'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_L1688():
    print("You will image the GBT Ammonia Survey data for L1688")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='L1688'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_OrionA():
    print("You will image the GBT Ammonia Survey data for OrionA")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='OrionA'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_OrionB():
    print("You will image the GBT Ammonia Survey data for OrionB")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='OrionB'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_B18():
    print("You will image the GBT Ammonia Survey data for B18")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='B18'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

<commit_msg>Customize Serpens_Aquila gridding<commit_after>
from . import gridregion

#from astropy.io import fits

def grid_SerAqu():
    print("You will image the GBT Ammonia Survey data for Serpens_Aquila")
    data_dir = '/lustre/pipeline/scratch/GAS'
    region_name = 'Serpens_Aquila'
    startChannel = 1024 + 668 # default 1024
    endChannel = 1024 + 1462  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11',
        startChannel = startChannel, endChannel = endChannel)

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    startChannel = 1024 + 630 # default 1024
    endChannel = 1024 + 1462  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)
    startChannel = 1024 + 790 # default 1024
    endChannel = 1024 + 1290  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)
    startChannel = 1024 + 790 # default 1024
    endChannel = 1024 + 1290  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)
    startChannel = 1024 + 790 # default 1024
    endChannel = 1024 + 1290  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)
    startChannel = 1024 + 950 # default 1024
    endChannel = 1024 + 1150  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)
    startChannel = 1024 + 950 # default 1024
    endChannel = 1024 + 1150  # default 3072
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21',
        startChannel = startChannel, endChannel = endChannel, templateHeader=hd_temp)

def grid_NGC1333():
    print("You will image the GBT Ammonia Survey data for NGC1333")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='NGC1333'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_L1455():
    print("You will image the GBT Ammonia Survey data for L1455")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='L1455'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_L1688():
    print("You will image the GBT Ammonia Survey data for L1688")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='L1688'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_OrionA():
    print("You will image the GBT Ammonia Survey data for OrionA")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='OrionA'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_OrionB():
    print("You will image the GBT Ammonia Survey data for OrionB")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='OrionB'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

def grid_B18():
    print("You will image the GBT Ammonia Survey data for B18")
    data_dir='/lustre/pipeline/scratch/GAS'
    region_name='B18'
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_11')

    hd_temp=fits.getheader(region_name+'_NH3_11.fits')
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_22',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_NH3_33',     templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_C2S',        templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC5N',       templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_21_20', templateHeader=hd_temp)
    gridregion.griddata( rootdir=data_dir, region=region_name, dirname=region_name+'_HC7N_22_21', templateHeader=hd_temp)

<|endoftext|>