def _Center_Velocity(field, data): """ Returns the center velocity for the current set center. """ global center dd = data.ds.all_data() center_vel = yt.YTArray(np.array([0.0, 0.0, 0.0]), 'cm/s') if center == 0 and ('gas', 'velocity_x') in data.ds.derived_field_list: if ('all', 'particle_mass') in data.ds.field_list: center_vel = dd.quantities.bulk_velocity(use_particles=True) else: center_vel = dd.quantities.bulk_velocity(use_particles=False) elif center == 0 and ('gas', 'velocity_x') not in data.ds.derived_field_list: center_vel = yt.YTArray([ np.sum(dd['velx'].in_units('cm/s').value), np.sum(dd['vely'].in_units('cm/s').value), np.sum(dd['velz'].in_units('cm/s').value) ], 'cm/s') else: center_vel = yt.YTArray([ dd['particle_velx'][center - 1].in_units('cm/s').value, dd['particle_vely'][center - 1].in_units('cm/s').value, dd['particle_velz'][center - 1].in_units('cm/s').value ], 'cm/s') del dd return center_vel
def _new_evolve_constant_density(fc, final_temperature=None, final_time=None, safety_factor=0.01): my_chemistry = fc.chemistry_data if final_temperature is None and final_time is None: raise RuntimeError("Must specify either final_temperature " + "or final_time.") data = defaultdict(list) current_time = 0.0 fc.calculate_cooling_time() dt = safety_factor * np.abs(fc["cooling_time"][0]) dt = safety_factor * 0.0005 * final_time fc.calculate_temperature() fc.calculate_cooling_time() dt = safety_factor * np.abs(fc["cooling_time"][0]) while True: if final_temperature is not None and fc["temperature"][ 0] <= final_temperature: break if final_time is not None and current_time >= final_time: break fc.calculate_temperature() print("Evolve constant density - t: %e s, rho: %e g/cm^3, T: %e K." % (current_time * my_chemistry.time_units, fc["density"][0] * my_chemistry.density_units, fc["temperature"][0])) fc.solve_chemistry(dt) for field in fc.density_fields: data[field].append(fc[field][0] * my_chemistry.density_units) data["energy"].append(fc["energy"][0]) fc.calculate_temperature() data["temperature"].append(fc["temperature"][0]) fc.calculate_pressure() data["pressure"].append(fc["pressure"][0]) data["time"].append(current_time * my_chemistry.time_units) current_time += dt for field in data: if field in fc.density_fields: data[field] = yt.YTArray(data[field], "g/cm**3") elif field == "energy": data[field] = yt.YTArray(data[field], "erg/g") elif field == "time": data[field] = yt.YTArray(data[field], "s") elif field == "temperature": data[field] = yt.YTArray(data[field], "K") elif field == "pressure": data[field] = yt.YTArray(data[field], "dyne/cm**2") else: data[field] = np.array(data[field]) return data
def cache(self): print(self.center) self.cached = True ad = self.ds.all_data() rsquaredParticles = np.power( ad['particle_position_x'] - self.center[0], 2) + np.power( ad['particle_position_y'] - self.center[1], 2) + np.power( ad['particle_position_z'] - self.center[2], 2) rsquaredCells = np.power(ad['x'] - self.center[0], 2) + np.power( ad['y'] - self.center[1], 2) + np.power(ad['z'] - self.center[2], 2) npts = 100 rs = yt.YTArray(np.power(10.0, np.linspace(-2, 0, npts)), 'kpc') ms = yt.YTArray(np.zeros(npts), 'msun') for i in range(npts): theseParticles = rsquaredParticles < rs[i] * rs[i] theseCells = rsquaredCells < rs[i] * rs[i] massInParticles = np.sum(ad['particle_mass'][theseParticles]) massInCells = np.sum(ad['cell_mass'][theseCells]) ms[i] = (massInParticles + massInCells).in_units('msun') print('rs: ', rs) print('ms: ', ms) print('log10(rs): ', np.log10(rs)) print('log10(ms): ', np.log10(ms)) print('rs limits: ', max(np.log10(rs)), min(np.log10(rs))) print('ms limits: ', max(np.log10(ms)), min(np.log10(ms))) self.f = scipy.interpolate.interp1d(np.log10(rs), np.log10(ms), kind='quadratic', fill_value="extrapolate")
def alignToAxis(particle, x, y, z): "aligns the coordinates of a particle with x, y and z" pos = np.asarray(particle[1]) vel = np.asarray(particle[2]) r = [np.dot(x, pos), np.dot(y, pos), np.dot(z, pos)] v = [np.dot(x, vel), np.dot(y, vel), np.dot(z, vel)] return [yt.YTArray(r, 'kpc'), yt.YTArray(v, 'km/s')]
def vmax_profile(ds, DDname, center, start_rad=5, end_rad=220., delta_rad=5): rs = np.arange(start_rad, end_rad, delta_rad) r_arr = zeros(len(rs)) m_arr = zeros(len(r_arr)) for rr, r in enumerate(rs): print(rr, r) r0 = ds.arr(r, 'kpc') r_arr[rr] = r0 critical_density = cosmo.critical_density(ds.current_redshift).value r0 = ds.arr(delta_rad, 'kpc') v_sphere = ds.sphere(center, r0) cell_mass, particle_mass = v_sphere.quantities.total_quantity( ["cell_mass", "particle_mass"]) m_arr[rr] = cell_mass.in_units('Msun') + particle_mass.in_units('Msun') m_arr = yt.YTArray(m_arr, 'Msun') r_arr = yt.YTArray(r_arr, 'kpc') to_save = {} to_save['m'] = m_arr to_save['r'] = r_arr G = yt.YTArray([c.G.value], 'm**3/kg/s**2') to_save['v'] = sqrt(2 * G * m_arr / r_arr).to('km/s') np.save( '/nobackupp2/rcsimons/foggie_momentum/catalogs/vescape/%s_%s_vescape.npy' % (DDname, simname), to_save)
def _Center_Velocity(field, data): """ Returns the center velocity for the current set center. """ global use_gas center_vel = yt.YTArray([0.0, 0.0, 0.0], 'cm/s') if ('gas', 'x') in data.ds.derived_field_list: center = get_center() dd = data.ds.all_data() if center == 0: if use_gas == False: try: center_vel = dd.quantities.bulk_velocity( use_particles=True, use_gas=False) except: center_vel = yt.YTArray([0.0, 0.0, 0.0], 'cm/s') else: try: center_vel = dd.quantities.bulk_velocity( use_particles=True) except: center_vel = dd.quantities.bulk_velocity( use_particles=False) else: particle_tag = np.argsort(dd['particle_tag']) center_tag = particle_tag[center - 1] center_vel = yt.YTArray([ dd['particle_velx'][center_tag].in_units('cm/s').value, dd['particle_vely'][center_tag].in_units('cm/s').value, dd['particle_velz'][center_tag].in_units('cm/s').value ], 'cm/s') set_center_vel(center_vel) return center_vel
def _Gravitational_Force_on_particles_z(field, data): """ Calculates the z component of the gravitational force on the sink particles """ try: dd = data.ds.all_data() F_z = yt.YTArray(np.zeros(np.shape(dd['particle_mass'])), 'cm*g/s**2') cell_mass = dd['cell_mass'].in_units('g') for part in range(len(dd['particle_mass'])): dx = dd['x'].in_units('cm') - dd['particle_posx'][part].in_units( 'cm') dy = dd['y'].in_units('cm') - dd['particle_posy'][part].in_units( 'cm') dz = dd['z'].in_units('cm') - dd['particle_posz'][part].in_units( 'cm') r = np.sqrt(dx**2. + dy**2. + dz**2.) F_z_arr = ((yt.physical_constants.G * dd['particle_mass'][part] * cell_mass) / r**3.) * dz F_z_tot = np.sum(F_z_arr) if len(dd['particle_mass']) > 1: dx = dd['particle_posx'].in_units( 'cm') - dd['particle_posx'][part].in_units('cm') dy = dd['particle_posy'].in_units( 'cm') - dd['particle_posy'][part].in_units('cm') dz = dd['particle_posz'].in_units( 'cm') - dd['particle_posz'][part].in_units('cm') r = np.sqrt(dx**2. + dy**2. + dz**2.) inds = np.argwhere(r != 0.0)[0] F_part = ((yt.physical_constants.G * dd['particle_mass'] * dd['particle_mass'][part]) / r**3.) * dz F_z_tot = F_z_tot + np.sum(F_part[inds]) F_z[part] = F_z_tot except: F_z = yt.YTArray([], 'cm*g/s**2') return F_z
def _Gravitational_Force_on_particles_Rad(field, data): """ The component of the gravitational force on the particles in the radial direction from the current center. """ try: dd = data.ds.all_data() center_pos = dd['Center_Position'] F_rad = yt.YTArray(np.zeros(np.shape(dd['particle_mass'])), 'cm*g/s**2') for part in range(len(dd['particle_mass'])): dx = center_pos[0].in_units( 'cm') - dd['particle_posx'][part].in_units('cm') dy = center_pos[1].in_units( 'cm') - dd['particle_posy'][part].in_units('cm') dz = center_pos[2].in_units( 'cm') - dd['particle_posz'][part].in_units('cm') r = np.array([dx.value, dy.value, dz.value]) F_x = dd['Gravitational_Force_on_particles_x'][part].value F_y = dd['Gravitational_Force_on_particles_y'][part].value F_z = dd['Gravitational_Force_on_particles_z'][part].value F = np.array([F_x, F_y, F_z]) F_proj = (np.dot(F, r) / np.dot(r, r)) * r F_mag = np.sqrt(F_proj[0]**2. + F_proj[1]**2. + F_proj[2]**2.) F_rad[part] = F_mag except: F_rad = yt.YTArray([], 'cm*g/s**2') return F_rad
def _rel_vel_2(_field, data): rel_vel = yt.YTArray([ data['velocity_x'] - yt.YTArray(center_vel[0], 'cm/s'), data['velocity_y'] - yt.YTArray(center_vel[1], 'cm/s'), data['velocity_z'] - yt.YTArray(center_vel[2], 'cm/s') ]) return yt.YTArray(np.tensordot(north, rel_vel, 1), 'cm/s')
def _CoM(field, data): """ Calculate the center of mass. Always includes particles where possible. """ TM = np.sum(data['cell_mass'].in_units('g')) x_top = yt.YTArray(0.0, 'cm*g') y_top = yt.YTArray(0.0, 'cm*g') z_top = yt.YTArray(0.0, 'cm*g') if ('all', 'particle_mass') in data.ds.field_list: TM = TM + np.sum(data['particle_mass'].in_units('g')) for part in range(len(data['particle_mass'])): x_top = x_top + data['particle_mass'][part].in_units( 'g') * data['particle_posx'][part].in_units('cm') y_top = y_top + data['particle_mass'][part].in_units( 'g') * data['particle_posy'][part].in_units('cm') z_top = z_top + data['particle_mass'][part].in_units( 'g') * data['particle_posz'][part].in_units('cm') x_top = x_top + np.sum( data['cell_mass'].in_units('g') * data['x'].in_units('cm')) y_top = y_top + np.sum( data['cell_mass'].in_units('g') * data['y'].in_units('cm')) z_top = z_top + np.sum( data['cell_mass'].in_units('g') * data['z'].in_units('cm')) com = [(x_top / TM), (y_top / TM), (z_top / TM)] com = yt.YTArray(com, 'cm') del x_top del y_top del z_top del TM return com
def write_total_box_time_series(filename,groupname,ts_data,field_list): # text f = h5py.File(filename, 'a') for field in field_list: yt.YTArray.write_hdf5(yt.YTArray(ts_data[field]),filename, dataset_name='/%s/%s' % (groupname,field)) # write centers yt.YTArray.write_hdf5(yt.YTArray(ts_data['centers']),filename, dataset_name='/%s/%s' % (groupname,'centers')) yt.YTArray.write_hdf5(yt.YTArray(ts_data['time']),filename, dataset_name='/%s/%s' % (groupname,'time')) f.close()
def _gammaenergydensity(field, data): #Fcal = 7e-2 energy = data['PartType0', 'CosmicRayEnergy'] energy = yt.YTArray(energy*2e53, "g*cm**2/s**2") mass = data['PartType0', 'Masses'].in_cgs() density = data['PartType0', 'Density'].in_cgs() crdensity = energy/mass*density tpi = 2e5/density*yt.YTArray(250.0,"g/cm**3") gammadensity = crdensity*0.25/tpi/3.2e7*0.7/3.0 return gammadensity
def write_energy_over_time_to_hdf5(filename, groupname, ts_data, field_list): f = h5py.File(filename, 'a') for field in field_list: yt.YTArray.write_hdf5(yt.YTArray(ts_data[field]),filename, dataset_name='/%s/%s' % (groupname,field)) # write centers yt.YTArray.write_hdf5(yt.YTArray(ts_data['centers']),filename, dataset_name='/%s/%s' % (groupname,'centers')) yt.YTArray.write_hdf5(yt.YTArray(ts_data['time']),filename, dataset_name='/%s/%s' % (groupname,'time')) f.close()
def getCMWeighted(snapObject, attribute, npArray=False, onlyStar=False): "calculates the center of mass velocity of the snap" V = np.array([ 0., 0., 0., ]) M = 0 if onlyStar == False: for particleType in ['dm', 'star', 'disk', 'bulge', 'gas', 'bndry']: try: i = 0 for v in eval('snapObject.' + particleType + attribute): m = eval('snapObject.' + particleType + \ 'Masses' + '[' + str(i) + ']') V += m * np.asarray(v) M += m i += 1 except AttributeError: print("There are no " + particleType + "-particles!") else: try: i = 0 for v in eval('snapObject.star' + attribute): m = snapObject.starMasses[i] V += m * np.asarray(v) M += m i += 1 except AttributeError: print("There are no " + particleType + "-particles!") if npArray == False: unit = getUnit(attribute) if M != 0: result = yt.YTArray(V * (1. / M), unit) return result else: return yt.YTArray([ 0., 0., 0., ], unit) else: if M != 0: result = V * (1. / M) return result else: return np.array([ 0., 0., 0., ])
def _sink_particle_age(field, data): """ Retrieve particle age from .snktxt file """ particle_age = [] if np.shape(data['x']) == (16, 16, 16): particle_age = yt.YTArray(np.array(particle_age), "yr") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) particle_age = (loaded_sink_data['snapshot_time']-loaded_sink_data['tcreate'])*data.ds.time_unit.in_units("yr").value particle_age = yt.YTArray(np.array(particle_age), "yr") return particle_age
def _sink_particle_tag(field, data): """ Retrieve particle tags from .snktxt file """ particle_tag = [] if np.shape(data['x']) == (16, 16, 16): particle_tag = yt.YTArray(np.array(particle_tag), "") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) particle_tag = np.arange(float(len(loaded_sink_data['x']))) particle_tag = yt.YTArray(np.array(particle_tag), "") return particle_tag
def _sink_particle_posz(field, data): """ Retrieve particle z position from .snktxt file """ particle_posz = [] if np.shape(data['x']) == (16, 16, 16): particle_posz = yt.YTArray(np.array(particle_posz), "pc") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) particle_posz = loaded_sink_data['z']*data.ds.length_unit.in_units("pc").value particle_posz = yt.YTArray(np.array(particle_posz), "pc") return particle_posz
def _sink_particle_mass(field, data): """ Retrieve particle mass from .snktxt file """ particle_mass = [] if np.shape(data['x']) == (16, 16, 16): particle_mass = yt.YTArray(np.array(particle_mass), "Msun") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) particle_mass = loaded_sink_data['m']*data.ds.mass_unit.in_units("Msun").value particle_mass = yt.YTArray(np.array(particle_mass), "Msun") return particle_mass
def _sink_particle_vely(field, data): """ Retrieve particle y velocity from .snktxt file """ particle_vely = [] if np.shape(data['x']) == (16, 16, 16): particle_vely = yt.YTArray(np.array(particle_vely), "km/s") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) particle_vely = loaded_sink_data['uy']*data.ds.velocity_unit.in_units("km/s").value particle_vely = yt.YTArray(np.array(particle_vely), "km/s") return particle_vely
def _sink_particle_accretion_rate(field, data): """ Retrieve particle accretion rate from sink file """ particle_mdot = [] if np.shape(data['x']) == (16, 16, 16): particle_mdot = yt.YTArray(np.array(particle_mdot), "Msun/yr") else: file_no = int(data.ds.directory.split('output_')[-1]) datadir = data.ds.directory.split('output_')[0] loaded_sink_data = rsink(file_no, datadir=datadir) numerator = loaded_sink_data['dm']*data.ds.mass_unit.in_units("Msun").value denominator = (loaded_sink_data['snapshot_time'] - loaded_sink_data['tflush'])*data.ds.time_unit.in_units("yr").value particle_mdot = numerator/denominator particle_mdot = yt.YTArray(np.array(particle_mdot), "Msun/yr") return particle_mdot
def _Center_Position(field, data): """ Returns the center position for the current set center. """ global use_gas center_pos = data.ds.domain_center if ('gas', 'x') in data.ds.derived_field_list: center = get_center() dd = data.ds.all_data() if center == 0: if use_gas == False: try: center_pos = dd.quantities.center_of_mass( use_particles=True, use_gas=False) except: center_pos = data.ds.domain_center else: try: center_pos = dd.quantities.center_of_mass( use_particles=True) except: center_pos = dd.quantities.center_of_mass( use_particles=False) else: particle_tag = np.argsort(dd['particle_tag']) center_tag = particle_tag[center - 1] center_pos = yt.YTArray([ dd['particle_posx'][center_tag].in_units('cm').value, dd['particle_posy'][center_tag].in_units('cm').value, dd['particle_posz'][center_tag].in_units('cm').value ], 'cm') set_center_pos(center_pos) return center_pos
def _B_gradient(field, data): """ Calculates the magnetic field gradient in the z direction """ if np.shape(data)[0] != 16: y = data['Squared_B_Mag'] #bin_data = np.abs(data['dz_from_Center'].in_units('cm') - (data['dz'].in_units('cm')/2.)) #x = np.abs(data['dz_from_Center'].in_units('cm')) bin_data = data['dz_from_Center'].in_units('cm') - ( data['dz'].in_units('cm') / 2) x = data['dz_from_Center'].in_units('cm') gradient = Gradient(x, y, bin_data) dB = yt.YTArray(np.abs(gradient), 'G**2/cm') else: dB = yt.YTArray(np.zeros(np.shape(data)), 'G**2/cm') return dB
def _kinetic_energy_total(field, data): bv = data.get_field_parameter('bulk_velocity') if bv is None: bv = yt.YTArray([0, 0, 0], 'cm/s') disp = (data['velocity_x'] - bv[0])**2 + ( data['velocity_y'] - bv[1])**2 + (data['velocity_z'] - bv[2])**2 return 0.5 * data['density_total'] * disp * data['cell_volume']
def reduceSnapToGalaxy(data, CM, radius, npArray=False): "reduces the data of a whole Zoom-in snap to only one galaxy" for particleType in ['dm', 'star', 'disk', 'bulge', 'gas', 'bndry']: try: temp = list() for particle in eval('data.' + particleType): if npArray == False: pos = yt.YTArray(particle[1], 'kpc') else: pos = particle[1] r = np.linalg.norm(CM - pos) if r <= radius: pos -= CM particle[1] = pos temp.append(particle) variableList = ['Masses', 'Coordinates', 'Velocities'] if particleType == 'gas' and data.gasTemperatures.size != 0: tempArrays = seperateList6D(temp, npArray) variableList.append('Density') variableList.append('SmoothingLength') variableList.append('Temperature') elif particleType == 'gas': tempArrays = seperateList5D(temp, npArray) variableList.append('Density') variableList.append('SmoothingLength') else: tempArrays = seperateList3D(temp, npArray) for i in range(len(variableList)): data.setVariable(tempArrays[i], particleType, variableList[i]) data.updateCombinedData(particleType) except AttributeError: print("there are no " + particleType + "-particles!") print("finished reducing the snap to Galaxy!")
def seperateList3D(listObject, npArray=False): "seperates 3D-list into 3 1D-arrays" array1 = list() array2 = list() array3 = list() for element in listObject: array1.append(element[0]) array2.append(element[1]) array3.append(element[2]) if npArray == False: return [yt.YTArray(array1, 'Msun'), \ yt.YTArray(array2, 'kpc'), \ yt.YTArray(array3, "km/s")] else: return [np.asarray(array1), np.asarray(array2), \ np.asarray(array3)]
def zoomIn(data, halo, ignoreH = False, npArray = False, \ PTCAM = ['gas', 'star'], PTCCM = ['star'], \ onlyDisk = False, diskHeight = np.inf, lengthUnit = 'Mpc', \ reduceToColdGas = False, Tmax = np.inf, dWAM = False): "Zooms in to halo" radius = halo[2] if npArray == False: CM = yt.YTArray(halo[3], 'kpc') else: CM = halo[3] print("Center of Galaxy: " + str(CM) + " [Mpc]") print("Virial Radius: " + str(radius) + " [Mpc]") sC.reduceSnapToGalaxy(data, CM, radius, npArray = npArray) print("There are " + str(data.starPositions.shape[0]) + " star particles left!") print("There are " + str(data.dmPositions.shape[0]) + " dm particles left!") print("There are " + str(data.gasPositions.shape[0]) + " gas particles left!") if reduceToColdGas == True: sC.reduceToColdGas(data, Tmax, npArray = npArray) if lengthUnit == 'Mpc': sC.MpcTokpc(data) sC.subtractCMWeighted(data, 'Velocities', npArray = npArray) sC.alignToHighestDensityGas(data, npArray = npArray, PTCCM = PTCCM) sC.alignToNewCS(data, sC.calculateAngularMomentum \ (data, PTCAM, densityWeighted = dWAM), \ npArray = npArray) if onlyDisk == True: sC.diskCut(data, diskHeight, npArray = npArray) print("successfully reduced gas to disk! There are " \ + str(data.gasPositions.shape[0]) + ' gas particles left!') print("successfully reduced stars to disk! There are " \ + str(data.starPositions.shape[0]) + ' star particles left!') return data
def dark_energy_density_field(field, data): yt_lambda_a = yt.YTArray(lambda_a, "g/cm**3") # print("-----yt lambda_a-----") # print(yt_lambda_a) # print("----------") # yt_lambda_a = YTArray([lambda_a]).in_units("g/cm**3") return ((yt_lambda_a[0]).in_units("g/cm**3"))
def _cosmicrayenergydensity(field, data): energy = data['PartType0', 'CosmicRayEnergy'] energy = yt.YTArray(1e10*Msun_in_g*km_in_cm*km_in_cm*erg_in_eV*energy,"eV") mass = data['PartType0', 'Masses'].in_cgs() density = data['PartType0', 'Density'].in_cgs() crdensity = energy/mass*density return crdensity
def _bhsed_sed(field, data): bhluminosity = data["bhluminosity"] nholes = len(bhluminosity) # get len of nu just for the 0th hole so we know how long the vector is log_lum_lsun = np.log10(bhluminosity[0].in_units("Lsun")) nu, l_band_vec = agn_spectrum(log_lum_lsun) nu = nu[0:-4] n_nu = len(nu) bh_sed = np.zeros([nholes, n_nu]) for i in range(nholes): log_lum_lsun = np.log10(bhluminosity[i].in_units("Lsun")) nu, l_band_vec = agn_spectrum(log_lum_lsun) l_band_vec = 10.**l_band_vec l_band_vec = l_band_vec[0:-4] for l in range(len(l_band_vec)): l_band_vec[l] = data.ds.quan(l_band_vec[l], "erg/s") bh_sed[i, :] = l_band_vec bh_sed = yt.YTArray(bh_sed, "erg/s") return bh_sed
def _Projected_Magnetic_Field(field, data): """ If the normal is [1,0,0] and there are two particles this calculates the projected magnetic field of the gas in the plane of their separation axis. If normal is set to something else, it calculates the projected """ global normal if normal != [1.0, 0.0, 0.0]: pos_vec = np.array([normal[1], -1 * normal[0]]) elif ('all', 'particle_mass') in data.ds.field_list: dd = data.ds.all_data() if len(dd['particle_mass']) == 2: pos_vec = np.array([ np.diff(dd[('all', 'particle_posx')].value)[0], np.diff(dd[('all', 'particle_posy')].value)[0] ]) else: pos_vec = np.array([0.0, -1.0]) del dd else: pos_vec = np.array([0.0, -1.0]) #pos_mag = np.sqrt(pos_vec[0]**2. + pos_vec[1]**2.) mags = np.array([data['magx'].value, data['magy'].value]) mags = mags.T c = ((np.dot(mags, pos_vec)) / (np.dot(pos_vec, pos_vec))) magx = pos_vec[0] * c magy = pos_vec[1] * c del c mags = np.sqrt(magx**2. + magy**2.) del magx del magy mags = yt.YTArray(mags, 'gauss') return mags