예제 #1
0
def sink_radius(IC):
    """
    Determine a reasonable sink radius for the star particles depending on 
    the star system type (e.g., single star, binary, etc...)
    
    Parameters
    ----------
    IC : IC object
    
    Returns
    -------
    r_sink : SimArray
        Sink radius for star particles
    """
    
    # Set up the sink radius
    starMode = IC.settings.physical.starMode.lower()
    
    if starMode == 'binary':
        
        binsys = IC.settings.physical.binsys
        #Set Sink Radius to be mass-weighted average of Roche lobes of two stars
        r1 = AddBinary.calcRocheLobe(binsys.m1/binsys.m2,binsys.a) 
        r2 = AddBinary.calcRocheLobe(binsys.m2/binsys.m1,binsys.a)
        p = strip_units(binsys.m1/(binsys.m1 + binsys.m2))
        r_sink = (r1*p) + (r2*(1.0-p))
    
    else:
    
        r_sink = IC.pos.r.min()
        
    return r_sink
예제 #2
0
def sink_radius(IC):
    """
    Determine a reasonable sink radius for the star particles depending on 
    the star system type (e.g., single star, binary, etc...)
    
    Parameters
    ----------
    IC : IC object
    
    Returns
    -------
    r_sink : SimArray
        Sink radius for star particles
    """
    
    # Set up the sink radius
    starMode = IC.settings.physical.starMode.lower()
    
    if starMode == 'binary':
        
        binsys = IC.settings.physical.binsys
        #Set Sink Radius to be mass-weighted average of Roche lobes of two stars
        r1 = AddBinary.calcRocheLobe(binsys.m1/binsys.m2,binsys.a) 
        r2 = AddBinary.calcRocheLobe(binsys.m2/binsys.m1,binsys.a)
        p = strip_units(binsys.m1/(binsys.m1 + binsys.m2))
        r_sink = (r1*p) + (r2*(1.0-p))
    
    else:
    
        r_sink = IC.pos.r.min()
        
    return r_sink
예제 #3
0
def orbElemsVsRadius(s,rBinEdges,average=False):
    """
    Computes the orbital elements for disk particles about a binary system in given radial bins.
    Assumes center of mass has v ~ 0

    Parameters
    ----------

    s: Tipsy snapshot
    rBinEdges: numpy array
        Radial bin edges [AU] preferably calculated using binaryUtils.calcDiskRadialBins
    average: bool
        True -> average over all particles in bin, false -> randomly select 1 particle in bin
        
    Returns
    -------
    orbElems: numpy array
        6 x len(rBinEdges) - 1 containing orbital elements at each radial bin
        as e, a, i, Omega, w, nu
    """
    
    #Read snapshot and pull out values of interest
    stars = s.stars
    gas = s.gas    
    M = np.sum(stars['mass'])
    zero = SimArray(np.zeros(3).reshape((1, 3)),'cm s**-1') 
    orbElems = np.zeros((6,len(rBinEdges)-1))    
    
    #Gas orbiting about system center of mass
    com = computeCOM(stars,gas)
   
    #Loop over radial bins calculating orbital elements
    for i in range(0,len(rBinEdges)-1):
        if average: #Average over all gas particles in subsection
            rMask = np.logical_and(gas['rxy'].in_units('au') > rBinEdges[i], gas['rxy'].in_units('au') < rBinEdges[i+1])
            if i > 0:
                #Include mass of disk interior to given radius
                mass = M + np.sum(gas[gas['rxy'] < rBinEdges[i]]['mass'])
            else:
                mass = M
            g = gas[rMask]
            N = len(g)
            if N > 0:
                orbElems[:,i] = np.sum(AddBinary.calcOrbitalElements(g['pos'],com,g['vel'],zero,mass,g['mass']),axis=-1)/N
            else: #If there are no particles in the bin, set it as a negative number to mask out later
                orbElems[:,i] = -1.0
        else: #Randomly select 1 particle in subsection for calculations
            rMask = np.logical_and(gas['rxy'].in_units('au') > rBinEdges[i], gas['rxy'].in_units('au') < rBinEdges[i+1])
            if i > 0:            
                mass = M + np.sum(gas[gas['rxy'] < rBinEdges[i]]['mass'])
            else:
                mass = M
            g = gas[rMask]            
            index = np.random.randint(0,len(g))
            particle = g[index]
            orbElems[:,i] = AddBinary.calcOrbitalElements(com,particle['pos'],zero,particle['vel'],mass,particle['mass'])
            
    return orbElems
예제 #4
0
 def computeCartesian(self):
     """
     Compute the Cartesian position and velocity in the reduced mass frame.
     """
     assert (self.state == "Kepler" or self.state ==
             "kepler"), "Already have cartesian coordinates."
     M = AddBinary.trueToMean(self.nu, self.e)
     self.r, self.v = AddBinary.keplerToCartesian(
         self.a, self.e, self.i, self.Omega, self.w, M, self.m1, self.m2)
예제 #5
0
파일: binary.py 프로젝트: dflemin3/diskpy
 def computeCartesian(self):
     """
     Compute the Cartesian position and velocity in the reduced mass frame.
     """
     assert (self.state == "Kepler" or self.state ==
             "kepler"), "Already have cartesian coordinates."
     M = AddBinary.trueToMean(self.nu, self.e)
     self.r, self.v = AddBinary.keplerToCartesian(
         self.a, self.e, self.i, self.Omega, self.w, M, self.m1, self.m2)
예제 #6
0
def estimateCBResonances(s, r_max, m_max=5, l_max=5, bins=2500):
    """
	Given pynbody snapshot star and gas SimArrays, computes the resonances of disk on binary as a function of period.
	Disk radius, in au, is convered to angular frequency which will then be used to compute corotation and inner/outer Lindblad resonances.
	Assumption: Assumes m_disk << m_bin which holds in general for simulations considered
	For reference: Kappa, omega computed in ~ 1/day intermediate units.
	Uses approximations from Artymowicz 1994

	Inputs:
	stars,gas: Pynbody snapshot .star and .gas SimArrays (in au, Msol, etc)
	r_max: maximum disk radius for calculations (au)
	bins: number of radial bins to calculate over

	Output:
	Orbital frequency for corotation and inner/outer resonances as float and 2 arrays
	"""
    stars = s.stars
    #gas = s.gas

    #Compute binary angular frequency
    #Strip units from all inputs
    x1 = np.asarray(isaac.strip_units(stars[0]['pos']))
    x2 = np.asarray(isaac.strip_units(stars[1]['pos']))
    v1 = np.asarray(isaac.strip_units(stars[0]['vel']))
    v2 = np.asarray(isaac.strip_units(stars[1]['vel']))
    m1 = np.asarray(isaac.strip_units(stars[0]['mass']))
    m2 = np.asarray(isaac.strip_units(stars[1]['mass']))
    a = AddBinary.calcSemi(x1, x2, v1, v2, m1, m2)
    #omega_b = 2.0*np.pi/AddBinary.aToP(a,m1+m2

    #Find corotation resonance where omega_d ~ omega_b
    r_c = a  #m=1 case
    o_c = 2.0 * np.pi / AddBinary.aToP(r_c, m1 + m2)

    #Find inner lindblad resonances for m = [m_min,m_max]
    #Lindblad resonance: omega = omega_pattern +/- kappa/m for int m > 1
    m_min = 1
    l_min = 1

    omega_Lo = np.zeros((m_max - m_min, l_max - l_min))
    omega_Li = np.zeros((m_max - m_min, l_max - l_min))

    #Find resonance radii, convert to angular frequency
    for m in range(m_min, m_max):
        for l in range(l_min, l_max):
            #oTmp = find_crit_radius(r,omega_d-(kappa/(float(m))),omega_b,bins) #outer LR
            oTmp = np.power(float(m + 1) / l, 2. / 3.) * a
            omega_Lo[m - m_min,
                     l - l_min] = 2.0 * np.pi / AddBinary.aToP(oTmp, m1 + m2)

            #iTmp = find_crit_radius(r,omega_d+(kappa/(float(m))),omega_b,bins) #inner LR
            iTmp = np.power(float(m - 1) / l, 2. / 3.) * a
            omega_Li[m - m_min,
                     l - l_min] = 2.0 * np.pi / AddBinary.aToP(iTmp, m1 + m2)

    return omega_Li, omega_Lo, o_c  #return inner, outer, co angular frequencies
예제 #7
0
def estimateCBResonances(s,r_max,m_max=5,l_max=5,bins=2500):
	"""
	Given pynbody snapshot star and gas SimArrays, computes the resonances of disk on binary as a function of period.
	Disk radius, in au, is convered to angular frequency which will then be used to compute corotation and inner/outer Lindblad resonances.
	Assumption: Assumes m_disk << m_bin which holds in general for simulations considered
	For reference: Kappa, omega computed in ~ 1/day intermediate units.
	Uses approximations from Artymowicz 1994

	Inputs:
	stars,gas: Pynbody snapshot .star and .gas SimArrays (in au, Msol, etc)
	r_max: maximum disk radius for calculations (au)
	bins: number of radial bins to calculate over

	Output:
	Orbital frequency for corotation and inner/outer resonances as float and 2 arrays
	"""
	stars = s.stars
	#gas = s.gas

	#Compute binary angular frequency
	#Strip units from all inputs
	x1 = np.asarray(isaac.strip_units(stars[0]['pos']))
	x2 = np.asarray(isaac.strip_units(stars[1]['pos']))
	v1 = np.asarray(isaac.strip_units(stars[0]['vel']))
	v2 = np.asarray(isaac.strip_units(stars[1]['vel']))
	m1 = np.asarray(isaac.strip_units(stars[0]['mass']))
	m2 = np.asarray(isaac.strip_units(stars[1]['mass']))
	a = AddBinary.calcSemi(x1, x2, v1, v2, m1, m2)
	#omega_b = 2.0*np.pi/AddBinary.aToP(a,m1+m2

	#Find corotation resonance where omega_d ~ omega_b
	r_c = a #m=1 case
	o_c = 2.0*np.pi/AddBinary.aToP(r_c,m1+m2)
        
	#Find inner lindblad resonances for m = [m_min,m_max]
	#Lindblad resonance: omega = omega_pattern +/- kappa/m for int m > 1
	m_min = 1
	l_min = 1    

	omega_Lo = np.zeros((m_max-m_min,l_max-l_min))
	omega_Li = np.zeros((m_max-m_min,l_max-l_min))
   
	#Find resonance radii, convert to angular frequency
	for m in range(m_min,m_max):
		for l in range(l_min,l_max):
		#oTmp = find_crit_radius(r,omega_d-(kappa/(float(m))),omega_b,bins) #outer LR
			oTmp = np.power(float(m+1)/l,2./3.)*a
			omega_Lo[m-m_min,l-l_min] = 2.0*np.pi/AddBinary.aToP(oTmp,m1+m2)
		
		#iTmp = find_crit_radius(r,omega_d+(kappa/(float(m))),omega_b,bins) #inner LR
			iTmp = np.power(float(m-1)/l,2./3.)*a
			omega_Li[m-m_min,l-l_min] = 2.0*np.pi/AddBinary.aToP(iTmp,m1+m2)

	return omega_Li, omega_Lo, o_c #return inner, outer, co angular frequencies
예제 #8
0
파일: binary.py 프로젝트: dflemin3/diskpy
    def computeOrbElems(self):
        """
        Compute the Kepler orbital elements.

        Input: Self (must have r, v set and in proper units)

        Output: sets and returns e,a,i,...
        """
        # Compute orbital elements from binary center of mass frame Cartesian
        # coordinates
        assert (self.state != 'Kepler' or self.state != 'kepler'), "Already have orbital elements."        
        
        zeroR = SimArray([[0.0, 0.0, 0.0]],'cm')
        zeroV = SimArray([[0.0, 0.0, 0.0]],'cm s**-1')
        oe = AddBinary.calcOrbitalElements(
            self.r,
            zeroR,
            self.v,
            zeroV,
            self.m1,
            self.m2)

        # Set orbital elements, return them as well
        self.assignOrbElems(oe)
        return oe
예제 #9
0
    def computeOrbElems(self):
        """
        Compute the Kepler orbital elements.

        Input: Self (must have r, v set and in proper units)

        Output: sets and returns e,a,i,...
        """
        # Compute orbital elements from binary center of mass frame Cartesian
        # coordinates
        assert (self.state != 'Kepler' or self.state != 'kepler'), "Already have orbital elements."        
        
        zeroR = SimArray([[0.0, 0.0, 0.0]],'cm')
        zeroV = SimArray([[0.0, 0.0, 0.0]],'cm s**-1')
        oe = AddBinary.calcOrbitalElements(
            self.r,
            zeroR,
            self.v,
            zeroV,
            self.m1,
            self.m2)

        # Set orbital elements, return them as well
        self.assignOrbElems(oe)
        return oe
예제 #10
0
파일: binary.py 프로젝트: dflemin3/diskpy
 def generateICs(self):
     """
     From Kepler orbital elements, compute the position, velocities for two stars in ChaNGa-friendly units.
     Called "generateICs" since I'll use this mainly to...generate initial conditions
     """
     x1, x2, v1, v2 = AddBinary.reduceToPhysical(
         self.r, self.v, self.m1, self.m2)
     x1 = np.asarray(x1).reshape((1, 3))
     x2 = np.asarray(x2).reshape((1, 3))
     v1 = np.asarray(v1).reshape((1, 3))
     v2 = np.asarray(v2).reshape((1, 3))
     return x1, x2, v1, v2
예제 #11
0
 def generateICs(self):
     """
     From Kepler orbital elements, compute the position, velocities for two stars in ChaNGa-friendly units.
     Called "generateICs" since I'll use this mainly to...generate initial conditions
     """
     x1, x2, v1, v2 = AddBinary.reduceToPhysical(
         self.r, self.v, self.m1, self.m2)
     x1 = np.asarray(x1).reshape((1, 3))
     x2 = np.asarray(x2).reshape((1, 3))
     v1 = np.asarray(v1).reshape((1, 3))
     v2 = np.asarray(v2).reshape((1, 3))
     return x1, x2, v1, v2
예제 #12
0
def calcDiskRadialBins(s, r_in=0, r_out=0, bins=50):
    """
    Cleanly partitions disk into radial bins and returns the bin edges and central bin values.  Note, default
    ndim = 2 so all bins are in 2D plane (i.e. radius r is polar/cylindrical radius in xy plane which makes 
    sense for thin disks)

    Parameters
    ----------
    s: Pynbody snapshot
    r_in: float 
        Inner disk radius you'll consider (AU)
    r_out: float 
        Outer disk radius you'll consider (AU)
    bins: int
        # of bins 

    Returns
    --------
    r: numpy array 
        central radial bin values (AU)
    rBinEdges: numpy array 
        edges of radial bins
    """
    #Load data, compute semimajor axis and strip units
    x1 = s.stars[0]['pos']
    x2 = s.stars[1]['pos']
    v1 = s.stars[0]['vel']
    v2 = s.stars[1]['vel']
    m1 = s.stars[0]['mass']
    m2 = s.stars[1]['mass']
    s_a = AddBinary.calcSemi(x1, x2, v1, v2, m1, m2)  #Units = au

    #Default r_in, r_out if none given
    if r_in == 0 and r_out == 0:
        r_in = 1.0 * s_a
        r_out = 4.0 * s_a

    #Bin gas particles by radius
    pg = pynbody.analysis.profile.Profile(s.gas, max=r_out, nbins=bins)
    r = pg['rbins'].in_units('au')

    mask = (r > r_in) & (r < r_out
                         )  #Ensure you're not right on binary or too far out.
    r = r[mask]

    #Make nice, evenly spaced radial bins vector
    rBinEdges = np.linspace(np.min(r), np.max(r), bins + 1)

    #Create compute center of radial bins
    r = 0.5 * (rBinEdges[1:] + rBinEdges[:-1])

    return r, rBinEdges
예제 #13
0
def calcDiskRadialBins(s,r_in=0,r_out=0,bins=50):
    """
    Cleanly partitions disk into radial bins and returns the bin edges and central bin values.  Note, default
    ndim = 2 so all bins are in 2D plane (i.e. radius r is polar/cylindrical radius in xy plane which makes 
    sense for thin disks)

    Parameters
    ----------
    s: Pynbody snapshot
    r_in: float 
        Inner disk radius you'll consider (AU)
    r_out: float 
        Outer disk radius you'll consider (AU)
    bins: int
        # of bins 

    Returns
    --------
    r: numpy array 
        central radial bin values (AU)
    rBinEdges: numpy array 
        edges of radial bins
    """
    #Load data, compute semimajor axis and strip units
    x1 = s.stars[0]['pos']
    x2 = s.stars[1]['pos']
    v1 = s.stars[0]['vel']
    v2 = s.stars[1]['vel']
    m1 = s.stars[0]['mass']
    m2 = s.stars[1]['mass']
    s_a = AddBinary.calcSemi(x1, x2, v1, v2, m1, m2) #Units = au

    #Default r_in, r_out if none given
    if r_in == 0 and r_out == 0:
        r_in = 1.0*s_a
        r_out = 4.0*s_a

    #Bin gas particles by radius
    pg = pynbody.analysis.profile.Profile(s.gas,max=r_out,nbins=bins)
    r = pg['rbins'].in_units('au')    
    
    mask = (r > r_in) & (r < r_out) #Ensure you're not right on binary or too far out.
    r = r[mask]

    #Make nice, evenly spaced radial bins vector
    rBinEdges = np.linspace(np.min(r),np.max(r),bins+1)
 
    #Create compute center of radial bins
    r = 0.5 * (rBinEdges[1:] + rBinEdges[:-1])

    return r, rBinEdges
예제 #14
0
def findCBResonances(s,r,r_min,r_max,m_max=4,l_max=4,bins=50):
    """
    Given Tipsy snapshot, computes the resonances of disk on binary as a function of orbital angular frequency omega.
    Disk radius, in au, is convered to angular frequency which will then be used to compute corotation 
    and inner/outer Lindblad resonances.
   
   Note: r given MUST correspond to r over which de/dt was calculated.  Otherwise, scale gets all messed up
   
   !!! NOTE: This function is awful and deprecated --- do NOT use it.  Instead, use calc_LB_resonance !!!
 
     Parameters
     ----------
     s: Tipsy-format snapshot
     r: array
         radius array over which de/dt was calculated
     r_min,r_max: floats
         min/maximum disk radius for calculations (au)
     bins: int
         number of radial bins to calculate over
     m_max,l_max: ints
         maximum orders of (m,l) LR

    Returns
    -------
    Orbital frequency: numpy array
        for corotation and inner/outer resonances and radii as float and numpy arrays
    """
    stars = s.stars
    gas = s.gas

    m_min = 1 #m >=1 for LRs, CRs
    l_min = 1 #l >=1 for LRs, CRs

    #Compute binary angular frequency
    x1 = stars[0]['pos']
    x2 = stars[1]['pos']
    v1 = stars[0]['vel']
    v2 = stars[1]['vel']
    m1 = stars[0]['mass']
    m2 = stars[1]['mass']
     
    a = strip_units(AddBinary.calcSemi(x1, x2, v1, v2, m1, m2))
    omega_b = 2.0*np.pi/AddBinary.aToP(a,m1+m2) #In units 1/day

    #Make r steps smaller for higher accuracy
    r_arr = np.linspace(r.min(),r.max(),len(r)*10)

    #Compute mass of disk interior to given r
    mask = np.zeros((len(gas),len(r_arr)),dtype=bool)
    m_disk = np.zeros(len(r_arr))
    for i in range(0,len(r_arr)):
        mask[:,i] = gas['rxy'] < r_arr[i]
        m_disk[i] = np.sum(gas['mass'][mask[:,i]])

    #Compute omega_disk in units 1/day (like omega_binary)
    omega_d = 2.0*np.pi/AddBinary.aToP(r_arr,m1+m2+m_disk)
        
    #Compute kappa (radial epicycle frequency = sqrt(r * d(omega^2)/dr + 4*(omega^2))
    o2 = omega_d*omega_d
    dr = r_arr[1] - r_arr[0]
    #dr = (r.max()-r.min())/float(bins) #Assuming r has evenly spaced bins!
    drdo2 = np.gradient(o2,dr) #I mean d/dr(omega^2)
    kappa = np.sqrt(r_arr*drdo2 + 4.0*o2)
   
    #Allocate arrays for output 
    omega_Lo = np.zeros((m_max,l_max))
    omega_Li = np.zeros((m_max,l_max))
    o_c = np.zeros(l_max)   
 
    #Find resonance angular frequency
    for m in range(m_min,m_max+1):
        for l in range(l_min,l_max+1):
            outer = omega_d + (float(l)/m)*kappa
            inner = omega_d - (float(l)/m)*kappa
            omega_Lo[m-m_min,l-l_min] = omega_d[np.argmin(np.fabs(omega_b-outer))]
            omega_Li[m-m_min,l-l_min] = omega_d[np.argmin(np.fabs(omega_b-inner))]

            #Find corotation resonance where omega_d ~ omega_b
            o_c[l-l_min] = omega_d[np.argmin(np.fabs(omega_d-omega_b/float(l)))]

    #Rescale omega_d, kappa to be of length bins again
    omega_d = np.linspace(omega_d.min(),omega_d.max(),bins)
    kappa = np.linspace(kappa.min(),kappa.max(),bins)
    return omega_Li, omega_Lo, o_c, omega_d, kappa
예제 #15
0
def orbElemsVsRadius(s, rBinEdges, average=False):
    """
    Computes the orbital elements for disk particles about a binary system in given radial bins.
    Assumes center of mass has v ~ 0

    Parameters
    ----------

    s: Tipsy snapshot
    rBinEdges: numpy array
        Radial bin edges [AU] preferably calculated using binaryUtils.calcDiskRadialBins
    average: bool
        True -> average over all particles in bin, false -> randomly select 1 particle in bin
        
    Returns
    -------
    orbElems: numpy array
        6 x len(rBinEdges) - 1 containing orbital elements at each radial bin
        as e, a, i, Omega, w, nu
    """

    #Read snapshot and pull out values of interest
    stars = s.stars
    gas = s.gas
    M = np.sum(stars['mass'])
    zero = SimArray(np.zeros(3).reshape((1, 3)), 'cm s**-1')
    orbElems = np.zeros((6, len(rBinEdges) - 1))

    #Gas orbiting about system center of mass
    com = computeCOM(stars, gas)

    #Loop over radial bins calculating orbital elements
    for i in range(0, len(rBinEdges) - 1):
        if average:  #Average over all gas particles in subsection
            rMask = np.logical_and(
                gas['rxy'].in_units('au') > rBinEdges[i],
                gas['rxy'].in_units('au') < rBinEdges[i + 1])
            if i > 0:
                #Include mass of disk interior to given radius
                mass = M + np.sum(gas[gas['rxy'] < rBinEdges[i]]['mass'])
            else:
                mass = M
            g = gas[rMask]
            N = len(g)
            if N > 0:
                orbElems[:, i] = np.sum(AddBinary.calcOrbitalElements(
                    g['pos'], com, g['vel'], zero, mass, g['mass']),
                                        axis=-1) / N
            else:  #If there are no particles in the bin, set it as a negative number to mask out later
                orbElems[:, i] = -1.0
        else:  #Randomly select 1 particle in subsection for calculations
            rMask = np.logical_and(
                gas['rxy'].in_units('au') > rBinEdges[i],
                gas['rxy'].in_units('au') < rBinEdges[i + 1])
            if i > 0:
                mass = M + np.sum(gas[gas['rxy'] < rBinEdges[i]]['mass'])
            else:
                mass = M
            g = gas[rMask]
            index = np.random.randint(0, len(g))
            particle = g[index]
            orbElems[:, i] = AddBinary.calcOrbitalElements(
                com, particle['pos'], zero, particle['vel'], mass,
                particle['mass'])

    return orbElems
예제 #16
0
def calc_LB_resonance(s, m_min=1, m_max=3, l_min=1, l_max=3):
    """
    Computes the locations of various Lindblad Resonances in the disk as a 
    function of binary pattern speed.
    
     Parameters
     ----------
     s : Tipsy-format snapshot
     m_min, l_min : ints
         minimum orders of (m,l) LR
     m_max,l_max : ints
         maximum orders of (m,l) LR

    Returns
    -------
    OLR, ILR, CR: numpy arrays
        location in AU of (m,l)th order Lindblad resonances
    """

    #Compute binary angular frequency in 1/day
    x1 = s.stars[0]['pos']
    x2 = s.stars[1]['pos']
    v1 = s.stars[0]['vel']
    v2 = s.stars[1]['vel']
    m1 = s.stars[0]['mass']
    m2 = s.stars[1]['mass']
    omega_b = 2.0 * np.pi / AddBinary.aToP(
        AddBinary.calcSemi(x1, x2, v1, v2, m1, m2), m1 + m2)
    guess = 0.05  #fsolve initial guess parameter

    #Allocate space for arrays
    OLR = np.zeros((m_max, l_max))
    ILR = np.zeros((m_max, l_max))
    CR = np.zeros(l_max)

    #Define resonance functions
    def OLR_func(omega_d, *args):
        m = args[0]
        l = args[1]
        omega_b = args[2]

        return omega_d * (1.0 + float(l) / m) - omega_b

    #end function

    def ILR_func(omega_d, *args):
        m = args[0]
        l = args[1]
        omega_b = args[2]

        return omega_d * (1.0 - float(l) / m) - omega_b

    #end function

    def CR_func(omega_d, *args):
        l = args[0]
        omega_b = args[1]

        return omega_d - omega_b / float(l)

    #end function

    for m in range(m_min, m_max + 1):
        for l in range(l_min, l_max + 1):
            OLR[m - m_min, l - l_min] = fsolve(OLR_func,
                                               guess,
                                               args=(m, l, omega_b))
            ILR[m - m_min, l - l_min] = fsolve(ILR_func,
                                               guess,
                                               args=(m, l, omega_b))
            CR[l - l_min] = fsolve(CR_func, guess, args=(l, omega_b))

    #Convert from 1/day -> au
    OLR = AddBinary.pToA(2.0 * np.pi / OLR, m1 + m2)
    ILR = AddBinary.pToA(2.0 * np.pi / ILR, m1 + m2)
    CR = AddBinary.pToA(2.0 * np.pi / CR, m1 + m2)

    return OLR, ILR, CR
예제 #17
0
def findCBResonances(s, r, r_min, r_max, m_max=4, l_max=4, bins=50):
    """
    Given Tipsy snapshot, computes the resonances of disk on binary as a function of orbital angular frequency omega.
    Disk radius, in au, is convered to angular frequency which will then be used to compute corotation 
    and inner/outer Lindblad resonances.
   
   Note: r given MUST correspond to r over which de/dt was calculated.  Otherwise, scale gets all messed up
   
   !!! NOTE: This function is awful and deprecated --- do NOT use it.  Instead, use calc_LB_resonance !!!
 
     Parameters
     ----------
     s: Tipsy-format snapshot
     r: array
         radius array over which de/dt was calculated
     r_min,r_max: floats
         min/maximum disk radius for calculations (au)
     bins: int
         number of radial bins to calculate over
     m_max,l_max: ints
         maximum orders of (m,l) LR

    Returns
    -------
    Orbital frequency: numpy array
        for corotation and inner/outer resonances and radii as float and numpy arrays
    """
    stars = s.stars
    gas = s.gas

    m_min = 1  #m >=1 for LRs, CRs
    l_min = 1  #l >=1 for LRs, CRs

    #Compute binary angular frequency
    x1 = stars[0]['pos']
    x2 = stars[1]['pos']
    v1 = stars[0]['vel']
    v2 = stars[1]['vel']
    m1 = stars[0]['mass']
    m2 = stars[1]['mass']

    a = strip_units(AddBinary.calcSemi(x1, x2, v1, v2, m1, m2))
    omega_b = 2.0 * np.pi / AddBinary.aToP(a, m1 + m2)  #In units 1/day

    #Make r steps smaller for higher accuracy
    r_arr = np.linspace(r.min(), r.max(), len(r) * 10)

    #Compute mass of disk interior to given r
    mask = np.zeros((len(gas), len(r_arr)), dtype=bool)
    m_disk = np.zeros(len(r_arr))
    for i in range(0, len(r_arr)):
        mask[:, i] = gas['rxy'] < r_arr[i]
        m_disk[i] = np.sum(gas['mass'][mask[:, i]])

    #Compute omega_disk in units 1/day (like omega_binary)
    omega_d = 2.0 * np.pi / AddBinary.aToP(r_arr, m1 + m2 + m_disk)

    #Compute kappa (radial epicycle frequency = sqrt(r * d(omega^2)/dr + 4*(omega^2))
    o2 = omega_d * omega_d
    dr = r_arr[1] - r_arr[0]
    #dr = (r.max()-r.min())/float(bins) #Assuming r has evenly spaced bins!
    drdo2 = np.gradient(o2, dr)  #I mean d/dr(omega^2)
    kappa = np.sqrt(r_arr * drdo2 + 4.0 * o2)

    #Allocate arrays for output
    omega_Lo = np.zeros((m_max, l_max))
    omega_Li = np.zeros((m_max, l_max))
    o_c = np.zeros(l_max)

    #Find resonance angular frequency
    for m in range(m_min, m_max + 1):
        for l in range(l_min, l_max + 1):
            outer = omega_d + (float(l) / m) * kappa
            inner = omega_d - (float(l) / m) * kappa
            omega_Lo[m - m_min,
                     l - l_min] = omega_d[np.argmin(np.fabs(omega_b - outer))]
            omega_Li[m - m_min,
                     l - l_min] = omega_d[np.argmin(np.fabs(omega_b - inner))]

            #Find corotation resonance where omega_d ~ omega_b
            o_c[l - l_min] = omega_d[np.argmin(
                np.fabs(omega_d - omega_b / float(l)))]

    #Rescale omega_d, kappa to be of length bins again
    omega_d = np.linspace(omega_d.min(), omega_d.max(), bins)
    kappa = np.linspace(kappa.min(), kappa.max(), bins)
    return omega_Li, omega_Lo, o_c, omega_d, kappa
예제 #18
0
def make_binary(IC, snapshot):
    """
    Turns a snapshot for a single star into a snapshot of a binary system
    
    Parameters
    ----------
    IC : IC object
    snapshot : SimSnap
        Single star system to turn into a binary
    
    Returns
    -------
    snapshotBinary : SimSnap
        A binary version of the simulation snapshot
    """
    # Initialize snapshot
    snapshotBinary = pynbody.new(star=2, gas=len(snapshot.g))
    # Copy gas particles over
    for key in snapshot.gas.keys():
        
        snapshotBinary.gas[key] = snapshot.gas[key]
        
    # Load Binary system obj to initialize system
    starMode = IC.settings.physical.starMode.lower()
    binsys = IC.settings.physical.binsys
    
    if starMode == 'stype':
        
        # Treate the primary as a star of mass mStar + mDisk
        m_disk = strip_units(np.sum(snapshotBinary.gas['mass']))
        binsys.m1 += m_disk
        binsys.computeCartesian()
        
    x1,x2,v1,v2 = binsys.generateICs()
    
    #Assign star parameters assuming CCW orbit
    snapshotBinary.star[0]['pos'] = x1
    snapshotBinary.star[0]['vel'] = v1
    snapshotBinary.star[1]['pos'] = x2
    snapshotBinary.star[1]['vel'] = v2
    
    #Set stellar masses
    priMass = binsys.m1
    secMass = binsys.m2    
    snapshotBinary.star[0]['mass'] = priMass
    snapshotBinary.star[1]['mass'] = secMass    
    snapshotBinary.star['metals'] = snapshot.s['metals']
    
    if starMode == 'stype':
        # We have the binary positions about their center of mass, (0,0,0), so 
        # shift the position, velocity of the gas disk to be around the primary.
        snapshotBinary.gas['pos'] += snapshotBinary.star[0]['pos']
        snapshotBinary.gas['vel'] += snapshotBinary.star[0]['vel']  
        # Remove disk mass from the effective star mass
        snapshotBinary[0]['mass'] -= m_disk
        binsys.m1 -= m_disk
        # Star smoothing
        snapshotBinary.star['eps'] = snapshot.star['eps']

        
    elif starMode == 'binary':
        
        # Estimate stars' softening length as fraction of distance to COM
        d = np.sqrt(AddBinary.dotProduct(x1-x2,x1-x2))
        pos_unit = snapshotBinary['pos'].units
        snapshotBinary.star['eps'] = SimArray(abs(d)/4.0,pos_unit)
        
    return snapshotBinary
예제 #19
0
def findCBResonances(s,r,r_min,r_max,m_max=4,l_max=4,bins=50):
    """
    Given Tipsy snapshot, computes the resonances of disk on binary as a function of orbital angular frequency omega.
    Disk radius, in au, is convered to angular frequency which will then be used to compute corotation 
    and inner/outer Lindblad resonances.
   
   Note: r given MUST correspond to r over which de/dt was calculated.  Otherwise, scale gets all messed up
 
     Parameters
     ----------
     s: Tipsy-format snapshot
     r: array
         radius array over which de/dt was calculated
     r_min,r_max: floats
         min/maximum disk radius for calculations (au)
     bins: int
         number of radial bins to calculate over
     m_max,l_max: ints
         maximum orders of (m,l) LR

    Returns
    -------
    Orbital frequency: numpy array
        for corotation and inner/outer resonances and radii as float and numpy arrays
    """
    stars = s.stars

    m_min = 1 #m >=1 for LRs, CRs
    l_min = 1 #l >=1 for LRs, CRs

    #Compute binary angular frequency
    #Strip units from all inputs
    #x1 = np.asarray(isaac.strip_units(stars[0]['pos']))
    #x2 = np.asarray(isaac.strip_units(stars[1]['pos']))
    #v1 = np.asarray(isaac.strip_units(stars[0]['vel']))
    #v2 = np.asarray(isaac.strip_units(stars[1]['vel']))
    #m1 = np.asarray(isaac.strip_units(stars[0]['mass']))
    #m2 = np.asarray(isaac.strip_units(stars[1]['mass']))
    x1 = stars[0]['pos']
    x2 = stars[1]['pos']
    v1 = stars[0]['vel']
    v2 = stars[1]['vel']
    m1 = stars[0]['mass']
    m2 = stars[1]['mass']
     
    a = isaac.strip_units(AddBinary.calcSemi(x1, x2, v1, v2, m1, m2))
    omega_b = 2.0*np.pi/AddBinary.aToP(a,m1+m2) #In units 1/day

    #Compute omega_disk in units 1/day (like omega_binary)
    omega_d = 2.0*np.pi/AddBinary.aToP(r,m1+m2)
        
    #Compute kappa (radial epicycle frequency = sqrt(r * d(omega^2)/dr + 4*(omega^2))
    o2 = omega_d*omega_d
    dr = (r.max()-r.min())/float(bins) #Assuming r has evenly spaced bins!
    drdo2 = np.gradient(o2,dr) #I mean d/dr(omega^2)
    kappa = np.sqrt(r*drdo2 + 4.0*o2)
   
    #Allocate arrays for output 
    omega_Lo = np.zeros((m_max,l_max))
    omega_Li = np.zeros((m_max,l_max))
    o_c = np.zeros(l_max)   
 
    #Find resonance angular frequency
    for m in range(m_min,m_max+1):
        for l in range(l_min,l_max+1):
            outer = omega_d + (float(l)/m)*kappa
            inner = omega_d - (float(l)/m)*kappa
            omega_Lo[m-m_min,l-l_min] = omega_d[np.argmin(np.fabs(omega_b-outer))]
            omega_Li[m-m_min,l-l_min] = omega_d[np.argmin(np.fabs(omega_b-inner))]

            #Find corotation resonance where omega_d ~ omega_b
            o_c[l-l_min] = omega_d[np.argmin(np.fabs(omega_d-omega_b/float(l)))]

    return omega_Li, omega_Lo, o_c, omega_d, kappa
예제 #20
0
def snapshot_gen(ICobj):
    """
    Generates a tipsy snapshot from the initial conditions object ICobj.
    
    Returns snapshot, param
    
        snapshot: tipsy snapshot
        param: dictionary containing info for a .param file
    Note: Code has been edited (dflemin3) such that now it returns a snapshot for a circumbinary disk
    where initial conditions generated assuming star at origin of mass M.  After gas initialized, replaced
    star at origin with binary system who's center of mass lies at the origin and who's mass m1 +m2 = M
    """
    
    print 'Generating snapshot...'
    # Constants
    G = SimArray(1.0,'G')
    # ------------------------------------
    # Load in things from ICobj
    # ------------------------------------
    print 'Accessing data from ICs'
    settings = ICobj.settings
    
    # snapshot file name
    snapshotName = settings.filenames.snapshotName
    paramName = settings.filenames.paramName   
 
    # particle positions
    r = ICobj.pos.r
    xyz = ICobj.pos.xyz
    
    # Number of particles
    nParticles = ICobj.pos.nParticles
    
    # molecular mass
    m = settings.physical.m
    
    # star mass
    m_star = settings.physical.M.copy()
    
    # disk mass
    m_disk = ICobj.sigma.m_disk.copy()
    m_disk = match_units(m_disk, m_star)[0]
    
    # mass of the gas particles
    m_particles = m_disk / float(nParticles)
    
    # re-scale the particles (allows making of low-mass disk)
    m_particles *= settings.snapshot.mScale
    
    # -------------------------------------------------
    # Assign output
    # -------------------------------------------------
    print 'Assigning data to snapshot'
    # Get units all set up
    m_unit = m_star.units
    pos_unit = r.units
    
    if xyz.units != r.units:
        
        xyz.convert_units(pos_unit)
        
    # time units are sqrt(L^3/GM)
    t_unit = np.sqrt((pos_unit**3)*np.power((G*m_unit), -1)).units
    # velocity units are L/t
    v_unit = (pos_unit/t_unit).ratio('km s**-1')
    # Make it a unit, save value for future conversion
    v_unit_vel = v_unit
    #Ensure v_unit_vel is the same as what I assume it is.
    assert(np.fabs(AddBinary.VEL_UNIT-v_unit_vel)<AddBinary.SMALL),"VEL_UNIT not equal to ChaNGa unit! Why??"			
	
    v_unit = pynbody.units.Unit('{0} km s**-1'.format(v_unit))
    
    # Other settings
    metals = settings.snapshot.metals
    star_metals = metals
    
    # Generate snapshot
    # Note that empty pos, vel, and mass arrays are created in the snapshot
    snapshot = pynbody.new(star=1,gas=nParticles)
    snapshot['vel'].units = v_unit
    snapshot['eps'] = 0.01*SimArray(np.ones(nParticles+1, dtype=np.float32), pos_unit)
    snapshot['metals'] = SimArray(np.zeros(nParticles+1, dtype=np.float32))
    snapshot['rho'] = SimArray(np.zeros(nParticles+1, dtype=np.float32))
    
    snapshot.gas['pos'] = xyz
    snapshot.gas['temp'] = ICobj.T(r)
    snapshot.gas['mass'] = m_particles
    snapshot.gas['metals'] = metals
    
    snapshot.star['pos'] = SimArray([[ 0.,  0.,  0.]],pos_unit)
    snapshot.star['vel'] = SimArray([[ 0.,  0.,  0.]], v_unit)
    snapshot.star['mass'] = m_star
    snapshot.star['metals'] = SimArray(star_metals)
    # Estimate the star's softening length as the closest particle distance
    #snapshot.star['eps'] = r.min()
    
    # Make param file
    param = make_param(snapshot, snapshotName)
    param['dMeanMolWeight'] = m
       
    gc.collect()
    
    # CALCULATE VELOCITY USING calc_velocity.py.  This also estimates the 
    # gravitational softening length eps
    print 'Calculating circular velocity'
    preset = settings.changa_run.preset
    max_particles = global_settings['misc']['max_particles']
    calc_velocity.v_xy(snapshot, param, changa_preset=preset, max_particles=max_particles)
    
    gc.collect()
  
	# -------------------------------------------------
    # Estimate time step for changa to use
    # -------------------------------------------------
    # Save param file
    configsave(param, paramName, 'param')
    # Save snapshot
    snapshot.write(filename=snapshotName, fmt=pynbody.tipsy.TipsySnap)
    # est dDelta
    dDelta = ICgen_utils.est_time_step(paramName, preset)
    param['dDelta'] = dDelta
 
	# -------------------------------------------------
    # Create director file
    # -------------------------------------------------
    # largest radius to plot
    r_director = float(0.9 * r.max())
    # Maximum surface density
    sigma_min = float(ICobj.sigma(r_director))
    # surface density at largest radius
    sigma_max = float(ICobj.sigma.input_dict['sigma'].max())
    # Create director dict
    director = make_director(sigma_min, sigma_max, r_director, filename=param['achOutName'])
    ## Save .director file
    #configsave(director, directorName, 'director')

    #Now that velocities and everything are all initialized for gas particles, create new snapshot to return in which
    #single star particle is replaced by 2, same units as above
    snapshotBinary = pynbody.new(star=2,gas=nParticles)
    snapshotBinary['eps'] = 0.01*SimArray(np.ones(nParticles+2, dtype=np.float32), pos_unit)
    snapshotBinary['metals'] = SimArray(np.zeros(nParticles+2, dtype=np.float32))
    snapshotBinary['vel'].units = v_unit
    snapshotBinary['pos'].units = pos_unit
    snapshotBinary['mass'].units = snapshot['mass'].units
    snapshotBinary['rho'] = SimArray(np.zeros(nParticles+2, dtype=np.float32))

    #Assign gas particles with calculated/given values from above
    snapshotBinary.gas['pos'] = snapshot.gas['pos']
    snapshotBinary.gas['vel'] = snapshot.gas['vel']
    snapshotBinary.gas['temp'] = snapshot.gas['temp']
    snapshotBinary.gas['rho'] = snapshot.gas['rho']
    snapshotBinary.gas['eps'] = snapshot.gas['eps']
    snapshotBinary.gas['mass'] = snapshot.gas['mass']
    snapshotBinary.gas['metals'] = snapshot.gas['metals']

    #Load Binary system obj to initialize system
    binsys = ICobj.settings.physical.binsys
    
    x1,x2,v1,v2 = binsys.generateICs()

    #Put velocity in sim units
    #!!! Note: v_unit_vel will always be 29.785598165 km/s when m_unit = Msol and r_unit = 1 AU in kpc!!!
    #conv = v_unit_vel #km/s in sim units
    #v1 /= conv
    #v2 /= conv

    #Assign position, velocity assuming CCW orbit

    snapshotBinary.star[0]['pos'] = SimArray(x1,pos_unit)
    snapshotBinary.star[0]['vel'] = SimArray(v1,v_unit)
    snapshotBinary.star[1]['pos'] = SimArray(x2,pos_unit)
    snapshotBinary.star[1]['vel'] = SimArray(v2,v_unit)

    #Set stellar masses
    #Set Mass units
    #Create simArray for mass, convert units to simulation mass units
    priMass = SimArray(binsys.m1,m_unit)
    secMass = SimArray(binsys.m2,m_unit)

    snapshotBinary.star[0]['mass'] = priMass
    snapshotBinary.star[1]['mass'] = secMass
    snapshotBinary.star['metals'] = SimArray(star_metals)

    #Estimate stars' softening length as fraction of distance to COM
    d = np.sqrt(AddBinary.dotProduct(x1-x2,x1-x2))

    snapshotBinary.star[0]['eps'] = SimArray(math.fabs(d)/4.0,pos_unit)
    snapshotBinary.star[1]['eps'] = SimArray(math.fabs(d)/4.0,pos_unit)
 
    print 'Wrapping up'
    # Now set the star particle's tform to a negative number.  This allows
    # UW ChaNGa treat it as a sink particle.
    snapshotBinary.star['tform'] = -1.0
    
    #Set Sink Radius to be mass-weighted average of Roche lobes of two stars
    r1 = AddBinary.calcRocheLobe(binsys.m1/binsys.m2,binsys.a) 
    r2 = AddBinary.calcRocheLobe(binsys.m2/binsys.m1,binsys.a)
    p = strip_units(binsys.m1/(binsys.m1 + binsys.m2))

    r_sink = (r1*p) + (r2*(1.0-p))
    param['dSinkBoundOrbitRadius'] = r_sink
    param['dSinkRadius'] = r_sink
    param['dSinkMassMin'] = 0.9 * strip_units(secMass)
    param['bDoSinks'] = 1
    
    return snapshotBinary, param, director
    
        
예제 #21
0
def snapshot_gen(ICobj):
    """
    Generates a tipsy snapshot from the initial conditions object ICobj.
    
    Returns snapshot, param
    
        snapshot: tipsy snapshot
        param: dictionary containing info for a .param file
    Note: Code has been edited (dflemin3) such that now it returns a snapshot for a circumbinary disk
    where initial conditions generated assuming star at origin of mass M.  After gas initialized, replaced
    star at origin with binary system who's center of mass lies at the origin and who's mass m1 +m2 = M
    """
    
    print 'Generating snapshot...'
    # Constants
    G = SimArray(1.0,'G')
    # ------------------------------------
    # Load in things from ICobj
    # ------------------------------------
    print 'Accessing data from ICs'
    settings = ICobj.settings
    
    # snapshot file name
    snapshotName = settings.filenames.snapshotName
    paramName = settings.filenames.paramName   
 
    # particle positions
    r = ICobj.pos.r
    xyz = ICobj.pos.xyz
    
    # Number of particles
    nParticles = ICobj.pos.nParticles
    
    # molecular mass
    m = settings.physical.m
    
    # star mass
    m_star = settings.physical.M.copy()
    
    # disk mass
    m_disk = ICobj.sigma.m_disk.copy()
    m_disk = match_units(m_disk, m_star)[0]
    
    # mass of the gas particles
    m_particles = m_disk / float(nParticles)
    
    # re-scale the particles (allows making of low-mass disk)
    m_particles *= settings.snapshot.mScale
    
    # -------------------------------------------------
    # Assign output
    # -------------------------------------------------
    print 'Assigning data to snapshot'
    # Get units all set up
    m_unit = m_star.units
    pos_unit = r.units
    
    if xyz.units != r.units:
        
        xyz.convert_units(pos_unit)
        
    # time units are sqrt(L^3/GM)
    t_unit = np.sqrt((pos_unit**3)*np.power((G*m_unit), -1)).units
    # velocity units are L/t
    v_unit = (pos_unit/t_unit).ratio('km s**-1')
    # Make it a unit, save value for future conversion
    v_unit_vel = v_unit
    #Ensure v_unit_vel is the same as what I assume it is.
    assert(np.fabs(AddBinary.VEL_UNIT-v_unit_vel)<AddBinary.SMALL),"VEL_UNIT not equal to ChaNGa unit! Why??"			
	
    v_unit = pynbody.units.Unit('{0} km s**-1'.format(v_unit))
    
    # Other settings
    metals = settings.snapshot.metals
    star_metals = metals
    
    # Generate snapshot
    # Note that empty pos, vel, and mass arrays are created in the snapshot
    snapshot = pynbody.new(star=1,gas=nParticles)
    snapshot['vel'].units = v_unit
    snapshot['eps'] = 0.01*SimArray(np.ones(nParticles+1, dtype=np.float32), pos_unit)
    snapshot['metals'] = SimArray(np.zeros(nParticles+1, dtype=np.float32))
    snapshot['rho'] = SimArray(np.zeros(nParticles+1, dtype=np.float32))
    
    snapshot.gas['pos'] = xyz
    snapshot.gas['temp'] = ICobj.T(r)
    snapshot.gas['mass'] = m_particles
    snapshot.gas['metals'] = metals
    
    snapshot.star['pos'] = SimArray([[ 0.,  0.,  0.]],pos_unit)
    snapshot.star['vel'] = SimArray([[ 0.,  0.,  0.]], v_unit)
    snapshot.star['mass'] = m_star
    snapshot.star['metals'] = SimArray(star_metals)
    # Estimate the star's softening length as the closest particle distance
    #snapshot.star['eps'] = r.min()
    
    # Make param file
    param = make_param(snapshot, snapshotName)
    param['dMeanMolWeight'] = m
       
    gc.collect()
    
    # CALCULATE VELOCITY USING calc_velocity.py.  This also estimates the 
    # gravitational softening length eps
    print 'Calculating circular velocity'
    preset = settings.changa_run.preset
    max_particles = global_settings['misc']['max_particles']
    calc_velocity.v_xy(snapshot, param, changa_preset=preset, max_particles=max_particles)
    
    gc.collect()
  
	# -------------------------------------------------
    # Estimate time step for changa to use
    # -------------------------------------------------
    # Save param file
    configsave(param, paramName, 'param')
    # Save snapshot
    snapshot.write(filename=snapshotName, fmt=pynbody.tipsy.TipsySnap)
    # est dDelta
    dDelta = ICgen_utils.est_time_step(paramName, preset)
    param['dDelta'] = dDelta
 
	# -------------------------------------------------
    # Create director file
    # -------------------------------------------------
    # largest radius to plot
    r_director = float(0.9 * r.max())
    # Maximum surface density
    sigma_min = float(ICobj.sigma(r_director))
    # surface density at largest radius
    sigma_max = float(ICobj.sigma.input_dict['sigma'].max())
    # Create director dict
    director = make_director(sigma_min, sigma_max, r_director, filename=param['achOutName'])
    ## Save .director file
    #configsave(director, directorName, 'director')

    #Now that velocities and everything are all initialized for gas particles, create new snapshot to return in which
    #single star particle is replaced by 2, same units as above
    snapshotBinary = pynbody.new(star=2,gas=nParticles)
    snapshotBinary['eps'] = 0.01*SimArray(np.ones(nParticles+2, dtype=np.float32), pos_unit)
    snapshotBinary['metals'] = SimArray(np.zeros(nParticles+2, dtype=np.float32))
    snapshotBinary['vel'].units = v_unit
    snapshotBinary['pos'].units = pos_unit
    snapshotBinary['mass'].units = snapshot['mass'].units
    snapshotBinary['rho'] = SimArray(np.zeros(nParticles+2, dtype=np.float32))

    #Assign gas particles with calculated/given values from above
    snapshotBinary.gas['pos'] = snapshot.gas['pos']
    snapshotBinary.gas['vel'] = snapshot.gas['vel']
    snapshotBinary.gas['temp'] = snapshot.gas['temp']
    snapshotBinary.gas['rho'] = snapshot.gas['rho']
    snapshotBinary.gas['eps'] = snapshot.gas['eps']
    snapshotBinary.gas['mass'] = snapshot.gas['mass']
    snapshotBinary.gas['metals'] = snapshot.gas['metals']

    #Load Binary system obj to initialize system
    binsys = ICobj.settings.physical.binsys
    
    x1,x2,v1,v2 = binsys.generateICs()

    #Put velocity in sim units
    #!!! Note: v_unit_vel will always be 29.785598165 km/s when m_unit = Msol and r_unit = 1 AU in kpc!!!
    #conv = v_unit_vel #km/s in sim units
    #v1 /= conv
    #v2 /= conv

    #Assign position, velocity assuming CCW orbit

    snapshotBinary.star[0]['pos'] = SimArray(x1,pos_unit)
    snapshotBinary.star[0]['vel'] = SimArray(v1,v_unit)
    snapshotBinary.star[1]['pos'] = SimArray(x2,pos_unit)
    snapshotBinary.star[1]['vel'] = SimArray(v2,v_unit)

    #Set stellar masses
    #Set Mass units
    #Create simArray for mass, convert units to simulation mass units
    priMass = SimArray(binsys.m1,m_unit)
    secMass = SimArray(binsys.m2,m_unit)

    snapshotBinary.star[0]['mass'] = priMass
    snapshotBinary.star[1]['mass'] = secMass
    snapshotBinary.star['metals'] = SimArray(star_metals)

    #Estimate stars' softening length as fraction of distance to COM
    d = np.sqrt(AddBinary.dotProduct(x1-x2,x1-x2))

    snapshotBinary.star[0]['eps'] = SimArray(math.fabs(d)/4.0,pos_unit)
    snapshotBinary.star[1]['eps'] = SimArray(math.fabs(d)/4.0,pos_unit)
 
    print 'Wrapping up'
    # Now set the star particle's tform to a negative number.  This allows
    # UW ChaNGa treat it as a sink particle.
    snapshotBinary.star['tform'] = -1.0
    
    #Set Sink Radius to be mass-weighted average of Roche lobes of two stars
    r1 = AddBinary.calcRocheLobe(binsys.m1/binsys.m2,binsys.a) 
    r2 = AddBinary.calcRocheLobe(binsys.m2/binsys.m1,binsys.a)
    p = strip_units(binsys.m1/(binsys.m1 + binsys.m2))

    r_sink = (r1*p) + (r2*(1.0-p))
    param['dSinkBoundOrbitRadius'] = r_sink
    param['dSinkRadius'] = r_sink
    param['dSinkMassMin'] = 0.9 * strip_units(secMass)
    param['bDoSinks'] = 1
    
    return snapshotBinary, param, director
예제 #22
0
def calc_LB_resonance(s,m_min=1,m_max=3,l_min=1,l_max=3):
    """
    Computes the locations of various Lindblad Resonances in the disk as a 
    function of binary pattern speed.
    
     Parameters
     ----------
     s : Tipsy-format snapshot
     m_min, l_min : ints
         minimum orders of (m,l) LR
     m_max,l_max : ints
         maximum orders of (m,l) LR

    Returns
    -------
    OLR, ILR, CR: numpy arrays
        location in AU of (m,l)th order Lindblad resonances
    """

    #Compute binary angular frequency in 1/day
    x1 = s.stars[0]['pos']
    x2 = s.stars[1]['pos']
    v1 = s.stars[0]['vel']
    v2 = s.stars[1]['vel']
    m1 = s.stars[0]['mass']
    m2 = s.stars[1]['mass']
    omega_b = 2.0*np.pi/AddBinary.aToP(AddBinary.calcSemi(x1,x2,v1,v2,m1,m2),m1+m2)
    guess = 0.05 #fsolve initial guess parameter

    #Allocate space for arrays
    OLR = np.zeros((m_max,l_max))
    ILR = np.zeros((m_max,l_max))
    CR = np.zeros(l_max)

    #Define resonance functions
    def OLR_func(omega_d, *args):
        m = args[0]
        l = args[1]
        omega_b = args[2]
        
        return omega_d*(1.0 + float(l)/m) - omega_b
        
    #end function        
        
    def ILR_func(omega_d, *args):
        m = args[0]
        l = args[1]
        omega_b = args[2]
        
        return omega_d*(1.0 - float(l)/m) - omega_b        
        
    #end function

    def CR_func(omega_d, *args):
        l = args[0]
        omega_b = args[1]
        
        return omega_d - omega_b/float(l)

    #end function

    for m in range(m_min,m_max+1):
        for l in range(l_min,l_max+1):
            OLR[m-m_min,l-l_min] = fsolve(OLR_func,guess,args=(m,l,omega_b)) 
            ILR[m-m_min,l-l_min] = fsolve(ILR_func,guess,args=(m,l,omega_b))
            CR[l-l_min] = fsolve(CR_func,guess,args=(l,omega_b))
            
    #Convert from 1/day -> au
    OLR = AddBinary.pToA(2.0*np.pi/OLR,m1+m2)
    ILR = AddBinary.pToA(2.0*np.pi/ILR,m1+m2)
    CR = AddBinary.pToA(2.0*np.pi/CR,m1+m2)        
    
    return OLR, ILR, CR
예제 #23
0
def make_binary(IC, snapshot):
    """
    Turns a snapshot for a single star into a snapshot of a binary system
    
    Parameters
    ----------
    IC : IC object
    snapshot : SimSnap
        Single star system to turn into a binary
    
    Returns
    -------
    snapshotBinary : SimSnap
        A binary version of the simulation snapshot
    """
    # Initialize snapshot
    snapshotBinary = pynbody.new(star=2, gas=len(snapshot.g))
    # Copy gas particles over
    for key in snapshot.gas.keys():
        
        snapshotBinary.gas[key] = snapshot.gas[key]
        
    # Load Binary system obj to initialize system
    starMode = IC.settings.physical.starMode.lower()
    binsys = IC.settings.physical.binsys
    
    if starMode == 'stype':
        
        # Treate the primary as a star of mass mStar + mDisk
        m_disk = strip_units(np.sum(snapshotBinary.gas['mass']))
        binsys.m1 += m_disk
        binsys.computeCartesian()
        
    x1,x2,v1,v2 = binsys.generateICs()
    
    #Assign star parameters assuming CCW orbit
    snapshotBinary.star[0]['pos'] = x1
    snapshotBinary.star[0]['vel'] = v1
    snapshotBinary.star[1]['pos'] = x2
    snapshotBinary.star[1]['vel'] = v2
    
    #Set stellar masses
    priMass = binsys.m1
    secMass = binsys.m2    
    snapshotBinary.star[0]['mass'] = priMass
    snapshotBinary.star[1]['mass'] = secMass    
    snapshotBinary.star['metals'] = snapshot.s['metals']
    
    if starMode == 'stype':
        # We have the binary positions about their center of mass, (0,0,0), so 
        # shift the position, velocity of the gas disk to be around the primary.
        snapshotBinary.gas['pos'] += snapshotBinary.star[0]['pos']
        snapshotBinary.gas['vel'] += snapshotBinary.star[0]['vel']  
        # Remove disk mass from the effective star mass
        snapshotBinary[0]['mass'] -= m_disk
        binsys.m1 -= m_disk
        # Star smoothing
        snapshotBinary.star['eps'] = snapshot.star['eps']

        
    elif starMode == 'binary':
        
        # Estimate stars' softening length as fraction of distance to COM
        d = np.sqrt(AddBinary.dotProduct(x1-x2,x1-x2))
        pos_unit = snapshotBinary['pos'].units
        snapshotBinary.star['eps'] = SimArray(abs(d)/4.0,pos_unit)
        
    return snapshotBinary
예제 #24
0
def findCBResonances(s, r, r_min, r_max, m_max=4, l_max=4, bins=50):
    """
    Given Tipsy snapshot, computes the resonances of disk on binary as a function of orbital angular frequency omega.
    Disk radius, in au, is convered to angular frequency which will then be used to compute corotation 
    and inner/outer Lindblad resonances.
   
   Note: r given MUST correspond to r over which de/dt was calculated.  Otherwise, scale gets all messed up
 
     Parameters
     ----------
     s: Tipsy-format snapshot
     r: array
         radius array over which de/dt was calculated
     r_min,r_max: floats
         min/maximum disk radius for calculations (au)
     bins: int
         number of radial bins to calculate over
     m_max,l_max: ints
         maximum orders of (m,l) LR

    Returns
    -------
    Orbital frequency: numpy array
        for corotation and inner/outer resonances and radii as float and numpy arrays
    """
    stars = s.stars

    m_min = 1  #m >=1 for LRs, CRs
    l_min = 1  #l >=1 for LRs, CRs

    #Compute binary angular frequency
    #Strip units from all inputs
    #x1 = np.asarray(isaac.strip_units(stars[0]['pos']))
    #x2 = np.asarray(isaac.strip_units(stars[1]['pos']))
    #v1 = np.asarray(isaac.strip_units(stars[0]['vel']))
    #v2 = np.asarray(isaac.strip_units(stars[1]['vel']))
    #m1 = np.asarray(isaac.strip_units(stars[0]['mass']))
    #m2 = np.asarray(isaac.strip_units(stars[1]['mass']))
    x1 = stars[0]['pos']
    x2 = stars[1]['pos']
    v1 = stars[0]['vel']
    v2 = stars[1]['vel']
    m1 = stars[0]['mass']
    m2 = stars[1]['mass']

    a = isaac.strip_units(AddBinary.calcSemi(x1, x2, v1, v2, m1, m2))
    omega_b = 2.0 * np.pi / AddBinary.aToP(a, m1 + m2)  #In units 1/day

    #Compute omega_disk in units 1/day (like omega_binary)
    omega_d = 2.0 * np.pi / AddBinary.aToP(r, m1 + m2)

    #Compute kappa (radial epicycle frequency = sqrt(r * d(omega^2)/dr + 4*(omega^2))
    o2 = omega_d * omega_d
    dr = (r.max() - r.min()) / float(bins)  #Assuming r has evenly spaced bins!
    drdo2 = np.gradient(o2, dr)  #I mean d/dr(omega^2)
    kappa = np.sqrt(r * drdo2 + 4.0 * o2)

    #Allocate arrays for output
    omega_Lo = np.zeros((m_max, l_max))
    omega_Li = np.zeros((m_max, l_max))
    o_c = np.zeros(l_max)

    #Find resonance angular frequency
    for m in range(m_min, m_max + 1):
        for l in range(l_min, l_max + 1):
            outer = omega_d + (float(l) / m) * kappa
            inner = omega_d - (float(l) / m) * kappa
            omega_Lo[m - m_min,
                     l - l_min] = omega_d[np.argmin(np.fabs(omega_b - outer))]
            omega_Li[m - m_min,
                     l - l_min] = omega_d[np.argmin(np.fabs(omega_b - inner))]

            #Find corotation resonance where omega_d ~ omega_b
            o_c[l - l_min] = omega_d[np.argmin(
                np.fabs(omega_d - omega_b / float(l)))]

    return omega_Li, omega_Lo, o_c, omega_d, kappa