def _add_background(self): if self.background_raw_pixels is not None: self.D.raw_pixels += self.background_raw_pixels else: if self.add_water: print('add water %f mm' % self.water_path_mm) water_scatter = flex.vec2_double([(0, 2.57), (0.0365, 2.58), (0.07, 2.8), (0.12, 5), (0.162, 8), (0.2, 6.75), (0.18, 7.32), (0.216, 6.75), (0.236, 6.5), (0.28, 4.5), (0.3, 4.3), (0.345, 4.36), (0.436, 3.77), (0.5, 3.17)]) self.D.Fbg_vs_stol = water_scatter self.D.amorphous_sample_thick_mm = self.water_path_mm self.D.amorphous_density_gcm3 = 1 self.D.amorphous_molecular_weight_Da = 18 self.D.add_background(1, 0) if self.add_air: print('add air %f mm' % self.air_path_mm) air_scatter = flex.vec2_double([(0, 14.1), (0.045, 13.5), (0.174, 8.35), (0.35, 4.78), (0.5, 4.22)]) self.D.Fbg_vs_stol = air_scatter self.D.amorphous_sample_thick_mm = self.air_path_mm self.D.amorphous_density_gcm3 = 0.0012 self.D.amorphous_sample_molecular_weight_Da = 28 self.D.add_background(1, 0)
def build_grid(Nq, Nphi, nls, moments): two_pi = smath.pi * 2.0 dq = 1 dphi = two_pi / Nphi qps = flex.vec2_double() xys = flex.vec2_double() image = flex.vec3_double() for xx in range(0, Nq + 1): for yy in range(0, Nq + 1): r = smath.sqrt(xx * xx + yy * yy) / Nq if (r <= 1): phi = smath.atan2(yy, xx) if (phi < 0): phi = phi + two_pi qps.append([r, phi]) xys.append([xx, yy]) c2 = compute_c2(nls, moments, r, phi) else: c2 = 0 image.append([Nq + xx, Nq + yy, c2]) if (xx > 0 and yy > 0): image.append([Nq - xx, Nq - yy, c2]) if (yy > 0): image.append([Nq + xx, Nq - yy, c2]) if (xx > 0): image.append([Nq - xx, Nq + yy, c2]) return image
def test_polygon(): poly = flex.vec2_double(((0, 0), (1, 0), (1, 1), (0, 1))) assert is_inside_polygon(poly, 0, 0) assert is_inside_polygon(poly, 0.5, 0.5) assert not is_inside_polygon(poly, 1, 1.01) points = flex.vec2_double(((0.3, 0.8), (0.3, 1.5), (-8, 9), (0.00001, 0.9999))) assert list(is_inside_polygon(poly, points)) == [True, False, False, True]
def exercise_polygon(): from dials.util import is_inside_polygon from scitbx.array_family import flex poly = flex.vec2_double(((0,0), (1,0), (1,1), (0,1))) assert is_inside_polygon(poly, 0, 0) assert is_inside_polygon(poly, 0.5, 0.5) assert not is_inside_polygon(poly, 1, 1.01) points = flex.vec2_double(((0.3, 0.8), (0.3, 1.5), (-8,9), (0.00001, 0.9999))) assert list(is_inside_polygon(poly, points)) == [True, False, False, True]
def exercise_polygon(): from dials.util import is_inside_polygon from scitbx.array_family import flex poly = flex.vec2_double(((0,0), (1,0), (1,1), (0,1))) assert is_inside_polygon(poly, 0, 0) assert is_inside_polygon(poly, 0.5, 0.5) assert not is_inside_polygon(poly, 1, 1.01) points = flex.vec2_double(((0.3, 0.8), (0.3, 1.5), (-8,9), (0.00001, 0.9999))) assert list(is_inside_polygon(poly, points)) == [True, False, False, True]
def test_SimpleWithConvex_non_intersecting(): for i in range(10000): # Generate nonintersecting polygons subject, target = generate_non_intersecting() # Do the clipping result = clip.simple_with_convex(flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we no vertices assert len(result) == 0
def test_SimpleWithConvex_intersecting(): for i in range(10000): # Generate intersecting polygons subject, target = generate_intersecting() # Do the clipping result = clip.simple_with_convex(flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we have roughly valid number of vertices assert len(result) >= 3 assert len(result) >= min([len(subject), len(target)])
def update(self,horizon_phil,matches,status_with_marked_outliers,verbose=False): # first time through: status with marked outliers is None; no input information # second time through after re-refinement: status is a list of SpotClass instances first_time_through = status_with_marked_outliers is None # update spot positions self.observed_spots = flex.vec2_double([(m.x_obs,m.y_obs) for m in matches]) self.predicted_spots = flex.vec2_double([(m.x_calc,m.y_calc) for m in matches]) # store Miller indices self.hkl = [m.miller_index for m in matches] current_status = self.get_new_status( old_status = status_with_marked_outliers ) return self.update_detail(horizon_phil,current_status,first_time_through,verbose)
def update(self,horizon_phil,matches,status_with_marked_outliers,verbose=False): # first time through: status with marked outliers is None; no input information # second time through after re-refinement: status is a list of SpotClass instances first_time_through = status_with_marked_outliers is None # update spot positions self.observed_spots = flex.vec2_double([(m.x_obs,m.y_obs) for m in matches]) self.predicted_spots = flex.vec2_double([(m.x_calc,m.y_calc) for m in matches]) # store Miller indices self.hkl = [m.miller_index for m in matches] current_status = self.get_new_status( old_status = status_with_marked_outliers ) return self.update_detail(horizon_phil,current_status,first_time_through,verbose)
def __init__(self, scene, settings=None): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot render_2d.__init__(self, scene, settings) self._open_circle_points = flex.vec2_double() self._open_circle_radii = [] self._open_circle_colors = [] self._filled_circle_points = flex.vec2_double() self._filled_circle_radii = [] self._filled_circle_colors = [] self.fig, self.ax = pyplot.subplots(figsize=self.settings.size_inches) self.render(self.ax)
def test_intersecting(self): from dials.algorithms.polygon import clip from scitbx.array_family import flex for i in range(10000): # Generate intersecting polygons subject, target = generate_intersecting() # Do the clipping result = clip.simple_with_convex(flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we have roughly valid number of vertices assert (len(result) >= 3) assert (len(result) >= min([len(subject), len(target)]))
def test_non_intersecting(self): from dials.algorithms.polygon import clip from scitbx.array_family import flex for i in range(10000): # Generate nonintersecting polygons subject, target = generate_non_intersecting() # Do the clipping result = clip.simple_with_convex(flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we no vertices assert (len(result) == 0)
def tst_larger_input(self): from scitbx.array_family import flex # Set the size of the grid input_height = 20 input_width = 20 output_height = 10 output_width = 10 # Create the grid data value = 13 grid = flex.double([value for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] for j in range(input_height + 1): for i in range(input_width + 1): xy.append((i / 2.0, j / 2.0)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(input_height + 1, input_width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (output_height, output_width)) # Check that each each pixel has a value of 4 times the input eps = 1e-7 for j in range(1, output_height): for i in range(1, output_width): assert abs(output[j, i] - 4 * value) <= eps # Test passed print "OK"
def test_conservation_of_counts(): from scitbx.array_family import flex from scitbx import matrix from math import sin, cos, pi # Set the size of the grid input_height = 10 input_width = 10 output_height = 50 output_width = 50 # Create the grid data grid = flex.double([random.uniform(0, 100) for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] angle = random.uniform(0, pi) R = matrix.sqr((cos(angle), -sin(angle), sin(angle), cos(angle))) for j in range(output_height + 1): for i in range(output_width + 1): ij = R * matrix.col((i, j)) xy.append((ij[0], ij[1])) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(output_height+1, output_width+1)) off = gridxy[output_height//2, output_width//2] for i in range(len(gridxy)): gridxy[i] = (gridxy[i][0] - off[0], gridxy[i][1] - off[1]) # Get the output grid output = regrid_grid_to_irregular_grid(grid, gridxy) # Check that the sum of the counts is conserved eps = 1e-7 assert(abs(flex.sum(output) - flex.sum(grid)) <= eps)
def filter_shadowed_reflections(experiments, reflections): from dials.util import mask_untrusted_polygon from dials.util import is_inside_polygon shadowed = flex.bool(reflections.size(), False) for expt_id in range(len(experiments)): expt = experiments[expt_id] imgset = expt.imageset masker = imgset.reader().get_format().get_goniometer_shadow_masker() detector = expt.detector sel = reflections['id'] == expt_id isel = sel.iselection() x,y,z = reflections['xyzcal.px'].select(isel).parts() start, end = expt.scan.get_array_range() for i in range(start, end): shadow = masker.project_extrema( detector, expt.scan.get_angle_from_array_index(i)) img_sel = (z >= i) & (z < (i+1)) img_isel = img_sel.iselection() for p_id in range(len(detector)): panel = reflections['panel'].select(img_isel) if shadow[p_id].size() < 4: continue panel_isel = img_isel.select(panel == p_id) inside = is_inside_polygon( shadow[p_id], flex.vec2_double(x.select(isel.select(panel_isel)), y.select(isel.select(panel_isel)))) shadowed.set_selected(panel_isel, inside) return shadowed
def test(self, dials_regression): filename = os.path.join(dials_regression, "image_examples", "XDS", "XPARM.XDS") import dxtbx models = dxtbx.load(filename) self.detector = models.get_detector() self.beam = models.get_beam() assert len(self.detector) == 1 self.t0 = 0.320 from cctbx.eltbx import attenuation_coefficient table = attenuation_coefficient.get_table("Si") self.mu = table.mu_at_angstrom(self.beam.get_wavelength()) / 10.0 self.distance = self.detector[0].get_distance() self.origin = self.detector[0].get_ray_intersection( self.detector[0].get_normal())[1] self.pixel_size = self.detector[0].get_pixel_size() from random import uniform # Generate some random coordinates and do the correction random_coord = lambda: (uniform(-1000, 1000), uniform(-1000, 1000)) for i in range(10000): xy = random_coord() self.tst_single(xy) from scitbx.array_family import flex xy = flex.vec2_double([random_coord() for i in range(100)]) self.tst_array(xy) self.tst_inverted_axis()
def test_larger_input(): from scitbx.array_family import flex # Set the size of the grid input_height = 20 input_width = 20 output_height = 10 output_width = 10 # Create the grid data value = 13 grid = flex.double([value for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] for j in range(input_height + 1): for i in range(input_width + 1): xy.append((i / 2.0, j / 2.0)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(input_height + 1, input_width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (output_height, output_width)) # Check that each each pixel has a value of 4 times the input eps = 1e-7 for j in range(1, output_height): for i in range(1, output_width): assert abs(output[j, i] - 4 * value) <= eps
def tst_larger_output(self): from scitbx.array_family import flex # Set the size of the grid height = 10 width = 10 # Create the grid data value = 13 grid = flex.double([value for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i * 2, j * 2)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (height * 2, width * 2)) # Check that each each pixel has a value of 0.25 the input eps = 1e-7 for j in range(1, height): for i in range(1, width): assert abs(output[j, i] - 0.25 * value) <= eps # Test passed print "OK"
def test_larger_output(): from scitbx.array_family import flex # Set the size of the grid height = 10 width = 10 # Create the grid data value = 13 grid = flex.double([value for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i * 2, j * 2)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (height * 2, width * 2)) # Check that each each pixel has a value of 0.25 the input eps = 1e-7 for j in range(1, height): for i in range(1, width): assert abs(output[j, i] - 0.25 * value) <= eps
def test_known_offset(): from scitbx.array_family import flex # Set the size of the grid height = 10 width = 10 # Create the grid data grid = flex.double([1 for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i + 0.5, j + 0.5)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (height, width)) # Check that each each pixel along the left and bottom has a value # of 0.5 and that everything else is 1 eps = 1e-7 assert abs(output[0, 0] - 0.25) <= eps for i in range(1, width): assert abs(output[0, i] - 0.5) <= eps for j in range(1, height): assert abs(output[j, 0] - 0.5) <= eps for j in range(1, height): for i in range(1, width): assert abs(output[j, i] - 1.0) <= eps
def __init__(self, scene, settings=None): import matplotlib matplotlib.use('Agg') from matplotlib import pyplot render_2d.__init__(self, scene, settings) self._open_circle_points = flex.vec2_double() self._open_circle_radii = [] self._open_circle_colors = [] self._filled_circle_points = flex.vec2_double() self._filled_circle_radii = [] self._filled_circle_colors = [] self.fig, self.ax = pyplot.subplots(figsize=self.settings.size_inches) self.render(self.ax) pyplot.close()
def __init__(self,imgobj,phil,inputpd,verbose=False): adopt_init_args(self,locals()) self.active_areas = imgobj.get_tile_manager(phil).effective_tiling_as_flex_int() B = self.active_areas #figure out which asics are on the central four sensors assert len(self.active_areas)%4 == 0 # apply an additional margin of 1 pixel, since we don't seem to be # registering the global margin. asics = [(B[i]+1,B[i+1]+1,B[i+2]-1,B[i+3]-1) for i in xrange(0,len(B),4)] from scitbx.matrix import col centre_mm = col((float(inputpd["xbeam"]),float(inputpd["ybeam"]))) centre = centre_mm / float(inputpd["pixel_size"]) distances = flex.double() cenasics = flex.vec2_double() self.corners = [] for iasic in xrange(len(asics)): cenasic = ((asics[iasic][2] + asics[iasic][0])/2. , (asics[iasic][3] + asics[iasic][1])/2. ) cenasics.append(cenasic) distances.append(math.hypot(cenasic[0]-centre[0], cenasic[1]-centre[1])) orders = flex.sort_permutation(distances) self.flags = flex.int(len(asics),0) #Use the central 8 asics (central 4 sensors) self.green = [] for i in xrange(32): #self.green.append( cenasics[orders[i]] ) self.corners.append (asics[orders[i]]) #self.green.append((self.corners[-1][0],self.corners[-1][1])) self.flags[orders[i]]=1 self.asic_filter = "distl.tile_flags="+",".join(["%1d"%b for b in self.flags])
def filter_shadowed_reflections(experiments, reflections, experiment_goniometer=False): from dxtbx.masking import is_inside_polygon from scitbx.array_family import flex shadowed = flex.bool(reflections.size(), False) for expt_id in range(len(experiments)): expt = experiments[expt_id] imageset = expt.imageset masker = imageset.masker() detector = expt.detector sel = reflections["id"] == expt_id isel = sel.iselection() x, y, z = reflections["xyzcal.px"].select(isel).parts() start, end = expt.scan.get_array_range() for i in range(start, end): shadow = masker.project_extrema( detector, expt.scan.get_angle_from_array_index(i) ) img_sel = (z >= i) & (z < (i + 1)) img_isel = img_sel.iselection() for p_id in range(len(detector)): panel = reflections["panel"].select(img_isel) if shadow[p_id].size() < 4: continue panel_isel = img_isel.select(panel == p_id) inside = is_inside_polygon( shadow[p_id], flex.vec2_double( x.select(isel.select(panel_isel)), y.select(isel.select(panel_isel)), ), ) shadowed.set_selected(panel_isel, inside) return shadowed
def test_identical(): from scitbx.array_family import flex # Set the size of the grid height = 10 width = 10 # Create the grid data grid = flex.double( [random.uniform(0, 100) for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i, j)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (height, width)) # Check that each pixel is identical eps = 1e-7 for j in range(height): for i in range(width): assert abs(output[j, i] - grid[j, i]) <= eps
def tst_identical(self): from scitbx.array_family import flex from random import uniform # Set the size of the grid height = 10 width = 10 # Create the grid data grid = flex.double([uniform(0, 100) for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i, j)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = rebin_pixels(grid, gridxy, (height, width)) # Check that each pixel is identical eps = 1e-7 for j in range(height): for i in range(width): assert (abs(output[j, i] - grid[j, i]) <= eps) # Test passed print 'OK'
def tst_identical(self): from scitbx.array_family import flex from random import uniform # Set the size of the grid height = 10 width = 10 # Create the grid data grid = flex.double([uniform(0, 100) for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i, j)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_grid_to_irregular_grid(grid, gridxy) # Check that each pixel is identical eps = 1e-7 for j in range(height): for i in range(width): assert abs(output[j, i] - grid[j, i]) <= eps # Test passed print "OK"
def tst_conservation_of_counts(self): from scitbx.array_family import flex from scitbx import matrix from math import sin, cos, pi from random import uniform # Set the size of the grid input_height = 10 input_width = 10 output_height = 50 output_width = 50 # Create the grid data grid = flex.double( [uniform(0, 100) for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] angle = uniform(0, pi) offset = (uniform(20, 30), uniform(20, 30)) R = matrix.sqr((cos(angle), -sin(angle), sin(angle), cos(angle))) for j in range(input_height + 1): for i in range(input_width + 1): ij = R * matrix.col((i, j)) xy.append((ij[0] + offset[0], ij[1] + offset[0])) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(input_height + 1, input_width + 1)) # Get the output grid output = rebin_pixels(grid, gridxy, (output_height, output_width)) # Check that the sum of the counts is conserved eps = 1e-7 assert (abs(flex.sum(output) - flex.sum(grid)) <= eps)
def generate_vec2_double(self, num): from scitbx.array_family import flex from random import uniform x0, x1, y0, y1 = 0, 100, 0, 100 result = flex.vec2_double(num) for i in range(num): result[i] = (uniform(x0, x1), uniform(y0, y1)) return result
def vec2_double(): from scitbx.array_family import flex num = 100 x0, x1, y0, y1 = 0, 100, 0, 100 result = flex.vec2_double(num) for i in range(num): result[i] = (random.uniform(x0, x1), random.uniform(y0, y1)) return result
def generate_vec2_double(self, num): from scitbx.array_family import flex from random import uniform x0, x1, y0, y1 = 0, 100, 0, 100 result = flex.vec2_double(num) for i in range(num): result[i] = (uniform(x0, x1), uniform(y0, y1)) return result
def tst_non_intersecting(self): from dials.algorithms.polygon import clip from scitbx.array_family import flex for i in range(10000): # Generate nonintersecting polygons subject, target = generate_non_intersecting() # Do the clipping result = clip.simple_with_convex( flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we no vertices assert(len(result) == 0) print 'OK'
def test_array(model): xy = flex.vec2_double( (random.uniform(-1000, 1000), random.uniform(-1000, 1000)) for i in range(100) ) xy_corr = model["detector"].get_lab_coord(xy) xy_corr_panel = model["detector"].get_lab_coord(xy) xy_corr_gold = [model["detector"].get_lab_coord(xy_single) for xy_single in xy] assert approx_equal(xy_corr, xy_corr_gold) assert approx_equal(xy_corr_panel, xy_corr_gold)
def __init__(self, scene, settings=None): render_2d.__init__(self, scene, settings) self._open_circle_points = flex.vec2_double() self._open_circle_radii = [] self._open_circle_colors = [] self._filled_circle_points = flex.vec2_double() self._filled_circle_radii = [] self._filled_circle_colors = [] self._text = {"x": [], "y": [], "text": []} self._lines = [] json_d = self.render(None) if self.settings.json.compact: indent = None else: indent = 2 with open(self.settings.json.filename, "w") as fh: json.dump(json_d, fh, indent=indent)
def centroid_px_to_mm_panel(panel, scan, position, variance, sd_error): '''Convenience function to calculate centroid in mm/rad from px''' from operator import mul # Get the pixel to millimeter function pixel_size = panel.get_pixel_size() if scan is None: oscillation = (0, 0) else: oscillation = scan.get_oscillation(deg=False) scale = pixel_size + (oscillation[1], ) scale2 = map(mul, scale, scale) if isinstance(position, tuple): # Convert Pixel coordinate into mm/rad x, y, z = position xy_mm = panel.pixel_to_millimeter((x, y)) if scan is None: z_rad = 0 else: z_rad = scan.get_angle_from_array_index(z, deg=False) # Set the position, variance and squared width in mm/rad # N.B assuming locally flat pixel to millimeter transform # for variance calculation. position_mm = xy_mm + (z_rad, ) variance_mm = map(mul, variance, scale2) sd_error_mm = map(mul, sd_error, scale2) else: from scitbx.array_family import flex # Convert Pixel coordinate into mm/rad x, y, z = position.parts() xy_mm = panel.pixel_to_millimeter(flex.vec2_double(x, y)) if scan is None: z_rad = flex.double(z.size(), 0) else: z_rad = scan.get_angle_from_array_index(z, deg=False) # Set the position, variance and squared width in mm/rad # N.B assuming locally flat pixel to millimeter transform # for variance calculation. x_mm, y_mm = xy_mm.parts() position_mm = flex.vec3_double(x_mm, y_mm, z_rad) v0, v1, v2 = variance.parts() variance_mm = flex.vec3_double(v0 * scale2[0], v1 * scale2[1], v2 * scale2[2]) s0, s1, s2 = sd_error.parts() sd_error_mm = flex.vec3_double(s0 * scale2[0], s1 * scale2[1], s2 * scale2[2]) # Return the stuff in mm/rad return position_mm, variance_mm, sd_error_mm
def __call__(self, ipanel=0): panel_a = self.det1[ipanel] panel_b = self.det2[ipanel] size_fast, size_slow = panel_a.get_image_size_mm() assert size_fast, size_slow == panel_b.get_image_size_mm() # num of sample intervals n_fast = int((size_fast) / SAMPLE_FREQ) n_slow = int((size_slow) / SAMPLE_FREQ) # interval width step_fast = size_fast / n_fast step_slow = size_slow / n_slow # samples samp_fast = [step_fast * i for i in range(n_fast + 1)] samp_slow = [step_slow * i for i in range(n_slow + 1)] lab1 = flex.vec3_double() lab2 = flex.vec3_double() sample_pts = flex.vec2_double() # loop for s in samp_slow: for f in samp_fast: lab1.append(panel_a.get_lab_coord((f, s))) lab2.append(panel_b.get_lab_coord((f, s))) sample_pts.append((f, s)) offset = lab2 - lab1 # store offset in the lab frame x_off, y_off, z_off = offset.parts() # reexpress offset in the basis fast, slow, normal of panel_a f_off = offset.dot(panel_a.get_fast_axis()) s_off = offset.dot(panel_a.get_slow_axis()) n_off = offset.dot(panel_a.get_normal()) f, s = sample_pts.parts() return { "lab_coord": lab1, "fast": f, "slow": s, "x_offset": x_off, "y_offset": y_off, "z_offset": z_off, "fast_offset": f_off, "slow_offset": s_off, "normal_offset": n_off, "size_fast": size_fast, "size_slow": size_slow, }
def test_polygon(): from dials.algorithms.polygon import polygon x = 1 y = 1 vertices = [(0,0), (2,0), (2,2), (0,2)] poly = polygon(vertices) assert poly.is_inside(x,y) poly = polygon([(3,5), (40,90), (80,70), (50,50), (70,20)]) for p in [(42,40), (16,25), (64,67), (16,30), (48, 45), (21,30)]: assert poly.is_inside(p[0], p[1]) for p in [(59,4), (70,15), (57,14), (21,78), (37,100), (88,89)]: assert not poly.is_inside(p[0], p[1]) if 0: # for visual confirmation of algorithm from scitbx.array_family import flex inside_points = flex.vec2_double() outside_points = flex.vec2_double() import random x_max = 100 y_max = 100 for i in range(1000): x = random.randint(0,x_max) y = random.randint(0,y_max) is_inside = poly.is_inside(x, y) if is_inside: inside_points.append((x,y)) else: outside_points.append((x,y)) from matplotlib import pyplot from matplotlib.patches import Polygon v = poly.vertices + poly.vertices[:1] fig = pyplot.figure() ax = fig.add_subplot(111) ax.add_patch(Polygon(poly.vertices, closed=True, fill=False)) inside_x, inside_y = inside_points.parts() outside_x, outside_y = outside_points.parts() ax.scatter(inside_x, inside_y, marker='+', c='r') ax.scatter(outside_x, outside_y, marker='+', c='b') pyplot.show()
def __init__(self, scene, settings=None): render_2d.__init__(self, scene, settings) self._open_circle_points = flex.vec2_double() self._open_circle_radii = [] self._open_circle_colors = [] self._filled_circle_points = flex.vec2_double() self._filled_circle_radii = [] self._filled_circle_colors = [] self._text = [] self._lines = [] json_d = self.render(None) import json if self.settings.json.compact: indent = None else: indent = 2 json_str = json.dumps(json_d, indent=indent) with open(self.settings.json.filename, 'wb') as f: print >> f, json_str
def centroid_px_to_mm_panel(panel, scan, position, variance, sd_error): '''Convenience function to calculate centroid in mm/rad from px''' from operator import mul # Get the pixel to millimeter function pixel_size = panel.get_pixel_size() if scan is None: oscillation = (0,0) else: oscillation = scan.get_oscillation(deg=False) scale = pixel_size + (oscillation[1],) scale2 = map(mul, scale, scale) if isinstance(position, tuple): # Convert Pixel coordinate into mm/rad x, y, z = position xy_mm = panel.pixel_to_millimeter((x, y)) if scan is None: z_rad = 0 else: z_rad = scan.get_angle_from_array_index(z, deg=False) # Set the position, variance and squared width in mm/rad # N.B assuming locally flat pixel to millimeter transform # for variance calculation. position_mm = xy_mm + (z_rad,) variance_mm = map(mul, variance, scale2) sd_error_mm = map(mul, sd_error, scale2) else: from scitbx.array_family import flex # Convert Pixel coordinate into mm/rad x, y, z = position.parts() xy_mm = panel.pixel_to_millimeter(flex.vec2_double(x, y)) if scan is None: z_rad = flex.double(z.size(), 0) else: z_rad = scan.get_angle_from_array_index(z, deg=False) # Set the position, variance and squared width in mm/rad # N.B assuming locally flat pixel to millimeter transform # for variance calculation. x_mm, y_mm = xy_mm.parts() position_mm = flex.vec3_double(x_mm, y_mm, z_rad) v0, v1, v2 = variance.parts() variance_mm = flex.vec3_double(v0*scale2[0], v1*scale2[1], v2*scale2[2]) s0, s1, s2 = sd_error.parts() sd_error_mm = flex.vec3_double(s0*scale2[0], s1*scale2[1], s2*scale2[2]) # Return the stuff in mm/rad return position_mm, variance_mm, sd_error_mm
def tst_intersecting(self): from dials.algorithms.polygon import clip from scitbx.array_family import flex for i in range(10000): # Generate intersecting polygons subject, target = generate_intersecting() # Do the clipping result = clip.simple_with_convex( flex.vec2_double(subject), flex.vec2_double(target)) # Ensure we have roughly valid number of vertices assert(len(result) >= 3) assert(len(result) >= min([len(subject), len(target)])) # for v in result: # assert(point_in_polygon(v, clip)) print 'OK'
def __call__(self, ipanel=0): panel_a = self.det1[ipanel] panel_b = self.det2[ipanel] size_fast, size_slow = panel_a.get_image_size_mm() assert size_fast, size_slow == panel_b.get_image_size_mm() # num of sample intervals n_fast = int((size_fast) / SAMPLE_FREQ) n_slow = int((size_slow) / SAMPLE_FREQ) # interval width step_fast = size_fast / n_fast step_slow = size_slow / n_slow # samples samp_fast = [step_fast * i for i in range(n_fast + 1)] samp_slow = [step_slow * i for i in range(n_slow + 1)] lab1 = flex.vec3_double() lab2 = flex.vec3_double() sample_pts = flex.vec2_double() # loop for s in samp_slow: for f in samp_fast: lab1.append(panel_a.get_lab_coord((f, s))) lab2.append(panel_b.get_lab_coord((f, s))) sample_pts.append((f,s)) offset = lab2 - lab1 # store offset in the lab frame x_off, y_off, z_off = offset.parts() # reexpress offset in the basis fast, slow, normal of panel_a f_off = offset.dot(panel_a.get_fast_axis()) s_off = offset.dot(panel_a.get_slow_axis()) n_off = offset.dot(panel_a.get_normal()) f, s = sample_pts.parts() return {'lab_coord':lab1, 'fast':f, 'slow':s, 'x_offset':x_off, 'y_offset':y_off, 'z_offset':z_off, 'fast_offset':f_off, 'slow_offset':s_off, 'normal_offset':n_off, 'size_fast':size_fast, 'size_slow':size_slow}
def test_SimpleWithRect_intersecting(): for i in range(10000): # Generate intersecting polygons subject, target = generate_intersecting(target_size=2) rect = ((0, 0), (10, 10)) # Do the clipping result = clip.simple_with_rect(flex.vec2_double(subject), rect) # Ensure we have roughly valid number of vertices assert len(result) >= 3 assert len(result) >= min([len(subject), 4])
def sim_background(DETECTOR, BEAM, wavelengths, wavelength_weights, total_flux, pidx=0, beam_size_mm=0.001, Fbg_vs_stol=None, sample_thick_mm=100, density_gcm3=1, molecular_weight=18): """ :param DETECTOR: :param BEAM: see sim_spots :param wavelengths: see sim_spots :param wavelength_weights: see sim_spots :param total_flux: see sim_spots :param pidx: see sim_spots :param beam_size_mm: see sim_spots :param Fbg_vs_stol: list of tuples where each tuple is (Fbg, sin theta over lambda) :param sample_thick_mm: path length of background that is exposed by the beam :param density_gcm3: density of background (defaults to water) :param molecular_weight: molecular weight of background (defaults to water) :return: raw_pixels as flex array, these can be passed to sim_spots function below """ wavelength_weights = np.array(wavelength_weights) weights = wavelength_weights / wavelength_weights.sum() * total_flux spectrum = list(zip(wavelengths, weights)) xray_beams = get_xray_beams(spectrum, BEAM) SIM = nanoBragg(DETECTOR, BEAM, panel_id=(int(pidx))) SIM.beamsize_mm = beam_size_mm SIM.xray_beams = xray_beams if Fbg_vs_stol is None: Fbg_vs_stol = flex.vec2_double([(0, 2.57), (0.0365, 2.58), (0.07, 2.8), (0.12, 5), (0.162, 8), (0.18, 7.32), (0.2, 6.75), (0.216, 6.75), (0.236, 6.5), (0.28, 4.5), (0.3, 4.3), (0.345, 4.36), (0.436, 3.77), (0.5, 3.17)]) SIM.flux = sum(weights) SIM.Fbg_vs_stol = Fbg_vs_stol SIM.amorphous_sample_thick_mm = sample_thick_mm SIM.amorphous_density_gcm3 = density_gcm3 SIM.amorphous_molecular_weight_Da = molecular_weight SIM.progress_meter = False SIM.add_background() background_raw_pixels = SIM.raw_pixels.deep_copy() SIM.free_all() del SIM return background_raw_pixels
def as_spot_center_of_mass(self,active_block,asic,percentile90): from scitbx.matrix import col maxima = flex.vec2_double() self.intensities = flex.double() for spot in self.spots: pixels = [col(((frow)+asic[0],(fcol)+asic[1])) for frow,fcol in spot] pixel_values = [active_block[(int(frow),int(fcol))] for frow,fcol in spot] numerator = col((0.0,0.0)); denominator = 0.0 for ispot in xrange(len(spot)): numerator += (pixel_values[ispot]-percentile90)*pixels[ispot] denominator += pixel_values[ispot]-percentile90 if len(spot) < 20: #any spot with more than 20 pixels is a clear outlier maxima.append( numerator/denominator ) self.intensities.append(denominator) return maxima
def tst_pixel_to_millimeter_to_pixel(detector): from scitbx import matrix from random import random eps = 1e-7 # Pick some random pixels and check that px -> mm -> px give px == px w, h = detector[0].get_image_size() random_pixel = lambda: (random() * w, random() * h) pixels = flex.vec2_double(random_pixel() for i in range(100)) xy_mm = detector[0].pixel_to_millimeter(pixels) xy_px = detector[0].millimeter_to_pixel(xy_mm) assert approx_equal(xy_px, pixels, eps=eps) for xy in pixels: xy_mm = detector[0].pixel_to_millimeter(xy) xy_px = detector[0].millimeter_to_pixel(xy_mm) assert(abs(matrix.col(xy_px) - matrix.col(xy)) < eps) # Test Passed print "OK"
def set_detector_points(self): detector = self.imageset.get_detector() points = flex.vec3_double() line_i_seqs = flex.vec2_double() i = 0 for p in detector: image_size = p.get_image_size_mm() points.append(p.get_lab_coord((0,0))) points.append(p.get_lab_coord((0,image_size[1]))) points.append(p.get_lab_coord(image_size)) points.append(p.get_lab_coord((image_size[0],0))) line_i_seqs.append((i, i+1)) line_i_seqs.append((i+1, i+2)) line_i_seqs.append((i+2, i+3)) line_i_seqs.append((i+3, i)) i += 4 line_i_seqs += (self.viewer.points.size(), self.viewer.points.size()) self.viewer.points.extend(points) for i_seqs in line_i_seqs: self.viewer.line_i_seqs.append([int(i_seq) for i_seq in i_seqs])
def set_obs_s1(reflections, experiments): """Set observed s1 vectors for reflections if required, return the number of reflections that have been set.""" refs_wo_s1_sel = (reflections['s1'].norms() < 1.e-6) nrefs_wo_s1 = refs_wo_s1_sel.count(True) if nrefs_wo_s1 == 0: return nrefs_wo_s1 for i_expt, expt in enumerate(experiments): detector = expt.detector beam = expt.beam expt_sel = reflections['id'] == i_expt for i_panel, panel in enumerate(detector): panel_sel = reflections['panel'] == i_panel isel = (expt_sel & panel_sel & refs_wo_s1_sel).iselection() spots = reflections.select(isel) x, y, rot_angle = spots['xyzobs.mm.value'].parts() s1 = panel.get_lab_coord(flex.vec2_double(x,y)) s1 = s1/s1.norms() * (1/beam.get_wavelength()) reflections['s1'].set_selected(isel, s1) return nrefs_wo_s1
def get_active_data_corrected_with_fft(self): #data = self.imgobj.linearintdata data = self.imgobj.correct_gain_in_place( filename = self.phil.speckfinder.dark_stddev, adu_scale = self.phil.speckfinder.dark_adu_scale, phil = self.phil ) indexing = [] for iraw,raw_asic in enumerate(self.corners): filtered_data = self.imgobj.correct_background_by_block(raw_asic) active_data = filtered_data.as_double().as_1d() order = flex.sort_permutation(active_data) stats = flex.mean_and_variance(active_data) if self.verbose: #print "Stats on %d pixels"%len(active_data) print "stats are mean",stats.mean(),"sigma",stats.unweighted_sample_standard_deviation() #print "The 90-percentile pixel is ",active_data[order[int(0.9*len(active_data))]] #print "The 99-percentile pixel is ",active_data[order[int(0.99*len(active_data))]] maximas = flex.vec2_double() for idx in xrange(len(active_data)-1, int(0.9*len(active_data)), -1): if active_data[order[idx]] > stats.mean() + 12.0*stats.unweighted_sample_standard_deviation(): if self.verbose: print " ", idx, active_data[order[idx]] irow = order[idx] // (raw_asic[3]-raw_asic[1]) icol = order[idx] % (raw_asic[3]-raw_asic[1]) maximas.append((irow, icol)) CLUS = clustering(maximas) coords = CLUS.as_spot_center_of_mass(filtered_data,raw_asic,stats.mean()) intensities = CLUS.intensities for coord,height in zip(coords,intensities): self.green.append(coord) indexing.append( ( coord[0] * float(self.inputpd["pixel_size"]), coord[1] * float(self.inputpd["pixel_size"]), 0.0, # 0 -degree offset for still image height) ) return indexing
def get_active_data_sigma(self): data = self.imgobj.linearintdata indexing = [] for asic in self.corners: block = data.matrix_copy_block( i_row=asic[0],i_column=asic[1], n_rows=asic[2]-asic[0], n_columns=asic[3]-asic[1]) active_data = block.as_1d().as_double() order = flex.sort_permutation(active_data) if self.verbose: print "The mean is ",flex.mean(active_data),"on %d pixels"%len(active_data) print "The 90-percentile pixel is ",active_data[order[int(0.9*len(active_data))]] print "The 99-percentile pixel is ",active_data[order[int(0.99*len(active_data))]] stats = flex.mean_and_variance(active_data) print "stats are mean",stats.mean(),"sigma",stats.unweighted_sample_standard_deviation() maximas = flex.vec2_double() for idx in xrange(len(active_data)-1, int(0.9*len(active_data)), -1): if active_data[order[idx]] > stats.mean() + 6.0*stats.unweighted_sample_standard_deviation(): if self.verbose: print " ", idx, active_data[order[idx]] irow = order[idx] // (asic[3]-asic[1]) icol = order[idx] % (asic[3]-asic[1]) #self.green.append((asic[0]+irow, asic[1]+icol)) maximas.append((irow, icol)) CLUS = clustering(maximas) #coords = CLUS.as_spot_max_pixels(block,asic) coords = CLUS.as_spot_center_of_mass(block,asic,stats.mean()) intensities = CLUS.intensities for coord,height in zip(coords,intensities): self.green.append(coord) indexing.append( ( coord[0] * float(self.inputpd["pixel_size"]), coord[1] * float(self.inputpd["pixel_size"]), 0.0, # 0 -degree offset for still image height) ) return indexing
def tst_known_orientation(self): from scitbx.array_family import flex from scitbx import matrix from math import sin, cos, pi, sqrt # Set the size of the grid input_height = 4 input_width = 4 output_height = 4 output_width = 4 # Create the grid data value = 13 grid = flex.double([value for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] R = matrix.sqr((cos(pi / 4), -sin(pi / 4), sin(pi / 4), cos(pi / 4))) for j in range(output_height + 1): for i in range(output_width + 1): ij = R * matrix.col((i * sqrt(8) / 2, j * sqrt(8) / 2)) xy.append((ij[0] + 2, ij[1] - 2)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(output_height + 1, output_width + 1)) # Get the output grid output = regrid_grid_to_irregular_grid(grid, gridxy) expected = [[0, 1, 1, 0], [1, 2, 2, 1], [1, 2, 2, 1], [0, 1, 1, 0]] # Check that each each pixel has a value of the input eps = 1e-7 for j in range(1, output_height): for i in range(1, output_width): assert abs(output[j, i] - expected[j][i] * value) <= eps # Test passed print "OK"
def tst_conservation_of_counts(self): from scitbx.array_family import flex from scitbx import matrix from math import sin, cos, pi from random import uniform # Set the size of the grid input_height = 10 input_width = 10 output_height = 50 output_width = 50 # Create the grid data grid = flex.double([uniform(0, 100) for i in range(input_height * input_width)]) grid.reshape(flex.grid(input_height, input_width)) # Create the grid coordinates xy = [] angle = uniform(0, pi) R = matrix.sqr((cos(angle), -sin(angle), sin(angle), cos(angle))) for j in range(output_height + 1): for i in range(output_width + 1): ij = R * matrix.col((i, j)) xy.append((ij[0], ij[1])) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(output_height + 1, output_width + 1)) off = gridxy[output_height // 2, output_width // 2] for i in range(len(gridxy)): gridxy[i] = (gridxy[i][0] - off[0], gridxy[i][1] - off[1]) # Get the output grid output = regrid_grid_to_irregular_grid(grid, gridxy) # Check that the sum of the counts is conserved eps = 1e-7 assert abs(flex.sum(output) - flex.sum(grid)) <= eps # Test passed print "OK"
def run(args): from matplotlib import pyplot from dials.util.command_line import Importer from scitbx.array_family import flex importer = Importer(args) #datablocks = importer.datablocks #assert len(datablocks) == 1 ##imagesets = datablocks[0].extract_imagesets() observed_xy = flex.vec2_double() for reflection_list in importer.reflections: for refl in reflection_list: centroid = refl['xyzobs.px.value'] if centroid != (0,0,0): x, y = centroid[:2] observed_xy.append((x,y)) obs_x, obs_y = observed_xy.parts() fig = pyplot.figure() pyplot.scatter(obs_x, obs_y, marker='.', c='black', lw=0, s=0.1) pyplot.axes().set_aspect('equal') pyplot.xlim((0, pyplot.xlim()[1])) pyplot.ylim((0, pyplot.ylim()[1])) pyplot.savefig("virtual_powder.png", size_inches=(10,10), dpi=600)
def generate_data(self): from scitbx.array_family import flex from random import random, randint # Generate a 3d array of pixels and points self.points3d = flex.vec3_double(flex.grid(5, 5, 5)) self.pixels3d = flex.double(flex.grid(5, 5, 5)) self.mask3d = flex.bool(flex.grid(5, 5, 5)) for k in range(0, 5): for j in range(0, 5): for i in range(0, 5): self.points3d[k,j,i] = (i + 0.5, j + 0.5, k + 0.5) self.pixels3d[k,j,i] = random() self.mask3d[k,j,i] = bool(randint(0, 1)) self.points2d = flex.vec2_double(flex.grid(5, 5)) self.pixels2d = flex.double(flex.grid(5, 5)) self.mask2d = flex.bool(flex.grid(5, 5)) for j in range(0, 5): for i in range(0, 5): self.points2d[j,i] = self.points3d[0, j, i][0:2] self.pixels2d[j,i] = self.pixels3d[0, j, i] self.mask2d[j,i] = self.mask3d[0, j, i]
def tst_known_offset(self): from scitbx.array_family import flex # Set the size of the grid height = 10 width = 10 # Create the grid data grid = flex.double([1 for i in range(height * width)]) grid.reshape(flex.grid(height, width)) # Create the grid coordinates xy = [] for j in range(height + 1): for i in range(width + 1): xy.append((i + 0.5, j + 0.5)) gridxy = flex.vec2_double(xy) gridxy.reshape(flex.grid(height + 1, width + 1)) # Get the output grid output = regrid_irregular_grid_to_grid(grid, gridxy, (height, width)) # Check that each each pixel along the left and bottom has a value # of 0.5 and that everything else is 1 eps = 1e-7 assert abs(output[0, 0] - 0.25) <= eps for i in range(1, width): assert abs(output[0, i] - 0.5) <= eps for j in range(1, height): assert abs(output[j, 0] - 0.5) <= eps for j in range(1, height): for i in range(1, width): assert abs(output[j, i] - 1.0) <= eps # Test passed print "OK"
def generate(self, imageset): ''' Generate the mask. ''' from dials.util import ResolutionMaskGenerator from dials.util import mask_untrusted_rectangle from dials.util import mask_untrusted_circle from dials.util import mask_untrusted_polygon from dials.util import mask_untrusted_resolution_range from dials.array_family import flex from math import floor, ceil # Get the detector and beam detector = imageset.get_detector() beam = imageset.get_beam() # Get the first image image = imageset.get_raw_data(0) assert(len(detector) == len(image)) # Create the mask for each image masks = [] for index, (im, panel) in enumerate(zip(image, detector)): # The image width height height, width = im.all() # Create the basic mask from the trusted range if self.params.use_trusted_range: low, high = panel.get_trusted_range() imd = im.as_double() mask = (imd > low) & (imd < high) else: mask = flex.bool(flex.grid(im.all()), True) # Add a border around the image if self.params.border > 0: logger.info("Generating border mask:") logger.info(" border = %d" % self.params.border) border = self.params.border height, width = mask.all() borderx = flex.bool(flex.grid(border, width), False) bordery = flex.bool(flex.grid(height, border), False) mask[0:border,:] = borderx mask[-border:,:] = borderx mask[:,0:border] = bordery mask[:,-border:] = bordery # Apply the untrusted regions for region in self.params.untrusted: if region.panel == index: if region.circle is not None: xc, yc, radius = region.circle logger.info("Generating circle mask:") logger.info(" panel = %d" % region.panel) logger.info(" xc = %d" % xc) logger.info(" yc = %d" % yc) logger.info(" radius = %d" % radius) mask_untrusted_circle(mask, xc, yc, radius) if region.rectangle is not None: x0, x1, y0, y1 = region.rectangle logger.info("Generating rectangle mask:") logger.info(" panel = %d" % region.panel) logger.info(" x0 = %d" % x0) logger.info(" y0 = %d" % y0) logger.info(" x1 = %d" % x1) logger.info(" y1 = %d" % y1) mask_untrusted_rectangle(mask, x0, x1, y0, y1) if region.polygon is not None: assert len(region.polygon) % 2 == 0, "Polygon must contain 2D coords" vertices = [] for i in range(int(len(region.polygon)/2)): x = region.polygon[2*i] y = region.polygon[2*i+1] vertices.append((x,y)) polygon = flex.vec2_double(vertices) logger.info("Generating polygon mask:") logger.info(" panel = %d" % region.panel) for vertex in vertices: logger.info(" coord = (%d, %d)" % (vertex)) mask_untrusted_polygon(mask, polygon) # Create the resolution mask generator class ResolutionMaskGeneratorGetter(object): def __init__(self, beam, panel): self.beam = beam self.panel = panel self.result = None def __call__(self): if self.result is None: self.result = ResolutionMaskGenerator(beam, panel) return self.result get_resolution_mask_generator = ResolutionMaskGeneratorGetter(beam, panel) # Generate high and low resolution masks if self.params.d_min is not None: logger.info("Generating high resolution mask:") logger.info(" d_min = %f" % self.params.d_min) get_resolution_mask_generator().apply(mask, 0, self.params.d_min) if self.params.d_max is not None: logger.info("Generating low resolution mask:") logger.info(" d_max = %f" % self.params.d_max) d_min = self.params.d_max d_max = max(d_min + 1, 1e9) get_resolution_mask_generator().apply(mask, d_min, d_max) # Mask out the resolution range for drange in self.params.resolution_range: d_min=min(drange) d_max=max(drange) assert d_min < d_max, "d_min must be < d_max" logger.info("Generating resolution range mask:") logger.info(" d_min = %f" % d_min) logger.info(" d_max = %f" % d_max) get_resolution_mask_generator().apply(mask, d_min, d_max) # Mask out the resolution ranges for the ice rings for drange in generate_ice_ring_resolution_ranges( beam, panel, self.params.ice_rings): d_min=min(drange) d_max=max(drange) assert d_min < d_max, "d_min must be < d_max" logger.info("Generating ice ring mask:") logger.info(" d_min = %f" % d_min) logger.info(" d_max = %f" % d_max) get_resolution_mask_generator().apply(mask, d_min, d_max) # Add to the list masks.append(mask) # Return the mask return tuple(masks)
aabb = ((0, 0), (10, 10)) ##quad = ((3, 3), (5, 3), (5, 5), (3, 5)) quad = ((0, -15), (15, 7.5), (7.5, 15), (-5, 5)) quad = ((5, -2), (12, 5), (5, 12), (-2, 5)) from dials.algorithms.polygon import clip from scitbx.array_family import flex from time import time bx = (aabb[0][0], aabb[1][0], aabb[1][0], aabb[0][0]) by = (aabb[0][1], aabb[0][1], aabb[1][1], aabb[1][1]) convex = zip(bx, by) poly1 = flex.vec2_double(quad) poly2 = flex.vec2_double(convex) rect = aabb st = time() for i in range(10000): result1 = clip.simple_with_convex(poly1, poly2) print time() - st st = time() for i in range(10000): # result2 = sutherland_hodgman(quad, aabb) result2 = clip.simple_with_rect(poly1, rect) print time() - st print list(result1)
def as_spot_max_pixels(self,active_block,asic): maxima = flex.vec2_double() for spot in self.spots: if self.verbose:print [(int(row)+asic[0],int(col)+asic[1]) for row,col in spot] pixel_values = [active_block[(int(row),int(col))] for row,col in spot]
def set_goniometer_points(self): gonio = self.imageset.get_goniometer() scan = self.imageset.get_scan() detector = self.imageset.get_detector() beam = self.imageset.get_beam() angle = self.settings.angle if angle: assert len(angle) == len(gonio.get_angles()) gonio.set_angles(angle) distance = self.settings.detector_distance if distance: import math from scitbx import matrix p_id = detector.get_panel_intersection(beam.get_s0()) if p_id >= 0: if len(detector) > 1: p = detector.hierarchy() else: p = detector[0] d_normal = matrix.col(p.get_normal()) d_origin = matrix.col(p.get_origin()) d_distance = math.fabs(d_origin.dot(d_normal) - p.get_directed_distance()) assert d_distance < 0.001, d_distance translation = d_normal * (distance - p.get_directed_distance()) new_origin = d_origin + translation d_distance = math.fabs(new_origin.dot(d_normal) - distance) assert d_distance < 0.001, d_distance p.set_frame(p.get_fast_axis(), p.get_slow_axis(), new_origin.elems) gonio_masker = self.imageset.reader().get_format().get_goniometer_shadow_masker(gonio) points = gonio_masker.extrema_at_scan_angle( gonio.get_angles()[gonio.get_scan_axis()]) points.insert(0, (0,0,0)) line_i_seqs = flex.vec2_double(((0,i) for i in range(1, points.size()))) line_i_seqs += (self.viewer.points.size(), self.viewer.points.size()) for i_seqs in line_i_seqs: self.viewer.line_i_seqs.append([int(i_seq) for i_seq in i_seqs]) self.viewer.line_colors[(i_seqs)] = (100/255, 120/255, 255/255) self.viewer.points.extend(points) shadow = gonio_masker.project_extrema( detector, gonio.get_angles()[gonio.get_scan_axis()]) for shadow_points, p in zip(shadow, detector): n = self.viewer.points.size() line_i_seqs = [] line_colors = {} for i in range(shadow_points.size()): if i < shadow_points.size() - 1: line_i_seqs.append((n+i, n+i+1)) else: line_i_seqs.append((n+i, n)) line_colors[line_i_seqs[-1]] = (1,1,1) self.viewer.line_colors.update(line_colors) self.viewer.line_i_seqs.extend(line_i_seqs) self.viewer.points.extend(p.get_lab_coord(shadow_points *p.get_pixel_size()[0]))
def project_extrema(self, detector, scan_angle): from dials.util import is_inside_polygon coords = self.extrema_at_scan_angle(scan_angle) shadow_boundary = [] for p_id, p in enumerate(detector): # project coordinates onto panel plane a = p.get_D_matrix() * coords x, y, z = a.parts() valid = z > 0 x.set_selected(valid, x.select(valid)/z.select(valid)) y.set_selected(valid, y.select(valid)/z.select(valid)) if valid.count(True) < 3: # no shadow projected onto this panel shadow_boundary.append(flex.vec2_double()) continue # Compute convex hull of shadow points points = flex.vec2_double(x.select(valid), y.select(valid)) shadow = flex.vec2_double(convex_hull(points)) shadow *= 1/p.get_pixel_size()[0] shadow_orig = shadow.deep_copy() for i in (0, p.get_image_size()[0]): points = flex.vec2_double(flex.double(p.get_image_size()[1], i), flex.double_range(0, p.get_image_size()[1])) inside = is_inside_polygon(shadow_orig, points) # only add those points needed to define vertices of shadow inside_isel = inside.iselection() outside_isel = (~inside).iselection() while inside_isel.size(): j = inside_isel[0] shadow.append(points[j]) outside_isel = outside_isel.select(outside_isel > j) if outside_isel.size() == 0: shadow.append(points[inside_isel[-1]]) break sel = inside_isel >= outside_isel[0] if sel.count(True) == 0: shadow.append(points[inside_isel[-1]]) break inside_isel = inside_isel.select(sel) for i in (0, p.get_image_size()[1]): points = flex.vec2_double(flex.double_range(0, p.get_image_size()[0]), flex.double(p.get_image_size()[0], i)) inside = is_inside_polygon(shadow_orig, points) # only add those points needed to define vertices of shadow inside_isel = inside.iselection() outside_isel = (~inside).iselection() while inside_isel.size(): j = inside_isel[0] shadow.append(points[j]) outside_isel = outside_isel.select(outside_isel > j) if outside_isel.size() == 0: shadow.append(points[inside_isel[-1]]) break sel = inside_isel >= outside_isel[0] if sel.count(True) == 0: shadow.append(points[inside_isel[-1]]) break inside_isel = inside_isel.select(sel) # Select only those vertices that are within the panel dimensions n_px = p.get_image_size() x, y = shadow.parts() valid = (x >= 0) & (x <= n_px[0]) & (y >= 0) & (y <= n_px[1]) shadow = shadow.select(valid) # sort vertices clockwise from centre of mass from scitbx.math import principal_axes_of_inertia_2d com = principal_axes_of_inertia_2d(shadow).center_of_mass() sx, sy = shadow.parts() shadow = shadow.select( flex.sort_permutation(flex.atan2(sy-com[1],sx-com[0]))) shadow_boundary.append(shadow) return shadow_boundary
def __init__(self,points): self.points = flex.vec2_double(parse(points)) print list(self.points)