Example #1
0
    def background(self, ray):
        unit_dir = ray.unit_direction()

        t = 0.5 * (unit_dir.y() + 1.0)  # scale y direction to [0, 1.0]
        white_grad = vec3([1, 1, 1]) * t
        blue_grad = vec3([0.5, 0.7, 1.0]) * (1.0 - t)
        return white_grad + blue_grad  # linear interpolation blue/white
Example #2
0
def f():
    a = vec3(1.0, 2.0, 3.0)
    b = vec3(2.0, 1.0, 3.0)
    if a.x > b.x:
        c = a.dot(b)
    else:
        c = b.dot(a)
    return c
Example #3
0
def f():
	a = vec3(1.0, 2.0, 3.0)
	b = vec3(2.0, 1.0, 3.0)
	if a.x > b.x:
		c = a.dot(b)
	else:
		c = b.dot(a)
	return c
Example #4
0
def testirregulargfx():
	o = piece2obj.piece2obj(['l'])
	assert len(o) == 1
	assert len(o[0].gfxmesh.vertices) == 10
	assert vec3(0,0,GRID) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 14*3	# Front and back optimization.
	assert len(o[0].physgeoms) == 1
	assert type(o[0].physgeoms[0]) == piece2obj.PhysMesh
	assert o[0].physgeoms[0].pos == vec3(0,0,0)
Example #5
0
def testtinyrotated2dcube():
	o = piece2obj.piece2obj(['<>'])
	assert len(o[0].gfxmesh.vertices) == 8
	assert piece2obj.invrotq == o[0].gfxmesh.q
	assert vec3(0,0,0) == o[0].gfxmesh.pos
	assert vec3(0,GRID,GRID) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 12*3
	assert len(o[0].physgeoms) == 1
	assert type(o[0].physgeoms[0]) == piece2obj.PhysBox
def give_fade_blue_down(ray):
	# goal color is vec3(.5, .7, 1.0)	//blue
	# start is white(1,1,1)
	# r's original y val goes from -1, 1
		# 1 then *.5, to go 0-1
	unit_direction = vec3.unit_vector( ray.direction() )
	percent = 0.5*(1.0 + unit_direction.e[1])

	return vec3.lerp( vec3.vec3(in_list=[1.0, 1.0, 1.0]), vec3.vec3(in_list=[0.5, 0.7, 1.0]), percent)
Example #7
0
def confuseMethods(a, b, c, d, e, f):
	va = vec3(a, b, c)
	vb = vec3(d, e, f)

	if a > b:
		vc = va.cross(vb)
	else:
		vc = vb.cross(va)

	return vc.dot(vc)
Example #8
0
def generateScene():
    world = hitableList()

    # Bottom "plane"
    world.add(sphere(vec3(0, -1000, 0), 1000, lambertian(vec3(0.5, 0.5, 0.5))))

    # three large spheres
    world.add(sphere(vec3(0, 1, 0), 1.0, dielectric(1.5)))
    world.add(sphere(vec3(-4, 1, 0), 1.0, lambertian(vec3(0.4, 0.2, 0.1))))
    world.add(sphere(vec3(4, 1, 0), 1.0, metal(vec3(0.7, 0.6, 0.5), 0.0)))

    # numerous small spheres
    i = 1
    for a in range(-11, 11):
        for b in range(-11, 11):
            chooseMat = random.random()
            center = vec3(a + 0.9 * random.random(), 0.2,
                          b + 0.9 * random.uniform(0, 1))
            if (center - vec3(4, 0.2, 0)).length() > 0.9:
                if chooseMat < 0.8:
                    # diffuse
                    albedo = vec3.random() * vec3.random()
                    world.add(sphere(center, 0.2, lambertian(albedo)))
                elif chooseMat < 0.95:
                    # metal
                    albedo = random.uniform(.5, 1)
                    fuzz = random.uniform(0, .5)
                    world.add(sphere(center, 0.2, metal(albedo, fuzz)))
                else:
                    # glass
                    world.add(sphere(center, 0.2, dielectric(1.5)))

    return world
Example #9
0
def test2dcube():
	o = piece2obj.piece2obj(['X'])
	assert len(o) == 1
	assert len(o[0].gfxmesh.vertices) == 8
	assert vec3(GRID,GRID,GRID) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 12*3	# Reduced two in the back, two in the front (and of course none in the middle).
	assert len(o[0].physgeoms) == 1
	assert type(o[0].physgeoms[0]) == piece2obj.PhysBox
	assert o[0].physgeoms[0].pos == vec3(0,0,0)
	assert o[0].physgeoms[0].size.x == G2
	assert o[0].physgeoms[0].size.y == G2
	assert o[0].physgeoms[0].size.z == G2
Example #10
0
def testasymmeticcubes():
	length = 7
	wide,high,deep = (['X'*length],vec3(length,1,1)), (['X']*length,vec3(1,length,1)), ('\n---\n'.join(['X']*length).split(),vec3(1,1,length))
	def innercubetest(ascii,size):
		o = piece2obj.piece2obj(ascii)
		assert len(o) == 1
		assert len(o[0].gfxmesh.vertices) == 8
		assert size/2 in o[0].gfxmesh.vertices
		assert len(o[0].gfxmesh.indices) == 12*3
		assert len(o[0].physgeoms) == 1
		assert type(o[0].physgeoms[0]) == piece2obj.PhysBox
	[innercubetest(ascii,size) for ascii,size in [wide,high,deep]]
Example #11
0
    def look_at(self, eye_x, eye_y, eye_z, c_x, c_y, c_z, u_x, u_y, u_z):
        f = vec3(c_x - eye_x, c_y - eye_y, c_z - eye_z).normalize()
        up = vec3(u_x, u_y, u_z).normalize()
        side = f.cross(up)
        up = side.normalize().cross(f)

        m = Matrix(
            side.x, side.y, side.z, -eye_x,
            up.x, up.y, up.z, -eye_y,
            -f.x, -f.y, -f.z, -eye_z,
            0., 0., 0., 1.)

        return self * m
Example #12
0
def assignMerge(s):
	a = vec3(3.0, 3.0, 3.0)
	b = vec3(5.0, 5.0, 5.0)

	#c = a if s else b
	if s:
		c = a
	else:
		c = b

	c.x = 7.0

	return c.x
Example #13
0
def rayColor(r, scene, depth):

    if depth == 0:
        return vec3(0, 0, 0)

    hit = scene.hit(r, 0.0001, float("inf"))
    if hit != None:
        result = hit.mat.scatter(r, hit)
        if result != None:
            return rayColor(result[1], scene, depth - 1) * result[0]

    t = (vec3.normalize(r.direction()).y() + 1) * 0.5
    return vec3(1.0, 1.0, 1.0) * (1.0 - t) + vec3(0.5, 0.7, 1.0) * t
Example #14
0
def assignMerge(s):
    a = vec3(3.0, 3.0, 3.0)
    b = vec3(5.0, 5.0, 5.0)

    #c = a if s else b
    if s:
        c = a
    else:
        c = b

    c.x = 7.0

    return c.x
Example #15
0
    def add_point(self, x, y, z):
        self.x = min(x, self.x)
        self.y = min(y, self.y)
        self.z = min(z, self.z)
        self.xmax = max(x, self.xmax)
        self.ymax = max(y, self.ymax)
        self.zmax = max(z, self.zmax)
        self.width = self.xmax - self.x
        self.height = self.ymax - self.y
        self.depth = self.zmax - self.z

        self.pos = vec3(self.x, self.y, self.z)
        self.size = vec3(self.width, self.height, self.depth)
        self.center = self.pos + (self.size*0.5)
        self.cx, self.cy, self.cz = self.center
Example #16
0
    def scatter(self, rIn, rec):
        attenuation = vec3(1, 1, 1)
        etaiOverEtat = (1.0 /
                        self.refIndex) if rec.frontFace else self.refIndex

        unitDirection = vec3.normalize(rIn.direction())
        cosTheta = min(vec3.dot(unitDirection * -1, rec.n), 1.0)
        sinTheta = math.sqrt(1.0 - cosTheta * cosTheta)

        # TIR
        if etaiOverEtat * sinTheta > 1.0:
            reflected = vec3.reflect(unitDirection, rec.n)
            scattered = ray(rec.p, reflected)
            return (attenuation, scattered)

        # prop. reflection / refraction
        reflectProb = dielectric.schlick(cosTheta, etaiOverEtat)

        # reflection
        if random.random() < reflectProb:
            reflected = vec3.reflect(unitDirection, rec.n)
            scattered = ray(rec.p, reflected)
            return (attenuation, scattered)

        # refraction
        refracted = vec3.refract(unitDirection, rec.n, etaiOverEtat)
        scattered = ray(rec.p, refracted)
        return (attenuation, scattered)
Example #17
0
def testsmall2dtriangle():
	o = piece2obj.piece2obj(['v'])
	assert len(o[0].gfxmesh.vertices) == 6
	assert vec3(0,GRID*2/3,GRID) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 8*3
	assert len(o[0].physgeoms) == 1
	assert type(o[0].physgeoms[0]) == piece2obj.PhysMesh
Example #18
0
def test3dcuboid():
	o = piece2obj.piece2obj(['XX','XX','---','XX','XX','---','XX','XX'])
	assert len(o) == 1
	assert len(o[0].gfxmesh.vertices) == 8
	assert vec3(-G2,-G2,-1.5*G2) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 12*3
	assert len(o[0].physgeoms) == 1
	assert type(o[0].physgeoms[0]) == piece2obj.PhysBox
Example #19
0
def test():
    objects = []
    t = objects[0]
    origin = vec3(0.5, 0.5, 0)
    screen_pos = coordinate_from_pixel(5, 5)
    direction = origin.direction_to(screen_pos)
    t.ray_tri_intersect(origin, direction)
    print(t)
Example #20
0
	def test_advanced_angle_fast(self):
		af = lambda v,x,y,z: round(mesh._angle_fast(v.normalize(),x,y,z), 3)
		self.assertEqual(af(vec3(1,1,0),1,0,0), 0.785)
		self.assertEqual(af(vec3(1,1,0),0,1,0), 0.785)
		self.assertEqual(af(vec3(1,1,0),0,0,1), 0.7)
		self.assertEqual(af(vec3(1,-1,0),1,0,0), 0.785)
		self.assertEqual(af(vec3(-1,0,-5),0,0,+1), 0.7)
		self.assertEqual(af(vec3(-1,0,-2),0,0,+1), 0.7)
		self.assertEqual(af(vec3(-1,0,-1),0,0,+1), 0.7)
		self.assertEqual(af(vec3(-5,0,-1),0,0,+1), 0.7)
Example #21
0
	def linearMove( self, splitLine ):
		"Parse a linear move gcode line and send the commands to the extruder."
		location = vec3()
		if self.oldLocation != None:
			location = self.oldLocation
		self.setFeedrate( splitLine )
		setPointToSplitLine( location, splitLine )
		self.moveExtruder( location )
		self.oldLocation = location
Example #22
0
	def helicalMove( self, isCounterclockwise, splitLine ):
		"Parse a helical move gcode line and send the commands to the extruder."
		if self.oldLocation == None:
			return
		location = vec3().getFromVec3( self.oldLocation )
		self.setFeedrate( splitLine )
		setPointToSplitLine( location, splitLine )
		location = location.plus( self.oldLocation )
		center = vec3().getFromVec3( self.oldLocation )
		indexOfR = indexOfStartingWithSecond( "R", splitLine )
		if indexOfR > 0:
			radius = getDoubleAfterFirstLetter( splitLine[ indexOfR ] )
			halfLocationMinusOld = location.minus( self.oldLocation )
			halfLocationMinusOld.scale( 0.5 )
			halfLocationMinusOldLength = halfLocationMinusOld.length()
			centerMidpointDistance = math.sqrt( radius * radius - halfLocationMinusOldLength * halfLocationMinusOldLength )
			centerMinusMidpoint = getRotatedWiddershinsQuarterAroundZAxis( halfLocationMinusOld )
			centerMinusMidpoint.normalize()
			centerMinusMidpoint.scale( centerMidpointDistance )
			if isCounterclockwise:
				center.getFromVec3( halfLocationMinusOld.plus( centerMinusMidpoint ) )
			else:
				center.getFromVec3( halfLocationMinusOld.minus( centerMinusMidpoint ) )
		else:
			center.x = getDoubleForLetter( "I", splitLine )
			center.y = getDoubleForLetter( "J", splitLine )
		curveSection = 0.5
		center = center.plus( self.oldLocation )
		afterCenterSegment = location.minus( center )
		beforeCenterSegment = self.oldLocation.minus( center )
		afterCenterDifferenceAngle = getAngleAroundZAxisDifference( afterCenterSegment, beforeCenterSegment )
		absoluteDifferenceAngle = abs( afterCenterDifferenceAngle )
		steps = int( math.ceil( max( absoluteDifferenceAngle * 2.4, absoluteDifferenceAngle * beforeCenterSegment.length() / curveSection ) ) )
		stepPlaneAngle = getPolar( afterCenterDifferenceAngle / steps, 1.0 )
		zIncrement = ( afterCenterSegment.z - beforeCenterSegment.z ) / float( steps )
		for step in range( 1, steps ):
			beforeCenterSegment = getRoundZAxisByPlaneAngle( stepPlaneAngle, beforeCenterSegment )
			beforeCenterSegment.z += zIncrement
			arcPoint = center.plus( beforeCenterSegment )
			self.moveExtruder( arcPoint )
		self.moveExtruder( location )
		self.oldLocation = location
Example #23
0
def testbig3dprism():
	o = piece2obj.piece2obj(codecs.open('big_3d_prism.txt', encoding='utf-8'))
	assert len(o[0].gfxmesh.vertices) == 6
	assert vec3(-GRID,-G2,-1.5*G2) in o[0].gfxmesh.vertices
	assert len(o[0].gfxmesh.indices) == 8*3
	assert len(o[0].physgeoms) == 5
	assert type(o[0].physgeoms[0]) == piece2obj.PhysBox
	assert type(o[0].physgeoms[1]) == piece2obj.PhysBox
	assert type(o[0].physgeoms[2]) == piece2obj.PhysBox
	assert type(o[0].physgeoms[3]) == piece2obj.PhysMesh
	assert type(o[0].physgeoms[4]) == piece2obj.PhysMesh
Example #24
0
    def __init__(self, **kwargs):
        self.mW = kwargs.get('mW', 1000.0)
        self.w = kwargs.get('waists', (30., 30.))
        self.l = kwargs.get('wavelength', 1.064)
        #
        self.axis = kwargs.get('axis', (np.pi / 2, 0.))
        self.origin = kwargs.get('origin', vec3(0, 0, 0))

        # Make sure vectors are of type(vec3)
        self.axisvec = vec3()
        th = self.axis[0]
        ph = self.axis[1]
        self.axisvec.set_spherical(1, th, ph)
        self.origin = vec3(self.origin)

        # Calculate two orthogonal directions
        # which will be used to specify the beam waists
        self.orth0 = vec3( np.cos(th)*np.cos(ph) , \
                           np.cos(th)*np.sin(ph), -1.*np.sin(th) )
        self.orth1 = vec3(-1. * np.sin(ph), np.cos(ph), 0.)
Example #25
0
    def draw_scene(self):
        for i in tqdm(range(self.cam.height)):
            for j in range(self.cam.width):
                pixel = vec3([0, 0, 0])
                for s in range(self.cam.samples_per_pixel):
                    u = (j + self.random()) / (self.cam.width - 1)
                    v = (self.cam.height - i +
                         self.random()) / (self.cam.height - 1)
                    r = self.cam.get_ray(u, v)

                    pixel += self.get_ray_colour(r, self.max_depth)
                colour(pixel).write_colour(self.cam.samples_per_pixel)
 def __init__( self,
              **kwargs ):
     self.mW = kwargs.get('mW',1000.0 )
     self.w  = kwargs.get('waists', (30.,30.) )
     self.l  = kwargs.get('wavelength', 1.064 )
     #
     self.axis   = kwargs.get('axis', (np.pi/2,0.) )
     self.origin = kwargs.get('origin', vec3(0,0,0) )
     
     
     # Make sure vectors are of type(vec3)
     self.axisvec = vec3()
     th = self.axis[0]
     ph = self.axis[1]
     self.axisvec.set_spherical( 1, th, ph) 
     self.origin = vec3(self.origin)
     
     # Calculate two orthogonal directions 
     # which will be used to specify the beam waists
     self.orth0 = vec3( np.cos(th)*np.cos(ph) , np.cos(th)*np.sin(ph), -1.*np.sin(th) )
     self.orth1 = vec3( -1.*np.sin(ph), np.cos(ph), 0. )
Example #27
0
    def pol(self):
        '''This method calculates the sum over final polarizations'''
        try:
          kin = self.kin
          kout = self.kout
          kipol = self.kipol
        except Exception as e:
          print "k vectors have not been defined in the crystal"
          print "program will stop"
          print e
          exit()

        # unit vectors for input polarization
        zvec = vec3.vec3(0.,0.,1.) 
        in1 = vec3.cross( zvec, kin )
        in1 = in1 / abs(in1) 
        in2 = vec3.cross( kin, in1)
        in2 = in2 / abs(in2)
        # input polarization
        inpol = kipol[0]*in1 + kipol[1]*in2
        
        # unit vectors for output polarization 
        out1 = vec3.cross( zvec, kout )
        out1 = out1 / abs(out1) 
        out2 = vec3.cross( kout, out1)
        out2 = out2 / abs(out2)

        # polarization of transition
        splus =  1/np.sqrt(2.) *( vec3.vec3(1.,0.,0.) + 1j * vec3.vec3(0.,1.,0.))
        sminus = 1/np.sqrt(2.) *( vec3.vec3(1.,0.,0.) - 1j * vec3.vec3(0.,1.,0.))

        # sum over output polarizations
        
        polsum = 0.
        for i,pout in enumerate([out1, out2]):
            term =  abs( (splus * pout)*(inpol*sminus) )**2.
            polsum = polsum + term
        if verbose:
            print "\tSum over output pol (vectors) = ", polsum
        self.polsum = polsum
   
        # also obtain this result using the angles 
        # with respect to the magnetic field
        cosIN  = kin/abs(kin) * zvec 
        cosOUT = kout/abs(kout) * zvec
        polsumANGLE =  1./4. * (1 + cosIN**2.) * (1 + cosOUT**2.)
        #print "Sum over output pol (angles)  = ", polsumANGLE
   
        # optional draw polarization vectors on bloch sphere
        if False: 
            b = bsphere.Bloch()
            origin = vec3.vec3()
            b.add_arrow( -kin/abs(kin), origin, 'red')
            b.add_arrow( -kin/abs(kin), -kin/abs(kin) + in1/2., 'black')
            b.add_arrow( -kin/abs(kin), -kin/abs(kin) + in2/2., 'black')
            b.add_arrow( origin, kout/abs(kout), 'red')
            b.add_arrow( origin, out1/2., 'black')
            b.add_arrow( origin, out2/2., 'black')
            b.show()
        return self.polsum
Example #28
0
	def test_basic_angle_fast(self):
		af = lambda v,x,y,z: round(mesh._angle_fast(v.normalize(),x,y,z), 3)
		self.assertEqual(af(vec3(1,0,0),1,0,0), 0)
		self.assertEqual(af(vec3(0,1,0),0,1,0), 0)
		self.assertEqual(af(vec3(0,0,1),0,0,1), 0)
		self.assertEqual(af(vec3(1,0,0),0,1,0), 0.7)
		self.assertEqual(af(vec3(1,0,0),0,0,1), 0.7)
		self.assertEqual(af(vec3(0,1,0),0,0,1), 0.7)
Example #29
0
def methodMerge(s):
	v = vec3(0.0, 0.0, 0.0)
	if s:
		vs = VecSetter(5.0)
	else:
		vs = VecSetter(3.0)

##	# Old analysis method chokes, as the types are unrelated.
##	if s:
##		vs = VecSetter5()
##	else:
##		vs = VecSetter3()

	vs.setter(v)

	return v.x
Example #30
0
 def get_lowest_world_point(self):
         p = self._scalenode.get_world_translation() - self._scalenode.getphysmaster().get_world_translation()
         lp = p[:3]
         if self._shapenode.nodetype == "polyCube":
                 lp[0] -= self.data[0]/2
                 lp[1] -= self.data[2]/2
                 lp[2] -= self.data[1]/2
         elif self._shapenode.nodetype == "polySphere":
                 lp[0] -= self.data[0]
                 lp[1] -= self.data[0]
                 lp[2] -= self.data[0]
         else:
                 print("Error: (2) primitive physics shape type '%s' on node '%s' is unknown." % (shapenode.nodetype, shapenode.getFullName()))
                 sys.exit(22)
         #print("Shape %s at %s says it has a lowest point of %s with size %s." %(self._scalenode.getName(), p, lp, self.data))
         return vec3(lp[:3])
Example #31
0
def methodMerge(s):
    v = vec3(0.0, 0.0, 0.0)
    if s:
        vs = VecSetter(5.0)
    else:
        vs = VecSetter(3.0)


##	# Old analysis method chokes, as the types are unrelated.
##	if s:
##		vs = VecSetter5()
##	else:
##		vs = VecSetter3()

    vs.setter(v)

    return v.x
Example #32
0
 def get_lowest_world_point(self):
     p = self._scalenode.get_world_translation(
     ) - self._scalenode.getphysmaster().get_world_translation()
     lp = p[:3]
     if self._shapenode.nodetype == "polyCube":
         lp[0] -= self.data[0] / 2
         lp[1] -= self.data[2] / 2
         lp[2] -= self.data[1] / 2
     elif self._shapenode.nodetype == "polySphere":
         lp[0] -= self.data[0]
         lp[1] -= self.data[0]
         lp[2] -= self.data[0]
     else:
         print(
             "Error: (2) primitive physics shape type '%s' on node '%s' is unknown."
             % (shapenode.nodetype, shapenode.getFullName()))
         sys.exit(22)
     #print("Shape %s at %s says it has a lowest point of %s with size %s." %(self._scalenode.getName(), p, lp, self.data))
     return vec3(lp[:3])
Example #33
0
def Barycentric(p, a, b, c):
    # Vector v0 = b - a
    v0 = b - a

    # Vector v1 = c - a
    v1 = c - a

    # Vector v2 = p - a
    v2 = p - a

    d00 = v0.dot(v0)
    d01 = v0.dot(v1)
    d11 = v1.dot(v1)
    d20 = v2.dot(v0)
    d21 = v2.dot(v1)

    denom = d00 * d11 - d01 * d01
    v = (d11 * d20 - d01 * d21) / denom
    w = (d00 * d21 - d01 * d20) / denom
    u = 1.0 - v - w

    return vec3(u, v, w)
    def Bands( self, X, Y, Z, **kwargs):
        NBand = kwargs.get('NBand',0.)
        
        # Make 1d array with distances 
        R_unit = vec3( X[-1]-X[0], Y[-1]-Y[0], Z[-1]-Z[0] ); R_unit = R_unit / abs(R_unit)
        # Below we get the signed distance from the origin
        self.R = X*R_unit[0]+Y*R_unit[1]+Z*R_unit[2]
        
        self.V0_ = self.V0(X,Y,Z) 
        self.Bottom_ = self.Bottom(X,Y,Z)
        
        self.LatticeMod_ = self.Bottom_ + np.amin(self.V0_,axis=0)*\
                           np.power( np.cos( 2.*np.pi*self.R / self.l / self.scale ), 2)
            
        bands = bands3dvec( self.V0_, NBand=0 ) 
        excband = bands3dvec( self.V0_, NBand=1 )
        
        # The zero of energy for this problem is exactly at the center
        # of the lowest band.  This comes from the t_{ii} matrix element
        # which is generally neglected in the Hamiltonian. 
        self.Ezero = (bands[1]+bands[0])/2. + self.Bottom_
        self.Ezero0 = self.Ezero.min()

        
        # The threshold for evaporation can ge obtaind from 
        # the bottom of the band going far along one beam
        self.evapTH = bands3dvec( self.V0( 100., 0., 0. ), NBand=0 )[0] + self.Bottom(100.,0.,0.)
        
        # Tunneling, onsite interactions, and localMu for phase diagram
        self.tunneling = (bands[1]-bands[0])/12. 
        
        self.onsite = Onsite( self.V0_, a_s=self.a_s, lattice_spacing= self.l/2. )
        self.onsite_t = self.onsite / self.tunneling
        
        # Offset the chemical potential for use in the phase diagram
        self.globalMuZ = self.Ezero0 + self.globalMu
        self.localMu_t = ( self.globalMuZ - self.Ezero )/ self.tunneling
        
        # Obtain the thermodynamic quantities
        density  = self.fHdens( self.onsite_t, self.localMu_t ) 
        doublons = self.fHdoub( self.onsite_t, self.localMu_t ) 
        entropy  = self.fHentr( self.onsite_t, self.localMu_t ) 
    
        
        # Higher zorder puts stuff in front
        return [ 
                 {'y':(bands[0] + self.Bottom_, self.Ezero ), 'color':'blue', 'lw':2., \
                  'fill':True, 'fillcolor':'blue', 'fillalpha':0.75,'zorder':10, 'label':'$\mathrm{band\ lower\ half}$'},
                 
                 {'y':(self.Ezero + self.onsite, bands[1] + self.Bottom_+self.onsite), 'color':'purple', 'lw':2., \
                  'fill':True, 'fillcolor':'plum', 'fillalpha':0.75,'zorder':10, 'label':'$\mathrm{band\ upper\ half}+U$'},
                  
                 {'y':(excband[0] + self.Bottom_, excband[1] + self.Bottom_ ), 'color':'red', 'lw':2., \
                  'fill':True, 'fillcolor':'pink', 'fillalpha':0.75,'zorder':10, 'label':'$\mathrm{exc\ band}$'},
                 
                 {'y':np.ones_like(X)*self.globalMuZ, 'color':'limegreen','lw':2,'zorder':1.9, 'label':'$\mu_{0}$'},
                 {'y':np.ones_like(X)*self.evapTH, 'color':'#FF6F00', 'lw':2,'zorder':1.9, 'label':'$\mathrm{evap\ th.}$'},
                 
                 {'y':self.Bottom_,'color':'gray', 'lw':0.5,'alpha':0.5},
                 {'y':self.LatticeMod_,'color':'gray', 'lw':1.5,'alpha':0.5,'label':r'$\mathrm{lattice\ potential\ \ }\lambda\times10$'},
                 
                 {'y':density,  'color':'blue', 'lw':1.75, 'axis':2, 'label':'$n$'},
                 {'y':doublons, 'color':'red', 'lw':1.75, 'axis':2, 'label':'$d$'},
                 {'y':entropy,  'color':'black', 'lw':1.75, 'axis':2, 'label':'$s$'},
                 {'y':density-2*doublons,  'color':'green', 'lw':1.75, 'axis':2, 'label':'$n-2d$'},
                 #{'y':self.localMu_t,  'color':'cyan', 'lw':1.75, 'axis':2, 'label':r'$\mu$'},
                 
                 
                 
                 {'figprop':True,'figsuptitle':self.figlabel, 'foottext':self.foottext}
                  ]
Example #35
0
def kinchamber( phi ):
    k = vec3.vec3()
    the_ = np.pi/2 
    phi_ = np.pi/2. + np.pi* phi/180.
    k.set_spherical( 2.*np.pi/l671, the_, phi_ )
    return k
Example #36
0
def kinsph(theta, phi):
    k = vec3.vec3()
    the_ = np.pi/2 - ( np.pi*theta/180. - np.pi/2.)
    phi_ = np.pi/2. + np.pi* phi/180.
    k.set_spherical( 2.*np.pi/l671, the_, phi_ )
    return k
 def __init__(self):
     self.lower_left_corner = vec3.vec3([-2.0, -1.0, -1.0])
     self.horizontal = vec3.vec3([4.0, 0.0, 0.0])
     self.vertical = vec3.vec3([0.0, 2.0, 0.0])
     self.origin = vec3.vec3([0.0, 0.0, 0.0])
Example #38
0
import scipy



l671 = 671.
l1064 = 1064.

# Coordinate system:
# input Bragg light for HHH propagates almost along +Y 
# +Z is up


# Q vector for bragg scattering HHH
# Remember that for AFM there is a doubling of the unit cell, so the
# lattice spacing is lambda instead of lambda/2
Q = 2*np.pi/l1064 * vec3.vec3( -1., -1., 1.)  
Qunit = Q/abs(Q)

# Calculate angle for HHH Bragg conditiion
# with respect to Q vector
braggTH = np.arccos( abs(Q) / 2. / (2.*np.pi/l671)  )  
print "HHH Bragg angle wrt Q = ", braggTH * 180. / np.pi 

# Calculate angle for HHH Bragg condition
# with respect to y axis, when coming from 
# under lattice beam 2. 
from scipy.optimize import fsolve
def cond(x):
    return np.sin(x)-np.cos(x) + 3./2. * l671 / l1064
braggTH2 = fsolve(cond, 0.)
print "HHH Bragg angle wrt -y axis = ", braggTH2 * 180. / np.pi
Example #39
0
def project_to_stereomap(p, r, w, h):
    sphere_center = vec3([w // 2, h // 2, r])
    v = p - sphere_center
    s = r * (v / abs(v))
    return np.array(s[:2])

sample_count = 1
cam = camera.camera()

with open('testPPM.ppm', 'w') as image_file:
    width = 200
    height = 100
#	fWidth = float(width)
#	fHeight = float(height)
    print_count=4000

    image_file.write("P3\n{w} {h}\n255\n".format(w=width, h=height))
    for i in range((height-1), -1,-1):
        for j in range(width):
            col = vec3.vec3(in_list=[0.0, 0.0, 0.0])
            for s in range(sample_count):
                # x_percent = (j + random()) / width
                # y_percent = (i + random()) / height

                x_percent = j / width
                y_percent = i / height

                r = cam.get_ray(x_percent = x_percent, y_percent = y_percent)
                col += color(ray = r)
            
            col.idiv_float(sample_count)
            if (print_count > 0):
                print_count-=1
                print("{red} {green} {blue}\n".format(red=col[0], green=col[1], blue=col[2]))
Example #41
0
def _normalize(ns):
	def xyzchunks(l):
		for i in range(0, len(l), 3):
			yield l[i:i+3]
	ns2 = [list(vec3(x,y,z).normalize()) for x,y,z in xyzchunks(ns)]
	return list(item for iter_ in ns2 for item in iter_)
Example #42
0
def testcrds():
	assert piece2obj.crd2diamondcrd(vec3(1,2,0)) == vec3(0,0,0)
	assert piece2obj.crd2diamondcrd(vec3(2,0,0)) == vec3(1,0,0)
	assert piece2obj.crd2diamondcrd(vec3(3,2,0)) == vec3(1,1,0)
	assert piece2obj.crd2diamondcrd(vec3(4,5,0)) == vec3(0,4,0)
	assert piece2obj.crd2diamondcrd(vec3(5,5,0)) == vec3(1,4,0)
	assert piece2obj.crd2diamondcrd(vec3(2,1,2)) == vec3(1,1,2)
	assert piece2obj.crd2diamondcrd(vec3(3,2,2)) == vec3(1,1,2)
	assert piece2obj.diamondcrd2crds(vec3(1,4,0)) == [vec3(5,5,0),vec3(6,4,0)]
	assert piece2obj.diamondcrd2crds(vec3(0,4,0)) == [vec3(4,5,0),vec3(5,6,0)]
	assert piece2obj.diamondcrd2crds(vec3(1,0,2)) == [vec3(1,1,2),vec3(2,0,2)]
	assert piece2obj.diamondcrd2crds(vec3(1,1,2)) == [vec3(2,1,2),vec3(3,2,2)]
 def plotLine(self, **kwargs):
     gs      = kwargs.get('gs',None)
     figGS   = kwargs.get('figGS',None)
     func    = kwargs.get('func',None)
     origin  = kwargs.get('origin', vec3(0.,0.,0.))
     direc   = kwargs.get('direc', (np.pi/2, 0.))
     lims    = kwargs.get('lims', (-80.,80.))
     extents = kwargs.get('extents',None)
     npoints = kwargs.get('npoints', 320)
     
     if func is None:
         func = self.evalpotential
     
     if extents is not None:
         lims = (-extents, extents)
     
     # Prepare set of points for plot 
     t = np.linspace( lims[0], lims[1], npoints )
     unit = vec3()
     th = direc[0]
     ph = direc[1] 
     unit.set_spherical(1, th, ph) 
     # Convert vec3s to ndarray
     unit = np.array(unit)
     origin = np.array(origin) 
     #
     XYZ = origin + np.outer(t, unit)
     X = XYZ[:,0]
     Y = XYZ[:,1]
     Z = XYZ[:,2] 
     
     if gs is None:
         # Prepare figure
         fig = plt.figure(figsize=(9,4.5))
         gs = matplotlib.gridspec.GridSpec( 1,2, wspace=0.2)
     
         ax0 = fig.add_subplot( gs[0,0], projection='3d')
         ax1 = fig.add_subplot( gs[0,1])
     else:
         gsSub0 = matplotlib.gridspec.GridSpecFromSubplotSpec( 2,2, subplot_spec=gs,\
                      width_ratios=[1,1.6], height_ratios=[1,1],\
                      wspace=0.25)
         ax0 = figGS.add_subplot( gsSub0[0,0], projection='3d')
         ax1 = figGS.add_subplot( gsSub0[0:2,1] )
         ax2 = figGS.add_subplot( gsSub0[1,0] )
         
         ax1.set_xlim( lims[0],lims[1])
         ax2.set_xlim( lims[0]/2.,lims[1]/2.)
         ax2.grid()
         ax2.set_xlabel('$\mu\mathrm{m}$', fontsize=14)
         
         
     ax0.plot(X, Y, Z, c='blue', lw=3)
     ax0.set_xlabel('X')
     ax0.set_ylabel('Y')
     ax0.set_zlabel('Z')
     lmin = min([ ax0.get_xlim()[0], ax0.get_ylim()[0], ax0.get_zlim()[0] ] )
     lmax = max([ ax0.get_xlim()[1], ax0.get_ylim()[1], ax0.get_zlim()[1] ] )
     ax0.set_xlim( lmin, lmax )
     ax0.set_ylim( lmin, lmax )
     ax0.set_zlim( lmin, lmax )
     LMIN = np.ones_like(X)*lmin
     LMAX = np.ones_like(X)*lmax
     ax0.plot(X, Y, LMIN, c='gray', lw=2,alpha=0.3)
     ax0.plot(LMIN, Y, Z, c='gray', lw=2,alpha=0.3)
     ax0.plot(X, LMAX, Z, c='gray', lw=2,alpha=0.3)
     ax0.set_yticklabels([])
     ax0.set_xticklabels([])
     ax0.set_zticklabels([])
     ax0.text2D(0.05, 0.87, kwargs.get('ax0label',None),transform=ax0.transAxes)
     
     # Evaluate function at points and make plot
     EVAL = func(X,Y,Z, **kwargs)
     # EVAL can be of various types, handled below
     Emin =[]; Emax=[]
     if isinstance(EVAL,list):
         for p in EVAL:
             if isinstance(p,dict):
                 if 'y' in p.keys():
                     whichax = p.get('axis',1)
                     axp = ax2 if whichax ==2 else ax1
                     porder = p.get('zorder',2)
                     labelstr = p.get('label',None)
                     
                     fill = p.get('fill', False)
                     if fill:
                         ydat = p.get('y',None)
                         if ydat is not None:
                             axp.plot(t,ydat[0],
                                      lw=p.get('lw',2.),\
                                      color=p.get('color','black'),\
                                      alpha=p.get('fillalpha',0.5),\
                                      zorder=porder,\
                                      label=labelstr
                                      )
                             axp.fill_between( t, ydat[0], ydat[1],\
                                               lw=p.get('lw',2.),\
                                               color=p.get('color','black'),\
                                               facecolor=p.get('fillcolor','gray'),\
                                               alpha=p.get('fillalpha',0.5),\
                                               zorder=porder
                                             ) 
                             Emin.append( min( ydat[0].min(), ydat[1].min() ))
                             Emax.append( max( ydat[0].max(), ydat[1].max() )) 
                     else:
                         ydat = p.get('y',None)
                         if ydat is not None:
                             axp.plot( t, ydat,\
                                       lw=p.get('lw',2.),\
                                       color=p.get('color','black'),\
                                       alpha=p.get('alpha',1.0),\
                                       zorder=porder,\
                                       label=labelstr
                                     )
                             Emin.append( ydat.min() ) 
                             Emax.append( ydat.max() ) 
                 elif 'figprop' in p.keys():
                     figsuptitle = p.get('figsuptitle',  None)
                     figGS.suptitle(figsuptitle, y=kwargs.get('suptitleY',1.0),fontsize=14) 
                     figGS.text(0.5,kwargs.get('foottextY',1.0),p.get('foottext',None),fontsize=14,
                                ha='center') 
                       
             else:
                 ax1.plot(t,p); Emin.append(p.min()); Emax.append(p.max())
         
     elif len(EVAL.shape) > 1 :
         for i,E in enumerate(EVAL):
             ax1.plot(t,E); Emin.append(E.min()); Emax.append(E.max())
             
     else:
         ax1.plot( t, EVAL); Emin.append(E.min()), Emax.append(E.max())
         
     Emin = min(Emin); Emax=max(Emax)
     dE = Emax-Emin
     
     ax1.grid()
     ax1.set_xlabel('$\mu\mathrm{m}$', fontsize=14)
     ax1.set_ylabel( self.unitlabel, rotation=0, fontsize=14, labelpad=-5 )
     
     
     # Finalize figure
     if gs is None:
         gs.tight_layout(fig, rect=[0.,0.,1.0,1.0])
         return Emin-0.05*dE, Emax+0.05*dE, ax1
     else:
         ax2.xaxis.set_major_locator( matplotlib.ticker.MultipleLocator(20) ) 
         ax2.xaxis.set_minor_locator( matplotlib.ticker.MultipleLocator(10) ) 
         return Emin-0.05*dE, Emax+0.05*dE, ax1, ax2
Example #44
0
                else:
                    # glass
                    world.add(sphere(center, 0.2, dielectric(1.5)))

    return world


width = 200
aspectRatio = 16 / 9
height = int(width / aspectRatio)
image = width * height * [None]

maxDepth = 10
sampleCount = 1

lookFrom = vec3(13, 2, 3)
lookAt = vec3(0, 0, 0)
vUp = vec3(0, 1, 0)
distToFocus = 10
aperture = 0  # 0.1
fovy = 20

myCamera = camera(lookFrom, lookAt, vUp, fovy, aspectRatio, aperture,
                  distToFocus)
scene = generateScene()

i = 0
for y in range(height):
    print("Berechne Zeile", y)
    for x in range(width):
        c = vec3(0, 0, 0)
Example #45
0
def doDot():
    v0 = vec3(1.0, 2.0, 3.0)
    v1 = vec3(2.0, 1.0, 3.0)
    return v0.dot(v1)
Example #46
0
def surfcut_points(**kwargs):
    """ 
    Defines an surface cut through the potential geometry.  Parameters are given
    as keyword arguments (kwargs).

    All distances are in microns. 

    Parameters 
    ----------
    npoints     :  number of points along the cut
 
    extents     :  a way of specifying the limits for a cut that is symmetric
                   about the cut origin.  the limits will be 
                   lims = (-extents, extents)  

    lims        :  used only if extents = None.   limits are specified using
                   a tuple  ( min, max ) 

    direc       :  tuple, two elements.  polar coordinates for the direcdtion 
                   of the cut 
 
    origin      :  tuple, three elements.  cartesian coordinates for the origin
                   of the cut  

    ax0         :  optional axes where the reference surface for the surface 
                   cut can be plotted 


    Returns 
    -------
    T0, T1      :  arrays which parameterizes the position on the cut surface
  
    X, Y, Z     :  each of X,Y,Z is an array with the same shape as T0 and T1. 
                   They correspond to the cartesian coordinates of all the 
                   points on the cut surface.  
                   
    Notes 
    ----  

    Examples
    --------
    """
    npoints = kwargs.get('npoints', 240)
    origin = kwargs.get('origin', vec3(0., 0., 0.))
    normal = kwargs.get('normal', (np.pi / 2., 0.))
    lims0 = kwargs.get('lims0', (-50., 50.))
    lims1 = kwargs.get('lims1', (-50., 50.))
    extents = kwargs.get('extents', None)

    if extents is not None:
        lims0 = (-extents, extents)
        lims1 = (-extents, extents)

    # Make the unit vectors that define the plane
    unit = vec3()
    th = normal[0]
    ph = normal[1]
    unit.set_spherical(1, th, ph)
    orth0 = vec3(-1. * np.sin(ph), np.cos(ph), 0.)
    orth1 = cross(unit, orth0)

    t0 = np.linspace(lims0[0], lims0[1], npoints)
    t1 = np.linspace(lims1[0], lims1[1], npoints)

    # Obtain points on which function will be evaluated
    T0, T1 = np.meshgrid(t0, t1)
    X = origin[0] + T0 * orth0[0] + T1 * orth1[0]
    Y = origin[1] + T0 * orth0[1] + T1 * orth1[1]
    Z = origin[2] + T0 * orth0[2] + T1 * orth1[2]

    # If given an axes it will plot the reference surface to help visusalize
    # the surface cut

    # Note that the axes needs to be created with a 3d projection.
    # For example:
    #    fig = plt.figure( figsize=(4.,4.) )
    #    gs = matplotlib.gridspec.GridSpec( 1,1 )
    #    ax0 = fig.add_subplot( gs[0,0], projection='3d' )

    ax0 = kwargs.get('ax0', None)
    if ax0 is not None:

        # Plot the reference surface
        ax0.plot_surface(X,
                         Y,
                         Z,
                         rstride=8,
                         cstride=8,
                         alpha=0.3,
                         linewidth=0.)
        ax0.set_xlabel('X')
        ax0.set_ylabel('Y')
        ax0.set_zlabel('Z')
        lmin = min([ax0.get_xlim()[0], ax0.get_ylim()[0], ax0.get_zlim()[0]])
        lmax = max([ax0.get_xlim()[1], ax0.get_ylim()[1], ax0.get_zlim()[1]])
        ax0.set_xlim(lmin, lmax)
        ax0.set_ylim(lmin, lmax)
        ax0.set_zlim(lmin, lmax)
        ax0.set_yticklabels([])
        ax0.set_xticklabels([])
        ax0.set_zticklabels([])

    # If given an axes and a potential it will plot the surface cut of the
    # potential

    ax1 = kwargs.get('ax1', None)
    pot = kwargs.get('potential', None)

    if (ax1 is not None) and (pot is not None):
        # Evaluate function at points and plot
        EVAL = pot.evalpotential(X, Y, Z)

        im = ax1.pcolormesh(T0, T1, EVAL, cmap=plt.get_cmap('jet'))
        # cmaps:  rainbow, jet

        plt.axes(ax1)
        cbar = plt.colorbar(im)
        cbar.set_label(pot.unitlabel, rotation=0)  #self.unitlabel

    return T0, T1, X, Y, Z
Example #47
0
def creategfxobject(vertices,indices):
	initgfxmesh(quat(1,0,0,0),vec3(0,0,0),vertices,indices)
	createobject()
Example #48
0
def testAttrMerge(s):
    v = vec3(0.0, 0.0, 0.0)
    if s: v.x = 1.0
    return v.x
Example #49
0
def coordinate_from_pixel(x, y):
    coor = vec3((x / dimension), (y / dimension), 1)
    return coor
   def plotCross(self,
           axes = None,
           func = None,
           origin  = vec3(0.,0.,0.), 
           normal   = (np.pi/2, 0),
           lims0   = (-50,50), 
           lims1   = (-50,50),
           extents = None,
           npoints = 240 ):
       
       if func is None:
           func = self.evalpotential
       
       if extents is not None:
           lims0 = (-extents, extents)
           lims1 = (-extents, extents)
       
       # Make the unit vectors that define the plane
       unit = vec3()
       th = normal[0]
       ph = normal[1]
       unit.set_spherical( 1, th, ph) 
       #orth1 = -1.*vec3( np.cos(th)*np.cos(ph) , np.cos(th)*np.sin(ph), -1.*np.sin(th) )
       orth0 = vec3( -1.*np.sin(ph), np.cos(ph), 0. )
       orth1 = cross(unit,orth0)
       
       t0 = np.linspace( lims0[0], lims0[1], npoints )
       t1 = np.linspace( lims1[0], lims1[1], npoints ) 
       
       # Obtain points on which function will be evaluated
       T0,T1 = np.meshgrid(t0,t1)
       X = origin[0] + T0*orth0[0] + T1*orth1[0] 
       Y = origin[1] + T0*orth0[1] + T1*orth1[1]
       Z = origin[2] + T0*orth0[2] + T1*orth1[2] 
       
   
       if axes is None:
           # Prepare figure
           fig = plt.figure(figsize=(9,4.5))
           gs = matplotlib.gridspec.GridSpec( 1,2, wspace=0.2)
       
           ax0 = fig.add_subplot( gs[0,0], projection='3d')
           ax1 = fig.add_subplot( gs[0,1])
       else:
           ax0 = axes[0]
           ax1 = axes[1]
       
       
       # Plot the reference surface
       ax0.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3, linewidth=0.)
       ax0.set_xlabel('X')
       ax0.set_ylabel('Y')
       ax0.set_zlabel('Z')
       lmin = min([ ax0.get_xlim()[0], ax0.get_ylim()[0], ax0.get_zlim()[0] ] )
       lmax = max([ ax0.get_xlim()[1], ax0.get_ylim()[1], ax0.get_zlim()[1] ] )
       ax0.set_xlim( lmin, lmax )
       ax0.set_ylim( lmin, lmax )
       ax0.set_zlim( lmin, lmax )
       ax0.set_yticklabels([])
       ax0.set_xticklabels([])
       ax0.set_zticklabels([])
       
       
       # Evaluate function at points and plot
       EVAL = func(X,Y,Z)
 
       T1_1d = np.ravel(T1)
       EVAL_1d = np.ravel(EVAL)
       
       im =ax1.pcolormesh(T0, T1, EVAL, cmap = plt.get_cmap('jet')) # cmaps:  rainbow, jet
       plt.axes( ax1)
       cbar = plt.colorbar(im)
       cbar.set_label(self.unitlabel, rotation=0 )#self.unitlabel
       
       if axes is None:
           # Finalize figure
           gs.tight_layout(fig, rect=[0.,0.,1.0,1.0])
           
       return EVAL.min(), EVAL.max(), im
Example #51
0
def doDotHalf(a, b, c):
    v0 = vec3(a, b, c)
    v1 = vec3(2.0, 1.0, 3.0)
    return v0.dot(v1)
    def __init__(self, **kwargs):
        """Simple cubic lattice potential """
        
        # Initialize lattice part 
        axes= [ (np.pi/2,0.), (np.pi/2, np.pi/2), (0,0) ] 
        self.l  = kwargs.get('wavelength', 1.064)
        self.m  = kwargs.get('mass', 6.)
        self.w  = kwargs.get('waists', ((47.,47.), (47.,47.), (47.,47.)) )
        self.r  = kwargs.get('retro', (1.,1.,1.) )
        self.a  = kwargs.get('alpha', (1.,1.,1.) )
        self.scale = kwargs.get('scale', 10.) 
        
        self.Er0 = Erecoil(self.l, self.m)
        
        if 'allIR' in kwargs.keys():
            self.Er = [kwargs.get('allIR', 7.0 )]*3
        else:
            self.Er = kwargs.get('Er', (7.0, 7.0, 7.0) ) 
        
        lattbeams = [ LatticeBeam( axis=axes[i], Er=self.Er[i], wavelength=self.l, scale=self.scale,\
                                   waists=self.w[i], retro=self.r[i], alpha=self.a[i] ) for i in range(3) ] 
        
        potential.__init__(self, lattbeams, units=('$E_{R}$', 1/self.Er0) )
        
        self.GRw  = kwargs.get('green_waists', ((40.,40.), (40.,40.), (40.,40.)) ) 
        if 'allGR' in kwargs.keys():
            self.GREr = [kwargs.get('allGR', 4.0 )]*3
        else:
            self.GREr = kwargs.get('green_Er', (4.0, 4.0, 4.0) ) 
        self.GRl  = kwargs.get('green_wavelength', 0.532)
        
        # Express the power requiered for each GR beam, given the Er compensation value
        # in units of the lattice recoil, and given the GR beam waists
        GRmW = [ 1000.* self.GREr[i]*  self.Er0/np.abs(U2uK(self.GRl)*2/np.pi) \
                      * self.GRw[i][0]*self.GRw[i][1]  for i in range(3)]
        
        self.greenbeams = [  GaussBeam( axis=axes[i], mW=GRmW[i], waists=self.GRw[i], wavelength=self.GRl) for i in range(3) ]
        
        # Initialize quantities that will be used for the phase diagram
        #
        self.T = kwargs.get('Temperature', 1.6 )
        self.fHdens = getHTSEInterp( self.T, name="density")
        self.fHdoub = getHTSEInterp( self.T, name="doublons")
        self.fHentr = getHTSEInterp( self.T, name="entropy" )
        self.a_s = kwargs.get('a_s',300.)
        #
        
        # Make a cut line along 111 to calculate integrals of the
        # thermodynamic quantities
        direc111 = (np.arctan(np.sqrt(2)), np.pi/4) 
        unit = vec3(); th = direc111[0]; ph = direc111[1] 
        unit.set_spherical(1, th, ph); unitArr = np.array(unit)
        t = np.linspace( -80, 80, 320 )
        XYZ = np.outer( t, unitArr)
        self.X111 = XYZ[:,0]
        self.Y111 = XYZ[:,1]
        self.Z111 = XYZ[:,2] 
        # Below we get the signed distance from the origin
        self.r111 =  self.X111*unit[0] + self.Y111*unit[1] + self.Z111*unit[2] 
        
        
        # Go ahead and calculate all relevant quantities along the 111
        # direction
        self.V0_111 = self.V0(self.X111,self.Y111,self.Z111) 
        self.Bottom_111 = self.Bottom(self.X111,self.Y111,self.Z111)
        self.bands_111 = bands3dvec( self.V0_111, NBand=0 ) 
        
        self.Ezero_111 = (self.bands_111[1]+self.bands_111[0])/2. + self.Bottom_111
        self.Ezero0_111 = self.Ezero_111.min()
        
        self.tunneling_111 = (self.bands_111[1]-self.bands_111[0])/12. 
        self.onsite_t_111 = Onsite( self.V0_111, a_s=self.a_s, lattice_spacing= self.l/2. ) / self.tunneling_111
        
        
        
        self.verbose = kwargs.get('verbose', False)
        
        
        # Initialize global chemical potential and atom number
        # globalMu can be given directly or can be specified via the 
        # number of atoms.  If the Natoms is specified we calculate 
        # the required gMu using this function: 
        muBrent = kwargs.get('muBrent', (0., 5.))
        if muBrent is None: muBrent = (0., 5.) 
        if 'Natoms' in kwargs.keys():
            self.Number = kwargs.get('Natoms', 3e5)
            fN = lambda x : self.getNumber(x)- self.Number
            if self.verbose:
                print "Searching for globalMu => N=%.0f, "% self.Number,
            self.globalMu, brentResults = optimize.brentq(fN, muBrent[0], muBrent[1], xtol=1e-2, rtol=2e4, full_output=True) 
            if self.verbose:
                print "gMu=%.3f, " % brentResults.root,
                print "n_iter=%d, " % brentResults.iterations,
                print "n eval=%d, " % brentResults.function_calls,
                print "conv?=", brentResults.converged
        else :
            # globalMu is given in Er, and is measured from the value
            # of Ezero at the center of the potential
            # When using it in the phase diagram it has to be changed to
            # units of the tunneling
            self.globalMu = kwargs.get('globalMu', 0.15)
        
        # After the chemical potential is established the local chemical
        # potential along 111 can be defined.  It is used for column density
        # plots and for calculating other thermodynamic quantities
        gMuZero = self.Ezero0_111 + self.globalMu
        self.localMu_t_111= (gMuZero - self.Ezero_111) / self.tunneling_111
        
        
        
        # Obtain trap integrated values of the thermodynamic quantities
        self.Number  = self.getNumber( self.globalMu )
        self.NumberD = self.getNumberD()
        self.Entropy = self.getEntropy()
        
        # MAKE FIGURE LABELS
        # V Lattice
        if len(np.unique(self.Er))==1:
            VLlabel = '$V_{L}=%.2f$' % self.Er[0] 
        else:
            VLlabel = '$V_{Lx}=%.1f, V_{Ly}=%.1f, V_{Lz}=%.1f$' % self.Er 
        # V Green
        if len(np.unique(self.GREr))==1:
            VGlabel = '$V_{G}=%.2f$' % self.GREr[0] 
        else:
            VGlabel = '$V_{Gx}=%.1f, V_{Gy}=%.1f, V_{Gz}=%.1f$' % self.GREr 
        # Scattering length
        aslabel = '$a_{s}=%.0f$' % self.a_s 
        # U/t label 
        Utlabel = '$U/t=%.1f$' % self.onsite_t_111.max()
        # Temperature label
        Tlabel = '$T/t=%.1f$' % self.T
        
        self.figlabel = ',  '.join([VLlabel, VGlabel, aslabel, Utlabel, Tlabel])

        Nlabel = r'$N=%.2f\times 10^{5}$' % (self.Number/1e5)
        Dlabel = r'$D=%.3f$' % ( self.NumberD / self.Number )
        Slabel = r'$S/N=%.2f$' % ( self.Entropy / self.Number )
        self.foottext = ',  '.join([Nlabel, Dlabel, Slabel]) 
Example #53
0
def doDotFull(a, b, c, d, e, f):
    v0 = vec3(a, b, c)
    v1 = vec3(d, e, f)
    return v0.dot(v1)
Example #54
0
def vecSwitch(s):
    if s:
        return vec3(11.0, 11.0, 11.0)
    else:
        return vec3(7.0, 7.0, 7.0)
Example #55
0
def linecut_points(**kwargs):
    """ 
    Defines an line cut through the potential geometry.  Parameters are given
    as keyword arguments (kwargs).

    All distances are in microns. 

    Parameters 
    ----------
    npoints     :  number of points along the cut
 
    extents     :  a way of specifying the limits for a cut that is symmetric
                   about the cut origin.  the limits will be 
                   lims = (-extents, extents)  

    lims        :  used only if extents = None.   limits are specified using
                   a tuple  ( min, max ) 

    direc       :  tuple, two elements.  polar coordinates for the direcdtion 
                   of the cut 
 
    origing     :  tuple, three elements.  cartesian coordinates for the origin
                   of the cut  


    Returns 
    -------
    t           :  array which parameterizes the distance along the cut   
  
    X, Y, Z     :  each of X,Y,Z is an array with the same shape as t. 
                   They correspond to the cartesian coordinates of all the 
                   points along the cut 
                   
    Notes 
    ----  

    Examples
    --------
    """
    npoints = kwargs.get('npoints', 320)
    extents = kwargs.get('extents', None)
    lims = kwargs.get('lims', (-80., 80.))
    direc = kwargs.get('direc', (np.pi / 2, 0.))
    origin = kwargs.get('origin', vec3(0., 0., 0.))

    if extents is not None:
        lims = (-extents, extents)

    # Prepare set of points for plot
    t = np.linspace(lims[0], lims[1], npoints)
    unit = vec3()
    th = direc[0]
    ph = direc[1]
    unit.set_spherical(1, th, ph)
    # Convert vec3s to ndarray
    unit = np.array(unit)
    origin = np.array(origin)
    #
    XYZ = origin + np.outer(t, unit)
    X = XYZ[:, 0]
    Y = XYZ[:, 1]
    Z = XYZ[:, 2]

    return t, X, Y, Z, lims
Example #56
0
def vecAttrSwitch(s):
    a = vec3(11.0, 11.0, 11.0)
    b = vec3(7.0, 7.0, 7.0)
    v = vec3(0.0, 0.0, 0.0)
    attrMunge(s, v, a, b)
    return v
Example #57
0
def confusedSite(b):
	if b:
		return vec3(7.0, 7.0, 7.0)
	else:
		return vec3(11.0, 11.0, 11.0)