def parse_trace(fname): ''' Parse McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' color = 0 # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False xstate = [] ystate = [] zstate = [] circlePoints = vtk.vtkPoints() circleLines = vtk.vtkCellArray() circle_pid = 0 multiPoints = vtk.vtkPoints() multiLines = vtk.vtkCellArray() multi_pid = 0 neutronPoints = vtk.vtkPoints() neutronLines = vtk.vtkCellArray() neutron_pid = 0 f = open(fname, 'r') lines = f.readlines() for i, line in enumerate(lines): if not line: break line = line.strip() # register components if line.startswith(UC_COMP): # grab info line info = lines[i + 1] assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3 + 9]]).reshape(3, 3) comps[name] = (pos, rot) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) points.pop(0) coords = rotate_points(points, comp) beg = multi_pid for p in coords: multiPoints.InsertNextPoint(p) multi_pid += 1 end = multi_pid for idx in range(beg, end - 1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0, idx) vline.GetPointIds().SetId(1, idx + 1) multiLines.InsertNextCell(vline) # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) coords = draw_circle(pla, pos, rad, comp) beg = circle_pid for p in coords: circlePoints.InsertNextPoint(p) circle_pid += 1 end = circle_pid for idx in range(beg, end - 1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0, idx) vline.GetPointIds().SetId(1, idx + 1) circleLines.InsertNextCell(vline) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color = 0 xstate = [] ystate = [] zstate = [] # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): coords = np.column_stack([xstate, ystate, zstate]) beg = neutron_pid for p in coords: neutronPoints.InsertNextPoint(p) neutron_pid += 1 end = neutron_pid for idx in range(beg, end - 1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0, idx) vline.GetPointIds().SetId(1, idx + 1) neutronLines.InsertNextCell(vline) active = False prev = None elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':') + 1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: xstate.append(xyz[0]) ystate.append(xyz[1]) zstate.append(xyz[2]) prev = xyz xstate.append(prev[0]) ystate.append(prev[1]) zstate.append(prev[2]) f.close() circlePolydata = vtk.vtkPolyData() circlePolydata.SetPoints(circlePoints) circlePolydata.SetLines(circleLines) circle_mapper = vtk.vtkPolyDataMapper() try: circle_mapper.SetInputData(circlePolydata) # VTK Python >= 6 except: circle_mapper.SetInput(circlePolydata) # VTK Python >= 5.8 circle_actor = vtk.vtkActor() circle_actor.SetMapper(circle_mapper) circle_actor.GetProperty().SetAmbient(0.2) circle_actor.GetProperty().SetDiffuse(0.5) circle_actor.GetProperty().SetSpecular(0.3) circle_actor.GetProperty().SetColor(0, 0.7, 0.7) circle_actor.GetProperty().SetLineWidth(3) multiPolydata = vtk.vtkPolyData() multiPolydata.SetPoints(multiPoints) multiPolydata.SetLines(multiLines) multi_mapper = vtk.vtkPolyDataMapper() try: multi_mapper.SetInputData(multiPolydata) except: multi_mapper.SetInput(multiPolydata) multi_actor = vtk.vtkActor() multi_actor.SetMapper(multi_mapper) multi_actor.GetProperty().SetAmbient(0.2) multi_actor.GetProperty().SetDiffuse(0.5) multi_actor.GetProperty().SetSpecular(0.3) multi_actor.GetProperty().SetColor(1, 0, 0.5) multi_actor.GetProperty().SetLineWidth(3) neutronPolydata = vtk.vtkPolyData() neutronPolydata.SetPoints(neutronPoints) neutronPolydata.SetLines(neutronLines) neutron_mapper = vtk.vtkPolyDataMapper() try: neutron_mapper.SetInputData(neutronPolydata) except: neutron_mapper.SetInput(neutronPolydata) neutron_actor = vtk.vtkActor() neutron_actor.SetMapper(neutron_mapper) neutron_actor.GetProperty().SetAmbient(0.2) neutron_actor.GetProperty().SetDiffuse(0.5) neutron_actor.GetProperty().SetSpecular(0.3) neutron_actor.GetProperty().SetColor(1, 1, 1) neutron_actor.GetProperty().SetLineWidth(2) renderer = vtk.vtkRenderer() renderer.AddActor(circle_actor) renderer.AddActor(multi_actor) renderer.AddActor(neutron_actor) renderer.SetBackground(0, 0, 0) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) iren.SetRenderWindow(renwin) iren.Initialize() renwin.Render() iren.Start()
def parse_trace(): ''' Parse McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure(figsize=plt.figaspect(0.5)*1.5) ax = fig.gca(projection='3d') ax.set_xlabel("z") ax.set_ylabel("x") ax.set_zlabel("y") ax.set_aspect('equal') # ax.autoscale_view(scalex=False, scaley=False, scalez=False) color = 0 # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3,3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False xstate=[] ystate=[] zstate=[] while True: # read line line = get_line() if not line: break # register components if line.startswith(UC_COMP): # grab info line info = get_line() assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3+9]]).reshape(3, 3) comps[name] = (pos, rot) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) start = points.pop(0) (x, y, z) = rotate_points(points, comp) ax.plot(z, x, y) # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) (x,y,z) = draw_circle(pla, pos, rad, comp) ax.plot(z, x, y) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color = 0 xstate=[] ystate=[] zstate=[] # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): ax.plot(zstate, xstate, ystate) active = False prev = None elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':')+1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: xstate.append(xyz[0]) ystate.append(xyz[1]) zstate.append(xyz[2]) prev = xyz xstate.append(prev[0]) ystate.append(prev[1]) zstate.append(prev[2]) # kick out legacy "junk" elif line.startswith(MC_MAGNIFY) or line.startswith(MC_START) or line.startswith(MC_END) or line.startswith(MC_STOP): continue else: print line # A little bit of logic for controlling the aspect ratios/view (xmin, xmax)=ax.get_xlim3d() (ymin, ymax)=ax.get_ylim3d() (zmin, zmax)=ax.get_zlim3d() dx = xmax - xmin dy = ymax - ymin dz = zmax - zmin dmax=max(dx,dy,dz) # Check ranges and define axis box of max length cubed if dmax > dx: mean=(xmax+xmin)/2 xmin=mean-dmax/2 xmax=mean+dmax/2 if dmax > dy: mean=(ymax+ymin)/2 ymin=mean-dmax/2 ymax=mean+dmax/2 if dmax > dz: mean=(zmax+zmin)/2 zmin=mean-dmax/2 zmax=mean+dmax/2 # Set new axis limits ax.set_xlim3d(xmin,xmax) ax.set_ylim3d(ymin,ymax) ax.set_zlim3d(zmin,zmax) plt.show()
def parse_trace(fname): ''' Parse McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' color = 0 # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3,3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False xstate=[] ystate=[] zstate=[] circlePoints = vtk.vtkPoints() circleLines = vtk.vtkCellArray() circle_pid = 0 multiPoints = vtk.vtkPoints() multiLines = vtk.vtkCellArray() multi_pid = 0 neutronPoints = vtk.vtkPoints() neutronLines = vtk.vtkCellArray() neutron_pid = 0 f = open(fname, 'r') lines = f.readlines() for i, line in enumerate(lines): if not line: break line = line.strip() # register components if line.startswith(UC_COMP): # grab info line info = lines[i+1] assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3+9]]).reshape(3, 3) comps[name] = (pos, rot) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) points.pop(0) coords = rotate_points(points, comp) beg = multi_pid for p in coords: multiPoints.InsertNextPoint(p) multi_pid += 1 end = multi_pid for idx in range(beg, end-1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0,idx) vline.GetPointIds().SetId(1,idx +1) multiLines.InsertNextCell(vline) # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) coords = draw_circle(pla, pos, rad, comp) beg = circle_pid for p in coords: circlePoints.InsertNextPoint(p) circle_pid += 1 end = circle_pid for idx in range(beg, end-1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0,idx) vline.GetPointIds().SetId(1,idx +1) circleLines.InsertNextCell(vline) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color = 0 xstate=[] ystate=[] zstate=[] # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): coords = np.column_stack([xstate, ystate, zstate]) beg = neutron_pid for p in coords: neutronPoints.InsertNextPoint(p) neutron_pid += 1 end = neutron_pid for idx in range(beg, end-1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0,idx) vline.GetPointIds().SetId(1,idx +1) neutronLines.InsertNextCell(vline) active = False prev = None elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':')+1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: xstate.append(xyz[0]) ystate.append(xyz[1]) zstate.append(xyz[2]) prev = xyz xstate.append(prev[0]) ystate.append(prev[1]) zstate.append(prev[2]) f.close() circlePolydata =vtk.vtkPolyData() circlePolydata.SetPoints(circlePoints) circlePolydata.SetLines(circleLines) circle_mapper = vtk.vtkPolyDataMapper() try: circle_mapper.SetInputData(circlePolydata) # VTK Python >= 6 except: circle_mapper.SetInput(circlePolydata) # VTK Python >= 5.8 circle_actor = vtk.vtkActor() circle_actor.SetMapper(circle_mapper) circle_actor.GetProperty().SetAmbient(0.2) circle_actor.GetProperty().SetDiffuse(0.5) circle_actor.GetProperty().SetSpecular(0.3) circle_actor.GetProperty().SetColor(0,0.7,0.7) circle_actor.GetProperty().SetLineWidth(3) multiPolydata =vtk.vtkPolyData() multiPolydata.SetPoints(multiPoints) multiPolydata.SetLines(multiLines) multi_mapper = vtk.vtkPolyDataMapper() try: multi_mapper.SetInputData(multiPolydata) except: multi_mapper.SetInput(multiPolydata) multi_actor = vtk.vtkActor() multi_actor.SetMapper(multi_mapper) multi_actor.GetProperty().SetAmbient(0.2) multi_actor.GetProperty().SetDiffuse(0.5) multi_actor.GetProperty().SetSpecular(0.3) multi_actor.GetProperty().SetColor(1,0,0.5) multi_actor.GetProperty().SetLineWidth(3) neutronPolydata =vtk.vtkPolyData() neutronPolydata.SetPoints(neutronPoints) neutronPolydata.SetLines(neutronLines) neutron_mapper = vtk.vtkPolyDataMapper() try: neutron_mapper.SetInputData(neutronPolydata) except: neutron_mapper.SetInput(neutronPolydata) neutron_actor = vtk.vtkActor() neutron_actor.SetMapper(neutron_mapper) neutron_actor.GetProperty().SetAmbient(0.2) neutron_actor.GetProperty().SetDiffuse(0.5) neutron_actor.GetProperty().SetSpecular(0.3) neutron_actor.GetProperty().SetColor(1,1,1) neutron_actor.GetProperty().SetLineWidth(2) renderer = vtk.vtkRenderer() renderer.AddActor(circle_actor) renderer.AddActor(multi_actor) renderer.AddActor(neutron_actor) renderer.SetBackground(0, 0, 0) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) iren.SetRenderWindow(renwin) iren.Initialize() renwin.Render() iren.Start()
def parse_trace(csv_comps, csv_lines): ''' Prase McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' color = 0 def out_point((p_x, p_y, p_z)): ''' Write a line to csv_lines ''' csv_lines.write('%s, %s, %s, %s\n' % (p_x, p_y, p_z, color)) # print headers csv_comps.write('name, x, y, z\n') csv_lines.write('x, y, z, c\n') # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3,3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False while True: # read line line = get_line() if not line: break # register components if line.startswith(UC_COMP): # grab info line info = get_line() assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3+9]]).reshape(3, 3) comps[name] = (pos, rot) csv_comps.write('%s, %s, %s, %s\n' % ((name,) + tuple(pos))) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) start = points.pop(0) while points: end = points.pop(0) for point in (start, end): out_point(rotate(point, comp)) start = end # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) draw_circle(pla, pos, rad, comp, out_point) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color += 1 # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): active = False elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':')+1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: out_point(prev) out_point(xyz) prev = xyz
def parse_trace(csv_comps, csv_lines): ''' Prase McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' color = 0 def out_point((p_x, p_y, p_z)): ''' Write a line to csv_lines ''' csv_lines.write('%s, %s, %s, %s\n' % (p_x, p_y, p_z, color)) # print headers csv_comps.write('name, x, y, z\n') csv_lines.write('x, y, z, c\n') # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False while True: # read line line = get_line() if not line: break # register components if line.startswith(UC_COMP): # grab info line info = get_line() assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3 + 9]]).reshape(3, 3) comps[name] = (pos, rot) csv_comps.write('%s, %s, %s, %s\n' % ((name, ) + tuple(pos))) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) start = points.pop(0) while points: end = points.pop(0) for point in (start, end): out_point(rotate(point, comp)) start = end # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) draw_circle(pla, pos, rad, comp, out_point) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color += 1 # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): active = False elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':') + 1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: out_point(prev) out_point(xyz) prev = xyz
def parse_trace(world, fp=sys.stdin, inspectComp=None): """ Prase McStas trace output from stdin and write result to output """ color = 0 # def out_point((p_x, p_y, p_z)): # ''' Write a line to csv_lines ''' # csv_lines.write('%s, %s, %s, %s\n' % (p_x, p_y, p_z, color)) # print headers # csv_comps.write('name, x, y, z\n') # csv_lines.write('x, y, z, c\n') # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3)) compName = "" # we are following a neutron active = False # we need to draw the neutron (it passed the "check-point"/inspect component) inspect = False # list of observed neutron positions neutron = [] # skip next neutron position skip = False # total count of drawed neutrons neutrons_drawed = 0 while True: # read line line = get_line(fp) if line is None: break # register components if line.startswith(UC_COMP): # grab info line info = get_line(fp) assert info[:4] == "POS:" nums = [x.strip() for x in info[4:].split(",")] # extract fields name = line[len(UC_COMP) :].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3 : 3 + 9]]).reshape(3, 3) comps[name] = (pos, rot) # csv_comps.write('%s, %s, %s, %s\n' % ((name,) + tuple(pos))) # switch perspective elif line.startswith(MC_COMP): color += 1 name = line[len(MC_COMP) + 1 :].strip() compName = name comp = comps[name] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1 :].strip('"') compName = name comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE) :].strip("()")) world.drawLine((rotate(p, comp) for p in points), color=getColor(color)) # process circle elif line.startswith(MC_CIRCLE): xyz = "xyz" items = line[len(MC_CIRCLE) :].strip("()").split(",") # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) points = draw_circle(pla, pos, rad, comp) world.drawLine(points, color=getColor(color)) # activate neutron when it enters elif line.startswith(MC_ENTER): neutron = [] skip = True active = True inspect = False color += 1 # deactivate neutron when it leaves elif line.startswith(MC_LEAVE) or line.startswith(MC_ABSORB): active = False if inspectComp is None or inspect: world.drawLine(neutron, color="1 0 0") neutrons_drawed += 1 # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue if inspectComp and inspectComp == compName: # We will draw this neutron! inspect = True # keep track of points the neutron passes through xyz = [float(x) for x in line[line.find(":") + 1 :].split(",")[:3]] xyz = rotate(xyz, comp) neutron.append(xyz) print "Neutrons drawed:", neutrons_drawed, (inspectComp and "(reaching %s)" % inspectComp or "(all)") return world
def parse_trace(world, fp=sys.stdin, inspectComp=None): ''' Prase McStas trace output from stdin and write result to output ''' color = 0 # def out_point((p_x, p_y, p_z)): # ''' Write a line to csv_lines ''' # csv_lines.write('%s, %s, %s, %s\n' % (p_x, p_y, p_z, color)) # print headers # csv_comps.write('name, x, y, z\n') # csv_lines.write('x, y, z, c\n') # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3)) compName = "" # we are following a neutron active = False # we need to draw the neutron (it passed the "check-point"/inspect component) inspect = False # list of observed neutron positions neutron = [] # skip next neutron position skip = False # total count of drawed neutrons neutrons_drawed = 0 while True: # read line line = get_line(fp) if line is None: break # register components if line.startswith(UC_COMP): # grab info line info = get_line(fp) assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3 + 9]]).reshape(3, 3) comps[name] = (pos, rot) # csv_comps.write('%s, %s, %s, %s\n' % ((name,) + tuple(pos))) # switch perspective elif line.startswith(MC_COMP): color += 1 name = line[len(MC_COMP) + 1:].strip() compName = name comp = comps[name] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') compName = name comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) world.drawLine((rotate(p, comp) for p in points), color=getColor(color)) # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) points = draw_circle(pla, pos, rad, comp) world.drawLine(points, color=getColor(color)) # activate neutron when it enters elif line.startswith(MC_ENTER): neutron = [] skip = True active = True inspect = False color += 1 # deactivate neutron when it leaves elif line.startswith(MC_LEAVE) or line.startswith(MC_ABSORB): active = False if inspectComp is None or inspect: world.drawLine(neutron, color="1 0 0") neutrons_drawed += 1 # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue if inspectComp and inspectComp == compName: # We will draw this neutron! inspect = True # keep track of points the neutron passes through xyz = [float(x) for x in line[line.find(':') + 1:].split(',')[:3]] xyz = rotate(xyz, comp) neutron.append(xyz) print('Neutrons drawed:', neutrons_drawed, (inspectComp and '(reaching %s)' % inspectComp or '(all)')) return world
def parse_trace(): ''' Parse McStas trace output from stdin and write results to file objects csv_comps and csv_lines ''' mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure(figsize=plt.figaspect(0.5) * 1.5) ax = fig.gca(projection='3d') ax.set_xlabel("z") ax.set_ylabel("x") ax.set_zlabel("y") ax.set_aspect('equal') # ax.autoscale_view(scalex=False, scaley=False, scalez=False) color = 0 # map from component name to (position, rotation matrix) comps = {} # active (position, rotation matrix) comp = (np.array([0, 0, 0]), np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).reshape(3, 3)) # previous neutron position prev = None skip = False # we are drawing a neutron active = False xstate = [] ystate = [] zstate = [] while True: # read line line = get_line() if not line: break # register components if line.startswith(UC_COMP): # grab info line info = get_line() assert info[:4] == 'POS:' nums = [x.strip() for x in info[4:].split(',')] # extract fields name = line[len(UC_COMP):].strip(' "\n') pos = np.array([float(x) for x in nums[:3]]) # read flat 3x3 rotation matrix rot = np.array([float(x) for x in nums[3:3 + 9]]).reshape(3, 3) comps[name] = (pos, rot) # switch perspective elif line.startswith(MC_COMP): color += 1 comp = comps[line[len(MC_COMP) + 1:]] elif line.startswith(MC_COMP_SHORT): name = line[len(MC_COMP_SHORT) + 1:].strip('"') comp = comps[name] skip = True # process multiline elif line.startswith(MC_LINE): points = parse_multiline(line[len(MC_LINE):].strip('()')) start = points.pop(0) (x, y, z) = rotate_points(points, comp) ax.plot(z, x, y) # process circle elif line.startswith(MC_CIRCLE): xyz = 'xyz' items = line[len(MC_CIRCLE):].strip('()').split(',') # plane pla = [xyz.find(a) for a in items[0].strip("''")] # center and radius pos = [float(x) for x in items[1:4]] rad = float(items[4]) (x, y, z) = draw_circle(pla, pos, rad, comp) ax.plot(z, x, y) # activate neutron when it enters elif line.startswith(MC_ENTER): prev = None skip = True active = True color = 0 xstate = [] ystate = [] zstate = [] # deactivate neutron when it leaves elif line.startswith(MC_LEAVE): ax.plot(zstate, xstate, ystate) active = False prev = None elif line.startswith(MC_ABSORB): pass # register state and scatter elif line.startswith(MC_STATE) or line.startswith(MC_SCATTER): if not active: continue if skip: skip = False continue xyz = [float(x) for x in line[line.find(':') + 1:].split(',')[:3]] xyz = rotate(xyz, comp) if prev is not None: xstate.append(xyz[0]) ystate.append(xyz[1]) zstate.append(xyz[2]) prev = xyz xstate.append(prev[0]) ystate.append(prev[1]) zstate.append(prev[2]) # kick out legacy "junk" elif line.startswith(MC_MAGNIFY) or line.startswith( MC_START) or line.startswith(MC_END) or line.startswith( MC_STOP): continue else: print(line) # A little bit of logic for controlling the aspect ratios/view (xmin, xmax) = ax.get_xlim3d() (ymin, ymax) = ax.get_ylim3d() (zmin, zmax) = ax.get_zlim3d() dx = xmax - xmin dy = ymax - ymin dz = zmax - zmin dmax = max(dx, dy, dz) # Check ranges and define axis box of max length cubed if dmax > dx: mean = (xmax + xmin) / 2 xmin = mean - dmax / 2 xmax = mean + dmax / 2 if dmax > dy: mean = (ymax + ymin) / 2 ymin = mean - dmax / 2 ymax = mean + dmax / 2 if dmax > dz: mean = (zmax + zmin) / 2 zmin = mean - dmax / 2 zmax = mean + dmax / 2 # Set new axis limits ax.set_xlim3d(xmin, xmax) ax.set_ylim3d(ymin, ymax) ax.set_zlim3d(zmin, zmax) plt.show()