def sum_vorticity(args):
    i, frame = args

    # Get Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density_zero
    vrad = np.array(fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = np.array(fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    # Get Background Data
    vtheta_keplerian = np.array(fromfile("gasvtheta0.dat").reshape(num_rad, num_theta))

    # Subtract off Keplerian velocity (and rotate back into non-rotating frame???)
    vtheta -= (vtheta_keplerian)
    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = 0)

    #vorticity = np.abs(vorticity) # should be all negative

    # Add up vorticity
    dr = rad[1] - rad[0] # assumes arithmetic grid
    d_phi = theta[1] - theta[0]

    radial_vorticity = np.average(vorticity, axis = 1)
    total_vorticity = np.sum((dr * d_phi) * rad[:-1, None] * radial_vorticity)
    
    # Print Update
    print "%d: %.4f" % (frame, total_vorticity)

    # Store Data
    vorticity_over_time[i] = total_vorticity
def get_data(frame_i, frame, modes = default_modes):
    """ frame_i is ith frame, frame is frame number """

    # Load Data Files
    normalized_density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(normalized_density, axis = 1)

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = ref_frame)
    vortensity = vorticity / normalized_density[1:, 1:]

    # Find Peak in Radial Profile (in Outer Disk)
    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 1.0 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = np.array([np.fft.fft(vortensity[azimuthal_index, :]) for azimuthal_index in azimuthal_indices])

    # Normalize by m = 0 mode (integral of density), Take Absolute Value
    azimuthal_profiles = np.array([np.abs(azimuthal_profile / azimuthal_profile[0]) for azimuthal_profile in azimuthal_profiles])

    for m, mode in enumerate(modes):
        modes_over_time[m, frame_i] = np.max(azimuthal_profiles[:, mode])

    print "%d: %.4f, %.4f, %.4f, %.4f, %.4f" % (frame, np.max(azimuthal_profiles[:, 1]), np.max(azimuthal_profiles[:, 2]), np.max(azimuthal_profiles[:, 3]), np.max(azimuthal_profiles[:, 4]), np.max(azimuthal_profiles[:, 5]))
示例#3
0
def find_extrema(args):
    # Unwrap Args
    i, frame = args

    # Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = ref_frame)
    vortensity = vorticity / density[1:, 1:]

    # Find Peak in Radial Profile (in Outer Disk)
    peak_rad, peak_rad_index, peak_density = find_radial_peak(averagedDensity)

    # Find Peaks in Azimuthal Profiles (and center around that peak)
    density_peak_theta, density_theta_index, max_density = find_azimuthal_extrema(density[peak_rad_index], maximum = True) # Max
    vortensity_peak_theta, vortensity_peak_theta_index, min_vortensity = find_azimuthal_extrema(vortensity[peak_rad_index], maximum = False) # Min

    print "%d, %.2f, %.3f" % (frame, max_density, min_vortensity)

    #return max_density, min_vortensity
    maximum_densities[i] = max_density
    minimum_vortensities[i] = min_vortensity
示例#4
0
def get_data(frame):
    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density
    dust_density = (fromfile("gasddens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density

    averagedDensity = np.average(density, axis=1)
    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 2.0 * scale_height  # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread,
                                  num_profiles)
    azimuthal_indices = [
        np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii
    ]
    azimuthal_profiles = [
        density[azimuthal_index, :] for azimuthal_index in azimuthal_indices
    ]

    dust_azimuthal_profiles = [
        dust_density[azimuthal_index, :]
        for azimuthal_index in azimuthal_indices
    ]

    return azimuthal_radii, azimuthal_profiles, dust_azimuthal_profiles
def get_data(frame):
    # Load Data Files
    normalized_density = (fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density
    averagedDensity = np.average(normalized_density, axis=1)

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame=ref_frame)
    vortensity = vorticity / normalized_density[1:, 1:]

    # Find Peak in Radial Profile (in Outer Disk)

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 2.0 * scale_height  # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread,
                                  num_profiles)
    azimuthal_indices = [
        np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii
    ]
    azimuthal_profiles = [
        vortensity[azimuthal_index, :] for azimuthal_index in azimuthal_indices
    ]

    return azimuthal_radii, azimuthal_profiles
def get_data(frame):
    # Load Data Files
    normalized_density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(normalized_density, axis = 1)

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = ref_frame)
    vortensity = vorticity / normalized_density[1:, 1:]

    # Find Peak in Radial Profile (in Outer Disk)

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 2.0 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = [vortensity[azimuthal_index, :] for azimuthal_index in azimuthal_indices]

    return azimuthal_radii, azimuthal_profiles
def get_min(args_here):
    # Unwrap Args
    i, frame, directory = args_here

    # Get Data
    density = fromfile("../%s/gasdens%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta)
    averagedDensity = np.average(density, axis=1)
    normalized_density = averagedDensity / surface_density_zero

    vrad = (fromfile("../%s/gasvy%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta))  # add a read_vrad to util.py!
    vtheta = (fromfile("../%s/gasvx%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta))  # add a read_vrad to util.py!
    vorticity = utilVorticity.velocity_curl(vrad,
                                            vtheta,
                                            rad,
                                            theta,
                                            rossby=rossby,
                                            residual=residual)

    averaged_vorticity = np.average(vorticity, axis=1)

    # Get Minima
    min_density = find_rossby_density(normalized_density, averaged_vorticity)

    # Print Update
    print "%d: %.3f, %.3f" % (frame, min_density, 1.0 / min_density)

    # Store Data
    gap_depth_over_time[i] = 1.0 / min_density
示例#8
0
def get_velocity(args_here):
    # Unwrap Args
    i, frame = args_here

    # Data
    if mpi:
      density = Fields("./", 'gas', frame).get_field("dens").reshape(num_z, num_rad, num_theta)
      vz = Fields("./", 'gas', frame).get_field("vz").reshape(num_z, num_rad, num_theta)
      vrad = Fields("./", 'gas', frame).get_field("vy").reshape(num_z, num_rad, num_theta)
      vtheta = Fields("./", 'gas', frame).get_field("vx").reshape(num_z, num_rad, num_theta)
    else:
      density = fromfile("gasdens%d.dat" % frame).reshape(num_z, num_rad, num_theta)
      vz = (fromfile("gasvz%d.dat" % frame).reshape(num_z, num_rad, num_theta)) # add a read_vrad to util.py!
      vrad = (fromfile("gasvy%d.dat" % frame).reshape(num_z, num_rad, num_theta)) # add a read_vrad to util.py!
      vtheta = (fromfile("gasvx%d.dat" % frame).reshape(num_z, num_rad, num_theta)) # add a read_vrad to util.py!
    midplane_density = density[num_z / 2 + args.sliver, :, :]
    midplane_vrad = vrad[num_z / 2 + args.sliver, :, :]
    midplane_vtheta = vtheta[num_z / 2 + args.sliver, :, :]
    midplane_vz = vz[num_z / 2 + args.sliver, :, :]

    dz = z_angles[1] - z_angles[0]
    surface_density = np.sum(density[:, :, :], axis = 0) * dz
    averagedDensity = np.average(surface_density, axis = -1)

    average_midplane_vz = np.average(np.abs(midplane_vz), axis = -1)
    composite_vz[i, :] = average_midplane_vz

    peak, _ = az.get_radial_peak(averagedDensity, fargo_par)
    composite_peak[i] = peak
示例#9
0
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Axis
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            plot.ylim(0, 1.2)
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]) - 0.05, float(fargo_par["Rmax"]) + 0.05)
            plot.ylim(0, 5.0)
            xlabel = "Radius"
            
        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        log_density = np.log(fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        averagedDensity = np.average(density, axis = 1) / surface_density

        ### Plot ###
        plot.plot(x, averagedDensity, linewidth = linewidth, label = "%d" % frame)

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel("Azimuthally Averaged Density", fontsize = fontsize)
        plot.title("%s" % this_title, fontsize = fontsize + 1)
def get_rossby_number(args_here):
    # Unwrap Args
    i, frame, directory = args_here

    if frame == 8800:
        frame = 8801  # Remove problem frame

    # Get Data
    density = fromfile("../%s/gasdens%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta) / surface_density_zero
    averagedDensity = np.average(density, axis=-1)
    peak_rad, peak_density = az.get_radial_peak(averagedDensity, fargo_par)

    vrad = (fromfile("../%s/gasvy%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta))  # add a read_vrad to util.py!
    vtheta = (fromfile("../%s/gasvx%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta))  # add a read_vrad to util.py!
    vorticity = utilVorticity.velocity_curl(vrad,
                                            vtheta,
                                            rad,
                                            theta,
                                            rossby=True,
                                            residual=True)

    #vorticity, shift_c = shift_data(vorticity, fargo_par, reference_density = density)

    # Find minimum
    start_rad = min([peak_rad - 0.05, 1.5])
    start_rad_i = np.searchsorted(rad, start_rad)  # Is this necessary?
    end_rad_i = np.searchsorted(rad, 2.5)
    azimuthal_profile = vorticity[start_rad_i:end_rad_i]

    rossby_number_over_time[i] = np.percentile(azimuthal_profile, 0.25)

    print i, frame, rossby_number_over_time[i]
示例#11
0
def sum_vorticity(args):
    i, frame = args

    # Get Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density_zero
    vrad = np.array(
        fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = np.array(
        fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    # Get Background Data
    vtheta_keplerian = np.array(
        fromfile("gasvtheta0.dat").reshape(num_rad, num_theta))

    # Subtract off Keplerian velocity (and rotate back into non-rotating frame???)
    vtheta -= (vtheta_keplerian)
    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame=0)

    #vorticity = np.abs(vorticity) # should be all negative

    # Add up vorticity
    dr = rad[1] - rad[0]  # assumes arithmetic grid
    d_phi = theta[1] - theta[0]

    radial_vorticity = np.average(vorticity, axis=1)
    total_vorticity = np.sum((dr * d_phi) * rad[:-1, None] * radial_vorticity)

    # Print Update
    print "%d: %.4f" % (frame, total_vorticity)

    # Store Data
    vorticity_over_time[i] = total_vorticity
def get_data(frame, size_a, size_b):
    # Find Peak in Radial Profile (in Outer Disk)
    density_a = (fromfile("../%s-size/gasdens%d.dat" %
                          (size_a, frame)).reshape(
                              num_rad, num_theta)) / surface_density
    density_b = (fromfile("../%s-size/gasdens%d.dat" %
                          (size_b, frame)).reshape(
                              num_rad, num_theta)) / surface_density
    averagedDensity_a = np.average(density_a, axis=1)

    peak_rad, peak_density = find_peak(averagedDensity_a)
    min_rad, min_density = find_min(averagedDensity_a, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 2.0 * scale_height  # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread,
                                  num_profiles)
    azimuthal_indices = [
        np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii
    ]

    azimuthal_profiles_a = [
        density_a[azimuthal_index, :] for azimuthal_index in azimuthal_indices
    ]
    azimuthal_profiles_b = [
        density_b[azimuthal_index, :] for azimuthal_index in azimuthal_indices
    ]

    return azimuthal_radii, azimuthal_profiles_a, azimuthal_profiles_b
def find_vortensity_min(frame):
    """ returns radius with maximum azimuthally averaged density """
    i = frame

    # Find density max (Search for vortensity minimum only near the density max)
    density_max = find_density_max(frame)
    start = density_max - (0.2 * (scale_height / 0.06))
    stop = density_max + (0.1 * (scale_height / 0.06))

    # Data
    truncated_rad = truncate(rad, start = start, stop = stop)

    density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta)
    vortensity = vorticity / normalized_density[1:, 1:]
    avg_vortensity = truncate(np.average(vortensity, axis = 1), start = start, stop = stop)

    kernel_size = 1
    smoothed_avg_vortensity = smooth(avg_vortensity, kernel_size)

    # Retrieve radius with min value
    arg_min = np.argmin(smoothed_avg_vortensity)
    radius_min = truncated_rad[arg_min]

    return radius_min
示例#14
0
def get_contrasts(args_here):
    # Unwrap Args
    i, frame = args_here

    # Get Data
    density = fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta) / surface_density_zero
    averagedDensity = np.average(density, axis=-1)
    peak_rad, peak_density = az.get_radial_peak(averagedDensity, fargo_par)

    vrad = (fromfile("gasvy%d.dat" % frame).reshape(num_rad, num_theta)
            )  # add a read_vrad to util.py!
    vtheta = (fromfile("gasvx%d.dat" % frame).reshape(num_rad, num_theta)
              )  # add a read_vrad to util.py!
    vorticity = utilVorticity.velocity_curl(vrad,
                                            vtheta,
                                            rad,
                                            theta,
                                            rossby=True,
                                            residual=True)

    #vorticity, shift_c = shift_data(vorticity, fargo_par, reference_density = density)

    # Find minimum
    start_rad_i = np.searchsorted(rad, peak_rad - 0.1)  # Is this necessary?
    end_rad_i = np.searchsorted(rad, peak_rad + 1.0)
    azimuthal_profile = vorticity[start_rad_i:end_rad_i]

    rossby_number_over_time[i] = np.min(azimuthal_profile)
    rossby_number_over_time_98[i] = np.percentile(azimuthal_profile, 0.2)
    rossby_number_over_time_95[i] = np.percentile(azimuthal_profile, 0.5)

    print i, frame, rossby_number_over_time[i], rossby_number_over_time_98[
        i], rossby_number_over_time_95[i]
示例#15
0
def read_rgb(fname):
	fid = open(fname, 'rb')
	res = fromfile(fid, 'd', 2)
	x = int(res[0])
	y = int(res[1])
	img = fromfile(fid, 'd', x*y*3).reshape(x, y, 3).swapaxes(0, 1)
	fid.close()
	return img
def get_vortensity_variation(frame, vortex_location, figure = False):
    """
    return variation in vortensity (defined to be min / avg at a particular radius)
    """
    i = frame
    # Data
    density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta)
    vortensity = vorticity / normalized_density[1:, 1:]

    # Azimuthal Profile (Average over width of vortex)
    arg_vortex = np.searchsorted(rad, vortex_location)
    half_width = int(16 * (num_rad / 512.0))
    kernel_size = num_theta / 200
    vortensity_at_vortex = smooth(np.average(vortensity[(arg_vortex - half_width):(arg_vortex + half_width), :], 
                                             weights = weights(half_width), axis = 0), kernel_size)
    # Replace values above maximum with maximum
    max_value = 0.3
    vortensity_at_vortex[vortensity_at_vortex > max_value] = max_value

    # Plot
    if figure:
        fig = plot.figure()

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.xlim(0, 2 * np.pi)
        plot.xticks(angles, degree_angles)

        # Plot
        plot.plot(theta[1:], vortensity_at_vortex, linewidth = linewidth)

        # Annotate
        plot.xlabel("Theta", fontsize = fontsize)
        plot.ylabel("Vortensity", fontsize = fontsize)

        # Save and Close
        directory = "azimuthalVortensity"

        plot.savefig("%s/azimuthalVortensity_%04d.png" % (directory, i), bbox_inches = 'tight', dpi = my_dpi)
        #plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)

    # Variation
    min_vortensity = np.min(vortensity_at_vortex)
    avg_vortensity = np.average(vortensity_at_vortex)

    #print min_vortensity

    variation = (1 + avg_vortensity - min_vortensity) / (2 * avg_vortensity)
    return variation
示例#17
0
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize=(700 / my_dpi, 600 / my_dpi), dpi=my_dpi)
        ax = fig.add_subplot(111)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)

        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40)  # to match the ApJL paper
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vortensity = util.velocity_curl(
            vrad, vtheta, rad, theta, frame=ref_frame) / normalized_density[1:,
                                                                            1:]

        ### Plot ###
        result = ax.pcolormesh(x, theta, np.transpose(vortensity), cmap=cmap)

        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        plot.xlabel(xlabel, fontsize=fontsize)
        plot.ylabel(r"$\phi$", fontsize=fontsize)
        plot.title("Vortensity Map at Orbit %d" % orbit, fontsize=fontsize + 1)

        # Save and Close
        plot.savefig("%s/%svortensityMap_%03d.png" %
                     (save_directory, prefix, i),
                     bbox_inches='tight',
                     dpi=my_dpi)
        if show:
            plot.show()
        plot.close(fig)  # Close Figure (to avoid too many figures)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)

        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        vrad = np.array(fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = np.array(fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vtheta_keplerian = np.array(fromfile("gasvtheta0.dat").reshape(num_rad, num_theta))

        # Subtract off Keplerian velocity (and rotate back into non-rotating frame???)
        vtheta -= (vtheta_keplerian)

        vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = 0)

        # Divide out Angular Frequency (for Rossby Number)
        vorticity = vorticity / (np.array([r**(-1.5) for r in rad[:-1]]))[:, None]

        ### Plot ###
        result = ax.pcolormesh(x, theta, np.transpose(vorticity), cmap = cmap)
    
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"$\phi$", fontsize = fontsize)
        plot.title("Vorticity (v - vK) Map at Orbit %d" % orbit, fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%sexcessVorticityMap_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
def make_plot(frame):
    # Orbit Number
    time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
    orbit = int(round(time / (2 * np.pi), 0)) * frame

    # Set up figure
    fig = plot.figure(figsize=(700 / my_dpi, 600 / my_dpi), dpi=my_dpi)

    # Data
    fargo_fn = "fargo2D1D"
    if os.path.exists(fargo_fn):
        # fargo2D1D
        rad = np.loadtxt("used_rad1D.dat")[:-1]
        vrad = fromfile("gasvrad1D%d.dat" % frame)
        avg_pseudo_viscosity = (2.0 / 3) * (np.multiply(rad, vrad)
                                            )  # should be equal to viscosity
    else:
        # fargo
        rad = np.loadtxt("used_rad.dat")[:-1]
        vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
        pseudo_viscosity = (2.0 / 3) * (np.multiply(rad[:, None], vrad)
                                        )  # should be equal to viscosity
        avg_pseudo_viscosity = np.average(pseudo_viscosity,
                                          axis=1)  # radial pseudo-viscosity

    # Curves
    plot.plot(rad,
              avg_pseudo_viscosity,
              color="blue",
              label="+",
              linewidth=linewidth)  # positive
    plot.plot(rad,
              -avg_pseudo_viscosity,
              color="red",
              label="-",
              linewidth=linewidth)  # negative
    plot.plot([rad[0], rad[-1]], [viscosity, viscosity],
              color="black",
              linewidth=linewidth - 1)

    # Limits
    plot.xlim(rad[0], rad[-1])
    plot.yscale('log')

    # Annotate
    plot.xlabel("Radius", fontsize=fontsize)
    plot.ylabel("Pseudo Viscosity", fontsize=fontsize)
    plot.title("Orbit %d" % orbit, fontsize=fontsize + 1)

    plot.legend(loc="upper right")

    # Save + Close
    plot.savefig("%s/viscosity_diagnosis_%04d.png" % (directory, frame),
                 bbox_inches='tight',
                 dpi=my_dpi)
    plot.show()
    plot.close(fig)  # Close Figure (to avoid too many figures)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)

        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vortensity = util.velocity_curl(vrad, vtheta, rad, theta, frame = ref_frame) / normalized_density[1:, 1:]
        avg_vortensity = np.average(vortensity, axis = 1)

        excess_vortensity = avg_vortensity[:, None] - vortensity #### Vortex is Positive ####

        ### Plot ###
        result = ax.pcolormesh(x, theta, np.transpose(excess_vortensity), cmap = cmap)
    
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"$\phi$", fontsize = fontsize)
        plot.title("Excess Vortensity Map at Orbit %d" % orbit, fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%sexcessVortensityMap_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize=(700 / my_dpi, 600 / my_dpi), dpi=my_dpi)

        # Axis
        plot.ylim(0, 1.3)
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40)  # to match the ApJL paper
            #plot.ylim(0, 1.3)
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vorticity = util.velocity_curl(vrad,
                                       vtheta,
                                       rad,
                                       theta,
                                       average=True,
                                       frame=ref_frame)
        vortensity = vorticity / normalized_density[1:, 1:]
        averaged_w = np.average(vortensity, axis=1)

        ### Plot ###
        plot.plot(x[1:], averaged_w, linewidth=linewidth)

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize=fontsize)
        plot.ylabel("Azimuthally Averaged Vortensity", fontsize=fontsize)
        plot.title("Orbit %d: %s" % (orbit, this_title), fontsize=fontsize + 1)

        # Save and Close
        plot.savefig("%s/%saveragedVortensity_%03d.png" %
                     (save_directory, prefix, i),
                     bbox_inches='tight',
                     dpi=my_dpi)
        if show:
            plot.show()
        plot.close(fig)  # Close Figure (to avoid too many figures)
示例#22
0
def convert_to_cylindrical(frame):
    # Converts Vector Field from Spherical to Cylindrical Coordinates
    radial_velocity = (fromfile("vx1.%04d.dbl" % frame).reshape(num_theta, num_z, num_rad))
    theta_velocity = (fromfile("vx2.%04d.dbl" % frame).reshape(num_theta, num_z, num_rad))
    phi_velocity = (fromfile("vx3.%04d.dbl" % frame).reshape(num_theta, num_z, num_rad))
    
    # Velocity Fields
    velocity_field = np.zeros((3, num_theta, num_z, num_rad))
    velocity_field[0] = radial_velocity
    velocity_field[1] = theta_velocity
    velocity_field[2] = phi_velocity

    # Angle Grids
    theta_field = np.zeros((num_theta, num_z, num_rad))
    theta_field[:, :, :] = zs[np.newaxis, :, np.newaxis]

    phi_field = np.zeros((num_theta, num_z, num_rad))
    phi_field[:, 0, 0] = theta
    phi_field[:, :, :] = phi_field[:, 0, 0]

    # cos, sin of angles (3-D grid)
    cos_theta = np.cos(theta_field)
    sin_theta = np.sin(theta_field)

    cos_phi = np.cos(phi_field)
    sin_phi = np.sin(phi_field)

    # combinations of angles (3-D grid)
    cos_theta_cos_phi = cos_theta * cos_phi
    cos_theta_sin_phi = cos_theta * sin_phi
    sin_theta_cos_phi = sin_theta * cos_phi
    sin_theta_sin_phi = sin_theta * sin_phi

    # Transform to Cartesian
    first_transformation_matrix = np.zeros((3, 3, num_theta, num_z, num_rad))
    f = first_transformation_matrix
    f[0, 0] = sin_theta_cos_phi; f[0, 1] = cos_theta_cos_phi; f[0, 2] = -sin_phi
    f[1, 0] = sin_theta_sin_phi; f[1, 1] = cos_theta_sin_phi; f[1, 2] = cos_phi
    f[2, 0] = cos_theta; f[2, 1] = -sin_theta; f[2, 2] = 0

    # Transform to Cylindrical
    second_transformation_matrix = np.zeros((3, 3, num_theta, num_z, num_rad))
    s = second_transformation_matrix
    s[0, 0] = cos_phi; s[0, 1] = sin_phi; s[0, 2] = 0
    s[1, 0] = -sin_phi; s[1, 1] = cos_phi; s[1, 2] = 0
    s[2, 0] = 0; s[2, 1] = 0; s[2, 2] = 1

    # Apply Transformations
    cartesian_velocity_field = np.einsum('ij...,j...->i...', first_transformation_matrix, velocity_field)
    cylindrical_field = np.einsum('ij...,j...->i...', second_transformation_matrix, cartesian_velocity_field)

    cylindrical_radial_velocity = cylindrical_field[0]

    return cylindrical_radial_velocity
def get_data(frame):
    # Load Data Files
    normalized_density = (fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density
    averagedDensity = np.average(normalized_density, axis=1)

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame=ref_frame)
    vortensity = vorticity / normalized_density[1:, 1:]

    # Find Peak in Radial Profile (in Outer Disk)

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 1.0 * scale_height  # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread,
                                  num_profiles)
    azimuthal_indices = [
        np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii
    ]
    azimuthal_profiles = [
        np.fft.fft(vortensity[azimuthal_index, :])
        for azimuthal_index in azimuthal_indices
    ]

    # Normalize by m = 0 mode (integral of vortensity), Take Absolute Value
    azimuthal_profiles = [
        np.abs(azimuthal_profile / azimuthal_profile[0])
        for azimuthal_profile in azimuthal_profiles
    ]

    ### Gather Averaged Profiles ###
    start_half = azimuthal_indices[1]
    end_half = azimuthal_indices[-2]
    avg_half_profile = np.average(vortensity[start_half:end_half, :], axis=0)
    avg_half = np.fft.fft(avg_half_profile)

    start_full = azimuthal_indices[0]
    end_full = azimuthal_indices[-1]
    avg_full_profile = np.average(vortensity[start_full:end_full, :], axis=0)
    avg_full = np.fft.fft(avg_full_profile)

    # Normalize
    avg_half = np.abs(avg_half / avg_half[0])
    avg_full = np.abs(avg_full / avg_full[0])

    return azimuthal_radii, azimuthal_profiles, avg_half, avg_full
def sum_vorticity(args):
    i, frame = args

    # Get Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density_zero
    vrad = np.array(fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = np.array(fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    # Get Background Data
    vtheta_keplerian = np.array(fromfile("gasvtheta0.dat").reshape(num_rad, num_theta))

    # Subtract off Keplerian velocity (and rotate back into non-rotating frame???)
    vtheta -= (vtheta_keplerian)
    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame = 0)

    # Mask Non-Vortex Regions
    min_vorticity = -0.65

    vorticity[density[:-1, :-1] < 0.45] = 0 # if density is too low, it's not in the vortex
    vorticity[vorticity > 0] = 0 # if vorticity is positive, it's not in the vortex
    vorticity[vorticity < min_vorticity] = min_vorticity # if vorticity is too low, it's not in the vortex

    vorticity = np.abs(vorticity) # everything that remains should be negative. switch to positive.

    # Extract Near Vortex
    averagedDensity = np.average(density, axis = 1)
    peak_rad, peak_density = find_peak(averagedDensity)

    vortex_start = np.max([1.0, peak_rad - 5.0 * scale_height])
    vortex_end = peak_rad + 5.0 * scale_height

    vortex_start_i = np.searchsorted(rad, vortex_start)
    vortex_end_i = np.searchsorted(rad, vortex_end)

    vortex_rad = rad[vortex_start_i : vortex_end_i]
    vortex_vorticity_grid = vorticity[vortex_start_i : vortex_end_i]

    vortex_vorticity = np.average(vortex_vorticity_grid, axis = 1)

    # Add up vorticity
    dr = rad[1] - rad[0] # assumes arithmetic grid
    d_phi = theta[1] - theta[0]

    total_vorticity = np.sum((dr * d_phi) * vortex_rad[:, None] * vortex_vorticity)

    ##### Instead: take max vorticity (90th percentile???) #####
    
    # Print Update
    print "%d: %.4f" % (frame, total_vorticity)

    # Store Data
    vorticity_over_time[i] = total_vorticity
def get_data(frame_i, frame, modes=default_modes):
    """ frame_i is ith frame, frame is frame number """

    # Load Data Files
    normalized_density = (fromfile("gasdens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density
    averagedDensity = np.average(normalized_density, axis=1)

    vrad = np.array(
        fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = np.array(
        fromfile("gasvtheta%d.dat" % frame).reshape(
            num_rad, num_theta)) - vtheta_keplerian

    vorticity = util.velocity_curl(vrad, vtheta, rad, theta, frame=ref_frame)
    combo = normalized_density[:-1, :-1] * vorticity

    # Find Peak in Radial Profile (in Outer Disk)
    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 5
    spread = 1.0 * scale_height  # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread,
                                  num_profiles)
    azimuthal_indices = [
        np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii
    ]
    azimuthal_profiles = np.array([
        np.fft.fft(combo[azimuthal_index, :])
        for azimuthal_index in azimuthal_indices
    ])

    # Normalize by m = 0 mode (integral of density), Take Absolute Value
    azimuthal_profiles = np.array([
        np.abs(azimuthal_profile / azimuthal_profile[0])
        for azimuthal_profile in azimuthal_profiles
    ])

    for m, mode in enumerate(modes):
        modes_over_time[m, frame_i] = np.max(azimuthal_profiles[:, mode])

    single_mode_strength[frame_i] = modes_over_time[0, frame_i] / np.max(
        modes_over_time[1:, frame_i])  # m = 1 / Max of Higher Number Modes

    print "%d: %.4f, %.4f, %.4f, %.4f, %.4f - [%.4f]" % (
        frame, np.max(azimuthal_profiles[:, 1]),
        np.max(azimuthal_profiles[:, 2]), np.max(azimuthal_profiles[:, 3]),
        np.max(azimuthal_profiles[:, 4]), np.max(
            azimuthal_profiles[:, 5]), single_mode_strength[frame_i])
示例#26
0
def polish(density,
           frame,
           shift_i,
           size,
           cavity_cutoff=0.92,
           scale_density=1,
           scale_sizes=1):
    """ Step 1: get rid of inner cavity, scale dust densities to different grain size, and only keep dust with negative vorticity """
    # Cavity
    if cavity_cutoff is not None:
        cavity_cutoff_i = np.searchsorted(rad, cavity_cutoff)
        density[:cavity_cutoff_i] = 0.0

        outer_cutoff = 2.75
        outer_cutoff_i = np.searchsorted(rad, outer_cutoff)
        density[outer_cutoff_i:] = 0.0

    # Scale
    density *= scale_density
    size *= scale_sizes

    if negative_vorticity_only > 0:
        tmp_density = density[1:, 1:]

        # Get rid of dust where there is positive vorticity
        vrad = (fromfile("gasvy%d.dat" % frame).reshape(num_rad, num_theta)
                )  # add a read_vrad to util.py!
        vtheta = (fromfile("gasvx%d.dat" % frame).reshape(num_rad, num_theta)
                  )  # add a read_vrad to util.py!
        vorticity = utilVorticity.velocity_curl(vrad,
                                                vtheta,
                                                rad,
                                                theta,
                                                rossby=True,
                                                residual=True)

        # Remember to shift the vorticity!
        vorticity = np.roll(vorticity, shift_i, axis=1)

        tmp_density[vorticity > 0] = 0.0
        density[1:, 1:] = tmp_density

        # Get rid of dust where density is below a threshold
        gas_density = fromfile("gasdens%d.dat" % frame).reshape(
            num_rad, num_theta) / surface_density_zero
        gas_density = np.roll(gas_density, shift_i, axis=1)

        threshold = negative_vorticity_only
        density[gas_density < threshold] = 0.0

    return density, size
示例#27
0
def gather_vortex_over_time():
    """ add up vortex mass over time """    
    for frame in times:
        density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

        vorticity = curl(vrad, vtheta, rad, theta)
        vortensity = vorticity / normalized_density[1:, 1:]

        vortex_mass_i, _ = vortex_mass(rad, theta, density, vortensity)
        vortex_masses.append(vortex_mass_i)
示例#28
0
def map_one_vortex(frame):
    """ get 2-D grid showing vortex """
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta)
    vortensity = vorticity / normalized_density[1:, 1:]

    this_vortex_mass, vortex_map = vortex_mass(rad, theta, density, vortensity)

    print "Vortex Mass at Frame %d: %.8f" % (frame, this_vortex_mass)
    return vortex_map
示例#29
0
def map_one_vortex(frame):
    """ get 2-D grid showing vortex """
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta)
    vortensity = vorticity / normalized_density[1:, 1:]

    this_vortex_mass, vortex_map = vortex_mass(rad, theta, density, vortensity)

    print "Vortex Mass at Frame %d: %.8f" % (frame, this_vortex_mass)
    return vortex_map
示例#30
0
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        blank_density = (fromfile("gasdens%d.dat" % blank_frame).reshape(num_rad, num_theta))
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))

        normalized_density = (density - blank_density) / surface_density_zero # Diff

        ### Plot ###
        result = ax.pcolormesh(x, theta, np.transpose(normalized_density), cmap = cmap)
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"$\phi$", fontsize = fontsize)
        plot.title("Gas Difference Density Map at Orbit %d (- Orbit %d)\n%s" % (orbit, blank_frame, this_title), fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%sdiff_densityMap_%04d-%04d.png" % (save_directory, prefix, blank_frame, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
def make_plot(frame, show=False):
    # Orbit Number
    time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
    orbit = int(round(time / (2 * np.pi), 0)) * frame

    # Set up figure
    fig = plot.figure()
    ax = fig.add_subplot(111)

    # Axis
    angles = np.linspace(0, 2 * np.pi, 7)
    degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

    plot.ylim(0, 2 * np.pi)
    plot.yticks(angles, degree_angles)

    plot.xlim(float(fargo_par["Rmin"]), 1.0)

    # Data
    x = rad
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta) / normalized_density[1:, 1:]

    ### Plot ###
    result = ax.pcolormesh(x, theta, np.transpose(vorticity), cmap=cmap)

    fig.colorbar(result)
    result.set_clim(clim[0], clim[1])

    # Annotate
    this_title = readTitle()
    plot.xlabel("Radius", fontsize=fontsize)
    plot.ylabel(r"$\phi$", fontsize=fontsize)
    plot.title("Vortensity Map at Orbit %d: %s" % (orbit, this_title),
               fontsize=fontsize + 1)

    # Save and Close
    plot.savefig("%s/vorticityMap_%03d.png" % (save_directory, frame),
                 bbox_inches='tight',
                 dpi=my_dpi)
    if show:
        plot.show()
    plot.close(fig)  # Close Figure (to avoid too many figures)
def get_data(frame_i, frame, modes = default_modes):
    """ frame_i is ith frame, frame is frame number """

    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    density = subtract_wave(density) # First, subtract wave!

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 7
    spread = 1.0 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = np.array([np.fft.fft(density[azimuthal_index, :]) for azimuthal_index in azimuthal_indices])

    # Normalize by m = 0 mode (integral of density), Take Absolute Value
    azimuthal_profiles = np.array([np.abs(azimuthal_profile / azimuthal_profile[0]) for azimuthal_profile in azimuthal_profiles])

    for m, mode in enumerate(modes):
        modes_over_time[m, frame_i] = np.max(azimuthal_profiles[:, mode]) #np.sqrt(np.sum(np.power(azimuthal_profiles[:, mode], 2))) 

    single_mode_strength[frame_i] = modes_over_time[0, frame_i] / np.max(modes_over_time[1:, frame_i]) # m = 1 / Max of Higher Number Modes
    single_mode_concentration[frame_i] = np.std(azimuthal_profiles[:, 1]) / modes_over_time[0, frame_i]

    print "%d: %.4f, %.4f, %.4f, %.4f, %.4f - [%.4f, %.4f]" % (frame, np.max(azimuthal_profiles[:, 1]), np.max(azimuthal_profiles[:, 2]), np.max(azimuthal_profiles[:, 3]), np.max(azimuthal_profiles[:, 4]), np.max(azimuthal_profiles[:, 5]), single_mode_strength[frame_i], single_mode_concentration[frame_i])
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Axis
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            #plot.ylim(0, 1.2)
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]) - 0.05, float(fargo_par["Rmax"]) + 0.05)
            #plot.ylim(0, 5.0)
            xlabel = "Radius"
            
        # Data
        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        averaged_vrad = np.average(vrad, axis = 1)

        ### Plot ###
        plot.plot(x, averaged_vrad, linewidth = linewidth, label = "%d" % frame)

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"Azimuthally Averaged $V_{rad}$", fontsize = fontsize)
        plot.title("%s" % this_title, fontsize = fontsize + 1)
def get_data(frame_i, frame, modes = default_modes):
    """ frame_i is ith frame, frame is frame number """

    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    # Gather Azimuthal Profiles
    num_profiles = 7
    spread = 1.0 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = np.array([np.fft.fft(density[azimuthal_index, :]) for azimuthal_index in azimuthal_indices])

    # Normalize by m = 0 mode (integral of density), Take Absolute Value
    azimuthal_profiles = np.array([np.abs(azimuthal_profile / azimuthal_profile[0]) for azimuthal_profile in azimuthal_profiles])

    for m, mode in enumerate(modes):
        modes_over_time[m, frame_i] = np.max(azimuthal_profiles[:, mode]) #np.sqrt(np.sum(np.power(azimuthal_profiles[:, mode], 2))) 

    single_mode_strength[frame_i] = modes_over_time[0, frame_i] / np.max(modes_over_time[1:, frame_i]) # m = 1 / Max of Higher Number Modes
    single_mode_concentration[frame_i] = np.std(azimuthal_profiles[:, 1]) / modes_over_time[0, frame_i]

    print "%d: %.4f, %.4f, %.4f, %.4f, %.4f - [%.4f, %.4f]" % (frame, np.max(azimuthal_profiles[:, 1]), np.max(azimuthal_profiles[:, 2]), np.max(azimuthal_profiles[:, 3]), np.max(azimuthal_profiles[:, 4]), np.max(azimuthal_profiles[:, 5]), single_mode_strength[frame_i], single_mode_concentration[frame_i])
示例#35
0
def get_data(frame):
    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    peak_rad, peak_index, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    peak_theta, peak_theta_index, peak_azimuthal_density = find_azimuthal_peak(density[peak_index])

    if len(sys.argv) > 2:
        # Supply central theta as an argument
        peak_theta = float(sys.argv[2])

    # Gather Azimuthal Profiles
    pressure = density * (scale_height)**2 * np.power(rad, -1)[:, None]

    num_profiles = 5
    spread = 30.0 # half-width

    radial_theta = np.linspace(peak_theta - spread, peak_theta + spread, num_profiles)
    radial_theta[radial_theta < 0] += 360.0
    radial_theta[radial_theta > 360] -= 360.0

    radial_indices = [np.searchsorted(theta, this_theta * (np.pi / 180.0)) for this_theta in radial_theta]
    radial_profiles = [pressure[:, radial_index] for radial_index in radial_indices]

    return radial_theta, radial_profiles
示例#36
0
文件: lynxio.py 项目: kghose/neurapy
def read_nse(fin):
  """Read single electrode spike record.
  Inputs:
    fin - file handle
    only_timestamps - if true, only load the timestamps, ignoring the waveform and feature data

  Output: Dictionary with fields
    'header'  - header info
    'packets' - pylab data structure with the spike data

  Notes:
    0. What is spike acquizition entity number? Ask neuralynx
    1. Removing LOAD_ATTR overhead by defining time_stamp_append = [time_stamp[n].append for n in xrange(100)] and using
       time_stamp_append[dwCellNumber](qwTimeStamp) in the loop does not seem to improve performance.
       It reduces readability so I did not use it.
    2. Disabling garbage collection did not help
    3. In general, dictionary lookups slow things down
    4. using numpy arrays, with preallocation is slower than the dumb, straightforward python list appending
  """

  hdr = read_header(fin)
  nse_packet = pylab.dtype([
    ('timestamp', 'Q'),
    ('saen', 'I'),
    ('cellno', 'I'),
    ('Features', '8I'),
    ('waveform', '32h')
  ])
  data = pylab.fromfile(fin, dtype=nse_packet, count=-1)
  return {'header': hdr, 'packets': data}
示例#37
0
def gather_vortex_over_time():
    """ add up vortex mass over time """
    for frame in times:
        density = (fromfile("gasdens%d.dat" % frame).reshape(
            num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(
            num_rad, num_theta))

        vorticity = curl(vrad, vtheta, rad, theta)
        vortensity = vorticity / normalized_density[1:, 1:]

        vortex_mass_i, _ = vortex_mass(rad, theta, density, vortensity)
        vortex_masses.append(vortex_mass_i)
def get_data(frame):
    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    peak_rad, peak_density = find_peak(averagedDensity)
    min_rad, min_density = find_min(averagedDensity, peak_rad)

    ### Gather Azimuthal Profiles ###
    num_profiles = 5
    spread = 1.0 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = np.array([np.fft.fft(density[azimuthal_index, :]) for azimuthal_index in azimuthal_indices])

    # Normalize by m = 0 mode (integral of density), Take Absolute Value
    azimuthal_profiles = [np.abs(azimuthal_profile / azimuthal_profile[0]) for azimuthal_profile in azimuthal_profiles]

    ### Gather Averaged Profiles ###
    start_half = azimuthal_indices[1]
    end_half = azimuthal_indices[-2]
    avg_half_profile = np.average(density[start_half : end_half, :], axis = 0)
    avg_half = np.fft.fft(avg_half_profile)

    start_full = azimuthal_indices[0]
    end_full = azimuthal_indices[-1]
    avg_full_profile = np.average(density[start_full : end_full, :], axis = 0)
    avg_full = np.fft.fft(avg_full_profile)

    # Normalize
    avg_half = np.abs(avg_half / avg_half[0])
    avg_full = np.abs(avg_full / avg_full[0])

    return azimuthal_radii, azimuthal_profiles, avg_half, avg_full
示例#39
0
def retrieve_density(frame, size):
    """ Step 0: Retrieve density """

    fn_i = "../%s-size/gasddens%d.dat" % (size, frame)
    density = fromfile(fn_i).reshape(num_rad, num_theta)

    return density
示例#40
0
def read_nse(fin):
    """Read single electrode spike record.
  Inputs:
    fin - file handle
    only_timestamps - if true, only load the timestamps, ignoring the waveform and feature data

  Output: Dictionary with fields
    'header'  - header info
    'packets' - pylab data structure with the spike data

  Notes:
    0. What is spike acquizition entity number? Ask neuralynx
    1. Removing LOAD_ATTR overhead by defining time_stamp_append = [time_stamp[n].append for n in xrange(100)] and using
       time_stamp_append[dwCellNumber](qwTimeStamp) in the loop does not seem to improve performance.
       It reduces readability so I did not use it.
    2. Disabling garbage collection did not help
    3. In general, dictionary lookups slow things down
    4. using numpy arrays, with preallocation is slower than the dumb, straightforward python list appending
  """

    hdr = read_header(fin)
    nse_packet = pylab.dtype([('timestamp', 'Q'), ('saen', 'I'),
                              ('cellno', 'I'), ('Features', '8I'),
                              ('waveform', '32h')])
    data = pylab.fromfile(fin, dtype=nse_packet, count=-1)
    return {'header': hdr, 'packets': data}
示例#41
0
def read_data(frame, fn, fargo_par, id_number = None, version = None, directory = "."):
    """ read data"""
    ######## Get Parameters #########
    num_rad = fargo_par["Nrad"]
    num_theta = fargo_par["Nsec"]

    ########### Method ##############
    # Dictionary
    basenames = {}
    basenames['gas'] = "gasdens%d.dat"; basenames['dust'] = "gasddens%d.dat"; basenames['input_density'] = "id%04d_gasddens%d.p";
    basenames['intensity'] = "id%04d_intensity%04d.dat"; basenames['polar_intensity'] = "id%04d_intensityMap%04d.p"; basenames['cartesian_intensity'] = "id%04d_intensityCartGrid%04d.p"

    # Specific Data
    basename = basenames[fn]

    if "id" in basename:
        basename = basename % (id_number, frame)
    else:
        basename = basename % frame

    # Add Version
    if version is not None:
        basename = "v%04d_%s" % (version, basename)

    # Load properly based on extension
    ext = basename[basename.find("."):]
    if fn == 'intensity':
        data = (np.loadtxt("%s/%s" % (directory, basename))[:, -1]).reshape(num_rad, num_theta)
    elif ext == ".dat":
        data = (fromfile("%s/%s" % (directory, basename)).reshape(num_rad, num_theta))
    elif ext == ".p":
        data = pickle.load(open("%s/%s" % (directory, basename), "rb"))
    return data
def get_contrasts(args_here):
    # Unwrap Args
    i, frame, directory = args_here

    if frame == 8800:
        frame = 8801  # Remove problem frame

    # Get Data
    density = fromfile("../%s/gasdens%d.dat" % (directory, frame)).reshape(
        num_rad, num_theta) / surface_density_zero
    density, shift_c = shift_density(density,
                                     fargo_par,
                                     reference_density=density)
    azimuthal_profile = az.get_mean_azimuthal_profile(density,
                                                      fargo_par,
                                                      sliver_width=1.5,
                                                      end=1.85)

    if "low_mass" in directory:
        azimuthal_profile /= (0.3)  # low-mass case

    maxima_over_time[i] = np.percentile(azimuthal_profile, 90)
    minima_over_time[i] = np.percentile(azimuthal_profile, 5)
    contrasts_over_time[i] = maxima_over_time[i] / minima_over_time[i]
    differences_over_time[i] = maxima_over_time[i] - minima_over_time[i]

    print i, frame, differences_over_time[i], maxima_over_time[
        i], minima_over_time[i], contrasts_over_time[i]
def make_plot(frame, show = False):
    # Orbit Number
    time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
    orbit = int(round(time / (2 * np.pi), 0)) * frame

    # Set up figure
    fig = plot.figure()
    ax = fig.add_subplot(111, polar = True) 

    # Axis
    rmax = 1.0 # to match ApJL paper

    plot.xticks([], []) # Angles
    plot.yticks([rmax], ["%.1f" % rmax]) # Max Radius
    plot.ylim(0, rmax)

    # Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    ### Plot ###
    result = ax.pcolormesh(theta, rad, normalized_density, cmap = cmap)
    fig.colorbar(result)
    result.set_clim(clim[0], clim[1])

    # Annotate
    this_title = readTitle()
    plot.title("Gas Density Map at Orbit %d: %s" % (orbit, this_title), fontsize = fontsize + 1)

    # Save and Close
    plot.savefig("%s/innerDensityMap_%04d.png" % (save_directory, frame), bbox_inches = 'tight', dpi = my_dpi)
    if show:
        plot.show()
    plot.close(fig) # Close Figure (to avoid too many figures)
def get_quartiles(args):
    # Unwrap Args
    i, frame = args

    # Get Dust Data
    density = (fromfile("gasddens%d.dat" % frame).reshape(
        num_rad, num_theta)) / surface_density_zero
    background_density = (fromfile("gasddens0.dat").reshape(
        num_rad, num_theta)) / surface_density_zero

    # Get Vortex Vicinity Indices
    averagedDensity = np.average(density, axis=1)
    peak_rad, peak_density = find_peak(averagedDensity)

    vortex_start = np.max([1.05, peak_rad - 5.0 * scale_height])
    vortex_end = peak_rad + 5.0 * scale_height

    vortex_start_i = np.searchsorted(rad, vortex_start)
    vortex_end_i = np.searchsorted(rad, vortex_end)

    # Extract Near Vortex
    vortex_rad = rad[vortex_start_i:vortex_end_i]
    vortex_density = density[vortex_start_i:vortex_end_i]
    vortex_background_density = background_density[vortex_start_i:vortex_end_i]

    # Look for 2x initial density (mask everything else)
    not_overdense = np.array(vortex_density < 2.0 * vortex_background_density)
    masked_density = (np.ma.array(
        vortex_density,
        mask=not_overdense)).compressed()  # return non-masked data only

    # Get Data (if not all masked)
    if not np.all(not_overdense):
        m50 = np.percentile(masked_density,
                            50)  # Note: mask has no effect on np.percentile
        m75 = np.percentile(masked_density, 75)
        m90 = np.percentile(masked_density, 90)
        m99 = np.percentile(masked_density, 99)

        # Store Data
        track50[i] = m50
        track75[i] = m75
        track90[i] = m90
        track99[i] = m99

        # Print Update
        print "%d: %.4f, %.4f, %.4f, %.4f" % (frame, m50, m75, m90, m99)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)

        # Axis
        plot.ylim(0, 1.3)
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            #plot.ylim(0, 1.3)
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vorticity = util.velocity_curl(vrad, vtheta, rad, theta, average = True, frame = ref_frame)
        vortensity = vorticity / normalized_density[1:, 1:]
        averaged_w = np.average(vortensity, axis = 1)

        ### Plot ###
        plot.plot(x[1:], averaged_w, linewidth = linewidth)

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel("Azimuthally Averaged Vortensity", fontsize = fontsize)
        plot.title("Orbit %d: %s" % (orbit, this_title), fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%saveragedVortensity_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
示例#46
0
def make_plot(frame, show = False):
    # Set up figure
    #fig = plot.figure(figsize = (7, 6), dpi = dpi)
    #ax = fig.add_subplot(111)

    # Data
    if merge > 0:
        num_merged_cores = merge
        density = util.read_merged_data(frame, num_merged_cores, num_rad, num_theta)
    elif mpi:
        field = "dens"
        density = Fields("./", 'gas', frame).get_field(field).reshape(num_rad, num_theta)
    else:
        density = fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)
    normalized_density = density / surface_density_zero

    start = np.searchsorted(rad, 0.9)
    end = np.searchsorted(rad, 1.1)

    density_sliver = density[start:end]

    planet_x = 1
    planet_y = 0
    planet_r = np.sqrt(planet_x**2 + planet_y**2)

    dt = all_times[1] # 0.00410595556163

    accreted_mass = 0.0
    count1 = 0; count2 = 0

    for i, r_i in enumerate(rad[start:end]):
        for j, az_i in enumerate(theta):
            xc = r_i * np.cos(az_i)
            yc = r_i * np.sin(az_i)

            dx = planet_x - xc
            dy = planet_y - yc

            distance = np.sqrt(dx**2 + dy**2)
            r_roche = (planet_mass * 1e-3 / 3.0)**(1.0 / 3.0) * planet_r

            cell_mass = density[start+i, j] * (np.pi / num_theta) * (rad[start+i+1]**2 - r_i**2)
            dm = 0.0

            if distance < 0.75 * r_roche:
                dm = (1.0 / 3.0 * dt) * cell_mass
                cell_mass *= (1.0 - 1.0 / 3.0 * dt)

                count1 += 1
                accreted_mass += dm

            if distance < 0.45 * r_roche:
                dm = (2.0 / 3.0 * dt) * cell_mass

                count2 += 1
                accreted_mass += dm

    print count1, count2
    print accreted_mass, accreted[0]
示例#47
0
def make_plot(frame, show = False):
    # Orbit Number
    time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
    orbit = int(round(time / (2 * np.pi), 0)) * frame

    # Set up figure
    fig = plot.figure()
    ax = fig.add_subplot(111)

    # Axis
    angles = np.linspace(0, 2 * np.pi, 7)
    degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

    plot.ylim(0, 2 * np.pi)
    plot.yticks(angles, degree_angles)

    plot.xlim(float(fargo_par["Rmin"]), 1.0)

    # Data
    x = rad
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta))
    normalized_density = density / surface_density_zero

    vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
    vtheta = (fromfile("gasvtheta%d.dat" % frame).reshape(num_rad, num_theta))

    vorticity = curl(vrad, vtheta, rad, theta) / normalized_density[1:, 1:]

    ### Plot ###
    result = ax.pcolormesh(x, theta, np.transpose(vorticity), cmap = cmap)

    fig.colorbar(result)
    result.set_clim(clim[0], clim[1])

    # Annotate
    this_title = readTitle()
    plot.xlabel("Radius", fontsize = fontsize)
    plot.ylabel(r"$\phi$", fontsize = fontsize)
    plot.title("Vortensity Map at Orbit %d: %s" % (orbit, this_title), fontsize = fontsize + 1)

    # Save and Close
    plot.savefig("%s/vorticityMap_%03d.png" % (save_directory, frame), bbox_inches = 'tight', dpi = my_dpi)
    if show:
        plot.show()
    plot.close(fig) # Close Figure (to avoid too many figures)
示例#48
0
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111, polar = True)

        # Axis
        if axis == "zoom":
            prefix = "zoom_"
            rmax = 2.4 # to match ApJL paper
        else:
            prefix = ""
            rmax = float(fargo_par["Rmax"])

        plot.xticks([], []) # Angles
        plot.yticks([rmax], ["%.1f" % rmax]) # Max Radius
        plot.ylim(0, rmax)

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vorticity = util.velocity_curl(vrad, vtheta, rad, theta) / normalized_density[1:, 1:]

        ### Plot ###
        result = ax.pcolormesh(theta, rad, vorticity, cmap = cmap)
    
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        this_title = readTitle()
        plot.title("Vortensity Map at Orbit %d\n%s" % (orbit, this_title), fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%svortensityMap_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
示例#49
0
def make_plot(frame):
    # Orbit Number
    time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
    orbit = int(round(time / (2 * np.pi), 0)) * frame

    # Set up figure
    fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)

    # Data
    fargo_fn = "fargo2D1D"
    if os.path.exists(fargo_fn):
        # fargo2D1D
        rad = np.loadtxt("used_rad1D.dat")[:-1]
        vrad = fromfile("gasvrad1D%d.dat" % frame)
        avg_pseudo_viscosity = (2.0 / 3) * (np.multiply(rad, vrad)) # should be equal to viscosity
    else:
        # fargo
        rad = np.loadtxt("used_rad.dat")[:-1]
        vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
        pseudo_viscosity = (2.0 / 3) * (np.multiply(rad[:, None], vrad)) # should be equal to viscosity
        avg_pseudo_viscosity = np.average(pseudo_viscosity, axis = 1) # radial pseudo-viscosity

    # Curves
    plot.plot(rad, avg_pseudo_viscosity, color = "blue", label = "+", linewidth = linewidth) # positive
    plot.plot(rad, -avg_pseudo_viscosity, color = "red", label = "-", linewidth = linewidth) # negative
    plot.plot([rad[0], rad[-1]], [viscosity, viscosity], color = "black", linewidth = linewidth - 1)

    # Limits
    plot.xlim(rad[0], rad[-1])
    plot.yscale('log')

    # Annotate
    plot.xlabel("Radius", fontsize = fontsize)
    plot.ylabel("Pseudo Viscosity", fontsize = fontsize)
    plot.title("Orbit %d" % orbit, fontsize = fontsize + 1)

    plot.legend(loc = "upper right")

    # Save + Close
    plot.savefig("%s/viscosity_diagnosis_%04d.png" % (directory, frame), bbox_inches = 'tight', dpi = my_dpi)
    plot.show()
    plot.close(fig) # Close Figure (to avoid too many figures)
def measure_asymmetry(frame):
    # Find Peak in Radial Profile (in Outer Disk)
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density
    averagedDensity = np.average(density, axis = 1)

    peak_rad, peak_rad_index, peak_density = find_radial_peak(averagedDensity)

    # Take Weighted Average of Azimuthal Profiles
    num_profiles = 7
    weights = gaussian(num_profiles, scale = num_profiles / 2.0)
    spread = 1.5 * scale_height # half-width

    azimuthal_radii = np.linspace(peak_rad - spread, peak_rad + spread, num_profiles)
    azimuthal_indices = [np.searchsorted(rad, this_radius) for this_radius in azimuthal_radii]
    azimuthal_profiles = np.array([density[azimuthal_index, :] for azimuthal_index in azimuthal_indices])

    weighted_azimuthal_profile = np.average(azimuthal_profiles, weights = weights, axis = 0)

    # Find Peak in Azimuthal Profile (and center around that peak)
    peak_theta, peak_theta_index = find_azimuthal_peak(weighted_azimuthal_profile)

    initial_center = np.searchsorted(theta, np.pi)

    centered_profiles = np.roll(azimuthal_profiles, initial_center - peak_theta_index, axis = 1)
    centered_profile = np.roll(weighted_azimuthal_profile, initial_center - peak_theta_index)

    # Choose Threshold
    #pass

    # Find Bounds Marked by Threshold
    high_bound_index = np.argmax(centered_profile[initial_center : ] < threshold)
    low_bound_index = np.argmax((centered_profile[::-1])[len(centered_profile) - initial_center : ] < threshold)

    # Convert Back to Thetas and Indices
    high_theta_index = (initial_center) + high_bound_index
    low_theta_index = (len(centered_profile) - initial_center) - low_bound_index

    high_theta = theta[high_theta_index]
    low_theta = theta[low_theta_index]

    azimuthal_extent = (180.0 / np.pi) * (high_theta - low_theta)

    print "%d: %.1f, %d, %d" % (frame, azimuthal_extent, low_theta_index, high_theta_index)

    if azimuthal_extent > 5:
        # Find Quartiles (25%, 50%, 75%)
        lower_quartile = np.percentile(centered_profiles[:, low_theta_index : high_theta_index], 25)
        avg_density = np.percentile(centered_profiles[:, low_theta_index : high_theta_index], 50)
        upper_quartile = np.percentile(centered_profiles[:, low_theta_index : high_theta_index], 75)

        return azimuthal_extent, avg_density, lower_quartile, upper_quartile
    else:
        # No Vortex Yet (or any features really)
        return azimuthal_extent, threshold, threshold, threshold
def get_excess_mass(args):
    # Unwrap Args
    i, frame = args

    # Get Data
    density = (fromfile("gasdens%d.dat" % frame).reshape(num_rad, num_theta)) / surface_density_zero
    background_density = (fromfile("gasdens%d.dat" % (frame - 1)).reshape(num_rad, num_theta)) / surface_density_zero

    diff_density = density - background_density
    diff_density[diff_density < 0] = 0 # only include excess

    # Extract Near Vortex
    averagedDensity = np.average(density, axis = 1)
    peak_rad, peak_density = find_peak(averagedDensity)

    vortex_start = np.max([1.0, peak_rad - 5.0 * scale_height])
    vortex_end = peak_rad + 5.0 * scale_height

    vortex_start_i = np.searchsorted(rad, vortex_start)
    vortex_end_i = np.searchsorted(rad, vortex_end)

    vortex_rad = rad[vortex_start_i : vortex_end_i]
    vortex_diff_density = diff_density[vortex_start_i : vortex_end_i]

    vortex_excess = np.average(vortex_diff_density, axis = 1)

    # Add up mass
    dr = rad[1] - rad[0] # assumes arithmetic grid
    d_phi = theta[1] - theta[0]

    excess_mass = np.sum((dr * d_phi) * vortex_rad[:, None] * vortex_diff_density)

    # Get Peak
    peak_diff_density = np.max(vortex_excess)

    # Print Update
    print "%d: %.4f, %.4f" % (frame, excess_mass, peak_diff_density)

    # Store Data
    mass_over_time[i] = excess_mass
    peak_over_time[i] = peak_diff_density
示例#52
0
def make_plot():
    # Set up figure
    fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)

    ### Data ###
    xs = range(mass_taper)

    # Measure 1: Diff Mass Accretion
    data = np.loadtxt(planet_fn)
    masses = (data[:, 5]) # Planet Mass from 0 to Mass Taper
    tapering_accretion = np.diff(masses[:mass_taper + 1])

    # Measure 2: Viscosity
    viscous_accretion = 3.0 * np.pi * surface_density * viscosity

    # Measure 3: Radial Velocity
    near_planet = 1.0
    radius_near_planet = np.searchsorted(rad, near_planet)
    
    rate = 10
    xs_vrad = range(0, mass_taper, rate)
    radial_velocity_at_planet = np.zeros(len(xs_vrad))

    for i, frame in enumerate(xs_vrad):
        vrad = (fromfile("gasvrad%d.dat" % frame).reshape(num_rad, num_theta))
        radial_velocity_at_planet[i] = np.average(vrad[radius_near_planet, :])

    radius = 1.0
    radial_accretion = 2.0 * np.pi * radius * surface_density * radial_velocity_at_planet

    # Curves
    plot.plot(xs, tapering_accretion, color = "blue", label = "taper", linewidth = linewidth)
    plot.plot([xs[0], xs[-1]], [viscous_accretion, viscous_accretion], color = "black", label = "viscous", linewidth = linewidth)
    plot.plot(xs_vrad, radial_velocity_at_planet, color = "red", label = "v_rad (+)", linewidth = linewidth) # Positive
    plot.plot(xs_vrad, -radial_velocity_at_planet, color = "orange", label = "v_rad (-)", linewidth = linewidth) # Negative

    # Limits
    plot.xlim(xs[0], xs[-1])
    plot.yscale('log')

    # Annotate
    this_title = readTitle()
    plot.xlabel("Number of Orbits", fontsize = fontsize)
    plot.ylabel("Accretion Rate", fontsize = fontsize)
    plot.title("Accretion for %s" % (this_title), fontsize = fontsize + 1)

    plot.legend(loc = "upper right", bbox_to_anchor = (1.36, 1.0)) # outside of plot

    # Save + Close
    plot.savefig("accretion_diagnosis.png", bbox_inches = 'tight', dpi = my_dpi)
    plot.show()
    plot.close(fig) # Close Figure (to avoid too many figures)
示例#53
0
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)

        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]), float(fargo_par["Rmax"]))
            xlabel = "Radius"

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        torque_map = util.torque(rad, theta, normalized_density, )
        abs_torque = np.abs(torque_map)
        log_torque = np.log(abs_torque) / np.log(10) # log torque in base 10

        ### Plot ###
        result = ax.pcolormesh(x, theta, np.transpose(abs_torque), cmap = cmap)
    
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"$\phi$", fontsize = fontsize)
        plot.title("Torque Map at Orbit %d" % orbit, fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%storqueMap_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Axis
        if axis == "zoom":
            x = (rad - 1) / scale_height
            prefix = "zoom_"
            plot.xlim(0, 40) # to match the ApJL paper
            #plot.ylim(0, 1.2)
            xlabel = r"($r - r_p$) $/$ $h$"
        else:
            x = rad
            prefix = ""
            plot.xlim(float(fargo_par["Rmin"]) - 0.05, float(fargo_par["Rmax"]) + 0.05)
            #plot.ylim(0, 5.0)
            xlabel = "Radius"
            
        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        vrad = (fromfile("gasvrad%d.dat" % i).reshape(num_rad, num_theta))
        vtheta = (fromfile("gasvtheta%d.dat" % i).reshape(num_rad, num_theta))

        vorticity = util.velocity_curl(vrad, vtheta, rad, theta, average = True, frame = ref_frame)
        vortensity = vorticity / normalized_density[1:, 1:]
        averaged_w = np.average(vortensity, axis = 1)

        ### Plot ###
        plot.plot(x, averaged_w, linewidth = linewidth, label = "%d" % frame)

        # Annotate
        this_title = readTitle()
        plot.xlabel(xlabel, fontsize = fontsize)
        plot.ylabel(r"Azimuthally Averaged Vortensity", fontsize = fontsize)
        plot.title("%s" % this_title, fontsize = fontsize + 1)
    def choose_axis(i, axis):
        # Orbit Number
        time = float(fargo_par["Ninterm"]) * float(fargo_par["DT"])
        orbit = int(round(time / (2 * np.pi), 0)) * i

        # Set up figure
        fig = plot.figure(figsize = (700 / my_dpi, 600 / my_dpi), dpi = my_dpi)
        ax = fig.add_subplot(111, polar = True)

        # Axis
        angles = np.linspace(0, 2 * np.pi, 7)
        degree_angles = ["%d" % d_a for d_a in np.linspace(0, 360, 7)]

        plot.ylim(0, 2 * np.pi)
        plot.yticks(angles, degree_angles)

        # Axis
        if axis == "zoom":
            prefix = "zoom_"
            rmax = 2.4 # to match ApJL paper
        else:
            prefix = ""
            rmax = float(fargo_par["Rmax"])

        plot.xticks([], []) # Angles
        plot.yticks([rmax], ["%.1f" % rmax]) # Max Radius
        plot.ylim(0, rmax)

        # Data
        density = (fromfile("gasdens%d.dat" % i).reshape(num_rad, num_theta))
        normalized_density = density / surface_density_zero

        torque_map = util.torque(rad, theta, normalized_density, planet_mass = planet_mass)
        abs_torque = np.abs(torque_map)
        log_torque = np.log(abs_torque) / np.log(10) # log torque in base 10

        ### Plot ###
        result = ax.pcolormesh(theta, rad, log_torque, cmap = cmap)
    
        fig.colorbar(result)
        result.set_clim(clim[0], clim[1])

        # Annotate
        plot.title("Torque Map at Orbit %d" % orbit, fontsize = fontsize + 1)

        # Save and Close
        plot.savefig("%s/%storqueMap_%03d.png" % (save_directory, prefix, i), bbox_inches = 'tight', dpi = my_dpi)
        if show:
            plot.show()
        plot.close(fig) # Close Figure (to avoid too many figures)
示例#56
0
文件: lynxio.py 项目: kghose/neurapy
def read_nev(fin, parse_event_string=False):
  """Read an event file.
  Input:
    fin - file handle
    parse_event_string - If set to true then parse the eventstrings nicely. This takes extra time. Default is False
  Ouput:
    Dictionary with fields
      'header' - the file header
      'packets' - the events. This is a new pylab dtype with fields corresponding to the event packets.
        'nstx'
        'npkt_id'
        'npkt_data_size'
        'timestamp' - timestamp (us)
        'eventid'
        'nttl' - value of the TTL port
        'ncrc'
        'ndummy1'
        'ndummy2'
        'dnExtra'
        'eventstring' - The alphanumeric string NeuraLynx attaches to this event

      'eventstring' - Only is parse_event_string is set to True. This is a nicely formatted eventstring
  """
  hdr = read_header(fin)
  nev_packet = pylab.dtype([
    ('nstx', 'h'),
    ('npkt_id', 'h'),
    ('npkt_data_size', 'h'),
    ('timestamp', 'Q'),
    ('eventid', 'h'),
    ('nttl', 'H'),
    ('ncrc', 'h'),
    ('ndummy1', 'h'),
    ('ndummy2', 'h'),
    ('dnExtra', '8i'),
    ('eventstring', '128c')
  ])
  data = pylab.fromfile(fin, dtype=nev_packet, count=-1)
  logger.debug('{:d} events'.format(data['timestamp'].size))
  if parse_event_string:
    logging.info('Packaging the event strings. This makes things slower.')
    # Makes things slow. Often this field is not needed
    evstring = [None]*data['timestamp'].size
    for n in xrange(data['timestamp'].size):
      str = ''.join(data['eventstring'][n])
      evstring[n] = str.replace('\00','').strip()
    return {'header': hdr, 'packets': data, 'eventstring': evstring}
  else:
    return {'header': hdr, 'packets': data}