def _import_ytsurface(vertices, colors, alpha, emisses, colorindex, meshname='Steve', meshlocation=(0,0,0), plot_index=0): import numpy as np deselect_all() nftype = [("f1","int"),("f2","int"),("f3","int"),("f4","int")] newfaces = np.empty(int(len(vertices)/3.), dtype=nftype) # store sets of face colors cc = 0 for i in range(0,int(len(vertices)/3.)): newfaces[i] = (cc, cc+1, cc+2, cc) # repeat last for triangles cc = cc+3 me = bpy.data.meshes.new(meshname+"Mesh") ob = bpy.data.objects.new(meshname,me) ob.location = meshlocation # position object at 3d-cursor bpy.context.scene.objects.link(ob) # Link object to scene # Fill the mesh with verts, edges, faces me.from_pydata(vertices.tolist(),[],newfaces.tolist()) me.update(calc_edges=True) # Update mesh with new data # materials woop woop! obj = bpy.data.objects[meshname] bpy.context.scene.objects.active=obj for i in range(0,len(colors[0])): mat = makeMaterial(meshname+str(i)+'_'+str(plot_index), (colors[0][i],colors[1][i],colors[2][i]), (1,1,1), alpha, emisses[i]) setMaterial(obj,mat) # now, do individual mat indecies for i in range(0,len(newfaces)): me.polygons[i].material_index = colorindex[i]
def color(self,color): bpy.context.scene.objects.active = bpy.data.objects[self.__name] delete_unused_materials(self.__name) sphmat = makeMaterial(self.__name, color, (1,1,1), 1.0, 0.0) # no emissivity or transperency for now setMaterial(bpy.data.objects[self.__name], sphmat) self.__color = color
def import_ytsph(filename, halo_sizes, color_field, color_map, color_log, n_ref): from yt import load import numpy as np import bmesh from scienceutils import deselect_all from scienceutils import makeMaterial, setMaterial ds = load(filename) # strip "/" for naming xnn2 = 0 xnn = 0 # you only want the file name, not all the directory stuff while xnn != -1: xnn2 = xnn xnn = filename.find('/',xnn+1) fname_out = filename[xnn2+1:] # get coords and color data dd = ds.all_data() #xcoord = dd['Gas','Coordinates'][:,0].v #ycoord = dd['Gas','Coordinates'][:,1].v #zcoord = dd['Gas','Coordinates'][:,2].v xcoord = (dd['Gas','Coordinates'][:,0].in_units('unitary')).v ycoord = (dd['Gas','Coordinates'][:,1].in_units('unitary')).v zcoord = (dd['Gas','Coordinates'][:,2].in_units('unitary')).v cs = dd[color_field] print('cs') print(len(cs)) # map colorcode to 256 material colors if color_log: cs = np.log10(cs) mi, ma = cs.min(), cs.max() cs = (cs - mi) / (ma - mi) from yt.visualization._colormap_data import color_map_luts # import colors # the rgb colors colors = color_map_luts[color_map] x = np.mgrid[0.0:1.0:colors[0].shape[0]*1j] # how the values map to the colors color_index = (np.interp(cs,x,x)*(colors[0].shape[0]-1)).astype("uint8") color_index_list = color_index.tolist() name = [] hused = [] scale = [(1.0, 1.0, 1.0)] # create scale if necessary if len(scale[:][:]) < color_index.max(): # generate larger scale sc = (scale[0][0], scale[0][1], scale[0][2]) scale = [] for i in range(color_index.min(), color_index.max()): scale.append(sc) # also, allow for multiple halo sizes if len(halo_sizes) < color_index.max(): hs = halo_sizes[0] halo_sizes = [] for i in range(color_index.min(), color_index.max()): halo_sizes.append(hs) # create sph data into meshes and color them for ind in range(color_index.min(), color_index.max()): cl = [i for i,j in enumerate(color_index_list) if j == ind] print(ind) if len(cl) > 0: #print("particle name") #print(name) fname = fname_out + '_' + str(ind) name.append('particle_'+fname) hused.append(halo_sizes[ind]) me = bpy.data.meshes.new('particleMesh_'+fname) ob = bpy.data.objects.new('particle_'+fname,me) ob.location = (0,0,0) bpy.context.scene.objects.link(ob) # Link object to scene coords = [(0,0,0)] me.from_pydata(coords,[],[]) ob.location = (0,0,0) ob = bpy.data.objects['particle_'+fname] # select right object deselect_all() ob.select = True bpy.context.scene.objects.active=ob mat = makeMaterial('particle_'+fname, (colors[0][ind],colors[1][ind],colors[2][ind]), (1,1,1), 1.0, 1.0, mat_type = 'HALO', halo_size=halo_sizes[ind]) setMaterial(ob,mat) # add in verts bpy.ops.object.mode_set(mode='EDIT') # toggle to edit mode bm = bmesh.from_edit_mesh(ob.data) # now, find all verts with this color index (ind) # move original vertex to actual location if hasattr(bm.verts, "ensure_lookup_table"): # to make it work with 2.73 bm.verts.ensure_lookup_table() bm.verts[0].co = (xcoord[cl[0]]*scale[ind][0],ycoord[cl[0]]*scale[ind][1],zcoord[cl[0]]*scale[ind][2]) print('coords') print(xcoord[cl[0]], ycoord[cl[0]], zcoord[cl[0]]) print(len(cl)) print(len(xcoord)) for i in range(1,len(xcoord[cl])): bm.verts.new((xcoord[cl[i]]*scale[ind][0],ycoord[cl[i]]*scale[ind][1],zcoord[cl[i]]*scale[ind][2])) bmesh.update_edit_mesh(ob.data) bpy.ops.object.mode_set(mode='OBJECT') #print(ind) #print(bpy.data.objects['particle_' + fname].name) print(bpy.data.objects['particle_' + fname].location) #print("NAME OUT HERE") #print(name) return name, ds, hused
def new_particle_set(self, dfile, particle_num=1, colors=None, halo_sizes=None, scale=(1, 1, 1)): # initial file, number of particles, colors array import bmesh deselect_all() location = (0, 0, 0) # strip "/" and ".txt"s for names xnn2 = 0 xnn = 0 # you only want the file name, not all the directory stuff while xnn != -1: xnn2 = xnn xnn = dfile.find('/', xnn + 1) fname = dfile[xnn2 + 1:] # take out .txt stufftoo xnn = fname.find('.txt') fname = fname[0:xnn] pname = [] # create different particle types for p in range(0, particle_num): #print(p) num = "%02d" % (p) pname.append(fname + 'particle' + num) me = bpy.data.meshes.new(fname + 'particleMesh' + num) ob = bpy.data.objects.new(fname + 'particle' + num, me) ob.location = (0, 0, 0) bpy.context.scene.objects.link(ob) # Link object to scene coords = [(0, 0, 0)] me.from_pydata(coords, [], []) ob.location = (0, 0, 0) if colors is not None: color = colors[:][p] halo_size = halo_sizes[p] else: print('no color') color = (1, 1, 1) halo_size = 0.1 mat = makeMaterial(fname + 'particle' + num, color, (1, 1, 1), 1.0, 1.0, mat_type='HALO', halo_size=halo_size) setMaterial(ob, mat) # sets everything to material 0 by default ob = bpy.data.objects[fname + 'particle' + num] # select right object ob.select = True bpy.context.scene.objects.active = ob # now, add in different data types p2 = -1 # for toggling to object mode when using a different particle f = open(dfile, 'r') # open file for reading for i, line in enumerate(f): pint = int(p) #p = data["p"][i] # get type - o - particle linep = line.strip() # get rid of end line data = linep.split(",") # split into data based on ","'s p = float(data[4]) if p != p2: bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode num = "%02d" % (p) deselect_all() ob = bpy.data.objects[fname + 'particle' + num] # select right object ob.select = True bpy.context.scene.objects.active = ob bpy.ops.object.mode_set(mode='EDIT') # toggle to edit mode bm = bmesh.from_edit_mesh(ob.data) if p != p2: # if first instance - move origional if hasattr(bm.verts, "ensure_lookup_table"): # to make it work with 2.73 bm.verts.ensure_lookup_table() bm.verts[0].co = (float(data[1]) * scale[pint][0], float(data[2]) * scale[pint][1], float(data[3]) * scale[pint][2]) p2 = p else: bm.verts.new((float(data[1]) * scale[pint][0], float(data[2]) * scale[pint][1], float(data[3]) * scale[pint][2])) f.close() # close up the file # update all meshes for p in range(0, particle_num): deselect_all() bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode num = "%02d" % (p) ob = bpy.data.objects[fname + 'particle' + num] # select right object ob.select = True bpy.context.scene.objects.active = ob bpy.ops.object.mode_set(mode='EDIT') # toggle to edit mode bmesh.update_edit_mesh(ob.data) bpy.ops.object.mode_set(mode='OBJECT') # toggle to edit mode return pname
def __init__(self, filelist, scale=(1.0,1.0,1.0), halo_sizes=None, particle_num=1, particle_colors=[(1,1,1)], # halo_sizes = [0.0008] isosurface_value = None, surf_type='sphere', radius = 10.0, radius_units = "mpc", surface_field="density", meshname = 'Allen', factor=1.0, transparency = 1.0, dist_fac = None, color_field = None, emit_field = None, color_map = "algae", color_log = True, emit_log = True, plot_index = None, color_field_max = None, color_field_min = None, emit_field_max = None, emit_field_min = None, emissivity_units = None, n_ref=8, domainbox=True, force_override=False): ifile = 0 location = (0,0,0) particle_hide = [] if isinstance(halo_sizes, tuple): hs = [] for h in halo_sizes: hs.append(h) halo_sizes = hs # format halo sizes if isinstance(halo_sizes, float): halo_sizes = [halo_sizes] # reformat if a single string if isinstance(filelist,str): filelist = [filelist] # how long is the file? filelistlength = len(filelist) # now, figure out the file type based on the extention... for now if filelist[ifile].find('.obj') is not -1: filetype = 'obj' elif filelist[ifile].find('.txt') is not -1: filetype = 'sphtxt' else: # default behavior is to assume we are dealing with yt files filetype = 'yt' # now, load if single file in all cases # -> only file for single case, first file for many files if filetype is 'obj': name = self.load_obj(filelist[ifile]) ds = [] elif filetype is 'sphtxt': scale = [scale] ds = [] if len(halo_sizes) < particle_num: hs = halo_sizes[0] halo_sizes = [] for i in range(0,particle_num): halo_sizes.append(hs) for i in range(0,particle_num): scale.append(scale[0]) name = self.new_particle_set(filelist[ifile], particle_num, particle_colors, halo_sizes, scale) elif filetype is 'yt': # figure out what sorts of yt data we are dealing with - amr or sph? from yt import load ds = load(filelist[ifile]) ds.index # we need to do this for some reason... if (ds.dataset_type.find('flash') != -1) or (ds.dataset_type.find('enzo') != -1) or (ds.dataset_type.find('athena') != -1): filetype = 'ytamr' # this supports surfaces name = [meshname + '_0'] # only make isosurfaces if we have asked for them if isosurface_value is not None: ds = objects.import_ytsurface(filelist[ifile], isosurface_value, surf_type, radius, radius_units, surface_field, meshname, transparency, dist_fac, color_field, emit_field, color_map, color_log, emit_log, plot_index, color_field_max, color_field_min, emit_field_max, emit_field_min, emissivity_units, force_override) location = ds.domain_center.in_units('unitary')*overall_scale bpy.data.objects[name[0]].location = location else: isosurface_value = 0.0 if domainbox: # add something about file to name kk = (filelist[ifile]).rfind('/') name = ['DomainBox_' + (filelist[ifile])[kk+1:]] flagg = True for ob in bpy.data.objects: if ob.name.find(name[0]) != -1: name = [ob.name + '_1'] print("Hey man, relax, we are just loading the file via yt.load") print(" here is a nice domain box of your grid sim") bpy.ops.mesh.primitive_cube_add(radius=1.0) bpy.ops.object.modifier_add(type='WIREFRAME') # make wireframe #bpy.data.objects['Cube'].name = name[0] bpy.context.active_object.name = name[0] bpy.data.objects[name[0]].location = ds.domain_center.in_units('unitary')*overall_scale # scaling things for your domain box # you need to divide by 2 since scale = 1 means a box takes up 2 BU blocks boxscalings = (ds.domain_right_edge-ds.domain_left_edge).in_units('unitary')*overall_scale bpy.data.objects[name[0]].scale = (scale[0]/2.*boxscalings[0], scale[1]/2.*boxscalings[1], scale[2]/2.*boxscalings[2]) location = bpy.data.objects[name[0]].location scale = (bpy.data.objects[name[0]].scale[0],bpy.data.objects[name[0]].scale[1],bpy.data.objects[name[0]].scale[2]) #scale = [scale] self.__name = name # futz with naming if multiple surfaces if isinstance(isosurface_value, float): isosurface_value = [isosurface_value] location = [location] filelist = [filelist] filetype = [filetype] filelistlength = [filelistlength] scale = [scale] if len(isosurface_value) > 1: location = [location] filelist = [filelist] filetype = [filetype] filelistlength = [filelistlength] scale = [scale] for i in range(1,len(isosurface_value)): name.append(meshname + '_' + str(i)) location.append(location[0]) filelist.append(filelist[0]) filetype.append(filetype[0]) filelistlength.append(filelistlength[0]) scale.append(scale[0]) #elif (ds.dataset_type is 'tipsy'): elif (ds.dataset_type.find('tipsy') != -1): filetype = 'ytsph' if halo_sizes is not None: name, ds, halo_sizes = objects.import_ytsph(filelist[ifile], halo_sizes, color_field, color_map, color_log, n_ref) #location = ds.domain_center.in_units('unitary')*overall_scale #print(name) #print(bpy.data.objects[name[len(name)-1]]) else: if domainbox: kk = (filelist[ifile]).rfind('/') name = ['DomainBox_' + (filelist[ifile])[kk+1:]] flagg = True for ob in bpy.data.objects: if ob.name.find(name[0]) != -1: name = [ob.name + '_1'] print("Hey man, relax, we are just loading the file via yt.load") print(" here is a nice domain box of your sph sim") bpy.ops.mesh.primitive_cube_add(radius=1.0) bpy.ops.object.modifier_add(type='WIREFRAME') # make wireframe bpy.context.active_object.name = name[0] # scaling things for your domain box bpy.data.objects[name[0]].location = ( (ds.domain_right_edge.in_units('unitary')-ds.domain_left_edge.in_units('unitary'))*0.5+ds.domain_left_edge.in_units('unitary') )*overall_scale # sometimes no center for particle data? # scaling things for your domain box # you need to divide by 2 since scale = 1 means a box takes up 2 BU blocks boxscalings = (ds.domain_right_edge-ds.domain_left_edge).in_units('unitary')*overall_scale bpy.data.objects[name[0]].scale = (scale[0]/2.*boxscalings[0], scale[1]/2.*boxscalings[1], scale[2]/2.*boxscalings[2]) location = bpy.data.objects[name[0]].location scale = [(bpy.data.objects[name[0]].scale[0],bpy.data.objects[name[0]].scale[1],bpy.data.objects[name[0]].scale[2])] self.__name = name mat = makeMaterial(name[0], (0,0,0), (1,1,1), 1.0, 1.0, mat_type = 'HALO', halo_size=0.008) #ob = bpy.data.objects[name[0]] #setMaterial(ob,mat) else: print("SORRY! Other yt data formats aren't supported yet! :(") else: print("DATA FORMAT NOT SUPPORTED!!!!") if isinstance(name, str): name = [name] location = [location] filelist = [filelist] filetype = [filetype] filelistlength = [filelistlength] scale = [scale] # or if sph, for # of particles # please note: THIS IS SLIGHTLY HACKTACULAR if filetype is 'sphtxt': #if isinstance(filelist,str): filelist=[filelist] filelistlength = [filelistlength] filetype = [filetype] location = [] particle_hide = [] #scale = [scale] for i in range(0,particle_num): location.append((0,0,0)) particle_hide.append(False) #scale.append(scale[0]) if filetype is 'ytsph': filelist=[filelist] filelistlength = [filelistlength] filetype = [filetype] location = [] particle_hide = [] for i in range(0,len(name)): location.append((0,0,0)) particle_hide.append(False) if isinstance(scale, tuple): scale = [scale] scale.append(scale[0]) self.filetype = filetype self.__name = name # return the name of the thing too #print(name) #print(bpy.data.objects[name[len(name)-1]].name) self.name = name self.location = location self.filelist = filelist self.filelistlength = filelistlength self.scale = scale self.__ifile = 0 self.isosurface_value = isosurface_value self.surf_type = surf_type self.radius = radius self.radius_units = radius_units self.surface_field = surface_field self.transparency = transparency self.dist_fac = dist_fac self.color_field = color_field self.emit_field = emit_field self.color_map = color_map self.color_log = color_log self.emit_log = emit_log self.plot_index = plot_index self.color_field_max = color_field_max self.color_field_min = color_field_min self.emit_field_max = emit_field_max self.emit_field_min = emit_field_min self.emissivity_units = emissivity_units self.particle_num = particle_num self.particle_colors = particle_colors if halo_sizes is None: halo_sizes = [0.0] self.__halo_sizes = halo_sizes self.halo_sizes = halo_sizes self.particle_hide = particle_hide self.ds = ds self.color_field = color_field self.color_map = color_map self.n_ref = n_ref
def __init__(self, ds, image_name="ytProjectionImage", axis='z', variable=('gas', 'temperature'), weight_variable=('gas', 'density'), center=[0.0, 0.0, 0.0], width=10.0, units='kpc', color_map='algae', show_annotations=False): from yt import ProjectionPlot, OffAxisProjectionPlot if (axis != 'z') and (axis != 'y') and (axis != 'x'): p = OffAxisProjectionPlot(ds, axis, variable, width=(width, units), weight_field=weight_variable) #plot = p.plots[variable] #fig = plot.figure #f = BytesIO() #vv = yt.write_image(np.log10(p.frb[variable][:,:-1].d),f, cmap_name = color_map) p.hide_axes() p.hide_colorbar() p.set_cmap(variable, color_map) p._setup_plots() plot = p.plots[variable] plot.canvas.draw() buff = plot.canvas.tostring_argb() ncols, nrows = plot.canvas.get_width_height() vv = np.fromstring(buff, dtype=np.uint8).reshape((nrows, ncols, 4), order="C") if show_annotations: p = OffAxisProjectionPlot(ds, axis, variable, width=(width, units), weight_field=weight_variable) p.set_cmap(variable, color_map) p._setup_plots() plot = p.plots[variable] plot.canvas.draw() buff2 = plot.canvas.tostring_argb() ncols2, nrows2 = plot.canvas.get_width_height() vv2 = np.fromstring(buff2, dtype=np.uint8).reshape( (nrows2, ncols2, 4), order="C") #plot.canvas.draw() #buff = plot.canvas.tostring_argb() #ncols2, nrows2 = plot.canvas.get_width_height() #vv2 = np.fromstring(buff, dtype=np.uint8).reshape((nrows2, ncols2, 4), order="C") else: p = ProjectionPlot(ds, axis, variable, center=center, width=(width, units), weight_field=weight_variable) #plot = p.plots[variable] #fig = plot.figure #f = BytesIO() #vv = yt.write_image(np.log10(p.frb[variable][:,:-1].d),f, cmap_name = color_map) p.hide_axes() p.hide_colorbar() p.set_cmap(variable, color_map) p._setup_plots() plot = p.plots[variable] plot.canvas.draw() buff = plot.canvas.tostring_argb() ncols, nrows = plot.canvas.get_width_height() vv = np.fromstring(buff, dtype=np.uint8).reshape((nrows, ncols, 4), order="C") if show_annotations: p = ProjectionPlot(ds, axis, variable, center=center, width=(width, units), weight_field=weight_variable) p.set_cmap(variable, color_map) p._setup_plots() plot = p.plots[variable] plot.canvas.draw() buff2 = plot.canvas.tostring_argb() ncols2, nrows2 = plot.canvas.get_width_height() vv2 = np.fromstring(buff2, dtype=np.uint8).reshape( (nrows2, ncols2, 4), order="C") #plot.canvas.draw() #buff = plot.canvas.tostring_argb() #ncols2, nrows2 = plot.canvas.get_width_height() #vv2 = np.fromstring(buff, dtype=np.uint8).reshape((nrows2, ncols2, 4), order="C") ncols = vv.shape[1] nrows = vv.shape[0] # delete if already there for im in bpy.data.images: if im.name == image_name: delete_unused_images(image_name) delete_unused_textures(image_name) delete_unused_materials(image_name) # for annotations for im in bpy.data.images: if im.name == image_name + '_ann': delete_unused_images(image_name + '_ann') delete_unused_textures(image_name + '_ann') delete_unused_materials(image_name + '_ann') # switching a from back to front, and flipping image # if also with annotation do a nice one in the domain pixels_tmp = np.array(vv) for i in range(0, nrows): #pixels_tmp[i,:,0] = vv[i,:,0] #pixels_tmp[i,:,1] = vv[i,:,1] #pixels_tmp[i,:,2] = vv[i,:,2] #pixels_tmp[i,:,3] = vv[i,:,3] pixels_tmp[i, :, 3] = vv[nrows - 1 - i, :, 0] pixels_tmp[i, :, 0] = vv[nrows - 1 - i, :, 1] pixels_tmp[i, :, 1] = vv[nrows - 1 - i, :, 2] pixels_tmp[i, :, 2] = vv[nrows - 1 - i, :, 3] if show_annotations: pixels_tmp2 = np.array(vv2) if show_annotations: for i in range(0, nrows2): pixels_tmp2[i, :, 3] = vv2[nrows2 - 1 - i, :, 0] pixels_tmp2[i, :, 0] = vv2[nrows2 - 1 - i, :, 1] pixels_tmp2[i, :, 1] = vv2[nrows2 - 1 - i, :, 2] pixels_tmp2[i, :, 2] = vv2[nrows2 - 1 - i, :, 3] # blank image image = bpy.data.images.new(image_name, width=ncols, height=nrows) if show_annotations: image2 = bpy.data.images.new(image_name + '_ann', width=ncols2, height=nrows2) pixels = pixels_tmp.ravel() / 255. #pixels = vv.ravel()/255. if show_annotations: pixels2 = pixels_tmp2.ravel() / 255. image.pixels = pixels if show_annotations: image2.pixels = pixels2 # activate the image in the uv editor for area in bpy.context.screen.areas: if area.type == 'IMAGE_EDITOR': if show_annotations: area.spaces.active.image = image2 else: area.spaces.active.image = image elif area.type == 'VIEW_3D': # make sure material/render view is on for space in area.spaces: if space.type == 'VIEW_3D': if (space.viewport_shade != 'RENDERED') and ( space.viewport_shade != 'MATERIAL'): space.viewport_shade = 'RENDERED' # material is too slow # also, attach to the projection in the blender 3d window # now, set color figmat = makeMaterial(image_name, (0, 0, 0), (1, 1, 1), 1.0, 0.0) # no emissivity or transperency for now setMaterial(bpy.data.objects[image_name], figmat) # also, make shadeless bpy.data.materials[image_name].use_shadeless = True # Create image texture from image cTex = bpy.data.textures.new(image_name, type='IMAGE') cTex.image = image # Add texture slot for color texture mat = bpy.data.materials[image_name] mtex = mat.texture_slots.add() mtex.texture = cTex #mtex.texture_coords = 'UV' mtex.texture_coords = 'OBJECT' # this seems to work better for figures, but certainly needs to be tested mtex.use_map_color_diffuse = True mtex.use_map_color_emission = True mtex.emission_color_factor = 0.5 mtex.use_map_density = True mtex.mapping = 'FLAT' # map to object mtex.object = bpy.data.objects[image_name]