<commit_before>import unittest
import os
import sys

class FixturesTest(unittest.TestCase):

    #------------------- setup and teardown ---------------------------
    @classmethod
    def setUpClass(cls):
        print('\nin set up - this takes about 80 secs')

        from tests.write_fixtures import generate_fixture_hashes, unpickle_hash
        cls.hash_dict_new = generate_fixture_hashes()
        cls.hash_dict_original = unpickle_hash()
        # define dictionary keys for individual files for checking
        folder = 'temporary_test_fixtures'
        cls.corrmat = folder + '/corrmat_file.txt'
        cls.gm = folder + '/network-analysis/GlobalMeasures_corrmat_file_COST010.csv'
        cls.lm = folder + '/network-analysis/NodalMeasures_corrmat_file_COST010.csv'
        cls.rich = folder + '/network-analysis/RICH_CLUB_corrmat_file_COST010.csv'

    #--------------------------- Tests --------------------------------
    # Each of these tests checks that ourly newly generated version of
    # file_x matches the fixture version

    def test_corrmat_matches_fixture(self):
        # test new correlation matrix against fixture
        print('\ntesting new correlation matrix against fixture')
        self.assertEqual(self.hash_dict_new[self.corrmat],
                        self.hash_dict_original[self.corrmat])

    def test_lm_against_fixture(self):
        # test new local measures against fixture
        print('\ntesting new nodal measures against fixture')
        self.assertEqual(self.hash_dict_new[self.lm],
                        self.hash_dict_original[self.lm])

    def test_gm_against_fixture(self):
        # test new global measures against fixture
        print('\ntesting new global measures against fixture')
        self.assertEqual(self.hash_dict_new[self.gm],
                        self.hash_dict_original[self.gm])

    def test_rich_against_fixture(self):
        # test rich club against fixture
        print('\ntesting rich club against fixture')
        self.assertEqual(self.hash_dict_new[self.rich],
                        self.hash_dict_original[self.rich])

if __name__ == '__main__':
    unittest.main()
<commit_msg>lint regression test<commit_after>import unittest

class FixturesTest(unittest.TestCase):

    # ------------------- setup and teardown ---------------------------
    @classmethod
    def setUpClass(cls):
        print('\nin set up - this takes about 80 secs')

        from tests.write_fixtures import generate_fixture_hashes, unpickle_hash
        cls.hash_dict_new = generate_fixture_hashes()
        cls.hash_dict_original = unpickle_hash()
        # define dictionary keys for individual files for checking
        folder = 'temporary_test_fixtures'
        cls.corrmat = folder + '/corrmat_file.txt'
        cls.gm = (folder +
                  '/network-analysis/GlobalMeasures_corrmat_file_COST010.csv')
        cls.lm = (folder +
                  '/network-analysis/NodalMeasures_corrmat_file_COST010.csv')
        cls.rich = (folder +
                    '/network-analysis/RICH_CLUB_corrmat_file_COST010.csv')

    # --------------------------- Tests --------------------------------
    # Each of these tests checks that ourly newly generated version of
    # file_x matches the fixture version

    def test_corrmat_matches_fixture(self):
        # test new correlation matrix against fixture
        print('\ntesting new correlation matrix against fixture')
        self.assertEqual(self.hash_dict_new[self.corrmat],
                         self.hash_dict_original[self.corrmat])

    def test_lm_against_fixture(self):
        # test new local measures against fixture
        print('\ntesting new nodal measures against fixture')
        self.assertEqual(self.hash_dict_new[self.lm],
                         self.hash_dict_original[self.lm])

    def test_gm_against_fixture(self):
        # test new global measures against fixture
        print('\ntesting new global measures against fixture')
        self.assertEqual(self.hash_dict_new[self.gm],
                         self.hash_dict_original[self.gm])

    def test_rich_against_fixture(self):
        # test rich club against fixture
        print('\ntesting rich club against fixture')
        self.assertEqual(self.hash_dict_new[self.rich],
                         self.hash_dict_original[self.rich])

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


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

import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.framebufferobjects import *
from OpenGL.arrays import vbo

import time
import sys
import math
import random
import numpy as np
from PIL import Image

class PyIBFV:

	def __init__(self):
		self.nmesh = 100
		self.pattern_res = 64
		self.num_patterns = 32
		self.alpha = 0.12
		self.textures = []
		self.scale = 4.0
		self.tmax = 512/(self.scale*self.pattern_res)
		self.dmax = self.scale / 512

		self.last_time = time.time()
		self.frames = 0
		self.sa = 0.01

	def InitGL(self, Width, Height):
		glClearColor(0.0, 0.0, 0.0, 0.0)
		glClearDepth(1.0)
		glShadeModel(GL_SMOOTH)

		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()

		gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)

		glMatrixMode(GL_MODELVIEW)

		# Create fbo with 2 textures.
		self.fbo = glGenFramebuffers(1)
		glBindFramebuffer(GL_FRAMEBUFFER, self.fbo )

		# FBO texture 1
		self.renderedTexture1 = glGenTextures(1)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture1)
		glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 512, 512, 0,GL_RGB, GL_UNSIGNED_BYTE, None)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

		# FBO texture 2
		self.renderedTexture2 = glGenTextures(1)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2)
		glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 512, 512, 0,GL_RGB, GL_UNSIGNED_BYTE, None)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

		# Set the first texture as color attachment
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture1, 0)

		# Set the list of draw buffers.
		glDrawBuffers(1, GL_COLOR_ATTACHMENT0) #"1" is the size of DrawBuffers
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

		# Clear the 2nd texture
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture2, 0)
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

		self.framenr = 0

		# Set the blending function
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

		# init VBO's for for mesh location and texture coordinates
		# based on: http://dan.lecocq.us/wordpress/2009/12/25/triangle-strip-for-grids-a-construction/
		self.DM = 1.0 / (self.nmesh-1.0)
		size = self.nmesh ** 2 * 2

		# locations
		locations = self.getDisplacements()
		self.vbo_locations = vbo.VBO(locations)

		# texture coordinates
		coords = np.empty(size, dtype=np.float32)
		index = 0
		for i in range(self.nmesh):
			x = self.DM*i
			for j in range(self.nmesh):
				y = self.DM*j
				coords[index + 0] = x
				coords[index + 1] = y
				index += 2
		self.vbo_coords = vbo.VBO(coords)

		# indices
		self.num_indices = self.nmesh * (self.nmesh - 1) * 2
		indices = np.empty(self.num_indices, dtype=np.uint16)
		index = 0
		i = 0
		for x in range(self.nmesh - 1):
			for y in range(self.nmesh):
				if x % 2 == 0:
					indices[i+0] = index + 0
					indices[i+1] = index + self.nmesh
					index += 1
					i += 2
				else:
					indices[i+0] = index + 0
					indices[i+1] = index + self.nmesh
					index -= 1
					i += 2
			index = indices[i-1]
		self.ibo = vbo.VBO(indices, GL_DYNAMIC_DRAW, GL_ELEMENT_ARRAY_BUFFER)

	def getDisplacements(self):
		size = self.nmesh ** 2 * 2
		locations = np.empty(size, dtype=np.float32)
		index = 0
		for i in range(self.nmesh):
			x = self.DM*i
			for j in range(self.nmesh):
				y = self.DM*j
				[px, py] = self.getDisplacement(x, y)
				locations[index + 0] = px
				locations[index + 1] = py
				index += 2
		return locations

	def updateDisplacements(self):
		self.sa = 0.010*math.cos(self.framenr*2.0*math.pi/200.0)
		self.vbo_locations.set_array(self.getDisplacements())

	# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
	def ReSizeGLScene(self, Width, Height):
		if Height == 0:                        # Prevent A Divide By Zero If The Window Is Too Small
			Height = 1

		glViewport(0, 0, Width, Height)        # Reset The Current Viewport And Perspective Transformation
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
		glMatrixMode(GL_MODELVIEW)

	def makePatterns(self):
		lut = np.empty(256)
		phase = np.empty((self.pattern_res,self.pattern_res), dtype=int)
		pat = np.empty((self.pattern_res,self.pattern_res, 4), dtype=np.uint8)

		for i in range(256):
			lut[i] = 0 if i < 127 else 255

		for i in range(self.pattern_res):
			for j in range(self.pattern_res):
				phase[i][j] = random.randint(0, 255)

		for k in range(self.num_patterns):
			t = k*256/self.num_patterns
			for i in range(self.pattern_res):
				for j in range(self.pattern_res):
					val = lut[(t + phase[i][j]) % 255]
					pat[i][j][0] = pat[i][j][1] = pat[i][j][2] = val
					pat[i][j][3] = int(self.alpha * 255)
			texture = glGenTextures(1)

			glBindTexture(GL_TEXTURE_2D, texture)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
			glTexImage2D(GL_TEXTURE_2D, 0, 4, self.pattern_res, self.pattern_res, 0, GL_RGBA, GL_UNSIGNED_BYTE, pat)
			#self.saveTexture((self.pattern_res, self.pattern_res), "screenshots/pattern_%d.png" % k)
			glBindTexture(GL_TEXTURE_2D, 0)

			self.textures.append(texture)

	def getDisplacement(self, x, y):
		dx = x - 0.5
		dy = y - 0.5
		r  = dx*dx + dy*dy
		if r < 0.0001:
			r = 0.0001
		vx = self.sa*dx/r + 0.02
		vy = self.sa*dy/r
		r  = vx*vx + vy*vy
		if r > self.dmax ** 2:
		  r  = math.sqrt(r)
		  vx *= self.dmax/r
		  vy *= self.dmax/r
		px = x + vx
		py = y + vy
		return [px, py]

	# The main drawing function.
	def DrawGLScene(self):
		# update displacements vbo
		self.updateDisplacements()

		# Draw to the texture in the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, self.fbo)
		glViewport(0,0,512,512)
		# pingpong between the 2 FBO textures
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture2 if self.framenr % 2 is 0 else self.renderedTexture1, 0)

		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glTranslatef(-1.0, -1.0, 0.0)
		glScalef(2.0, 2.0, 1.0)

		# bind the other FBO texture, so that we can warp it
		DM = 1.0 / (self.nmesh-1.0)
		texture = self.framenr % self.num_patterns
		glEnable(GL_TEXTURE_2D)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2 if self.framenr % 2 is not 0  else self.renderedTexture1)

		# warp the texture!
		glEnableClientState(GL_VERTEX_ARRAY)
		glEnableClientState(GL_TEXTURE_COORD_ARRAY)

		self.vbo_locations.bind()
		glVertexPointer(2, GL_FLOAT, 0, self.vbo_locations)
		self.vbo_coords.bind()
		glTexCoordPointer(2, GL_FLOAT, 0, self.vbo_coords)

		self.ibo.bind()
		# remember that the last param should be None, not 0!
		glDrawElements(GL_TRIANGLE_STRIP, self.num_indices, GL_UNSIGNED_SHORT, None)

		self.ibo.unbind()
		self.vbo_locations.unbind()
		self.vbo_coords.unbind()

		glDisableClientState(GL_TEXTURE_COORD_ARRAY)
		glDisableClientState(GL_VERTEX_ARRAY)

		# Blend in some "fresh" noise
		glEnable(GL_BLEND)
		glBindTexture(GL_TEXTURE_2D, self.textures[texture])
		glBegin(GL_QUAD_STRIP)
		glTexCoord2f(0.0,  0.0)
		glVertex2f(0.0, 0.0)
		glTexCoord2f(0.0,  self.tmax)
		glVertex2f(0.0, 1.0)
		glTexCoord2f(self.tmax, 0.0)
		glVertex2f(1.0, 0.0)
		glTexCoord2f(self.tmax, self.tmax)
		glVertex2f(1.0, 1.0)
		glEnd();
		glDisable(GL_BLEND);

		# Draw texture to the screen
		glBindFramebuffer(GL_FRAMEBUFFER, 0)
		glViewport(0,0,512,512)

		glLoadIdentity()
		glTranslatef(-1.0, -1.0, 0.0)
		glScalef(2.0, 2.0, 1.0)

		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2 if self.framenr % 2 is 0  else self.renderedTexture1)
		#self.saveTexture((512, 512), "screenshots/%d.png" % self.framenr)

		glBegin(GL_QUAD_STRIP)
		glTexCoord2f(0.0,  0.0)
		glVertex2f(0.0, 0.0)
		glTexCoord2f(0.0,  1.0)
		glVertex2f(0.0, 1.0)
		glTexCoord2f(1.0, 0.0)
		glVertex2f(1.0, 0.0)
		glTexCoord2f(1.0, 1.0)
		glVertex2f(1.0, 1.0)
		glEnd()
		glDisable(GL_TEXTURE_2D)

		glutSwapBuffers()
		self.framenr += 1
		self.fps()
		#time.sleep(0.01)

	def saveTexture(self, size, filename):
		tex = np.empty(size[0] * size[1], dtype=np.uint8)
		string = glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, tex)
		imm = Image.fromstring("L", size, string)
		imm.save(filename)

	def fps(self):
		self.frames += 1
		if time.time() - self.last_time >= 5:
			current_fps = self.frames / (time.time() - self.last_time)
			print '%.2f fps' % current_fps
			self.frames = 0
			self.last_time = time.time()

	def keyPressed(self, *args):
		# escape
		if args[0] == '\x1b':
			sys.exit()

	def main(self):
		glutInit(sys.argv)
		glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
		glutInitWindowSize(512, 512)
		glutInitWindowPosition(0, 0)
		window = glutCreateWindow("PyIBFV")
		glutDisplayFunc(self.DrawGLScene)
		glutIdleFunc(self.DrawGLScene)
		glutReshapeFunc(self.ReSizeGLScene)
		glutKeyboardFunc(self.keyPressed)
		self.InitGL(512, 512)
		falloffValue = 1.0
		self.rotY = 0.0

		self.makePatterns()
		glutMainLoop()

if __name__ == "__main__":
	print "Hit ESC key to quit."
	ibfv = PyIBFV()
	ibfv.main()
	main()
<commit_msg>Refactored into 2 separate drawing methods. One for drawing IBFV on the FBO texture, and one for drawing the FBO texture to the screen<commit_after>#! /usr/bin/env python

import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.framebufferobjects import *
from OpenGL.arrays import vbo

import time
import sys
import math
import random
import numpy as np
from PIL import Image

class PyIBFV:

	def __init__(self):
		self.nmesh = 100
		self.pattern_res = 64
		self.num_patterns = 32
		self.alpha = 0.12
		self.textures = []
		self.scale = 4.0
		self.tmax = 512/(self.scale*self.pattern_res)
		self.dmax = self.scale / 512

		self.last_time = time.time()
		self.frames = 0
		self.sa = 0.01

	def InitGL(self, Width, Height):
		glClearColor(0.0, 0.0, 0.0, 0.0)
		glClearDepth(1.0)
		glShadeModel(GL_SMOOTH)

		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()

		gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)

		glMatrixMode(GL_MODELVIEW)

		# Create fbo with 2 textures.
		self.fbo = glGenFramebuffers(1)
		glBindFramebuffer(GL_FRAMEBUFFER, self.fbo )

		# FBO texture 1
		self.renderedTexture1 = glGenTextures(1)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture1)
		glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 512, 512, 0,GL_RGB, GL_UNSIGNED_BYTE, None)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

		# FBO texture 2
		self.renderedTexture2 = glGenTextures(1)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2)
		glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 512, 512, 0,GL_RGB, GL_UNSIGNED_BYTE, None)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

		# Set the first texture as color attachment
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture1, 0)

		# Set the list of draw buffers.
		glDrawBuffers(1, GL_COLOR_ATTACHMENT0) #"1" is the size of DrawBuffers
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

		# Clear the 2nd texture
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture2, 0)
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

		self.framenr = 0

		# Set the blending function
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

		# init VBO's for for mesh location and texture coordinates
		# based on: http://dan.lecocq.us/wordpress/2009/12/25/triangle-strip-for-grids-a-construction/
		self.DM = 1.0 / (self.nmesh-1.0)
		size = self.nmesh ** 2 * 2

		# locations
		locations = self.getDisplacements()
		self.vbo_locations = vbo.VBO(locations)

		# texture coordinates
		coords = np.empty(size, dtype=np.float32)
		index = 0
		for i in range(self.nmesh):
			x = self.DM*i
			for j in range(self.nmesh):
				y = self.DM*j
				coords[index + 0] = x
				coords[index + 1] = y
				index += 2
		self.vbo_coords = vbo.VBO(coords)

		# indices
		self.num_indices = self.nmesh * (self.nmesh - 1) * 2
		indices = np.empty(self.num_indices, dtype=np.uint16)
		index = 0
		i = 0
		for x in range(self.nmesh - 1):
			for y in range(self.nmesh):
				if x % 2 == 0:
					indices[i+0] = index + 0
					indices[i+1] = index + self.nmesh
					index += 1
					i += 2
				else:
					indices[i+0] = index + 0
					indices[i+1] = index + self.nmesh
					index -= 1
					i += 2
			index = indices[i-1]
		self.ibo = vbo.VBO(indices, GL_DYNAMIC_DRAW, GL_ELEMENT_ARRAY_BUFFER)

	def getDisplacements(self):
		size = self.nmesh ** 2 * 2
		locations = np.empty(size, dtype=np.float32)
		index = 0
		for i in range(self.nmesh):
			x = self.DM*i
			for j in range(self.nmesh):
				y = self.DM*j
				[px, py] = self.getDisplacement(x, y)
				locations[index + 0] = px
				locations[index + 1] = py
				index += 2
		return locations

	def updateDisplacements(self):
		self.sa = 0.010*math.cos(self.framenr*2.0*math.pi/200.0)
		self.vbo_locations.set_array(self.getDisplacements())

	# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
	def ReSizeGLScene(self, Width, Height):
		if Height == 0:                        # Prevent A Divide By Zero If The Window Is Too Small
			Height = 1

		glViewport(0, 0, Width, Height)        # Reset The Current Viewport And Perspective Transformation
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
		glMatrixMode(GL_MODELVIEW)

	def makePatterns(self):
		lut = np.empty(256)
		phase = np.empty((self.pattern_res,self.pattern_res), dtype=int)
		pat = np.empty((self.pattern_res,self.pattern_res, 4), dtype=np.uint8)

		for i in range(256):
			lut[i] = 0 if i < 127 else 255

		for i in range(self.pattern_res):
			for j in range(self.pattern_res):
				phase[i][j] = random.randint(0, 255)

		for k in range(self.num_patterns):
			t = k*256/self.num_patterns
			for i in range(self.pattern_res):
				for j in range(self.pattern_res):
					val = lut[(t + phase[i][j]) % 255]
					pat[i][j][0] = pat[i][j][1] = pat[i][j][2] = val
					pat[i][j][3] = int(self.alpha * 255)
			texture = glGenTextures(1)

			glBindTexture(GL_TEXTURE_2D, texture)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
			glTexImage2D(GL_TEXTURE_2D, 0, 4, self.pattern_res, self.pattern_res, 0, GL_RGBA, GL_UNSIGNED_BYTE, pat)
			#self.saveTexture((self.pattern_res, self.pattern_res), "screenshots/pattern_%d.png" % k)
			glBindTexture(GL_TEXTURE_2D, 0)

			self.textures.append(texture)

	def getDisplacement(self, x, y):
		dx = x - 0.5
		dy = y - 0.5
		r  = dx*dx + dy*dy
		if r < 0.0001:
			r = 0.0001
		vx = self.sa*dx/r + 0.02
		vy = self.sa*dy/r
		r  = vx*vx + vy*vy
		if r > self.dmax ** 2:
		  r  = math.sqrt(r)
		  vx *= self.dmax/r
		  vy *= self.dmax/r
		px = x + vx
		py = y + vy
		return [px, py]

	def drawToFbo(self):
		# Draw to the texture in the FBO
		glBindFramebuffer(GL_FRAMEBUFFER, self.fbo)
		glViewport(0,0,512,512)
		# pingpong between the 2 FBO textures
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.renderedTexture2 if self.framenr % 2 is 0 else self.renderedTexture1, 0)

		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glTranslatef(-1.0, -1.0, 0.0)
		glScalef(2.0, 2.0, 1.0)

		# bind the other FBO texture, so that we can warp it
		DM = 1.0 / (self.nmesh-1.0)
		texture = self.framenr % self.num_patterns
		glEnable(GL_TEXTURE_2D)
		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2 if self.framenr % 2 is not 0  else self.renderedTexture1)

		# warp the texture!
		glEnableClientState(GL_VERTEX_ARRAY)
		glEnableClientState(GL_TEXTURE_COORD_ARRAY)

		self.vbo_locations.bind()
		glVertexPointer(2, GL_FLOAT, 0, self.vbo_locations)
		self.vbo_coords.bind()
		glTexCoordPointer(2, GL_FLOAT, 0, self.vbo_coords)

		self.ibo.bind()
		# remember that the last param should be None, not 0!
		glDrawElements(GL_TRIANGLE_STRIP, self.num_indices, GL_UNSIGNED_SHORT, None)

		self.ibo.unbind()
		self.vbo_locations.unbind()
		self.vbo_coords.unbind()

		glDisableClientState(GL_TEXTURE_COORD_ARRAY)
		glDisableClientState(GL_VERTEX_ARRAY)

		# Blend in some "fresh" noise
		glEnable(GL_BLEND)
		glBindTexture(GL_TEXTURE_2D, self.textures[texture])
		glBegin(GL_QUAD_STRIP)
		glTexCoord2f(0.0,  0.0)
		glVertex2f(0.0, 0.0)
		glTexCoord2f(0.0,  self.tmax)
		glVertex2f(0.0, 1.0)
		glTexCoord2f(self.tmax, 0.0)
		glVertex2f(1.0, 0.0)
		glTexCoord2f(self.tmax, self.tmax)
		glVertex2f(1.0, 1.0)
		glEnd()
		glDisable(GL_BLEND)

	def drawFboTOScreen(self):
		glBindFramebuffer(GL_FRAMEBUFFER, 0)
		glViewport(0,0,512,512)

		glLoadIdentity()
		glTranslatef(-1.0, -1.0, 0.0)
		glScalef(2.0, 2.0, 1.0)

		glBindTexture(GL_TEXTURE_2D, self.renderedTexture2 if self.framenr % 2 is 0  else self.renderedTexture1)
		#self.saveTexture((512, 512), "screenshots/%d.png" % self.framenr)

		glBegin(GL_QUAD_STRIP)
		glTexCoord2f(0.0,  0.0)
		glVertex2f(0.0, 0.0)
		glTexCoord2f(0.0,  1.0)
		glVertex2f(0.0, 1.0)
		glTexCoord2f(1.0, 0.0)
		glVertex2f(1.0, 0.0)
		glTexCoord2f(1.0, 1.0)
		glVertex2f(1.0, 1.0)
		glEnd()
		glDisable(GL_TEXTURE_2D)

	# The main drawing function.
	def DrawGLScene(self):
		# update displacements vbo
		self.updateDisplacements()
		self.drawToFbo()
		self.drawFboTOScreen()
		glutSwapBuffers()
		self.framenr += 1
		self.fps()

	def saveTexture(self, size, filename):
		tex = np.empty(size[0] * size[1], dtype=np.uint8)
		string = glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, tex)
		imm = Image.fromstring("L", size, string)
		imm.save(filename)

	def fps(self):
		self.frames += 1
		if time.time() - self.last_time >= 5:
			current_fps = self.frames / (time.time() - self.last_time)
			print '%.2f fps' % current_fps
			self.frames = 0
			self.last_time = time.time()

	def keyPressed(self, *args):
		# escape
		if args[0] == '\x1b':
			sys.exit()

	def main(self):
		glutInit(sys.argv)
		glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
		glutInitWindowSize(512, 512)
		glutInitWindowPosition(0, 0)
		window = glutCreateWindow("PyIBFV")
		glutDisplayFunc(self.DrawGLScene)
		glutIdleFunc(self.DrawGLScene)
		glutReshapeFunc(self.ReSizeGLScene)
		glutKeyboardFunc(self.keyPressed)
		self.InitGL(512, 512)
		falloffValue = 1.0
		self.rotY = 0.0

		self.makePatterns()
		glutMainLoop()

if __name__ == "__main__":
	print "Hit ESC key to quit."
	ibfv = PyIBFV()
	ibfv.main()
	main()
<|endoftext|>


<commit_before>from abc import ABC
from django.utils.html import format_html, format_html_join, mark_safe
from itertools import chain
from rdflib import Graph, BNode, URIRef, Literal
import json
from modelview.rdf import handler, field, connection
from modelview.rdf.namespace import *

FACTORIES = {}

def get_factory_templates():
    return {n: f.build_structure_spec() for n, f in FACTORIES.items()}

def get_factory(identifier):
    return FACTORIES[identifier]

class RDFFactory(ABC):
    _field_handler = {}
    _factory_id = None
    _direct_parent = None
    _fields = {}
    _label_field = None

    @classmethod
    def doc(self):
        s = f"""Factory class for {self._direct_parent}. This class has the following fields:

"""
        for f in self.iter_field_names():
            fld = getattr(self, f)
            s += f"* `{f} <{field.rdf_name}>`_ ({fld.rdf_name})"
            if fld.help_text is not None:
                s += ": " + fld.help_text
            s += "\n"
        s += "\n"
        return s

    def __init_subclass__(cls, **kwargs):
        if cls._factory_id is not None:
            FACTORIES[cls._factory_id] = cls
        cls._field_map = {f.rdf_name: k for k, f in cls._fields.items()}
        cls._fields["iri"] = field.IRIField(None, hidden=True)
        cls._field_handler = {f: f.handler for k, f in cls._fields.items()}
        if cls._label_field is None:
            cls._label_field = "iri"

    def __init__(self, iri=None, **kwargs):
        for fld_name, fld in self._fields.items():
            setattr(self, fld_name, field.Container(fld))
        if iri:
            if isinstance(iri, list):
                assert len(iri) <= 1, "Too many IRIs"
                iri = iri[0]
        self.iri.values = [iri] if iri else []
        _internal_fields = set(self.iter_field_names())
        for f in _internal_fields:
            getattr(self, f).field_name = f
        for k, v in kwargs.items():
            if k in _internal_fields:
                getattr(self, k).values = v
            else:
                self.additional_fields[k] = v

    @classmethod
    def from_iri(cls, iri):
        return cls

    def iter_fields(self):
        """Returns an iterator of all fields in this factory"""
        return (getattr(self, k) for k in self.iter_field_names())

    def iter_field_names(self):
        """Returns an iterator of all field names in this factory"""
        return self._fields.keys()

    @classmethod
    def _load_many(cls, identifiers, context, cache=None):
        if cache is None:
            cache = dict()
        cached_objects = {i: cache[i] for i in identifiers if i in cache}
        new_items = [i for i in identifiers if i not in cache]
        result = context.query_all_objects(new_items, cls._fields.items())
        head = result["head"]
        d = dict()
        for t in result["results"]["bindings"]:
            if "s" in t:
                s = cls._read_value(t["s"])
                o = cls._read_value(t.get("o"))
                lo = cls._read_value(t.get("lo"))
                lp = cls._read_value(t.get("lp"))
                fname = t["fname"]["value"]
                d[s] = d.get(s, dict())
                d[s][fname] = d[s].get(fname, []) + [(o, lo)]

        cached_objects.update(
            {i: cls._parse(i, context, d[i], cache=cache) if i in d else cls(iri=i) for i in identifiers}
        )
        return cached_objects

    @staticmethod
    def _read_value(v):
        if isinstance(v, dict):
            t = v["type"]
            if t == "uri":
                return URIRef(v["value"])
            if t == "literal":
                return Literal(v["value"])
            if t == "bnode":
                return BNode(v["value"])
        if v is None:
            return None
        raise Exception(v)

    @classmethod
    def _load_one(cls, identifier, context: connection.ConnectionContext):
        return cls._load_many(
            [identifier],
            context,
        )[identifier]

    @classmethod
    def _find_field(cls, predicate_iri, obj):
        # TODO: There should be a fallback here for additional fields
        return cls._field_map.get(predicate_iri, None)

    @classmethod
    def _parse(cls, identifier, context, obj, cache=None):
        if cache is None:
            cache = dict()
        # obj = cache.get(identifier, dict())
        skipped = set()
        if skipped:
            print("Warning! Some predicates were not processed:", skipped)
        res = cache[identifier] = cls(
            iri=identifier,
            **{p: cls._fields[p].handler(os, context) for p, os in obj.items()},
        )
        return res

    @classmethod
    def _parse_from_structure(cls, structure: dict, identifier=None, cache=None):

        res = cls(
            **{
                p: cls._fields[p].handler.from_structure(
                    structure[p],
                )
                for p in structure
            }
        )

        if identifier:
            res.iri = identifier
            cache[identifier] = res
        return res

    def to_json(self):
        return {f: list(getattr(self, f).to_json()) for f in self.iter_field_names()}

    @classmethod
    def build_structure_spec(cls):
        return {f: fld.spec for f, fld in cls._fields.items()}

    @classmethod
    def _label_option(cls, o, lo):
        return None

    @classmethod
    def load_all_instances(cls, context):
        result = context.query_all_factory_instances(cls)
        l = []
        for t in result["results"]["bindings"]:
            if "s" in t:
                s = cls._read_value(t["s"])
                label = cls._read_value(t.get("ls"))
                l.append(dict(element=s.split("/")[-1], label=label or s))
        return l

class IRIFactory(RDFFactory):
    _fields = dict(
        iri=field.IRIField(rdf_name=dbo.abbreviation, verbose_name="Abbreviation")
    )

class Institution(RDFFactory):
    _factory_id = "institution"
    _direct_parent = OEO.OEO_00000238
    _label_field = "name"
    _fields = dict(
        name=field.TextField(rdf_name=foaf.name, verbose_name="Name"),
        address=field.TextField(rdf_name=foaf.address, verbose_name="Address"),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}."

class Person(RDFFactory):
    _direct_parent = OEO.OEO_00000323
    _factory_id = "person"
    _fields = dict(
        first_name=field.TextField(rdf_name=foaf.givenName, verbose_name="First name"),
        last_name=field.TextField(rdf_name=foaf.familyName, verbose_name="Last name"),
        affiliation=field.FactoryField(
            factory=Institution,
            rdf_name=schema.affiliation,
            verbose_name="Affiliation",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['last_name'].rdf_name}> {lo}."

class AnalysisScope(RDFFactory):
    _factory_id = "scope"
    _direct_parent = OEO_KG.AnalysisScope
    _fields = dict(
        is_defined_by=field.IRIField(
            rdf_name=OEO.OEO_00000504, verbose_name="is defined by"
        ),
        covers_sector=field.PredefinedInstanceField(rdf_name=OEO.OEO_00000505, verbose_name="Sectors", cls_iri=OEO.OEO_00000367),
        covers_energy_carrier=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000331,
            verbose_name="Covers energy carriers",
            subclass=True,
        ),
        covers_energy=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000150,
            verbose_name="Related to energy",
            subclass=True,
        ),
    )

class Scenario(RDFFactory):
    _direct_parent = OEO.OEO_00000364
    _label_field = "name"
    _factory_id = "scenario"
    _fields = dict(
        abbreviation=field.TextField(
            rdf_name=dbo.abbreviation, verbose_name="Abbreviation"
        ),
        abstract=field.TextAreaField(
            rdf_name=dbo.abstract,
            verbose_name="Abstract",
            help_text="A short description of this scenario",
        ),
        name=field.TextField(
            rdf_name=foaf.name,
            verbose_name="Name",
            help_text="Name of this scenario",
        ),
        analysis_scope=field.FactoryField(
            AnalysisScope,
            rdf_name=OEO.OEO_00000504,
            inverse=True,
            verbose_name="Analysis Scope",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}"

class Publication(RDFFactory):
    _factory_id = "publication"
    _direct_parent = OEO.OEO_00020012
    _fields = dict(
        title=field.TextField(
            rdf_name=dc.title,
            verbose_name="Title",
            help_text="Title of the publication",
        ),
        subtitle=field.TextField(rdf_name=dbo.subtitle, verbose_name="Subtitle"),
        publication_year=field.YearField(
            rdf_name=npg.publicationYear,
            verbose_name="Publication year",
            help_text="Year this publication was published in",
        ),
        abstract=field.TextAreaField(
            rdf_name=dbo.abstract,
            verbose_name="Abstract",
            help_text="Abstract of the publication",
        ),
        url=field.IRIField(
            rdf_name=schema.url,
            verbose_name="URL",
            help_text="Link to this publication",
        ),
        authors=field.FactoryField(
            rdf_name=OEO.OEO_00000506,
            verbose_name="Authors",
            help_text="Authors of this publication",
            factory=Person,
        ),
        about=field.IRIField(
            rdf_name=obo.IAO_0000136,
            verbose_name="About",
            help_text="Elements of this publication",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['title'].rdf_name}> {lo}."

class Model(RDFFactory):
    _factory_id = "model"
    _direct_parent = OEO.OEO_00020011
    _fields = dict(
        url=field.IRIField(rdf_name=schema.url, verbose_name="URL"),
        name=field.TextField(rdf_name=dc.title, verbose_name="Name"),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}"

class Dataset(RDFFactory):
    _factory_id = "dataset"
    _fields = dict(
        url=field.IRIField(rdf_name=schema.url, verbose_name="URL"),
    )

    @property
    def label(self):
        return self.url.values[0]

class ModelCalculation(RDFFactory):
    _factory_id = "model_calculation"
    _fields = dict(
        has_input=field.FactoryField(
            rdf_name=obo.RO_0002233, factory=Dataset, verbose_name="Inputs"
        ),
        has_output=field.FactoryField(
            rdf_name=obo.RO_0002234, factory=Dataset, verbose_name="Outputs"
        ),
        uses=field.IRIField(
            rdf_name=OEO.OEO_00000501,
            verbose_name="Involved Models",
        ),
    )

class Study(RDFFactory):
    _factory_id = "study"
    _direct_parent = OEO.OEO_00020011
    _fields = dict(
        funding_source=field.FactoryField(
            Institution,
            rdf_name=OEO.OEO_00000509,
            verbose_name="Funding source",
        ),
        covers_energy_carrier=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000331,
            verbose_name="Covers energy carriers",
            subclass=True,
        ),
        covers_energy=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000150,
            verbose_name="Related to energy",
            subclass=True,
        ),
        model_calculations=field.FactoryField(
            rdf_name=obo.BFO_0000051,
            factory=ModelCalculation,
            filter=[f"a <{OEO.OEO_00000275}>"],
            verbose_name="Model Calculations",
        ),
        published_in=field.FactoryField(
            Publication,
            rdf_name=obo.IAO_0000136,
            inverse=True,
            verbose_name="Publications",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"_:b <{cls._fields['published_in'].rdf_name}> {o}; <{dc.title}> {lo}"
<commit_msg>Add link to Scenarios<commit_after>from abc import ABC
from django.utils.html import format_html, format_html_join, mark_safe
from itertools import chain
from rdflib import Graph, BNode, URIRef, Literal
import json
from modelview.rdf import handler, field, connection
from modelview.rdf.namespace import *

FACTORIES = {}

def get_factory_templates():
    return {n: f.build_structure_spec() for n, f in FACTORIES.items()}

def get_factory(identifier):
    return FACTORIES[identifier]

class RDFFactory(ABC):
    _field_handler = {}
    _factory_id = None
    _direct_parent = None
    _fields = {}
    _label_field = None

    @classmethod
    def doc(self):
        s = f"""Factory class for {self._direct_parent}. This class has the following fields:

"""
        for f in self.iter_field_names():
            fld = getattr(self, f)
            s += f"* `{f} <{field.rdf_name}>`_ ({fld.rdf_name})"
            if fld.help_text is not None:
                s += ": " + fld.help_text
            s += "\n"
        s += "\n"
        return s

    def __init_subclass__(cls, **kwargs):
        if cls._factory_id is not None:
            FACTORIES[cls._factory_id] = cls
        cls._field_map = {f.rdf_name: k for k, f in cls._fields.items()}
        cls._fields["iri"] = field.IRIField(None, hidden=True)
        cls._field_handler = {f: f.handler for k, f in cls._fields.items()}
        if cls._label_field is None:
            cls._label_field = "iri"

    def __init__(self, iri=None, **kwargs):
        for fld_name, fld in self._fields.items():
            setattr(self, fld_name, field.Container(fld))
        if iri:
            if isinstance(iri, list):
                assert len(iri) <= 1, "Too many IRIs"
                iri = iri[0]
        self.iri.values = [iri] if iri else []
        _internal_fields = set(self.iter_field_names())
        for f in _internal_fields:
            getattr(self, f).field_name = f
        for k, v in kwargs.items():
            if k in _internal_fields:
                getattr(self, k).values = v
            else:
                self.additional_fields[k] = v

    @classmethod
    def from_iri(cls, iri):
        return cls

    def iter_fields(self):
        """Returns an iterator of all fields in this factory"""
        return (getattr(self, k) for k in self.iter_field_names())

    def iter_field_names(self):
        """Returns an iterator of all field names in this factory"""
        return self._fields.keys()

    @classmethod
    def _load_many(cls, identifiers, context, cache=None):
        if cache is None:
            cache = dict()
        cached_objects = {i: cache[i] for i in identifiers if i in cache}
        new_items = [i for i in identifiers if i not in cache]
        result = context.query_all_objects(new_items, cls._fields.items())
        head = result["head"]
        d = dict()
        for t in result["results"]["bindings"]:
            if "s" in t:
                s = cls._read_value(t["s"])
                o = cls._read_value(t.get("o"))
                lo = cls._read_value(t.get("lo"))
                lp = cls._read_value(t.get("lp"))
                fname = t["fname"]["value"]
                d[s] = d.get(s, dict())
                d[s][fname] = d[s].get(fname, []) + [(o, lo)]

        cached_objects.update(
            {i: cls._parse(i, context, d[i], cache=cache) if i in d else cls(iri=i) for i in identifiers}
        )
        return cached_objects

    @staticmethod
    def _read_value(v):
        if isinstance(v, dict):
            t = v["type"]
            if t == "uri":
                return URIRef(v["value"])
            if t == "literal":
                return Literal(v["value"])
            if t == "bnode":
                return BNode(v["value"])
        if v is None:
            return None
        raise Exception(v)

    @classmethod
    def _load_one(cls, identifier, context: connection.ConnectionContext):
        return cls._load_many(
            [identifier],
            context,
        )[identifier]

    @classmethod
    def _find_field(cls, predicate_iri, obj):
        # TODO: There should be a fallback here for additional fields
        return cls._field_map.get(predicate_iri, None)

    @classmethod
    def _parse(cls, identifier, context, obj, cache=None):
        if cache is None:
            cache = dict()
        # obj = cache.get(identifier, dict())
        skipped = set()
        if skipped:
            print("Warning! Some predicates were not processed:", skipped)
        res = cache[identifier] = cls(
            iri=identifier,
            **{p: cls._fields[p].handler(os, context) for p, os in obj.items()},
        )
        return res

    @classmethod
    def _parse_from_structure(cls, structure: dict, identifier=None, cache=None):

        res = cls(
            **{
                p: cls._fields[p].handler.from_structure(
                    structure[p],
                )
                for p in structure
            }
        )

        if identifier:
            res.iri = identifier
            cache[identifier] = res
        return res

    def to_json(self):
        return {f: list(getattr(self, f).to_json()) for f in self.iter_field_names()}

    @classmethod
    def build_structure_spec(cls):
        return {f: fld.spec for f, fld in cls._fields.items()}

    @classmethod
    def _label_option(cls, o, lo):
        return None

    @classmethod
    def load_all_instances(cls, context):
        result = context.query_all_factory_instances(cls)
        l = []
        for t in result["results"]["bindings"]:
            if "s" in t:
                s = cls._read_value(t["s"])
                label = cls._read_value(t.get("ls"))
                l.append(dict(element=s.split("/")[-1], label=label or s))
        return l

class IRIFactory(RDFFactory):
    _fields = dict(
        iri=field.IRIField(rdf_name=dbo.abbreviation, verbose_name="Abbreviation")
    )

class Institution(RDFFactory):
    _factory_id = "institution"
    _direct_parent = OEO.OEO_00000238
    _label_field = "name"
    _fields = dict(
        name=field.TextField(rdf_name=foaf.name, verbose_name="Name"),
        address=field.TextField(rdf_name=foaf.address, verbose_name="Address"),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}."

class Person(RDFFactory):
    _direct_parent = OEO.OEO_00000323
    _factory_id = "person"
    _fields = dict(
        first_name=field.TextField(rdf_name=foaf.givenName, verbose_name="First name"),
        last_name=field.TextField(rdf_name=foaf.familyName, verbose_name="Last name"),
        affiliation=field.FactoryField(
            factory=Institution,
            rdf_name=schema.affiliation,
            verbose_name="Affiliation",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['last_name'].rdf_name}> {lo}."

class AnalysisScope(RDFFactory):
    _factory_id = "scope"
    _direct_parent = OEO_KG.AnalysisScope
    _fields = dict(
        is_defined_by=field.IRIField(
            rdf_name=OEO.OEO_00000504, verbose_name="is defined by"
        ),
        covers_sector=field.PredefinedInstanceField(rdf_name=OEO.OEO_00000505, verbose_name="Sectors", cls_iri=OEO.OEO_00000367),
        covers_energy_carrier=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000331,
            verbose_name="Covers energy carriers",
            subclass=True,
        ),
        covers_energy=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000150,
            verbose_name="Related to energy",
            subclass=True,
        ),
    )

class Scenario(RDFFactory):
    _direct_parent = OEO.OEO_00000364
    _label_field = "name"
    _factory_id = "scenario"
    _fields = dict(
        abbreviation=field.TextField(
            rdf_name=dbo.abbreviation, verbose_name="Abbreviation"
        ),
        abstract=field.TextAreaField(
            rdf_name=dbo.abstract,
            verbose_name="Abstract",
            help_text="A short description of this scenario",
        ),
        name=field.TextField(
            rdf_name=foaf.name,
            verbose_name="Name",
            help_text="Name of this scenario",
        ),
        analysis_scope=field.FactoryField(
            AnalysisScope,
            rdf_name=OEO.OEO_00000504,
            inverse=True,
            verbose_name="Analysis Scope",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}"

class Publication(RDFFactory):
    _factory_id = "publication"
    _direct_parent = OEO.OEO_00020012
    _fields = dict(
        title=field.TextField(
            rdf_name=dc.title,
            verbose_name="Title",
            help_text="Title of the publication",
        ),
        subtitle=field.TextField(rdf_name=dbo.subtitle, verbose_name="Subtitle"),
        publication_year=field.YearField(
            rdf_name=npg.publicationYear,
            verbose_name="Publication year",
            help_text="Year this publication was published in",
        ),
        abstract=field.TextAreaField(
            rdf_name=dbo.abstract,
            verbose_name="Abstract",
            help_text="Abstract of the publication",
        ),
        url=field.IRIField(
            rdf_name=schema.url,
            verbose_name="URL",
            help_text="Link to this publication",
        ),
        authors=field.FactoryField(
            rdf_name=OEO.OEO_00000506,
            verbose_name="Authors",
            help_text="Authors of this publication",
            factory=Person,
        ),
        about=field.IRIField(
            rdf_name=obo.IAO_0000136,
            verbose_name="About",
            help_text="Elements of this publication",
        ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['title'].rdf_name}> {lo}."

class Model(RDFFactory):
    _factory_id = "model"
    _direct_parent = OEO.OEO_00020011
    _fields = dict(
        url=field.IRIField(rdf_name=schema.url, verbose_name="URL"),
        name=field.TextField(rdf_name=dc.title, verbose_name="Name"),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"{o} <{cls._fields['name'].rdf_name}> {lo}"

class Dataset(RDFFactory):
    _factory_id = "dataset"
    _fields = dict(
        url=field.IRIField(rdf_name=schema.url, verbose_name="URL"),
    )

    @property
    def label(self):
        return self.url.values[0]

class ModelCalculation(RDFFactory):
    _factory_id = "model_calculation"
    _fields = dict(
        has_input=field.FactoryField(
            rdf_name=obo.RO_0002233, factory=Dataset, verbose_name="Inputs"
        ),
        has_output=field.FactoryField(
            rdf_name=obo.RO_0002234, factory=Dataset, verbose_name="Outputs"
        ),
        uses=field.IRIField(
            rdf_name=OEO.OEO_00000501,
            verbose_name="Involved Models",
        ),
    )

class Study(RDFFactory):
    _factory_id = "study"
    _direct_parent = OEO.OEO_00020011
    _fields = dict(
        funding_source=field.FactoryField(
            Institution,
            rdf_name=OEO.OEO_00000509,
            verbose_name="Funding source",
        ),
        covers_energy_carrier=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000331,
            verbose_name="Covers energy carriers",
            subclass=True,
        ),
        covers_energy=field.PredefinedInstanceField(
            rdf_name=OEO.OEO_00000523,
            cls_iri=OEO.OEO_00000150,
            verbose_name="Related to energy",
            subclass=True,
        ),
        model_calculations=field.FactoryField(
            rdf_name=obo.BFO_0000051,
            factory=ModelCalculation,
            filter=[f"a <{OEO.OEO_00000275}>"],
            verbose_name="Model Calculations",
        ),
        published_in=field.FactoryField(
            Publication,
            rdf_name=obo.IAO_0000136,
            inverse=True,
            verbose_name="Publications",
        ),
        scenarios=field.FactoryField(
                Scenario,
                rdf_name=obo.RO_0000057,
                verbose_name="Scenarios",
            ),
    )

    @classmethod
    def _label_option(cls, o, lo):
        return f"_:b <{cls._fields['published_in'].rdf_name}> {o}; <{dc.title}> {lo}"
<|endoftext|>


<commit_before>from __future__ import absolute_import
from ..constants import CLUSTER_OPERATIONS
from ..layer import Layer

def cluster_size_layer(
        source, operation='count', value=None, resolution=32,
        title='', size=None, color=None, description='', footer='',
        legend=True, popup=True, widget=False, animate=None):
    """Helper function for quickly creating a size symbol map with
    continuous size scaled by cluster.

    Args:
        source (:py:class:`Dataset <cartoframes.data.Dataset>` or str): Dataset
          or text representing a table or query associated with user account.
        value (str): Column to symbolize by.
        title (str, optional): Title of legend.
        size (str, optiona): Min/max size array in CARTO VL syntax. Default is
          '[2, 40]' for point geometries and '[1, 10]' for lines.
        color (str, optional): Hex value, rgb expression, or other valid
          CARTO VL color. Defaults is '#FFB927' for point geometries and
          '#4CC8A3' for lines.
        description (str, optional): Description text legend placed under legend title.
        footer (str, optional): Footer text placed under legend items.
        legend (bool, optional): Display map legend: "True" or "False".
          Set to "True" by default.
        popup (bool, optional): Display popups on hover and click: "True" or "False".
          Set to "True" by default.
        widget (bool, optional): Display a widget for mapped data.
          Set to "False" by default.
        animate (str, optional): Animate features by date/time or other numeric field.

    Returns:
        cartoframes.viz.Layer: Layer styled by `value`.
        Includes a legend, popup and widget on `value`.
    """

    breakpoints = _get_breakpoints(resolution)
    cluster_operation = _get_cluster_operation(operation, value)
    cluster_operation_title = _get_cluster_operation_title(operation, value)
    animation_filter = _get_animation(animate, cluster_operation)

    return Layer(
        source,
        style={
            'point': {
                'width': 'ramp(linear({0}, viewportMIN({1}), viewportMAX({2})), [{3}])'.format(
                    cluster_operation, cluster_operation, cluster_operation, breakpoints),
                'color': 'opacity({0}, 0.8)'.format(color or '#FFB927'),
                'strokeColor': 'opacity(#222, ramp(linear(zoom(), 0, 18),[0, 0.6]))',
                'filter': animation_filter,
                'resolution': '{0}'.format(resolution)
            }
        },
        popup=popup and not animate and {
            'hover': {
                'title': title or cluster_operation_title,
                'value': cluster_operation
            }
        },
        legend=legend and {
            'type': {
                'point': 'size-continuous-point'
            },
            'title': title or cluster_operation_title,
            'description': description,
            'footer': footer
        },
        widgets=[
            animate and {
                'type': 'time-series',
                'value': animate,
                'title': 'Animation'
            },
            widget and value is not None and {
                'type': 'histogram',
                'value': value,
                'title': 'Distribution'
            }
        ]
    )

def _get_animation(animate, cluster_operation):
    return 'animation(linear({0}), 5, fade(1,1))'.format(cluster_operation) if animate else '1'

def _get_breakpoints(resolution):
    return ', '.join([
        '{0}'.format(resolution / 8),
        '{0}'.format(resolution / 2),
        '{0}'.format(resolution)
    ])

def _get_cluster_operation_title(operation, value):
    if value is not None and operation != 'count':
        return '{0} ({1})'.format(value, operation)

    return operation

def _get_cluster_operation(operation, value):
    if value is not None and operation != 'count':
        return '{0}(${1})'.format(CLUSTER_OPERATIONS[operation], value)

    return '{0}()'.format(CLUSTER_OPERATIONS[operation])
<commit_msg>Add blank line<commit_after>from __future__ import absolute_import

from ..constants import CLUSTER_OPERATIONS
from ..layer import Layer

def cluster_size_layer(
        source, operation='count', value=None, resolution=32,
        title='', size=None, color=None, description='', footer='',
        legend=True, popup=True, widget=False, animate=None):
    """Helper function for quickly creating a size symbol map with
    continuous size scaled by cluster.

    Args:
        source (:py:class:`Dataset <cartoframes.data.Dataset>` or str): Dataset
          or text representing a table or query associated with user account.
        value (str): Column to symbolize by.
        title (str, optional): Title of legend.
        size (str, optiona): Min/max size array in CARTO VL syntax. Default is
          '[2, 40]' for point geometries and '[1, 10]' for lines.
        color (str, optional): Hex value, rgb expression, or other valid
          CARTO VL color. Defaults is '#FFB927' for point geometries and
          '#4CC8A3' for lines.
        description (str, optional): Description text legend placed under legend title.
        footer (str, optional): Footer text placed under legend items.
        legend (bool, optional): Display map legend: "True" or "False".
          Set to "True" by default.
        popup (bool, optional): Display popups on hover and click: "True" or "False".
          Set to "True" by default.
        widget (bool, optional): Display a widget for mapped data.
          Set to "False" by default.
        animate (str, optional): Animate features by date/time or other numeric field.

    Returns:
        cartoframes.viz.Layer: Layer styled by `value`.
        Includes a legend, popup and widget on `value`.
    """

    breakpoints = _get_breakpoints(resolution)
    cluster_operation = _get_cluster_operation(operation, value)
    cluster_operation_title = _get_cluster_operation_title(operation, value)
    animation_filter = _get_animation(animate, cluster_operation)

    return Layer(
        source,
        style={
            'point': {
                'width': 'ramp(linear({0}, viewportMIN({1}), viewportMAX({2})), [{3}])'.format(
                    cluster_operation, cluster_operation, cluster_operation, breakpoints),
                'color': 'opacity({0}, 0.8)'.format(color or '#FFB927'),
                'strokeColor': 'opacity(#222, ramp(linear(zoom(), 0, 18),[0, 0.6]))',
                'filter': animation_filter,
                'resolution': '{0}'.format(resolution)
            }
        },
        popup=popup and not animate and {
            'hover': {
                'title': title or cluster_operation_title,
                'value': cluster_operation
            }
        },
        legend=legend and {
            'type': {
                'point': 'size-continuous-point'
            },
            'title': title or cluster_operation_title,
            'description': description,
            'footer': footer
        },
        widgets=[
            animate and {
                'type': 'time-series',
                'value': animate,
                'title': 'Animation'
            },
            widget and value is not None and {
                'type': 'histogram',
                'value': value,
                'title': 'Distribution'
            }
        ]
    )

def _get_animation(animate, cluster_operation):
    return 'animation(linear({0}), 5, fade(1,1))'.format(cluster_operation) if animate else '1'

def _get_breakpoints(resolution):
    return ', '.join([
        '{0}'.format(resolution / 8),
        '{0}'.format(resolution / 2),
        '{0}'.format(resolution)
    ])

def _get_cluster_operation_title(operation, value):
    if value is not None and operation != 'count':
        return '{0} ({1})'.format(value, operation)

    return operation

def _get_cluster_operation(operation, value):
    if value is not None and operation != 'count':
        return '{0}(${1})'.format(CLUSTER_OPERATIONS[operation], value)

    return '{0}()'.format(CLUSTER_OPERATIONS[operation])
<|endoftext|>


<commit_before>import subprocess
import re
import collections

def sh(cmd, shell=True):
    return Sh(None, cmd, shell)

class Stream(object):
    _stream_classes = {}

    def __init__(self, stream):
        if not self._stream_classes:
            self.__reg_class(Stream)

        self._stream = stream

        self.__is_end = False

    def __reg_class(self, cls):
        self._stream_classes[cls.__name__] = cls
        for subclass in cls.__subclasses__():
            self.__reg_class(subclass)

    def __getattr__(self, name):
        cap_name = name.capitalize()
        if cap_name not in self._stream_classes:
            # try to update the inheritance hierarchy
            self.__reg_class(Stream)

        if cap_name in self._stream_classes:
            cls = self._stream_classes[cap_name]
            return lambda *args, **kwargs: cls(self, *args, **kwargs)
        else:
            return None

    def __iter__(self):
        for elem in self._do_iter():
            yield elem
            if self.__is_end:
                break

        self._end_iter()

    def _do_iter(self):
        raise NotImplemented

    def _end_iter(self):
        if not self.__is_end:
            self._do_end_iter()
            if self._stream:
                self._stream._end_iter()
            self.__is_end = True

    def _do_end_iter(self):
        pass

class Sh(Stream):
    ''' Run a shell program
    '''

    def __init__(self, stream, cmd, shell=True):
        Stream.__init__(self, stream)
        if shell:
            if not isinstance(cmd, str):
                cmd = ' '.join(cmd)
        else:
            if isinstance(cmd, str):
                cmd = cmd.split()

        self.__cmd = cmd
        if stream:
            if isinstance(stream, Sh):
                stdin_pipe = stream.get_process().stdout
            else:
                stdin_pipe = subprocess.PIPE
        else:
            stdin_pipe = None
        self.__p = subprocess.Popen(cmd, shell=shell,
                                    stdin=stdin_pipe, stdout=subprocess.PIPE)

    def get_process(self):
        return self.__p

    def _do_iter(self):
        if self._stream and not isinstance(self._stream, Sh):
            for line in self._stream:
                self.__p.stdin.write(line)
            self.__p.stdin.close()

        for line in self.__p.stdout.xreadlines():
            yield line

    def _do_end_iter(self):
        self.__p.stdout.close()
        self.__p.wait()

class Grep(Stream):
    def __init__(self, stream, pattern):
        Stream.__init__(self, stream)
        self.__regex = re.compile(pattern)

    def _do_iter(self):
        for elem in self._stream:
            if self.__regex.search(elem):
                yield elem

class Col(Stream):
    def __init__(self, stream, column, sep=None, newline=True):
        Stream.__init__(self, stream)
        self.__column = column
        self.__sep = sep
        self.__line_end = '\n' if newline else ''

    def _do_iter(self):
        col = self.__column
        line_end = self.__line_end
        for line in self._stream:
            cols = line.split(self.__sep)
            yield (cols[col] if col < len(cols) else '') + line_end

class Head(Stream):
    def __init__(self, stream, line_num = 10):
        Stream.__init__(self, stream)
        self.__line_num = line_num if line_num > 0 else 10

    def _do_iter(self):
        for line_num, line in enumerate(self._stream):
            if line_num < self.__line_num:
                yield line
                if line_num == self.__line_num - 1:
                    return

class Tail(Stream):
    def __init__(self, stream, line_num = 10):
        Stream.__init__(self, stream)
        self.__line_num = line_num

    def _do_iter(self):
        last_lines = collections.deque()
        stream_iter = iter(self._stream)
        while len(last_lines) < self.__line_num:
            try:
                last_lines.append(stream_iter.next())
            except StopIteration:
                break

        for line in stream_iter:
            last_lines.popleft()
            last_lines.append(line)

        for line in last_lines:
            yield line<commit_msg>Add list method<commit_after>import subprocess
import re
import collections

def sh(cmd, shell=True):
    return Sh(None, cmd, shell)

class Stream(object):
    _stream_classes = {}

    def __init__(self, stream):
        if not self._stream_classes:
            self.__reg_class(Stream)

        self._stream = stream

        self.__is_end = False

    def __reg_class(self, cls):
        self._stream_classes[cls.__name__] = cls
        for subclass in cls.__subclasses__():
            self.__reg_class(subclass)

    def list(self):
        return list(self)

    def __getattr__(self, name):
        cap_name = name.capitalize()
        if cap_name not in self._stream_classes:
            # try to update the inheritance hierarchy
            self.__reg_class(Stream)

        if cap_name in self._stream_classes:
            cls = self._stream_classes[cap_name]
            return lambda *args, **kwargs: cls(self, *args, **kwargs)
        else:
            return None

    def __iter__(self):
        for elem in self._do_iter():
            yield elem
            if self.__is_end:
                break

        self._end_iter()

    def _do_iter(self):
        raise NotImplemented

    def _end_iter(self):
        if not self.__is_end:
            self._do_end_iter()
            if self._stream:
                self._stream._end_iter()
            self.__is_end = True

    def _do_end_iter(self):
        pass

class Sh(Stream):
    ''' Run a shell program
    '''

    def __init__(self, stream, cmd, shell=True):
        Stream.__init__(self, stream)
        if shell:
            if not isinstance(cmd, str):
                cmd = ' '.join(cmd)
        else:
            if isinstance(cmd, str):
                cmd = cmd.split()

        self.__cmd = cmd
        if stream:
            if isinstance(stream, Sh):
                stdin_pipe = stream.get_process().stdout
            else:
                stdin_pipe = subprocess.PIPE
        else:
            stdin_pipe = None
        self.__p = subprocess.Popen(cmd, shell=shell,
                                    stdin=stdin_pipe, stdout=subprocess.PIPE)

    def get_process(self):
        return self.__p

    def _do_iter(self):
        if self._stream and not isinstance(self._stream, Sh):
            for line in self._stream:
                self.__p.stdin.write(line)
            self.__p.stdin.close()

        for line in self.__p.stdout.xreadlines():
            yield line

    def _do_end_iter(self):
        self.__p.stdout.close()
        self.__p.wait()

class Grep(Stream):
    def __init__(self, stream, pattern):
        Stream.__init__(self, stream)
        self.__regex = re.compile(pattern)

    def _do_iter(self):
        for elem in self._stream:
            if self.__regex.search(elem):
                yield elem

class Col(Stream):
    def __init__(self, stream, column, sep=None, newline=True):
        Stream.__init__(self, stream)
        self.__column = column
        self.__sep = sep
        self.__line_end = '\n' if newline else ''

    def _do_iter(self):
        col = self.__column
        line_end = self.__line_end
        for line in self._stream:
            cols = line.split(self.__sep)
            yield (cols[col] if col < len(cols) else '') + line_end

class Head(Stream):
    def __init__(self, stream, line_num = 10):
        Stream.__init__(self, stream)
        self.__line_num = line_num if line_num > 0 else 10

    def _do_iter(self):
        for line_num, line in enumerate(self._stream):
            if line_num < self.__line_num:
                yield line
                if line_num == self.__line_num - 1:
                    return

class Tail(Stream):
    def __init__(self, stream, line_num = 10):
        Stream.__init__(self, stream)
        self.__line_num = line_num

    def _do_iter(self):
        last_lines = collections.deque()
        stream_iter = iter(self._stream)
        while len(last_lines) < self.__line_num:
            try:
                last_lines.append(stream_iter.next())
            except StopIteration:
                break

        for line in stream_iter:
            last_lines.popleft()
            last_lines.append(line)

        for line in last_lines:
            yield line<|endoftext|>


<commit_before>from django.db import models
from myauth.models import MyUser

from django.utils import timezone
from django.utils.translation import ugettext as _

class Community(models.Model):
    name = models.CharField(max_length=32)
    members = models.ManyToManyField(MyUser, related_name="members")
    conf_sendmail = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Bill(models.Model):
    name = models.CharField(max_length=1023)
    community = models.ForeignKey(Community)
    is_open = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Payer(models.Model):
    # TODO user should be unique per bill
    user = models.ForeignKey(MyUser)
    bill = models.ForeignKey(Bill, related_name="payers")
    fraction = models.DecimalField(max_digits=3, decimal_places=2)

    def __str__(self):
        return _("Bill '%(bill)s': %(user)s with fraction %(fraction)s") % {'bill': self.bill, 'user': self.user, 'fraction': self.fraction}

class Shop(models.Model):
    name = models.CharField(max_length=30)
    community = models.ForeignKey(Community)

    def __str__(self):
        return self.name

class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True)
    community = models.ForeignKey(Community)
    visible = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Shopping(models.Model):
    user = models.ForeignKey(MyUser)
    community = models.ForeignKey(Community)
    time = models.DateField(default=timezone.now)
    shop = models.ForeignKey(Shop, related_name="shoppings")
    expenses = models.DecimalField(max_digits=10, decimal_places=2)
    num_products = models.PositiveIntegerField()
    tags = models.ManyToManyField(Tag, related_name="tags")
    # this shopping will be part of the monthly billing
    is_regular_shopping = models.BooleanField(default=True)
    # this shopping is assigned to a specific bill
    bill = models.ForeignKey(Bill, null=True, blank=True, related_name="shoppings")
    comment = models.CharField(max_length=1024, blank=True, null=True)

    def __str__(self):
        return _("%(expenses)s with %(products)d items by %(user)s at %(shop)s") % {'expenses': self.expenses, 'user': self.user, 'products': self.num_products, 'shop': self.shop}
<commit_msg>some minor model changes<commit_after>from django.db import models
from myauth.models import MyUser

from django.utils import timezone
from django.utils.translation import ugettext as _

class Community(models.Model):
    name = models.CharField(max_length=32)
    time = models.DateTimeField(default=timezone.now)
    members = models.ManyToManyField(MyUser, related_name="members")
    conf_sendmail = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Bill(models.Model):
    name = models.CharField(max_length=1023)
    community = models.ForeignKey(Community)
    is_open = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Payer(models.Model):
    # TODO user should be unique per bill
    user = models.ForeignKey(MyUser)
    bill = models.ForeignKey(Bill, related_name="payers")
    fraction = models.DecimalField(max_digits=3, decimal_places=2)

    def __str__(self):
        return _("Bill '%(bill)s': %(user)s with fraction %(fraction)s") % {'bill': self.bill, 'user': self.user, 'fraction': self.fraction}

class Shop(models.Model):
    name = models.CharField(max_length=30)
    community = models.ForeignKey(Community)

    def __str__(self):
        return self.name

class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True)
    community = models.ForeignKey(Community)
    visible = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Shopping(models.Model):
    user = models.ForeignKey(MyUser)
    community = models.ForeignKey(Community)
    time = models.DateTimeField(default=timezone.now)
    shopping_day = models.DateField(default=timezone.now)
    shop = models.ForeignKey(Shop, related_name="shoppings")
    expenses = models.DecimalField(max_digits=10, decimal_places=2)
    num_products = models.PositiveIntegerField()
    tags = models.ManyToManyField(Tag, related_name="tags")
    # this shopping will be part of the monthly billing
    automatic_billing = models.BooleanField(default=True)
    # this shopping is assigned to a specific bill
    bill = models.ForeignKey(Bill, null=True, blank=True, related_name="shoppings")
    comment = models.CharField(max_length=1024, blank=True, null=True)

    def __str__(self):
        return _("%(expenses)s with %(products)d items by %(user)s at %(shop)s") % {'expenses': self.expenses, 'user': self.user, 'products': self.num_products, 'shop': self.shop}
<|endoftext|>


<commit_before>from collections import namedtuple

from graphql.core.type import (
    GraphQLID,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString,
    GraphQLField
)

from graphql_relay.node.node import (
    nodeDefinitions,
    globalIdField,
    fromGlobalId
)

from graphql_relay.connection.arrayconnection import (
    connectionFromArray
)

from graphql_relay.connection.connection import (
    connectionArgs,
    connectionDefinitions
)

from graphql_relay.mutation.mutation import (
    mutationWithClientMutationId
)

from .data import (
    Faction,
    Ship,
    getFaction,
    getShip,
    getRebels,
    getEmpire,
    createShip,
)

# This is a basic end-to-end test, designed to demonstrate the various
# capabilities of a Relay-compliant GraphQL server.
#
# It is recommended that readers of this test be familiar with
# the end-to-end test in GraphQL.js first, as this test skips
# over the basics covered there in favor of illustrating the
# key aspects of the Relay spec that this test is designed to illustrate.
#
# We will create a GraphQL schema that describes the major
# factions and ships in the original Star Wars trilogy.
#
# NOTE: This may contain spoilers for the original Star
# Wars trilogy.

# Using our shorthand to describe type systems, the type system for our
# example will be the followng:
#
# interface Node {
#   id: ID!
# }
#
# type Faction : Node {
#   id: ID!
#   name: String
#   ships: ShipConnection
# }
#
# type Ship : Node {
#   id: ID!
#   name: String
# }
#
# type ShipConnection {
#   edges: [ShipEdge]
#   pageInfo: PageInfo!
# }
#
# type ShipEdge {
#   cursor: String!
#   node: Ship
# }
#
# type PageInfo {
#   hasNextPage: Boolean!
#   hasPreviousPage: Boolean!
#   startCursor: String
#   endCursor: String
# }
#
# type Query {
#   rebels: Faction
#   empire: Faction
#   node(id: ID!): Node
# }
#
# input IntroduceShipInput {
#   clientMutationId: string!
#   shipName: string!
#   factionId: ID!
# }
#
# input IntroduceShipPayload {
#   clientMutationId: string!
#   ship: Ship
#   faction: Faction
# }
#
# type Mutation {
#   introduceShip(input IntroduceShipInput!): IntroduceShipPayload
# }

# We get the node interface and field from the relay library.
#
# The first method is the way we resolve an ID to its object. The second is the
# way we resolve an object that implements node to its type.
def getNode(globalId, *args):
    resolvedGlobalId = fromGlobalId(globalId)
    _type, _id = resolvedGlobalId.type, resolvedGlobalId.id
    if _type == 'Faction':
        return getFaction(_id)
    elif _type == 'Ship':
        return getShip(_id)
    else:
        return None

def getNodeType(obj):
    if isinstance(obj, Faction):
        return factionType
    else:
        return shipType

_nodeDefinitions = nodeDefinitions(getNode, getNodeType)
nodeField, nodeInterface = _nodeDefinitions.nodeField, _nodeDefinitions.nodeInterface

# We define our basic ship type.
#
# This implements the following type system shorthand:
#   type Ship : Node {
#     id: String!
#     name: String
#   }
shipType = GraphQLObjectType(
    name='Ship',
    description= 'A ship in the Star Wars saga',
    fields=lambda: {
        'id': globalIdField('Ship'),
        'name': GraphQLField(
            GraphQLString,
            description= 'The name of the ship.',
        )
    },
    interfaces= [nodeInterface]
)

# We define a connection between a faction and its ships.
#
# connectionType implements the following type system shorthand:
#   type ShipConnection {
#     edges: [ShipEdge]
#     pageInfo: PageInfo!
#   }
#
# connectionType has an edges field - a list of edgeTypes that implement the
# following type system shorthand:
#   type ShipEdge {
#     cursor: String!
#     node: Ship
#   }
shipConnection = connectionDefinitions('Ship', shipType).connectionType

# We define our faction type, which implements the node interface.
#
# This implements the following type system shorthand:
#   type Faction : Node {
#     id: String!
#     name: String
#     ships: ShipConnection
#   }
factionType = GraphQLObjectType(
    name= 'Faction',
    description= 'A faction in the Star Wars saga',
    fields= lambda: {
        'id': globalIdField('Faction'),
        'name': GraphQLField(
            GraphQLString,
            description='The name of the faction.',
        ),
        'ships': GraphQLField(
            shipConnection,
            description= 'The ships used by the faction.',
            args= connectionArgs,
            resolver= lambda faction, args, *_: connectionFromArray(
                [getShip(ship) for ship in faction.ships],
                args
            ),
        )
    },
    interfaces= [nodeInterface]
)

# This is the type that will be the root of our query, and the
# entry point into our schema.
#
# This implements the following type system shorthand:
#   type Query {
#     rebels: Faction
#     empire: Faction
#     node(id: String!): Node
#   }
queryType = GraphQLObjectType(
    name= 'Query',
    fields= lambda: {
        'rebels': GraphQLField(
            factionType,
            resolver= lambda *_: getRebels(),
        ),
        'empire': GraphQLField(
            factionType,
            resolver= lambda *_: getEmpire(),
        ),
        'node': nodeField
    }
)

# This will return a GraphQLFieldConfig for our ship
# mutation.
#
# It creates these two types implicitly:
#   input IntroduceShipInput {
#     clientMutationId: string!
#     shipName: string!
#     factionId: ID!
#   }
#
#   input IntroduceShipPayload {
#     clientMutationId: string!
#     ship: Ship
#     faction: Faction
#   }
class IntroduceShipMutation(object):
    def __init__(self, shipId, factionId, clientMutationId=None):
        self.shipId = shipId
        self.factionId = factionId
        self.clientMutationId = None

def mutateAndGetPayload(data, *_):
    shipName = data.get('shipName')
    factionId = data.get('factionId')
    newShip = createShip(shipName, factionId)
    return IntroduceShipMutation(
        shipId=newShip.id,
        factionId=factionId,
    )

shipMutation = mutationWithClientMutationId(
    'IntroduceShip',
    inputFields={
        'shipName': GraphQLField(
            GraphQLNonNull(GraphQLString)
        ),
        'factionId': GraphQLField(
            GraphQLNonNull(GraphQLID)
        )
    },
    outputFields= {
        'ship': GraphQLField(
            shipType,
            resolver= lambda payload, *_: getShip(payload.shipId)
        ),
        'faction': GraphQLField(
            factionType,
            resolver= lambda payload, *_: getFaction(payload.factionId)
        )
    },
    mutateAndGetPayload=mutateAndGetPayload
)

# This is the type that will be the root of our mutations, and the
# entry point into performing writes in our schema.
#
# This implements the following type system shorthand:
#   type Mutation {
#     introduceShip(input IntroduceShipInput!): IntroduceShipPayload
#   }
mutationType = GraphQLObjectType(
    'Mutation',
    fields= lambda: {
        'introduceShip': shipMutation
    }
)

# Finally, we construct our schema (whose starting query type is the query
# type we defined above) and export it.
StarWarsSchema = GraphQLSchema(
    query= queryType,
    mutation= mutationType
)<commit_msg>Fixed inputobjecttypes in test<commit_after>from collections import namedtuple

from graphql.core.type import (
    GraphQLID,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLInputObjectField,
    GraphQLSchema,
    GraphQLString,
    GraphQLField
)

from graphql_relay.node.node import (
    nodeDefinitions,
    globalIdField,
    fromGlobalId
)

from graphql_relay.connection.arrayconnection import (
    connectionFromArray
)

from graphql_relay.connection.connection import (
    connectionArgs,
    connectionDefinitions
)

from graphql_relay.mutation.mutation import (
    mutationWithClientMutationId
)

from .data import (
    Faction,
    Ship,
    getFaction,
    getShip,
    getRebels,
    getEmpire,
    createShip,
)

# This is a basic end-to-end test, designed to demonstrate the various
# capabilities of a Relay-compliant GraphQL server.
#
# It is recommended that readers of this test be familiar with
# the end-to-end test in GraphQL.js first, as this test skips
# over the basics covered there in favor of illustrating the
# key aspects of the Relay spec that this test is designed to illustrate.
#
# We will create a GraphQL schema that describes the major
# factions and ships in the original Star Wars trilogy.
#
# NOTE: This may contain spoilers for the original Star
# Wars trilogy.

# Using our shorthand to describe type systems, the type system for our
# example will be the followng:
#
# interface Node {
#   id: ID!
# }
#
# type Faction : Node {
#   id: ID!
#   name: String
#   ships: ShipConnection
# }
#
# type Ship : Node {
#   id: ID!
#   name: String
# }
#
# type ShipConnection {
#   edges: [ShipEdge]
#   pageInfo: PageInfo!
# }
#
# type ShipEdge {
#   cursor: String!
#   node: Ship
# }
#
# type PageInfo {
#   hasNextPage: Boolean!
#   hasPreviousPage: Boolean!
#   startCursor: String
#   endCursor: String
# }
#
# type Query {
#   rebels: Faction
#   empire: Faction
#   node(id: ID!): Node
# }
#
# input IntroduceShipInput {
#   clientMutationId: string!
#   shipName: string!
#   factionId: ID!
# }
#
# input IntroduceShipPayload {
#   clientMutationId: string!
#   ship: Ship
#   faction: Faction
# }
#
# type Mutation {
#   introduceShip(input IntroduceShipInput!): IntroduceShipPayload
# }

# We get the node interface and field from the relay library.
#
# The first method is the way we resolve an ID to its object. The second is the
# way we resolve an object that implements node to its type.
def getNode(globalId, *args):
    resolvedGlobalId = fromGlobalId(globalId)
    _type, _id = resolvedGlobalId.type, resolvedGlobalId.id
    if _type == 'Faction':
        return getFaction(_id)
    elif _type == 'Ship':
        return getShip(_id)
    else:
        return None

def getNodeType(obj):
    if isinstance(obj, Faction):
        return factionType
    else:
        return shipType

_nodeDefinitions = nodeDefinitions(getNode, getNodeType)
nodeField, nodeInterface = _nodeDefinitions.nodeField, _nodeDefinitions.nodeInterface

# We define our basic ship type.
#
# This implements the following type system shorthand:
#   type Ship : Node {
#     id: String!
#     name: String
#   }
shipType = GraphQLObjectType(
    name='Ship',
    description= 'A ship in the Star Wars saga',
    fields=lambda: {
        'id': globalIdField('Ship'),
        'name': GraphQLField(
            GraphQLString,
            description= 'The name of the ship.',
        )
    },
    interfaces= [nodeInterface]
)

# We define a connection between a faction and its ships.
#
# connectionType implements the following type system shorthand:
#   type ShipConnection {
#     edges: [ShipEdge]
#     pageInfo: PageInfo!
#   }
#
# connectionType has an edges field - a list of edgeTypes that implement the
# following type system shorthand:
#   type ShipEdge {
#     cursor: String!
#     node: Ship
#   }
shipConnection = connectionDefinitions('Ship', shipType).connectionType

# We define our faction type, which implements the node interface.
#
# This implements the following type system shorthand:
#   type Faction : Node {
#     id: String!
#     name: String
#     ships: ShipConnection
#   }
factionType = GraphQLObjectType(
    name= 'Faction',
    description= 'A faction in the Star Wars saga',
    fields= lambda: {
        'id': globalIdField('Faction'),
        'name': GraphQLField(
            GraphQLString,
            description='The name of the faction.',
        ),
        'ships': GraphQLField(
            shipConnection,
            description= 'The ships used by the faction.',
            args= connectionArgs,
            resolver= lambda faction, args, *_: connectionFromArray(
                [getShip(ship) for ship in faction.ships],
                args
            ),
        )
    },
    interfaces= [nodeInterface]
)

# This is the type that will be the root of our query, and the
# entry point into our schema.
#
# This implements the following type system shorthand:
#   type Query {
#     rebels: Faction
#     empire: Faction
#     node(id: String!): Node
#   }
queryType = GraphQLObjectType(
    name= 'Query',
    fields= lambda: {
        'rebels': GraphQLField(
            factionType,
            resolver= lambda *_: getRebels(),
        ),
        'empire': GraphQLField(
            factionType,
            resolver= lambda *_: getEmpire(),
        ),
        'node': nodeField
    }
)

# This will return a GraphQLFieldConfig for our ship
# mutation.
#
# It creates these two types implicitly:
#   input IntroduceShipInput {
#     clientMutationId: string!
#     shipName: string!
#     factionId: ID!
#   }
#
#   input IntroduceShipPayload {
#     clientMutationId: string!
#     ship: Ship
#     faction: Faction
#   }
class IntroduceShipMutation(object):
    def __init__(self, shipId, factionId, clientMutationId=None):
        self.shipId = shipId
        self.factionId = factionId
        self.clientMutationId = None

def mutateAndGetPayload(data, *_):
    shipName = data.get('shipName')
    factionId = data.get('factionId')
    newShip = createShip(shipName, factionId)
    return IntroduceShipMutation(
        shipId=newShip.id,
        factionId=factionId,
    )

shipMutation = mutationWithClientMutationId(
    'IntroduceShip',
    inputFields={
        'shipName': GraphQLInputObjectField(
            GraphQLNonNull(GraphQLString)
        ),
        'factionId': GraphQLInputObjectField(
            GraphQLNonNull(GraphQLID)
        )
    },
    outputFields= {
        'ship': GraphQLField(
            shipType,
            resolver= lambda payload, *_: getShip(payload.shipId)
        ),
        'faction': GraphQLField(
            factionType,
            resolver= lambda payload, *_: getFaction(payload.factionId)
        )
    },
    mutateAndGetPayload=mutateAndGetPayload
)

# This is the type that will be the root of our mutations, and the
# entry point into performing writes in our schema.
#
# This implements the following type system shorthand:
#   type Mutation {
#     introduceShip(input IntroduceShipInput!): IntroduceShipPayload
#   }
mutationType = GraphQLObjectType(
    'Mutation',
    fields= lambda: {
        'introduceShip': shipMutation
    }
)

# Finally, we construct our schema (whose starting query type is the query
# type we defined above) and export it.
StarWarsSchema = GraphQLSchema(
    query= queryType,
    mutation= mutationType
)<|endoftext|>


<commit_before>"""Provides interface for frequently used or very important constant values."""

import numpy as np

# Shape of the input in NHWC format.
IN_SHAPE = [1, 128, 128, 3]
# Color space that the input-image will be converted to.
COLORSPACE = 'CIELAB'
# Provides `encoding` argument for `preprocessing.ImagePreprocessor.preprocess_classes`.
# ALL LABELS MUST BE RANK 1 TENSORS! (i.e. shape=[1, X] where X is some integer)
# For obvious reasons, the labels' shapes must also match the model's output shape.
ENCODING = {'cats': np.array([[1, 0]]), 'dogs': np.array([[0, 1]])}
# Provides `train_dir` argument for `preprocessing.ImagePreprocessor.preprocess_classes`.
TRAIN_DIR = '../data/train'
# X/Y : X is the name of the directory that will hold saved data about the model.
# Y is the prefix for the .data, .index, and .meta files.
SAVEMODEL_DIR = '../bin/saved/model'
# This directory will hold tensorboard files.
TENSORBOARD_DIR = '../bin/tensorboard'
<commit_msg>Fixed labels for tf impl<commit_after>"""Provides interface for frequently used or very important constant values."""

import numpy as np

# Shape of the input in NHWC format.
IN_SHAPE = [1, 128, 128, 3]
# Color space that the input-image will be converted to.
COLORSPACE = 'CIELAB'
# Provides `encoding` argument for `preprocessing.ImagePreprocessor.preprocess_classes`.
# ALL LABELS MUST BE RANK 1 TENSORS! (i.e. shape=[1, X] where X is some integer)
# For obvious reasons, the labels' shapes must also match the model's output shape.
ENCODING = {'cat': np.array([[1, 0]]), 'dog': np.array([[0, 1]])}
# Provides `train_dir` argument for `preprocessing.ImagePreprocessor.preprocess_classes`.
TRAIN_DIR = '../data/train'
# X/Y : X is the name of the directory that will hold saved data about the model.
# Y is the prefix for the .data, .index, and .meta files.
SAVEMODEL_DIR = '../bin/saved/model'
# This directory will hold tensorboard files.
TENSORBOARD_DIR = '../bin/tensorboard'
<|endoftext|>