Advertisement
Guest User

Energy Calculations

a guest
Jun 30th, 2015
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.47 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from pylab import *
  4. import os
  5.  
  6. H_0 = 70
  7. h = 0.7
  8. path = 'testhalos/'
  9.  
  10. #KINEMATIC FUNCTIONS
  11. #returns the relative velocity, taking into account hubble expansion
  12. def relative_velocity(xnew,ynew,znew,x,y,z,vx,vy,vz,system):
  13.    vexpx = vx[system] + H_0 * (x[system]-xnew)
  14.    vexpy = vy[system] + H_0 * (y[system]-ynew)
  15.    vexpz = vz[system] + H_0 * (z[system]-znew)
  16.    vrel = ((vexpx - vx[0])**2 + (vexpy - vy[0])**2 + (vexpz - vz[0])**2)**.5
  17.    
  18.    return vrel
  19.  
  20. #defines center of mass of system and returns components for new origin
  21. def center_of_mass(rad,x,y,z,mass,system):
  22.    totmass = np.sum(mass[0:system])
  23.    compr = rad[0:system] * mass[0:system]
  24.    compx = x[0:system] * mass[0:system]
  25.    compy = y[0:system] * mass[0:system]
  26.    compz = z[0:system] * mass[0:system]
  27.    radnew = sum(compr) / totmass
  28.    xnew = sum(compx) / totmass
  29.    ynew = sum(compy) / totmass
  30.    znew = sum(compz) / totmass
  31.  
  32.      
  33.    return radnew, xnew, ynew, znew
  34.  
  35. #scales the mass for the radial velocity figure
  36. def scale_mass(mass, system):
  37.    maximum = np.log10(np.amax(mass))
  38.    minimum = np.log10(np.amin(mass))
  39.    ranges = maximum - minimum
  40.    boundmass = 50**((np.log10(mass[:system]) - minimum) / ranges + 1)
  41.    unboundmass = 50**((np.log10(mass[system:]) - minimum) / ranges + 1)
  42.  
  43.    #print "These are the bound masses:", boundmass
  44.    return boundmass, unboundmass
  45.  
  46.  
  47. #defines radial velocity
  48. def radial_velocity(x,y,z,vx,vy,vz,system):
  49.    vxpol = vx + H_0 * (x - x[0])
  50.    vypol = vy + H_0 * (y - y[0])
  51.    vzpol = vz + H_0 * (z - z[0])
  52.    numerator = vxpol*(x-x[0]) + vypol*(y-y[0]) + vzpol*(z-z[0])
  53.    denominator = ((x-x[0])**2 + (y-y[0])**2 + (z-z[0])**2)**.5
  54.  
  55.    vradial = np.zeros(numerator.shape[0])
  56.    vradial[1:] = numerator[1:]/denominator[1:]
  57.  
  58.    return vradial
  59.  
  60. ########################BEGINNING OF ANALYSIS##############################
  61.  
  62. def plot_velocities(halos, halofile, system):
  63.    h = 0.7
  64.    listno = halos[0,:]
  65.    rad = halos[1,:] / h
  66.    mass = halos[2,:]
  67.    x = halos[3,:] / h
  68.    y = halos[4,:] / h
  69.    z = halos[5,:] / h
  70.    vx = halos[6,:]
  71.    vy = halos[7,:]
  72.    vz = halos[8,:]
  73.  
  74.    #print "What does system equal?:", system
  75.    vrad = radial_velocity(x, y, z, vx, vy, vz, system)
  76.  
  77.    fig = plt.figure()
  78.    ax1 = fig.add_subplot(111)
  79.    xax = np.linspace(0, rad[system+200], 100)
  80.    yax = 70 * xax
  81.    ax1.plot(xax, yax, color = 'c', linewidth = 2)
  82.  
  83.    bmass, ubmass = scale_mass(mass, system)
  84.  
  85.    target = ax1.scatter(0, vrad[0], s = bmass[0], c = 'black', alpha = 0.7)
  86.    bound = ax1.scatter(rad[1:system], vrad[1:system], s = bmass[1:], c = 'green', alpha = 0.7)
  87.    unbound = ax1.scatter(rad[system:system+200], vrad[system:system+200], s = ubmass[0:200], c = 'red', alpha = 0.7)
  88.    for i in range(0,system+200):
  89.       ax1.annotate('%d'%listno[i], xy = (rad[i], vrad[i]), xytext = (rad[i], vrad[i]), fontweight = 'bold')
  90.  
  91.    plt.xlim(xmin = 0)
  92.    ax = plt.axes()
  93.    ax.xaxis.grid()
  94.    ax.yaxis.grid()
  95.    ax1.set_xlabel('radius [Mpc]')
  96.    ax1.set_ylabel('velocity [km/s]')
  97.    plt.legend((target, bound, unbound), ('Target Halo', 'Bound Halos', 'Unbound Halos'), scatterpoints = 1, loc = 'upper left', labelspacing = 1)
  98.    massy = np.array_str(mass[0])
  99.    plt.title('Target Halo Mass = ' + massy + " M_sun")
  100. ######################need to change to given directory!
  101.    plt.savefig(path+halofile+'velocity.png')
  102.    #plt.show()
  103.    plt.close()
  104.    #print "Plotting done!"
  105.  
  106.  
  107. #Plots T/V vs. radius until the point where the system becomes unbound
  108. def plot_energy_ratio(Kinetic, Potential, halos, halofile):
  109.    rad = halos[1,:] / h
  110.    T = np.array(Kinetic)
  111.    V = np.array(Potential)
  112.    #print "Kinetic", T
  113.    #print "Potential", V
  114.    ratio = T / V
  115.    
  116.    plt.clf()
  117.    ratioo, = plt.plot(rad[0:ratio.shape[0]], np.abs(ratio), 'darkmagenta')
  118.    plt.xlabel('r [Mpc]')
  119.    plt.ylabel('T/V')
  120.    plt.legend([ratioo],["T/V"], loc='best')
  121.    plt.grid()
  122.    massy = np.array_str(halos[2,0])
  123.    plt.title('Target Halo Mass = ' + massy + " M_sun")
  124.    plt.savefig(path+halofile+'ratio.png')
  125.    #plt.show()
  126.  
  127.  
  128. #############################MAIN FUNCTION##################################
  129. #Produces energy output of every cluster step until the system is unbound
  130. def calculate_energy(halos, halofile):
  131.    h= 0.7
  132.    rad = halos[1,:]/h     #Mpc
  133.    mass = halos[2,:]    #M_sun
  134.    x = halos[3,:] / h   #Mpc
  135.    y = halos[4,:] / h   #Mpc
  136.    z = halos[5,:] / h   #Mpc
  137.    vx = halos[6,:]      #km/s
  138.    vy = halos[7,:]      #km/s
  139.    vz = halos[8,:]      #km/s
  140.    G = 4.302 * 10**-9  #Mpc M_s^-1 (km/s)^2
  141.    H_0 = 70
  142.    Potential = []
  143.    Kinetic = []
  144.    Energy = []
  145.    E = 0
  146.    system = 1
  147.  
  148.    #Calculates the energy in the system starting with the closest halo
  149.    #to the target halo. If the value is negative, an additional
  150.    #closest halo is added into the calculation. This repeats until
  151.    #the energy values go positive.
  152.    while (E <= 0):
  153.       system += 1
  154.       rnew, xnew, ynew, znew = center_of_mass(rad,x,y,z,mass,system)
  155.       KE = 0
  156.       PE = 0
  157.        
  158.       for i in range(0, system):
  159.          #Kinetic Energy Calculation
  160.          targmass = mass[i]
  161.          vrel = relative_velocity(xnew,ynew,znew,x,y,z,vx,vy,vz,i)
  162.          KE += .5 * targmass * vrel**2
  163.          "KE:", KE
  164.          #print "targmass:", targmass
  165.          #print "vrel:", vrel
  166.  
  167.          #Potential Energy Calculation
  168.          PE_comp = G * mass[i] * mass[0:i] / np.absolute((rad[i] - rad[0:i]))
  169.          #print "Sums of PE", PE_comp
  170.          PE -= np.sum(PE_comp)
  171.          #print "PE:", PE
  172.    
  173.       E = KE + PE
  174.       print "Potential: ", PE
  175.       print "Kinetic: ", KE
  176.       print "Total Energy: ", E
  177.       print "System: ", system
  178.       print ""
  179.    
  180.       Kinetic.append(KE)
  181.       Potential.append(PE)
  182.       Energy.append(E)
  183.      
  184.       #If system includes over a certain amount of halos, target is trashed      
  185.       if (system > 200):
  186.          print "All halos bound"
  187.          return -1, -1, -1, -1
  188.  
  189.    #print "system: ", system
  190.    number = system
  191.  
  192.    #Plots the velocity distribution and the |T/V| energy ratio as a function
  193.    #of radius
  194.    plot_velocities(halos, halofile, system)
  195.    plot_energy_ratio(Kinetic, Potential, halos, halofile)
  196.    value = rad[number]
  197.    totmass = np.sum(mass[0:number+1])
  198.    print totmass
  199.    halomass = mass[0]
  200.  
  201.    return number, value, halomass, totmass
  202.  
  203. #######################################################################
  204.  
  205.  
  206. files = []
  207.  
  208. for root, dirnames, filenames in os.walk(path):
  209.    for file in filenames:
  210.       files.append(file)
  211.  
  212. print files
  213.  
  214. halofiles = [x for x in files if '.npy' in x]
  215. trial = 0
  216.  
  217. #print halofiles
  218. haloabundance = []
  219. boundradius = []
  220. halomass = []
  221. totalmass = []
  222.  
  223. ############all halos in directory
  224. for halofile in halofiles:
  225.    if '.png' in halofile:
  226.       continue
  227.    trial += 1
  228.    print "##########################################################"
  229.    print "file #:", trial
  230.    print "##########################################################"
  231.    halos = np.load(path+halofile)
  232.    number, radius, hmass, totmass = calculate_energy(halos, halofile)
  233.    if number == -1:
  234.       continue
  235.    halomass.append(hmass)
  236.    haloabundance.append(number)
  237.    boundradius.append(radius)
  238.    totalmass.append(totmass)
  239.  
  240. statistics = np.array([halomass,haloabundance,boundradius, totalmass])
  241. np.save("halostatistics.npy", statistics)
  242.  
  243. #############single halo
  244. #user = raw_input("choose halo\n")
  245. #halos = np.load(path+user)
  246. #calculate_energy(halos, user)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement