repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
dls-controls/scanpointgenerator
tests/test_core/test_compoundgenerator.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import CompoundGenerator, Mutator, Generator, Excluder from scanpointgenerator import LineGenerator from scanpointgenerator import SpiralGenerator from scanpointgenerator import LissajousGenerator from scanpointgenerator import StaticPointGenerator from scanpointgenerator import ROIExcluder from scanpointgenerator import SquashingExcluder from scanpointgenerator.rois import CircularROI, RectangularROI, EllipticalROI, SectorROI, PolygonalROI from scanpointgenerator.mutators import RandomOffsetMutator from scanpointgenerator.compat import range_, np from pkg_resources import require require("mock") from mock import patch, MagicMock, ANY class CompoundGeneratorTest(ScanPointGeneratorTest): def test_init(self): x = LineGenerator("x", "mm", 1.0, 1.2, 3, True) y = LineGenerator("y", "mm", 2.0, 2.1, 2, False) g = CompoundGenerator([y, x], [], [], 0.2, False) self.assertEqual(g.generators[0], y) self.assertEqual(g.generators[1], x) self.assertEqual(g.units, dict(y="mm", x="mm")) self.assertEqual(g.axes, ["y", "x"]) self.assertEqual(g.duration, 0.2) def test_default_init_values(self): g = CompoundGenerator([], [], []) self.assertEqual(-1, g.duration) self.assertEqual(True, g.continuous) def test_given_compound_raise_error(self): g = CompoundGenerator([], [], []) with self.assertRaises(AssertionError): CompoundGenerator([g], [], []) def test_duplicate_name_raises(self): x = LineGenerator("x", "mm", 1.0, 1.2, 3, True) y = LineGenerator("x", "mm", 2.0, 2.1, 2, False) with self.assertRaises(ValueError): CompoundGenerator([y, x], [], []) def test_raise_before_prepare(self): x = LineGenerator("x", "mm", 1.0, 1.2, 3, True) g = CompoundGenerator([x], [], []) with self.assertRaises(ValueError): g.get_point(0) with self.assertRaises(ValueError): for p in g.iterator(): pass def test_prepare_idempotent(self): x = LineGenerator("x", "mm", 1.0, 1.2, 3, True) g = CompoundGenerator([x], [], []) x.prepare_positions = MagicMock(return_value=x.prepare_positions()) g.prepare() x.prepare_positions.assert_called_once_with() x.prepare_positions.reset_mock() g.prepare() x.prepare_positions.assert_not_called() def test_iterator(self): x = LineGenerator("x", "mm", 1.0, 2.0, 5, False) y = LineGenerator("y", "mm", 1.0, 2.0, 5, False) g = CompoundGenerator([y, x], [], []) g.prepare() points = list(g.iterator()) expected_pos = [{"x":x/4., "y":y/4.} for y in range_(4, 9) for x in range_(4, 9)] self.assertEqual(expected_pos, [p.positions for p in points]) expected_indexes = [[y, x] for y in range_(0, 5) for x in range_(0, 5)] self.assertEqual(expected_indexes, [p.indexes for p in points]) def test_get_point(self): x = LineGenerator("x", "mm", -1., 1, 5, False) y = LineGenerator("y", "mm", -1., 1, 5, False) z = LineGenerator("z", "mm", -1., 1, 5, False) r = CircularROI([0., 0.], 1) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([z, y, x], [e], []) g.prepare() points = [g.get_point(n) for n in range(0, g.size)] pos = [p.positions for p in points] idx = [p.indexes for p in points] xy_expected = [(x/2., y/2.) for y in range_(-2, 3) for x in range_(-2, 3)] xy_expected = [(x, y) for (x, y) in xy_expected if x*x + y*y <= 1] expected = [{"x":x, "y":y, "z":z/2.} for z in range_(-2, 3) for (x, y) in xy_expected] self.assertEqual(expected, pos) expected_idx = [[z, xy] for z in range_(5) for xy in range_(len(xy_expected))] self.assertEqual(expected_idx, idx) def test_get_point_large_scan(self): s = SpiralGenerator(["x", "y"], "mm", [0, 0], 6, 1) #114 points z = LineGenerator("z", "mm", 0, 1, 100) w = LineGenerator("w", "mm", 0, 1, 5) t = LineGenerator("t", "mm", 0, 1, 5) rad1 = 2.8 r1 = CircularROI([1., 1.], rad1) e1 = ROIExcluder([r1], ["x", "y"]) rad2 = 2 r2 = CircularROI([0.5, 0.5], rad2) e2 = ROIExcluder([r2], ["y", "z"]) rad3 = 0.5 r3 = CircularROI([0.5, 0.5], rad3) e3 = ROIExcluder([r3], ["w", "t"]) g = CompoundGenerator([t, w, z, s], [e1, e2, e3], []) g.prepare() spiral = [(x, y) for (x, y) in zip(s.positions["x"], s.positions["y"])] zwt = [(z/99., w/4., t/4.) for t in range_(0, 5) for w in range_(0, 5) for z in range_(0, 100)] expected = [(x, y, z, w, t) for (z, w, t) in zwt for (x, y) in spiral] expected = [{"x":x, "y":y, "z":z, "w":w, "t":t} for (x,y,z,w,t) in expected if (x-1)*(x-1) + (y-1)*(y-1) <= rad1*rad1 and (y-0.5)*(y-0.5) + (z-0.5)*(z-0.5) <= rad2*rad2 and (w-0.5)*(w-0.5) + (t-0.5)*(t-0.5) <= rad3*rad3] points = [g.get_point(n) for n in range_(0, g.size)] pos = [p.positions for p in points] # assertEqual on a sequence of dicts is *really* slow for (e, p) in zip(expected, pos): self.assertEquals(e.keys(), p.keys()) for k in e.keys(): self.assertAlmostEqual(e[k], p[k]) def test_alternating_simple(self): y = LineGenerator("y", "mm", 1, 5, 5) x = LineGenerator("x", "mm", 1, 5, 5, alternate=True) g = CompoundGenerator([y, x], [], []) g.prepare() expected = [] expected_idx = [] expected_lower = [] expected_upper = [] for y in range_(1, 6): x_f = y % 2 == 1 r = range_(1, 6) if x_f else range_(5, 0, -1) for x in r: expected.append({"y":float(y), "x":float(x)}) expected_idx.append([y - 1, x - 1]) expected_lower.append(x + (-0.5 if x_f else 0.5)) expected_upper.append(x + (0.5 if x_f else -0.5)) points = list(g.iterator()) self.assertEqual(expected, [p.positions for p in points]) self.assertEqual(expected_idx, [p.indexes for p in points]) self.assertEqual(expected_lower, [p.lower["x"] for p in points]) self.assertEqual(expected_upper, [p.upper["x"] for p in points]) def test_alternating_three_axis(self): z = LineGenerator("z", "mm", 1, 2, 2) y = LineGenerator("y", "mm", 1, 2, 2, True) x = LineGenerator("x", "mm", 3, 1, 3, True) g = CompoundGenerator([z, y, x], [], []) g.prepare() expected = [] expected_idx = [] expected_lower = [] expected_upper = [] y_f = True x_f = True for z in range_(1, 3): y_r = range_(1, 3) if y_f else range_(2, 0, -1) y_f = not y_f for y in y_r: x_r = range_(3, 0, -1) if x_f else range_(1, 4) for x in x_r: expected.append({"x":float(x), "y":float(y), "z":float(z)}) expected_idx.append([z-1, y-1, 3-x]) expected_lower.append(x + (0.5 if x_f else -0.5)) expected_upper.append(x + (-0.5 if x_f else 0.5)) x_f = not x_f points = list(g.iterator()) self.assertEqual(expected, [p.positions for p in points]) self.assertEqual(expected_idx, [p.indexes for p in points]) self.assertEqual(expected_lower, [p.lower["x"] for p in points]) self.assertEqual(expected_upper, [p.upper["x"] for p in points]) def test_alternating_with_region(self): y = LineGenerator("y", "mm", 1, 5, 5, True) x = LineGenerator("x", "mm", 1, 5, 5, True) r1 = CircularROI([3, 3], 1.5) e1 = ROIExcluder([r1], ["y", "x"]) g = CompoundGenerator([y, x], [e1], []) g.prepare() expected = [] x_f = True for y in range_(1, 6): r = range_(1, 6) if x_f else range(5, 0, -1) x_f = not x_f for x in r: expected.append({"y":float(y), "x":float(x)}) expected = [p for p in expected if ((p["x"]-3)**2 + (p["y"]-3)**2 <= 1.5**2)] expected_idx = [[xy] for xy in range_(len(expected))] points = list(g.iterator()) self.assertEqual(expected, [p.positions for p in points]) self.assertEqual(expected_idx, [p.indexes for p in points]) self.assertEqual((len(expected),), g.shape) def test_inner_alternating(self): z = LineGenerator("z", "mm", 1, 5, 5) y = LineGenerator("y", "mm", 1, 5, 5, alternate=True) x = LineGenerator("x", "mm", 1, 5, 5, alternate=True) r1 = CircularROI([3, 3], 1.5) e1 = ROIExcluder([r1], ["x", "y"]) g = CompoundGenerator([z, y, x], [e1], []) g.prepare() expected = [] xy_expected = [] x_f = True for y in range_(1, 6): for x in (range_(1, 6) if x_f else range(5, 0, -1)): if (x-3)**2 + (y-3)**2 <= 1.5**2: xy_expected.append((x, y)) x_f = not x_f xy_f = True for z in range_(1, 6): for (x, y) in (xy_expected if xy_f else xy_expected[::-1]): expected.append({"x":float(x), "y":float(y), "z":float(z)}) xy_f = not xy_f expected_idx = [] xy_f = True for z in range_(0, 5): xy_idx = range_(len(xy_expected)) if xy_f \ else range_(len(xy_expected)-1, -1, -1) expected_idx += [[z, xy] for xy in xy_idx] xy_f = not xy_f points = list(g.iterator()) self.assertEqual(expected, [p.positions for p in points]) self.assertEqual(expected_idx, [p.indexes for p in points]) def test_two_dim_inner_alternates(self): wg = LineGenerator("w", "mm", 0, 1, 2) zg = LineGenerator("z", "mm", 0, 1, 2) yg = LineGenerator("y", "mm", 1, 3, 3, True) xg = LineGenerator("x", "mm", 0, 1, 2, True) r1 = EllipticalROI([0, 1], [1, 2]) r2 = SectorROI([0, 0], [0.2, 1], [0, 7]) e1 = ROIExcluder([r1], ['x', 'y']) e2 = ROIExcluder([r2], ['w', 'z']) g = CompoundGenerator([wg, zg, yg, xg], [e1, e2], []) g.prepare() actual = [p.positions for p in g.iterator()] expected = [(0, 1, 1, 0), (1, 1, 1, 0), (0, 2, 1, 0), (0, 3, 1, 0), (0, 3, 0, 1), (0, 2, 0, 1), (1, 1, 0, 1), (0, 1, 0, 1)] expected = [{"x":float(x), "y":float(y), "z":float(z), "w":float(w)} for (x, y, z, w) in expected] self.assertEqual(expected, actual) def test_three_dim_alternating_no_filter(self): zg = LineGenerator("z", "mm", 0, 2, 3, True) yg = LineGenerator("y", "mm", 0, 3, 4, True) xg = LineGenerator("x", "mm", 0, 2, 3, True) r1 = CircularROI([0, 0], 1000) e1 = ROIExcluder([r1], ["x", "y"]) e2 = ROIExcluder([r1], ["x", "z"]) g1 = CompoundGenerator([zg, yg, xg], [], []) g2 = CompoundGenerator([zg, yg, xg], [e1], []) g3 = CompoundGenerator([zg, yg, xg], [e2], []) g1.prepare() g2.prepare() g3.prepare() self.assertEquals((3, 4, 3), g1.shape) self.assertEquals((3, 12), g2.shape) self.assertEquals((36,), g3.shape) self.assertEqual(["z", "y", "x"], g1.axes) self.assertEqual(["z", "y", "x"], g2.axes) self.assertEqual(["z", "y", "x"], g3.axes) expected = [ {'z':0, 'y':0, 'x':0}, {'z':0, 'y':0, 'x':1}, {'z':0, 'y':0, 'x':2}, {'z':0, 'y':1, 'x':2}, {'z':0, 'y':1, 'x':1}, {'z':0, 'y':1, 'x':0}, {'z':0, 'y':2, 'x':0}, {'z':0, 'y':2, 'x':1}, {'z':0, 'y':2, 'x':2}, {'z':0, 'y':3, 'x':2}, {'z':0, 'y':3, 'x':1}, {'z':0, 'y':3, 'x':0}, {'z':1, 'y':3, 'x':0}, {'z':1, 'y':3, 'x':1}, {'z':1, 'y':3, 'x':2}, {'z':1, 'y':2, 'x':2}, {'z':1, 'y':2, 'x':1}, {'z':1, 'y':2, 'x':0}, {'z':1, 'y':1, 'x':0}, {'z':1, 'y':1, 'x':1}, {'z':1, 'y':1, 'x':2}, {'z':1, 'y':0, 'x':2}, {'z':1, 'y':0, 'x':1}, {'z':1, 'y':0, 'x':0}, {'z':2, 'y':0, 'x':0}, {'z':2, 'y':0, 'x':1}, {'z':2, 'y':0, 'x':2}, {'z':2, 'y':1, 'x':2}, {'z':2, 'y':1, 'x':1}, {'z':2, 'y':1, 'x':0}, {'z':2, 'y':2, 'x':0}, {'z':2, 'y':2, 'x':1}, {'z':2, 'y':2, 'x':2}, {'z':2, 'y':3, 'x':2}, {'z':2, 'y':3, 'x':1}, {'z':2, 'y':3, 'x':0}, ] expected_lower_bounds = [ -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, ] expected_upper_bounds = [ 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, ] p1 = list(g1.iterator()) p2 = list(g2.iterator()) p3 = list(g3.iterator()) self.assertEqual(len(expected), len(p1)) self.assertEqual(len(expected), len(p2)) self.assertEqual(len(expected), len(p3)) for i, p in enumerate(p1): self.assertEqual(expected[i], p.positions) for i, p in enumerate(p2): self.assertEqual(expected[i], p.positions) for i, p in enumerate(p3): self.assertEqual(expected[i], p.positions) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in p1]) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in p2]) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in p3]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in p1]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in p2]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in p3]) def test_three_axis_alternating_filtered(self): zg = LineGenerator("z", "mm", 0, 2, 3, True) yg = LineGenerator("y", "mm", 0, 3, 4, True) xg = LineGenerator("x", "mm", 0, 2, 3, True) r = CircularROI([0, 0], 2.2) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([zg, yg, xg], [e], []) g.prepare() self.assertEqual((3, 6), g.shape) expected = [ {'z':0, 'y':0, 'x':0}, {'z':0, 'y':0, 'x':1}, {'z':0, 'y':0, 'x':2}, {'z':0, 'y':1, 'x':1}, {'z':0, 'y':1, 'x':0}, {'z':0, 'y':2, 'x':0}, {'z':1, 'y':2, 'x':0}, {'z':1, 'y':1, 'x':0}, {'z':1, 'y':1, 'x':1}, {'z':1, 'y':0, 'x':2}, {'z':1, 'y':0, 'x':1}, {'z':1, 'y':0, 'x':0}, {'z':2, 'y':0, 'x':0}, {'z':2, 'y':0, 'x':1}, {'z':2, 'y':0, 'x':2}, {'z':2, 'y':1, 'x':1}, {'z':2, 'y':1, 'x':0}, {'z':2, 'y':2, 'x':0}, ] expected_lower_bounds = [ -0.5, 0.5, 1.5, 1.5, 0.5, -0.5, 0.5, -0.5, 0.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 1.5, 0.5, -0.5, ] expected_upper_bounds = [ 0.5, 1.5, 2.5, 0.5, -0.5, 0.5, -0.5, 0.5, 1.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 0.5, -0.5, 0.5, ] points = list(g.iterator()) self.assertEqual(len(expected), len(points)) for i, p in enumerate(points): self.assertEqual(expected[i], p.positions) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in points]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in points]) def test_three_axis_alternating_outer_filtered(self): zg = LineGenerator("z", "mm", 0, 2, 3, True) yg = LineGenerator("y", "mm", 0, 3, 4, True) xg = LineGenerator("x", "mm", 0, 2, 3, True) r = CircularROI([0, 0], 2.2) e = ROIExcluder([r], ["y", "z"]) g = CompoundGenerator([zg, yg, xg], [e], []) g.prepare() self.assertEqual((6, 3), g.shape) expected = [ {'z':0, 'y':0, 'x':0}, {'z':0, 'y':0, 'x':1}, {'z':0, 'y':0, 'x':2}, {'z':0, 'y':1, 'x':2}, {'z':0, 'y':1, 'x':1}, {'z':0, 'y':1, 'x':0}, {'z':0, 'y':2, 'x':0}, {'z':0, 'y':2, 'x':1}, {'z':0, 'y':2, 'x':2}, {'z':1, 'y':1, 'x':2}, {'z':1, 'y':1, 'x':1}, {'z':1, 'y':1, 'x':0}, {'z':1, 'y':0, 'x':0}, {'z':1, 'y':0, 'x':1}, {'z':1, 'y':0, 'x':2}, {'z':2, 'y':0, 'x':2}, {'z':2, 'y':0, 'x':1}, {'z':2, 'y':0, 'x':0}, ] expected_lower_bounds = [ -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, ] expected_upper_bounds = [ 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, ] expected_indexes = [ [0, 0], [0, 1], [0, 2], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [5, 2], [5, 1], [5, 0], ] points = list(g.iterator()) self.assertEqual(len(expected), len(points)) for i, p in enumerate(points): self.assertEqual(expected[i], p.positions) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in points]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in points]) self.assertEqual(expected_indexes, [p.indexes for p in g.iterator()]) def test_three_axis_alternating_all_filtered(self): z1g = LineGenerator("z1", "mm", 0, 2, 3, True) z2g = LineGenerator("z2", "mm", 0, 100, 2, True) # dummy axis to emulate 1D excluder yg = LineGenerator("y", "mm", 0, 3, 4, True) xg = LineGenerator("x", "mm", 0, 2, 3, True) r1 = CircularROI([0, 0], 2.8) r2 = CircularROI([2.5, 0], 1.5) e1 = ROIExcluder([r1], ["x", "y"]) e2 = ROIExcluder([r2], ["z1", "z2"]) g = CompoundGenerator([z2g, z1g, yg, xg], [e1, e2], []) g.prepare() self.assertEqual((2, 8), g.shape) expected = [ {'z1':1, 'z2':0, 'x':0, 'y':0}, {'z1':1, 'z2':0, 'x':1, 'y':0}, {'z1':1, 'z2':0, 'x':2, 'y':0}, {'z1':1, 'z2':0, 'x':2, 'y':1}, {'z1':1, 'z2':0, 'x':1, 'y':1}, {'z1':1, 'z2':0, 'x':0, 'y':1}, {'z1':1, 'z2':0, 'x':0, 'y':2}, {'z1':1, 'z2':0, 'x':1, 'y':2}, {'z1':2, 'z2':0, 'x':1, 'y':2}, {'z1':2, 'z2':0, 'x':0, 'y':2}, {'z1':2, 'z2':0, 'x':0, 'y':1}, {'z1':2, 'z2':0, 'x':1, 'y':1}, {'z1':2, 'z2':0, 'x':2, 'y':1}, {'z1':2, 'z2':0, 'x':2, 'y':0}, {'z1':2, 'z2':0, 'x':1, 'y':0}, {'z1':2, 'z2':0, 'x':0, 'y':0}, ] expected_lower_bounds = [ -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5] expected_upper_bounds = [ 0.5, 1.5, 2.5, 1.5, 0.5, -0.5, 0.5, 1.5, 0.5, -0.5, 0.5, 1.5, 2.5, 1.5, 0.5, -0.5] points = list(g.iterator()) self.assertEqual(len(expected), len(points)) for i, p in enumerate(points): self.assertEqual(expected[i], p.positions) self.assertEqual(expected_lower_bounds, [p.lower["x"] for p in points]) self.assertEqual(expected_upper_bounds, [p.upper["x"] for p in points]) def test_three_dim_middle_alternates(self): tg = LineGenerator("t", "mm", 1, 5, 5) zg = LineGenerator("z", "mm", -1, 3, 5, True) spiral = SpiralGenerator(["s1", "s2"], "mm", [1, 1], 2, 1, True) yg = LineGenerator("y", "mm", 0, 4, 5) xg = LineGenerator("x", "mm", 0, 4, 5) r1 = CircularROI([0, 0], 1) e1 = ROIExcluder([r1], ["s1", "z"]) e2 = ROIExcluder([r1], ["y", "x"]) g = CompoundGenerator([tg, zg, spiral, yg, xg], [e2, e1], []) g.prepare() it = 0 iz = 0 iy = 0 ix = 0 tzs = [] points = [] for t in range_(1, 6): for z in (range_(-1, 4) if it % 2 == 0 else range_(3, -2, -1)): s1p = spiral.positions["s1"] if iz % 2 == 0 else spiral.positions["s1"][::-1] s2p = spiral.positions["s2"] if iz % 2 == 0 else spiral.positions["s2"][::-1] points += [(x, y, s1, s2, z, t) for (s1, s2) in zip(s1p, s2p) for y in range(0, 5) for x in range(0, 5) if s1*s1 + z*z <= 1 and y*y + x*x <= 1] iz += 1 it += 1 expected = [{"x":float(x), "y":float(y), "s1":s1, "s2":s2, "z":float(z), "t":float(t)} for (x, y, s1, s2, z, t) in points] actual = [p.positions for p in list(g.iterator())] for e, a in zip(expected, actual): self.assertEqual(e, a) def test_triple_alternating_linked_gen(self): tg = LineGenerator("t", "mm", 1, 5, 5) zg = LineGenerator("z", "mm", -1, 3, 5, True) yg = LineGenerator("y", "mm", 0, 4, 5, True) xg = LineGenerator("x", "mm", 0, 4, 5, True) r1 = RectangularROI([-1, -1], 5.5, 3.5) r2 = RectangularROI([1, 0], 2.5, 2.5) e1 = ROIExcluder([r1], ["z", "y"]) e2 = ROIExcluder([r2], ["x", "y"]) g = CompoundGenerator([tg, zg, yg, xg], [e1, e2], []) g.prepare() zf = True yf = True xf = True expected = [] for t in range_(1, 6): zr = range_(-1, 4) if zf else range_(3, -2, -1) zf = not zf for z in zr: yr = range_(0, 5) if yf else range_(4, -1, -1) yf = not yf for y in yr: xr = range_(0, 5) if xf else range_(4, -1, -1) xf = not xf for x in xr: if z >= -1 and z < 4.5 and y >= 0 and y < 2.5 \ and x >= 1 and x < 3.5: expected.append({"x":float(x), "y":float(y), "z":float(z), "t":float(t)}) actual = [p.positions for p in g.iterator()] self.assertEqual(len(expected), len(actual)) for e, a in zip(expected, actual): self.assertEqual(e, a) def test_alternating_regions_2(self): z = LineGenerator("z", "mm", 1, 5, 5) y = LineGenerator("y", "mm", 1, 5, 5, True) x = LineGenerator("x", "mm", 1, 5, 5, True) r1 = CircularROI([3, 3], 1.5) e1 = ROIExcluder([r1], ["x", "y"]) e2 = ROIExcluder([r1], ["z", "y"]) g = CompoundGenerator([z, y, x], [e1, e2], []) #20 points g.prepare() actual = [p.positions for p in list(g.iterator())] expected = [] yf = True xf = True for z in range_(1, 6): yr = range_(1, 6) if yf else range_(5, 0, -1) yf = not yf for y in yr: xr = range_(1, 6) if xf else range_(5, 0, -1) xf = not xf for x in xr: expected.append({"x":float(x), "y":float(y), "z":float(z)}) expected = [p for p in expected if (p["x"]-3)**2 + (p["y"]-3)**2 <= 1.5**2 and (p["z"]-3)**2 + (p["y"]-3)**2 <= 1.5**2] self.assertEqual(expected, actual) def test_alternating_complex(self): tg = LineGenerator("t", "mm", 1, 5, 5) zg = LineGenerator("z", "mm", 1, 5, 5, True) yg = LineGenerator("y", "mm", 1, 5, 5, True) xg = LineGenerator("x", "mm", 1, 5, 5, True) r1 = RectangularROI([3., 3.], 2., 2.) e1 = ROIExcluder([r1], ["y", "x"]) e2 = ROIExcluder([r1], ["z", "y"]) g = CompoundGenerator([tg, zg, yg, xg], [e1, e2], []) g.debug = True g.prepare() points = [p.positions for p in list(g.iterator())] expected = [] zf, yf, xf = True, True, True for t in range_(1, 6): r_1 = range_(1,6) if zf else range_(5, 0, -1) zf = not zf for z in r_1: r_2 = range_(1,6) if yf else range_(5, 0, -1) yf = not yf for y in r_2: r_3 = range_(1, 6) if xf else range_(5, 0, -1) xf = not xf for x in r_3: expected.append( {"t":float(t), "z":float(z), "y":float(y), "x":float(x)}) expected = [p for p in expected if (p["y"] >= 3 and p["y"] <= 5 and p["x"] >= 3 and p["x"] <= 5) and (p["z"] >= 3 and p["z"] <= 5 and p["y"] >= 3 and p["y"] <= 5)] self.assertEqual(expected, points) def test_mixed_alternating_simple(self): zg = LineGenerator("z", "mm", 1, 5, 5) yg = LineGenerator("y", "mm", 1, 5, 5) xg = LineGenerator("x", "mm", 1, 5, 5, True) e = SquashingExcluder(["x", "y"]) g = CompoundGenerator([zg, yg, xg], [e], []) g.prepare() expected = [] expected_idx = [] expected_dim_x = [ 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5] expected_dim_y = [ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5] for n1, z in enumerate(range_(1, 6)): for n2, (x, y) in enumerate(zip(expected_dim_x, expected_dim_y)): expected.append({"z":float(z), "y":float(y), "x":float(x)}) expected_idx.append([n1, n2]) points = [p.positions for p in list(g.iterator())] self.assertEqual(expected, points) self.assertEqual(expected_idx, [p.indexes for p in list(g.iterator())]) def test_mixed_dim_complex(self): tg = LineGenerator("t", "mm", 1, 5, 5, False) zg = LineGenerator("z", "mm", 11, 13, 3, True) yg = LineGenerator("y", "mm", 21, 23, 3, True) xg = LineGenerator("x", "mm", 31, 33, 3, False) wg = LineGenerator("w", "mm", 41, 43, 3, True) m1 = np.array([0, 0, 1, 1, 0, 1, 1, 1, 0]) m2 = np.array([1, 1, 0, 1, 1, 0, 1, 0, 1]) e1 = MagicMock(spec=Excluder([]), axes=["x", "w"]) e2 = MagicMock(spec=Excluder([]), axes=["z", "y"]) e1.create_mask.return_value=m1 e2.create_mask.return_value=m2 i1, i2 = np.nonzero(m1)[0], np.nonzero(m2)[0] g = CompoundGenerator([tg, zg, yg, xg, wg], [e1, e2], []) g.prepare() d1_w = np.array([41, 42, 43, 43, 42, 41, 41, 42, 43])[i1] d1_x = np.array([31, 31, 31, 32, 32, 32, 33, 33, 33])[i1] d2_y = np.array([21, 22, 23, 23, 22, 21, 21, 22, 23])[i2] d2_z = np.array([11, 11, 11, 12, 12, 12, 13, 13, 13])[i2] expected = [] expected_idx = [] d2_y_alt = d2_y d2_z_alt = d2_z d2_idx = list(range_(len(d2_z))) d2_idx_alt = d2_idx for n1, t in enumerate(range_(1, 6)): for n2, y, z in zip(d2_idx_alt, d2_y_alt, d2_z_alt): for n3, (w, x) in enumerate(zip(d1_w, d1_x)): expected.append({"t":float(t), "z":float(z), "y":float(y), "x":float(x), "w":float(w)}) expected_idx.append([n1, n2, n3]) d2_y_alt = d2_y_alt[::-1] d2_z_alt = d2_z_alt[::-1] d2_idx_alt = d2_idx_alt[::-1] points = [p.positions for p in list(g.iterator())] indexes = [p.indexes for p in list(g.iterator())] self.assertEqual(expected, points) self.assertEqual(expected_idx, indexes) def test_alternating_dim_inside_filtered(self): tg = LineGenerator("t", "mm", 1, 5, 5, False) zg = LineGenerator("z", "mm", 11, 13, 3, False) yg = LineGenerator("y", "mm", 21, 23, 3, True) xg = LineGenerator("x", "mm", 31, 33, 3, True) wg = LineGenerator("w", "mm", 41, 43, 3, True) m1 = np.array([0, 0, 1, 1, 0, 1, 1, 1, 0]) m2 = np.array([1, 1, 0, 1, 1, 0, 1, 0, 1]) e1 = MagicMock(spec=Excluder([]), axes=["x", "w"]) e2 = MagicMock(spec=Excluder([]), axes=["z", "y"]) e1.create_mask.return_value=m1 e2.create_mask.return_value=m2 i1, i2 = np.nonzero(m1)[0], np.nonzero(m2)[0] g = CompoundGenerator([tg, zg, yg, xg, wg], [e1, e2], []) g.prepare() d1_w = np.array([41, 42, 43, 43, 42, 41, 41, 42, 43])[i1] d1_x = np.array([31, 31, 31, 32, 32, 32, 33, 33, 33])[i1] d2_y = np.array([21, 22, 23, 23, 22, 21, 21, 22, 23])[i2] d2_z = np.array([11, 11, 11, 12, 12, 12, 13, 13, 13])[i2] d1_idx = list(range_(len(np.nonzero(m1)[0]))) expected = [] expected_idx = [] d1_w_alt = d1_w d1_x_alt = d1_x d1_idx_alt = d1_idx m1_alt = m1 for n1, t in enumerate(range_(1, 6)): n2 = 0 for (y, z) in zip(d2_y, d2_z): idx_iter = iter(d1_idx_alt) for (w, x, m1v) in zip(d1_w_alt, d1_x_alt, m1_alt): n3 = next(idx_iter) expected.append({"t":float(t), "z":float(z), "y":float(y), "x":float(x), "w":float(w)}) expected_idx.append([n1, n2, n3]) n2 += 1 d1_x_alt = d1_x_alt[::-1] d1_w_alt = d1_w_alt[::-1] d1_idx_alt = d1_idx_alt[::-1] points = [p.positions for p in list(g.iterator())] indexes = [p.indexes for p in list(g.iterator())] self.assertEqual(expected, points) self.assertEqual(expected_idx, indexes) def test_line_spiral(self): expected = [{'y': -0.3211855677650875, 'x': 0.23663214944574582, 'z': 0.0}, {'y': -0.25037538922751695, 'x': -0.6440318266552169, 'z': 0.0}, {'y': 0.6946549630820702, 'x': -0.5596688286164636, 'z': 0.0}, {'y': 0.6946549630820702, 'x': -0.5596688286164636, 'z': 2.0}, {'y': -0.25037538922751695, 'x': -0.6440318266552169, 'z': 2.0}, {'y': -0.3211855677650875, 'x': 0.23663214944574582, 'z': 2.0}, {'y': -0.3211855677650875, 'x': 0.23663214944574582, 'z': 4.0}, {'y': -0.25037538922751695, 'x': -0.6440318266552169, 'z': 4.0}, {'y': 0.6946549630820702, 'x': -0.5596688286164636, 'z': 4.0}, ] z = LineGenerator("z", "mm", 0.0, 4.0, 3) spiral = SpiralGenerator(['x', 'y'], "mm", [0.0, 0.0], 0.8, alternate=True) g = CompoundGenerator([z, spiral], [], []) g.prepare() self.assertEqual(g.axes, ["z", "x", "y"]) points = list(g.iterator()) self.assertEqual(len(expected), len(points)) for i, p in enumerate(points): self.assertEqual(expected[i], p.positions) def test_line_lissajous(self): expected = [{'y': 0.0, 'x': 0.5, 'z': 0.0}, {'y': 0.2938926261462366, 'x': 0.15450849718747375, 'z': 0.0}, {'y': -0.4755282581475768, 'x': -0.40450849718747367, 'z': 0.0}, {'y': 0.47552825814757677, 'x': -0.4045084971874738, 'z': 0.0}, {'y': -0.2938926261462364, 'x': 0.1545084971874736, 'z': 0.0}, {'y': 0.0, 'x': 0.5, 'z': 2.0}, {'y': 0.2938926261462366, 'x': 0.15450849718747375, 'z': 2.0}, {'y': -0.4755282581475768, 'x': -0.40450849718747367, 'z': 2.0}, {'y': 0.47552825814757677, 'x': -0.4045084971874738, 'z': 2.0}, {'y': -0.2938926261462364, 'x': 0.1545084971874736, 'z': 2.0}, {'y': 0.0, 'x': 0.5, 'z': 4.0}, {'y': 0.2938926261462366, 'x': 0.15450849718747375, 'z': 4.0}, {'y': -0.4755282581475768, 'x': -0.40450849718747367, 'z': 4.0}, {'y': 0.47552825814757677, 'x': -0.4045084971874738, 'z': 4.0}, {'y': -0.2938926261462364, 'x': 0.1545084971874736, 'z': 4.0}] z = LineGenerator("z", "mm", 0.0, 4.0, 3) liss = LissajousGenerator(['x', 'y'], "mm", [0., 0.], [1., 1.], 1, size=5) g = CompoundGenerator([z, liss], [], []) g.prepare() self.assertEqual(g.axes, ["z", "x", "y"]) points = list(g.iterator()) self.assertEqual(len(expected), len(points)) for i, p in enumerate(points): self.assertEqual(expected[i], p.positions) def test_horrible_scan(self): lissajous = LissajousGenerator( ["j1", "j2"], "mm", [-0.5, 0.7], [2, 3.5], 7, 100) line2 = LineGenerator(["l2"], "mm", -3, 3, 7, True) line1 = LineGenerator(["l1"], "mm", -1, 2, 5, True) spiral = SpiralGenerator(["s1", "s2"], "mm", [1, 2], 5, 2.5, True) r1 = CircularROI([1, 1], 2) r2 = CircularROI([-1, -1], 4) r3 = CircularROI([1, 1], 2) e1 = ROIExcluder([r1], ["j1", "l2"]) e2 = ROIExcluder([r2], ["s2", "l1"]) e3 = ROIExcluder([r3], ["s1", "s2"]) g = CompoundGenerator([lissajous, line2, line1, spiral], [e1, e2, e3], []) g.prepare() d1_s1 = np.append(spiral.positions["s1"], spiral.positions["s1"][::-1]) d1_s1 = np.append(np.tile(d1_s1, 2), spiral.positions["s1"]) d1_s2 = np.append(spiral.positions["s2"], spiral.positions["s2"][::-1]) d1_s2 = np.append(np.tile(d1_s2, 2), spiral.positions["s2"]) d1_l1 = np.repeat(line1.positions["l1"], len(spiral.positions["s1"])) d1_m = ((d1_s2+1)**2 + (d1_l1+1)**2 <= 16) & ((d1_s1-1)**2 + (d1_s2-1)**2 <= 4) d1_i = np.nonzero(d1_m)[0] d2_j1 = np.repeat(lissajous.positions["j1"], len(line2.positions["l2"])) d2_j2 = np.repeat(lissajous.positions["j2"], len(line2.positions["l2"])) d2_l2 = np.append(line2.positions["l2"], line2.positions["l2"][::-1]) d2_l2 = np.tile(d2_l2, int(lissajous.size//2)) d2_m = ((d2_j1-1)**2 + (d2_l2-1)**2) <= 4 d2_i = np.nonzero(d2_m)[0] expected = [] expected_idx = [] d1_i_alt = d1_i n1_alt = list(range_(len(d1_i))) for n2, (j1, j2, l2) in enumerate(zip(d2_j1[d2_i], d2_j2[d2_i], d2_l2[d2_i])): for n1, s1, s2, l1 in zip(n1_alt, d1_s1[d1_i_alt], d1_s2[d1_i_alt], d1_l1[d1_i_alt]): expected.append({"j1":j1, "j2":j2, "l2":l2, "l1":l1, "s1":s1, "s2":s2}) expected_idx.append([n2, n1]) d1_i_alt = d1_i_alt[::-1] n1_alt = n1_alt[::-1] self.assertEqual((181, 10), g.shape) self.assertEqual(expected, [p.positions for p in g.iterator()]) def test_double_spiral_scan(self): line1 = LineGenerator(["l1"], "mm", -1, 2, 5) spiral_s = SpiralGenerator(["s1", "s2"], "mm", [1, 2], 5, 2.5, True) spiral_t = SpiralGenerator(["t1", "t2"], "mm", [0, 0], 5, 2.5, True) line2 = LineGenerator(["l2"], "mm", -1, 2, 5, True) r = CircularROI([0, 0], 1) e1 = ROIExcluder([r], ["s1", "l1"]) e2 = ROIExcluder([r], ["l2", "t1"]) g = CompoundGenerator([line1, spiral_s, spiral_t, line2], [e1, e2], []) g.prepare() d1_s1 = np.append(spiral_s.positions["s1"], spiral_s.positions["s1"][::-1]) d1_s1 = np.append(np.tile(d1_s1, 2), spiral_s.positions["s1"]) d1_s2 = np.append(spiral_s.positions["s2"], spiral_s.positions["s2"][::-1]) d1_s2 = np.append(np.tile(d1_s2, 2), spiral_s.positions["s2"]) d1_l1 = np.repeat(line1.positions["l1"], spiral_s.size) d1_m = d1_s1*d1_s1 + d1_l1*d1_l1 <= 1 d1_i = np.nonzero(d1_m)[0] d2_l2 = np.append(line2.positions["l2"], line2.positions["l2"][::-1]) d2_l2_u = np.append(line2.bounds["l2"][1:], line2.bounds["l2"][:-1][::-1]) d2_l2_l = np.append(line2.bounds["l2"][:-1], line2.bounds["l2"][1:][::-1]) d2_l2 = np.tile(d2_l2, int(spiral_t.size // 2)) d2_l2_u = np.tile(d2_l2_u, int(spiral_t.size // 2)) d2_l2_l = np.tile(d2_l2_l, int(spiral_t.size // 2)) if len(d2_l2) != spiral_t.size: d2_l2 = np.append(d2_l2, line2.positions["l2"]) d2_l2_u = np.append(d2_l2_u, line2.bounds["l2"][1:]) d2_l2_l = np.append(d2_l2_l, line2.bounds["l2"][:-1]) d2_t1 = np.repeat(spiral_t.positions["t1"], line2.size) d2_t2 = np.repeat(spiral_t.positions["t2"], line2.size) d2_m = d2_l2*d2_l2 + d2_t1*d2_t1 <= 1 d2_i = np.nonzero(d2_m)[0] expected = [] expected_lower = [] expected_upper = [] expected_idx = [] d2_i_alt = d2_i d2_l2_l_alt = d2_l2_l d2_l2_u_alt = d2_l2_u n2_alt = list(range(len(d2_i))) for n1, (l1, s1, s2) in enumerate(zip(d1_l1[d1_i], d1_s1[d1_i], d1_s2[d1_i])): for n2, t1, t2, l2, l2u, l2l in zip( n2_alt, d2_t1[d2_i_alt], d2_t2[d2_i_alt], d2_l2[d2_i_alt], d2_l2_u_alt[d2_i_alt], d2_l2_l_alt[d2_i_alt]): expected.append({"l1":l1, "s1":s1, "s2":s2, "t1":t1, "t2":t2, "l2":l2}) expected_upper.append({"l1":l1, "s1":s1, "s2":s2, "t1":t1, "t2":t2, "l2":l2u}) expected_lower.append({"l1":l1, "s1":s1, "s2":s2, "t1":t1, "t2":t2, "l2":l2l}) expected_idx.append([n1, n2]) d2_i_alt = d2_i_alt[::-1] n2_alt = n2_alt[::-1] d2_l2_l_alt, d2_l2_u_alt = d2_l2_u_alt, d2_l2_l_alt g_points = list(g.iterator()) self.assertEqual(expected_lower, [p.lower for p in g_points]) self.assertEqual(expected, [p.positions for p in g_points]) self.assertEqual(expected_upper, [p.upper for p in g_points]) self.assertEqual(expected_idx, [p.indexes for p in g_points]) def test_mutators(self): mutator_1 = MagicMock(spec=Mutator) mutator_1.mutate = MagicMock(side_effect = lambda x,n:x) mutator_2 = RandomOffsetMutator(0, ["x"], {"x":1}) mutator_2.calc_offset = MagicMock(return_value=0.1) x = LineGenerator('x', 'mm', 1, 5, 5) g = CompoundGenerator([x], [], [mutator_1, mutator_2], 0.2) g.prepare() x_pos = 1 n = 0 for p in g.iterator(): self.assertEqual(0.2, p.duration) self.assertEqual({"x":x_pos + 0.1}, p.positions) mutator_1.mutate.assert_called_once_with(p, n) mutator_1.mutate.reset_mock() n += 1 x_pos += 1 self.assertEqual(6, x_pos) def test_grid_rect_region(self): xg = LineGenerator("x", "mm", 1, 10, 10) yg = LineGenerator("y", "mm", 1, 10, 10) r = RectangularROI([3, 3], 6, 6) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([yg, xg], [e], []) g.prepare() self.assertEqual(49, g.size) p = g.get_point(8) self.assertEqual([1, 1], p.indexes) self.assertEqual((4, 4), (p.positions['y'], p.positions['x'])) p = g.get_point(48) self.assertEqual([6, 6], p.indexes) self.assertEqual((9, 9), (p.positions['y'], p.positions['x'])) p = g.get_point(14) self.assertEqual([2, 0], p.indexes) self.assertEqual((5, 3), (p.positions['y'], p.positions['x'])) def test_grid_double_rect_region_then_not_reduced(self): xg = LineGenerator("x", "mm", 1, 10, 10) yg = LineGenerator("y", "mm", 1, 10, 10) r1 = RectangularROI([3, 3], 6, 6) r2 = RectangularROI([3, 3], 6, 6) e = ROIExcluder([r1, r2], ["x", "y"]) g = CompoundGenerator([yg, xg], [e], []) g.prepare() self.assertEqual(2, len(g.excluders[0].rois)) def test_multi_roi_excluder(self): x = LineGenerator("x", "mm", 0.0, 4.0, 5, alternate=True) y = LineGenerator("y", "mm", 0.0, 3.0, 4) circles = ROIExcluder([CircularROI([1.0, 2.0], 2.0), CircularROI([1.0, 2.0], 2.0)], ["x", "y"]) expected_positions = [{'x': 1.0, 'y': 0.0}, {'x': 2.0, 'y': 1.0}, {'x': 1.0, 'y': 1.0}, {'x': 0.0, 'y': 1.0}, {'x': 0.0, 'y': 2.0}, {'x': 1.0, 'y': 2.0}, {'x': 2.0, 'y': 2.0}, {'x': 3.0, 'y': 2.0}, {'x': 2.0, 'y': 3.0}, {'x': 1.0, 'y': 3.0}, {'x': 0.0, 'y': 3.0}] g = CompoundGenerator([y, x], [circles], []) g.prepare() positions = [point.positions for point in list(g.iterator())] self.assertEqual(positions, expected_positions) def test_excluder_spread_axes(self): sp = SpiralGenerator(["s1", "s2"], ["mm", "mm"], centre=[0, 0], radius=1, scale=0.5, alternate=True) y = LineGenerator("y", "mm", 0, 1, 3, True) z = LineGenerator("z", "mm", -2, 3, 6, True) e = ROIExcluder([CircularROI([0., 0.], 1.0)], ["s1", "z"]) g = CompoundGenerator([z, y, sp], [e], []) g.prepare() s1_pos, s2_pos = sp.positions["s1"], sp.positions["s2"] s1_pos = np.tile(np.append(s1_pos, s1_pos[::-1]), 9) s2_pos = np.tile(np.append(s2_pos, s2_pos[::-1]), 9) y_pos = np.tile(np.repeat(np.array([0, 0.5, 1.0, 1.0, 0.5, 0]), sp.size), 3) z_pos = np.repeat(np.array([-2, -1, 0, 1, 2, 3]), sp.size * 3) mask_func = lambda ps1, pz: ps1**2 + pz**2 <= 1 mask = mask_func(s1_pos, z_pos) expected_s1 = s1_pos[mask] expected_s2 = s2_pos[mask] expected_y = y_pos[mask] expected_z = z_pos[mask] expected_positions = [{'s1':ps1, 's2':ps2, 'y':py, 'z':pz} for (ps1, ps2, py, pz) in zip(expected_s1, expected_s2, expected_y, expected_z)] positions = [point.positions for point in list(g.iterator())] self.assertEqual(positions, expected_positions) def test_bounds_applied_in_rectangle_roi_secial_case(self): x = LineGenerator("x", "mm", 0, 1, 2, True) y = LineGenerator("y", "mm", 0, 1, 2, True) r = RectangularROI([0, 0], 1, 1) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([y, x], [e], []) g.prepare() p = g.get_point(0) self.assertEqual({"x":-0.5, "y":0.}, p.lower) self.assertEqual({"x":0., "y":0.}, p.positions) self.assertEqual({"x":0.5, "y":0.}, p.upper) p = g.get_point(2) self.assertEqual({"x":1.5, "y":1}, p.lower) self.assertEqual({"x":1, "y":1}, p.positions) self.assertEqual({"x":0.5, "y":1}, p.upper) def test_no_bounds_for_non_continuous(self): x_points = np.array([1, 2]) y_points = np.array([11, 12]) x = MagicMock(axes=["x"], positions={"x":x_points}, size=len(x_points), alternate=False, spec=Generator) y = MagicMock(axes=["y"], positions={"y":y_points}, size=len(y_points), alternate=False, spec=Generator) g = CompoundGenerator([y, x], [], [], continuous=False) g.prepare() positions = [p.positions for p in g.iterator()] lower = [p.lower for p in g.iterator()] upper = [p.upper for p in g.iterator()] x.prepare_bounds.assert_not_called() y.prepare_bounds.assert_not_called() expected_positions = [{"x":1, "y":11}, {"x":2, "y":11}, {"x":1, "y":12}, {"x":2, "y":12}] self.assertEqual(expected_positions, positions) self.assertEqual(expected_positions, lower) self.assertEqual(expected_positions, upper) def test_staticpointgen(self): m = StaticPointGenerator(3) g = CompoundGenerator([m], [], []) g.prepare() expected_positions = [{}] * 3 positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual([], g.axes) self.assertEqual({}, g.units) self.assertEqual(3, g.size) self.assertEqual((3,), g.shape) self.assertEqual(1, len(g.dimensions)) self.assertEqual([], g.dimensions[0].upper) self.assertEqual([], g.dimensions[0].lower) self.assertEqual([], g.dimensions[0].axes) self.assertEqual(3, g.dimensions[0].size) def test_inner_staticpointgen(self): x = LineGenerator("x", "mm", 0, 1, 3, False) m = StaticPointGenerator(5) g = CompoundGenerator([x, m], [], []) g.prepare() expected_positions = [{'x':0.0}] * 5 + [{'x':0.5}] * 5 + [{'x':1.0}] * 5 positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(15, g.size) self.assertEqual((3, 5), g.shape) self.assertEqual(["x"], g.axes) self.assertEqual({"x":"mm"}, g.units) expected_dimensions = [{"axes":["x"], "size":3, "alternate":False, "upper":[1.0], "lower":[0.0]}, {"axes":[], "size":5, "alternate":False, "upper":[], "lower":[]}] dimensions = [{"axes":d.axes, "size":d.size, "alternate":d.alternate, "upper":d.upper, "lower":d.lower} for d in g.dimensions] self.assertEqual(expected_dimensions, dimensions) def test_line_with_staticpointgen(self): x = LineGenerator("x", "mm", 0, 1, 3, False) m = StaticPointGenerator(5) g = CompoundGenerator([m, x], [], []) g.prepare() expected_positions = [{'x':0.0}, {'x':0.5}, {'x':1.0}] * 5 positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(15, g.size) self.assertEqual((5, 3), g.shape) self.assertEqual(["x"], g.axes) self.assertEqual({"x":"mm"}, g.units) expected_dimensions = [{"axes":[], "size":5, "alternate":False, "upper":[], "lower":[]}, {"axes":["x"], "size":3, "alternate":False, "upper":[1.0], "lower":[0.0]}] dimensions = [{"axes":d.axes, "size":d.size, "alternate":d.alternate, "upper":d.upper, "lower":d.lower} for d in g.dimensions] self.assertEqual(expected_dimensions, dimensions) def test_alternating_line_with_staticpointgen(self): x = LineGenerator("x", "mm", 0, 1, 3, True) m = StaticPointGenerator(5) g = CompoundGenerator([m, x], [], []) g.prepare() expected_positions = [ {'x':0.0}, {'x':0.5}, {'x':1.0}, {'x':1.0}, {'x':0.5}, {'x':0.0}, {'x':0.0}, {'x':0.5}, {'x':1.0}, {'x':1.0}, {'x':0.5}, {'x':0.0}, {'x':0.0}, {'x':0.5}, {'x':1.0}] positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(15, g.size) self.assertEqual((5, 3), g.shape) self.assertEqual(["x"], g.axes) self.assertEqual({"x":"mm"}, g.units) expected_dimensions = [{"axes":[], "size":5, "alternate":False, "upper":[], "lower":[]}, {"axes":["x"], "size":3, "alternate":True, "upper":[1.0], "lower":[0.0]}] dimensions = [{"axes":d.axes, "size":d.size, "alternate":d.alternate, "upper":d.upper, "lower":d.lower} for d in g.dimensions] self.assertEqual(expected_dimensions, dimensions) def test_intermediate_staticpointgen(self): x = LineGenerator("x", "mm", 0, 1, 3, False) y = LineGenerator("y", "cm", 2, 3, 4, False) m = StaticPointGenerator(5) g = CompoundGenerator([y, m, x], [], []) g.prepare() expected_positions = [] for yp in [2.0, 2 + 1./3, 2 + 2./3, 3.0]: for mp in range_(5): for xp in [0.0, 0.5, 1.0]: expected_positions.append({"y":yp, "x":xp}) positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(60, g.size) self.assertEqual((4, 5, 3), g.shape) self.assertEqual(["y", "x"], g.axes) self.assertEqual({"y":"cm", "x":"mm"}, g.units) self.assertEqual(3, len(g.dimensions)) def test_staticpointgen_with_axis(self): x = LineGenerator("x", "mm", 0, 1, 3, False) y = LineGenerator("y", "cm", 2, 3, 4, False) m = StaticPointGenerator(5, "repeats") g = CompoundGenerator([y, x, m], [], []) g.prepare() expected_positions = [] for yp in [2.0, 2 + 1./3, 2 + 2./3, 3.0]: for xp in [0.0, 0.5, 1.0]: for mp in range_(5): expected_positions.append({"y": yp, "x": xp, "repeats": mp + 1}) positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(60, g.size) self.assertEqual((4, 3, 5), g.shape) self.assertEqual(["y", "x", "repeats"], g.axes) self.assertEqual({"y": "cm", "x": "mm", "repeats": ""}, g.units) def test_staticpointgen_with_axis_and_excluder(self): x = LineGenerator("x", "mm", 0, 1, 3, False) y = LineGenerator("y", "cm", 2, 3, 4, False) m = StaticPointGenerator(5, "repeats") e = SquashingExcluder(["x", "repeats"]) g = CompoundGenerator([y, x, m], [e], []) g.prepare() # Expected positions should be the same as without the excluder expected_positions = [] for yp in [2.0, 2 + 1./3, 2 + 2./3, 3.0]: for xp in [0.0, 0.5, 1.0]: for mp in range_(5): expected_positions.append({"y": yp, "x": xp, "repeats": mp + 1}) positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(60, g.size) self.assertEqual((4, 15), g.shape) self.assertEqual(["y", "x", "repeats"], g.axes) self.assertEqual({"y": "cm", "x": "mm", "repeats": ""}, g.units) self.assertEqual(2, len(g.dimensions)) def test_staticpointgen_in_alternating(self): x = LineGenerator("x", "mm", 0, 1, 3, True) y = LineGenerator("y", "cm", 2, 3, 4, False) m = StaticPointGenerator(5) r = CircularROI((0.5, 2.5), 0.4) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([y, m, x], [e], []) g.prepare() expected_positions = [] x_positions = [0.0, 0.5, 1.0] direction = 1 for yp in [2.0, 2 + 1./3, 2 + 2./3, 3.0]: for mp in range_(5): for xp in x_positions[::direction]: if (xp-0.5)**2 + (yp-2.5)**2 <= 0.4**2: expected_positions.append({"y":yp, "x":xp}) direction *= -1 positions = [point.positions for point in g.iterator()] self.assertEqual(expected_positions, positions) self.assertEqual(len(expected_positions), g.size) self.assertEqual((len(expected_positions),), g.shape) self.assertEqual(["y", "x"], g.axes) self.assertEqual({"y":"cm", "x":"mm"}, g.units) self.assertEqual(1, len(g.dimensions)) def test_delay_after(self): x = LineGenerator("x", "mm", 0, 1, 1) g = CompoundGenerator([x], [], [], duration=1, delay_after=2) g.prepare() delays = [point.delay_after for point in g.iterator()] self.assertEqual([2], delays) def test_negative_delay_after(self): x = LineGenerator("x", "mm", 0, 1, 1) g = CompoundGenerator([x], [], [], duration=1, delay_after=-1) g.prepare() delays = [point.delay_after for point in g.iterator()] self.assertEqual([0], delays) class CompoundGeneratorInternalDataTests(ScanPointGeneratorTest): """Tests on datastructures internal to CompoundGenerator""" def test_post_prepare(self): x = LineGenerator("x", "mm", 1.0, 1.2, 3, True) y = LineGenerator("y", "mm", 2.0, 2.1, 2, False) g = CompoundGenerator([y, x], [], []) g.prepare() self.assertEqual(g.size, 6) self.assertEqual(2, len(g.dimensions)) dim_0 = g.dimensions[0] dim_1 = g.dimensions[1] self.assertEqual(["y"], dim_0.axes) self.assertEqual([True] * 2, dim_0.mask.tolist()) self.assertEqual(["x"], dim_1.axes) self.assertEqual([True] * 3, dim_1.mask.tolist()) self.assertEqual((2, 3), g.shape) def test_prepare_with_regions(self): x = LineGenerator("x", "mm", 0, 1, 5, False) y = LineGenerator("y", "mm", 0, 1, 5, False) circle = CircularROI([0., 0.], 1) excluder = ROIExcluder([circle], ['x', 'y']) g = CompoundGenerator([y, x], [excluder], []) g.prepare() self.assertEqual(1, len(g.dimensions)) self.assertEqual(["y", "x"], g.dimensions[0].axes) expected_mask = [(x/4.)**2 + (y/4.)**2 <= 1 for y in range(0, 5) for x in range(0, 5)] self.assertEqual(expected_mask, g.dimensions[0].mask.tolist()) self.assertEqual((len([v for v in expected_mask if v]),), g.shape) def test_simple_mask(self): x = LineGenerator("x", "mm", -1.0, 1.0, 5, False) y = LineGenerator("y", "mm", -1.0, 1.0, 5, False) r = CircularROI([0, 0], 1) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([y, x], [e], []) g.prepare() p = [(x/2., y/2.) for y in range_(-2, 3) for x in range_(-2, 3)] expected_mask = [x*x + y*y <= 1 for (x, y) in p] self.assertEqual(expected_mask, g.dimensions[0].mask.tolist()) def test_simple_mask_alternating(self): x = LineGenerator("x", "mm", -1.0, 1.0, 5, alternate=True) y = LineGenerator("y", "mm", -1.0, 1.0, 5, alternate=True) r = CircularROI([0.5, 0], 1) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([y, x], [e], []) g.prepare() reverse = False p = [] for y in range_(-2, 3): if reverse: p += [(x/2., y/2.) for x in range_(2, -3, -1)] else: p += [(x/2., y/2.) for x in range_(-2, 3)] reverse = not reverse expected_mask = [(x-0.5)**2 + y**2 <= 1**2 for (x, y) in p] self.assertEqual(expected_mask, g.dimensions[0].mask.tolist()) def test_double_mask_alternating_spiral(self): zgen = LineGenerator("z", "mm", 0.0, 4.0, 5, alternate=True) spiral = SpiralGenerator(['x', 'y'], "mm", [0.0, 0.0], 3, alternate=True) #29 points r1 = RectangularROI([-2, -2], 4, 3) r2 = RectangularROI([-2, 0], 4, 3) e1 = ROIExcluder([r1], ["y", "x"]) e2 = ROIExcluder([r2], ["y", "z"]) g = CompoundGenerator([zgen, spiral], [e1, e2], []) g.prepare() xy = list(zip(spiral.positions['x'], spiral.positions['y'])) p = [] for z in range_(0, 5): p += [(x, y, z) for (x, y) in (xy if z % 2 == 0 else xy[::-1])] expected = [x >= -2 and x <= 1 and y >= -2 and y <= 2 and z >= 0 and z <= 3 for (x, y, z) in p] actual = g.dimensions[0].mask.tolist() self.assertEqual(expected, actual) def test_double_mask_spiral(self): zgen = LineGenerator("z", "mm", 0.0, 4.0, 5) spiral = SpiralGenerator(['x', 'y'], "mm", [0.0, 0.0], 3) #29 points r1 = RectangularROI([-2, -2], 4, 3) r2 = RectangularROI([-2, 0], 4, 3) e1 = ROIExcluder([r1], ["y", "x"]) e2 = ROIExcluder([r2], ["y", "z"]) g = CompoundGenerator([zgen, spiral], [e1, e2], []) g.prepare() p = list(zip(spiral.positions['x'], spiral.positions['y'])) p = [(x, y, z) for z in range_(0, 5) for (x, y) in p] expected = [x >= -2 and x <= 1 and y >= -2 and y <= 2 and z >= 0 and z <= 3 for (x, y, z) in p] actual = g.dimensions[0].mask.tolist() self.assertEqual(expected, actual) def test_simple_mask_alternating_spiral(self): z = LineGenerator("z", "mm", 0.0, 4.0, 5) spiral = SpiralGenerator(['x', 'y'], "mm", [0.0, 0.0], 3, alternate=True) #29 points r = RectangularROI([-2, -2], 3, 4) e = ROIExcluder([r], ["x", "y"]) g = CompoundGenerator([z, spiral], [e], []) g.prepare() p = list(zip(spiral.positions['x'], spiral.positions['y'])) expected = [x >= -2 and x < 1 and y >= -2 and y < 2 for (x, y) in p] expected_r = [x >= -2 and x < 1 and y >= -2 and y < 2 for (x, y) in p[::-1]] actual = g.dimensions[1].mask.tolist() self.assertEqual(expected, actual) def test_double_mask(self): x = LineGenerator("x", "mm", -1.0, 1.0, 5, False) y = LineGenerator("y", "mm", -1.0, 1.0, 5, False) z = LineGenerator("z", "mm", -1.0, 1.0, 5, False) r = CircularROI([0.1, 0.2], 1) e1 = ROIExcluder([r], ["x", "y"]) e2 = ROIExcluder([r], ["y", "z"]) g = CompoundGenerator([z, y, x], [e1, e2], []) g.prepare() p = [(x/2., y/2., z/2.) for z in range_(-2, 3) for y in range_(-2, 3) for x in range_(-2, 3)] m1 = [(x-0.1)**2 + (y-0.2)**2 <= 1 for (x, y, z) in p] m2 = [(y-0.1)**2 + (z-0.2)**2 <= 1 for (x, y, z) in p] expected_mask = [(b1 and b2) for (b1, b2) in zip(m1, m2)] self.assertEqual(expected_mask, g.dimensions[0].mask.tolist()) def test_complex_masks(self): tg = LineGenerator("t", "mm", 1, 5, 5) zg = LineGenerator("z", "mm", 0, 4, 5, alternate=True) yg = LineGenerator("y", "mm", 1, 5, 5, alternate=True) xg = LineGenerator("x", "mm", 2, 6, 5, alternate=True) r1 = CircularROI([4., 4.], 1.5) e1 = ROIExcluder([r1], ["y", "x"]) e2 = ROIExcluder([r1], ["z", "y"]) g = CompoundGenerator([tg, zg, yg, xg], [e1, e2], []) g.prepare() t_mask = [True] * 5 iy = 0 ix = 0 xyz_mask = [] xyz = [] for z in range_(0, 5): for y in (range_(1, 6) if iy % 2 == 0 else range_(5, 0, -1)): for x in (range_(2, 7) if ix % 2 == 0 else range_(6, 1, -1)): xyz_mask.append( (x-4)**2 + (y-4)**2 <= 1.5**2 \ and (y-4)**2 + (z-4)**2 <= 1.5**2) xyz.append((x, y, z)) ix += 1 iy += 1 self.assertEqual(t_mask, g.dimensions[0].mask.tolist()) self.assertEqual(xyz_mask, g.dimensions[1].mask.tolist()) def test_separate_indexes(self): x1 = LineGenerator("x1", "mm", -1.0, 1.0, 5, False) y1 = LineGenerator("y1", "mm", -1.0, 1.0, 5, False) z1 = LineGenerator("z1", "mm", -1.0, 1.0, 5, False) x2 = LineGenerator("x2", "mm", -1.0, 1.0, 5, False) y2 = LineGenerator("y2", "mm", -1.0, 1.0, 5, False) x3 = LineGenerator("x3", "mm", 0, 1.0, 5, False) y3 = LineGenerator("y3", "mm", 0, 1.0, 5, False) r = CircularROI([0, 0], 1) e1 = ROIExcluder([r], ["x1", "y1"]) e2 = ROIExcluder([r], ["y1", "z1"]) e3 = ROIExcluder([r], ["x1", "y1"]) e4 = ROIExcluder([r], ["x2", "y2"]) e5 = ROIExcluder([r], ["x3", "y3"]) g = CompoundGenerator( [x3, y3, y2, x2, z1, y1, x1], [e1, e2, e3, e4, e5], []) g.prepare() p = [(x/2., y/2., z/2.) for z in range_(-2, 3) for y in range_(-2, 3) for x in range_(-2, 3)] m1 = [x*x + y*y <= 1 for (x, y, z) in p] m2 = [y*y + z*z <= 1 for (x, y, z) in p] expected_mask = [(b1 and b2) for (b1, b2) in zip(m1, m2)] self.assertEqual(expected_mask, g.dimensions[2].mask.tolist()) p = [(x/2., y/2.) for y in range_(-2, 3) for x in range_(-2, 3)] expected_mask = [x*x + y*y <= 1 for (x, y) in p] self.assertEqual(expected_mask, g.dimensions[1].mask.tolist()) p = [(x/4., y/4.) for y in range_(0, 5) for x in range_(0, 5)] expected_mask = [x*x + y*y <= 1 for (x, y) in p] self.assertEqual(expected_mask, g.dimensions[0].mask.tolist()) class TestSerialisation(unittest.TestCase): def setUp(self): self.l1 = MagicMock(spec=Generator) self.l1.name = ['x'] self.l1.axes = ['x'] self.l1_dict = MagicMock() self.l2 = MagicMock(spec=Generator) self.l2.name = ['y'] self.l2.axes = ['y'] self.l2_dict = MagicMock() self.m1 = MagicMock(spec=Mutator) self.m1_dict = MagicMock() self.e1 = MagicMock(spec=Excluder) self.e1.name = "e1" self.e1_dict = MagicMock() def test_to_dict(self): self.g = CompoundGenerator([self.l2, self.l1], [self.e1], [self.m1], -1, True) self.l1.to_dict.return_value = self.l1_dict self.l2.to_dict.return_value = self.l2_dict self.e1.to_dict.return_value = self.e1_dict self.m1.to_dict.return_value = self.m1_dict gen_list = [self.l2_dict, self.l1_dict] mutators_list = [self.m1_dict] excluders_list = [self.e1_dict] expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/CompoundGenerator:1.0" expected_dict['generators'] = gen_list expected_dict['excluders'] = excluders_list expected_dict['mutators'] = mutators_list expected_dict['duration'] = -1 expected_dict['continuous'] = True expected_dict['delay_after'] = 0 d = self.g.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): # todo Should test the delay_after here? g1 = LineGenerator("x1", "mm", -1.0, 1.0, 5, False) g1_dict = g1.to_dict() g2 = LineGenerator("y1", "mm", -1.0, 1.0, 5, False) g2_dict = g2.to_dict() r = CircularROI([0, 0], 1) excl_1 = ROIExcluder([r], ["x1", "y1"]) excl1_1_dict = excl_1.to_dict() mutator_1 = RandomOffsetMutator(0, ["x"], {"x": 1}) mutator_1_dict = mutator_1.to_dict() _dict = dict() _dict['generators'] = [g1_dict, g2_dict] _dict['excluders'] = [excl1_1_dict] _dict['mutators'] = [mutator_1_dict] _dict['duration'] = 12 _dict['continuous'] = False units_dict = dict() units_dict['x'] = 'mm' units_dict['y'] = 'mm' gen = CompoundGenerator.from_dict(_dict) self.assertEqual(gen.generators[0].to_dict(), g1.to_dict()) self.assertEqual(gen.generators[1].to_dict(), g2.to_dict()) self.assertEqual(gen.mutators[0].to_dict(), mutator_1.to_dict()) self.assertEqual(gen.excluders[0].to_dict(), excl_1.to_dict()) self.assertEqual(gen.duration, 12) self.assertEqual(gen.continuous, False) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
scanpointgenerator/__init__.py
<reponame>dls-controls/scanpointgenerator ### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from scanpointgenerator.core import * from scanpointgenerator.generators import * from scanpointgenerator.excluders import * from scanpointgenerator.rois import * from scanpointgenerator.mutators import *
dls-controls/scanpointgenerator
scanpointgenerator/rois/rectangular_roi.py
<gh_stars>1-10 ### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from math import cos, sin from scanpointgenerator.core import ROI from scanpointgenerator.compat import np with Anno("The start point of the rectangle"): AStart = Array[float] UStart = Union[AStart, Sequence[float]] with Anno("The width of the rectangle"): AWidth = float with Anno("The height of the rectangle"): AHeight = float with Anno("The angle of the rectangle"): AAngle = float @ROI.register_subclass("scanpointgenerator:roi/RectangularROI:1.0") class RectangularROI(ROI): def __init__(self, start, width, height, angle=0): # type: (UStart, AWidth, AHeight, AAngle) -> None super(RectangularROI, self).__init__() if 0.0 in [height, width]: raise ValueError("Rectangle must have some size") self.start = AStart(start) self.width = AWidth(width) self.height = AHeight(height) self.angle = AAngle(angle) def contains_point(self, point): # transform point to the rotated rectangle frame x = point[0] - self.start[0] y = point[1] - self.start[1] if self.angle != 0: phi = -self.angle rx = x * cos(phi) - y * sin(phi) ry = x * sin(phi) + y * cos(phi) x = rx y = ry return (x >= 0 and x <= self.width) \ and (y >= 0 and y <= self.height) def mask_points(self, points): x = points[0].copy() x -= self.start[0] y = points[1].copy() y -= self.start[1] if self.angle != 0: phi = -self.angle rx = x * cos(phi) - y * sin(phi) ry = x * sin(phi) + y * cos(phi) x = rx y = ry mask_x = np.logical_and(x >= 0, x <= self.width) mask_y = np.logical_and(y >= 0, y <= self.height) return np.logical_and(mask_x, mask_y)
dls-controls/scanpointgenerator
tests/test_rois/test_linear_roi.py
<filename>tests/test_rois/test_linear_roi.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from math import pi, sqrt from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.linear_roi import LinearROI from scanpointgenerator.compat import np class LinearROIInitTest(unittest.TestCase): def test_init(self): l = LinearROI([0, 1], 2, 3) self.assertEquals([0, 1], l.start) self.assertEquals(2, l.length) self.assertEquals(3, l.angle) def test_invalid_length_raises(self): with self.assertRaises(ValueError): l = LinearROI([0, 0], 0, 0) class LinearROIContainsTest(unittest.TestCase): def test_default_epsilon(self): l = LinearROI([0, 0], 1, 0) p = [0, 1e-16] self.assertNotEqual([0, 0], p) self.assertTrue(l.contains_point(p)) p = [0, 2e-15] self.assertFalse(l.contains_point(p)) def test_near_endpoints(self): l = LinearROI([1, 1], 1.4, pi/4) p = [0.9, 0.9] self.assertFalse(l.contains_point(p, 0)) self.assertTrue(l.contains_point(p, 0.2)) p = [2, 2] self.assertFalse(l.contains_point(p, 0)) self.assertTrue(l.contains_point(p, 0.02)) l = LinearROI([0, 0], sqrt(2), pi/4) p = [1, 1] self.assertTrue(l.contains_point(p)) def test_near_midsection(self): l = LinearROI([-1, -1], 3 * sqrt(2), pi/4) p = [0, 0] self.assertTrue(l.contains_point(p)) p = [0, 0.1] self.assertFalse(l.contains_point(p)) def test_wide_angle(self): l = LinearROI([0, 0], sqrt(2), 5 * pi/4) p = [-1, -1] self.assertTrue(l.contains_point(p)) p = [-1.0001, -1.0001] self.assertFalse(l.contains_point(p)) p = [-0.1, -0.001] self.assertFalse(l.contains_point(p)) def test_negative_length(self): l = LinearROI([0, 0], -sqrt(2), pi/4) p = [-1, -1] self.assertTrue(l.contains_point(p)) p = [-1.0001, -1.0001] self.assertFalse(l.contains_point(p)) p = [-0.1, -0.001] self.assertFalse(l.contains_point(p)) def test_negative_angle(self): l = LinearROI([0, 0], sqrt(2), -pi/4) p = [0, 0] self.assertTrue(l.contains_point(p)) p = [1, -1] self.assertTrue(l.contains_point(p)) p = [0.1, 0.1] self.assertFalse(l.contains_point(p)) p = [-0.0001, 0.0001] self.assertFalse(l.contains_point(p)) def test_wraparound_angle(self): l = LinearROI([0, 0], sqrt(2), 2*pi + pi/4) p = [1, 1] self.assertTrue(l.contains_point(p)) def test_mask_points(self): l = LinearROI([1, 1], 2*sqrt(2), -pi/4 - 2*pi) px = [1, 2, 3, 1+1e-10, 3-1e-10, 2+1e-10, 2-1e-14, 3+1e-14, 1] py = [1, 0, -1, 1 , -1 , 0+1e-10, 0+1e-14, -1-1e-14, 1+1e-14] p = [np.array(px), np.array(py)] points_cp = [axis.copy().tolist() for axis in p] expected = [True, True, True, False, False, False, True, True, True] mask = l.mask_points(p, 1e-12) self.assertEquals(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in p]) class LinearROIDictTest(unittest.TestCase): def test_to_dict(self): l = LinearROI([1.1, 2.2], 3.3, pi/3) expected = { "typeid":"scanpointgenerator:roi/LinearROI:1.0", "start":[1.1, 2.2], "length":3.3, "angle":pi/3} self.assertEquals(expected, l.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/LinearROI:1.0", "start":[0, 1], "length":0.2, "angle":pi/6} l = LinearROI.from_dict(d) self.assertEqual([0.0, 1.0], l.start) self.assertEqual(0.2, l.length) self.assertEqual(pi/6, l.angle) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_core/test_generator.py
<gh_stars>1-10 import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import Generator from pkg_resources import require require("mock") from mock import MagicMock class ScanPointGeneratorBaseTest(ScanPointGeneratorTest): def setUp(self): self.g = Generator(["x", "y"], ["mm", "cm"], 1) def test_init(self): self.assertEqual(dict(x="mm", y="cm"), self.g.axis_units()) self.assertEqual(["x", "y"], self.g.axes) self.assertEqual(1, self.g.size) self.assertEqual(False, self.g.alternate) def test_prepare_positions_raises(self): with self.assertRaises(NotImplementedError): self.g.prepare_positions() def test_prepare_bounds_raises(self): with self.assertRaises(NotImplementedError): self.g.prepare_bounds() def test_to_dict(self): expected_dict = dict() expected_dict['axes'] = ["x", "y"] expected_dict['units'] = ["mm", "cm"] expected_dict['size'] = 1 expected_dict['alternate'] = False self.assertEqual(expected_dict, self.g.to_dict()) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_rois/test_elliptical_roi.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from math import pi from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.elliptical_roi import EllipticalROI from scanpointgenerator.compat import np class EllipticalROITest(unittest.TestCase): def test_init(self): roi = EllipticalROI([1.1, 2.2], [3.3, 4.4], pi/4) self.assertEqual([1.1, 2.2], roi.centre) self.assertEqual([3.3, 4.4], roi.semiaxes) self.assertEqual(pi/4, roi.angle) def test_default_angle(self): roi = EllipticalROI([1.1, 2.2], [3.3, 4.4]) self.assertEqual([1.1, 2.2], roi.centre) self.assertEqual([3.3, 4.4], roi.semiaxes) self.assertEqual(0, roi.angle) def test_invalid_semiaxes_fails(self): with self.assertRaises(ValueError): roi = EllipticalROI([0, 0], [-1, 1]) with self.assertRaises(ValueError): roi = EllipticalROI([0, 0], [1, -1]) with self.assertRaises(ValueError): roi = EllipticalROI([0, 0], [1, 0]) def test_point_contains(self): roi = EllipticalROI([1, 1], [2, 1], 0) p = (-1, 1) self.assertTrue(roi.contains_point(p)) p = (1, 0) self.assertTrue(roi.contains_point(p)) p = (3, 1) self.assertTrue(roi.contains_point(p)) p = (0, 0) self.assertFalse(roi.contains_point(p)) def test_rotated_point_contains(self): roi = EllipticalROI([1, 2], [2, 1], pi/6) p = (3, 1) self.assertFalse(roi.contains_point(p)) p = (1, 0) self.assertFalse(roi.contains_point(p)) p = (2.73, 3) self.assertTrue(roi.contains_point(p)) p = (3, 4.27) self.assertFalse(roi.contains_point(p)) p = (-0.73, 1) self.assertTrue(roi.contains_point(p)) def test_mask_points(self): roi = EllipticalROI([1, 2], [2, 1], pi/6) points = [np.array([3, 1, 2.73, 3.00, -0.73]), np.array([1, 0, 3.00, 4.27, 1.000])] points_cp = [axis.copy().tolist() for axis in points] expected = [False, False, True, False, True] self.assertEquals(expected, roi.mask_points(points).tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in points]) def test_to_dict(self): roi = EllipticalROI([1.1, 2.2], [3.3, 4.4], pi/4) expected = { "typeid":"scanpointgenerator:roi/EllipticalROI:1.0", "centre":[1.1, 2.2], "semiaxes":[3.3, 4.4], "angle":pi/4} self.assertEquals(expected, roi.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/EllipticalROI:1.0", "centre":[-1, 0], "semiaxes":[3, 4], "angle":pi/4} roi = EllipticalROI.from_dict(d) self.assertEqual([-1, 0], roi.centre) self.assertEqual([3, 4], roi.semiaxes) self.assertEqual(pi/4, roi.angle) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_generators/test_lissajousgenerator.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import LissajousGenerator class LissajousGeneratorTest(ScanPointGeneratorTest): def test_init(self): g = LissajousGenerator(["x", "y"], ["mm", "cm"], [0., 0.], [1., 1.], 1) self.assertEqual(g.axis_units(), dict(x="mm", y="cm")) self.assertEqual(g.axes, ["x", "y"]) def test_duplicate_name_raises(self): with self.assertRaises(AssertionError): LissajousGenerator(["x", "x"], ["mm", "mm"], [0., 0,], [1., 1.], 1) def test_array_positions(self): g = LissajousGenerator(['x', 'y'], ["mm", "mm"], [0., 0.], [1., 1.], 1, size=10) expected_x = [0.5, 0.4045084971874737, 0.15450849718747375, -0.15450849718747364, -0.40450849718747367, -0.5, -0.4045084971874738, -0.1545084971874738, 0.1545084971874736, 0.4045084971874736] expected_y = [0.0, 0.47552825814757677, 0.2938926261462366, -0.2938926261462365, -0.4755282581475768, -1.2246467991473532e-16, 0.47552825814757677, 0.2938926261462367, -0.2938926261462364, -0.4755282581475769] expected_bx = [0.47552825814757677, 0.4755282581475768, 0.2938926261462366, 6.123233995736766e-17, -0.2938926261462365, -0.47552825814757677, -0.47552825814757682, -0.2938926261462367, -1.2246467991473532e-16, 0.29389262614623646, 0.47552825814757677] expected_by = [-0.29389262614623657, 0.29389262614623657, 0.4755282581475768, 6.123233995736766e-17, -0.47552825814757677, -0.2938926261462367, 0.29389262614623607, 0.4755282581475768, 1.8369701987210297e-16, -0.4755282581475767, -0.29389262614623674] g.prepare_positions() g.prepare_bounds() self.assertListAlmostEqual(expected_x, g.positions['x'].tolist()) self.assertListAlmostEqual(expected_y, g.positions['y'].tolist()) self.assertListAlmostEqual(expected_bx, g.bounds['x'].tolist()) self.assertListAlmostEqual(expected_by, g.bounds['y'].tolist()) def test_array_positions_with_offset(self): g = LissajousGenerator( ['x', 'y'], ['mm', 'mm'], [1., 0.,], [2., 1.], 1, size=5) g.prepare_positions() g.prepare_bounds() expected_x = [2.0, 1.3090169943749475, 0.19098300532505266, 0.19098300532505266, 1.3090169943749475] expected_y = [0.0, 0.2938926261462366, -0.4755282581475768, 0.47552825814757677, -0.2938926261462364] expected_bx = [1.8090169943749475, 1.8090169943749475, 0.6909830056250528, 0.0, 0.6909830056250523, 1.8090169943749472] expected_by = [-0.47552825814757677, 0.47552825814757677, -0.2938926261462365, -1.2246467991473532e-16, 0.2938926261462367, -0.4755282581475769] self.assertListAlmostEqual(expected_x, g.positions['x'].tolist()) self.assertListAlmostEqual(expected_y, g.positions['y'].tolist()) self.assertListAlmostEqual(expected_bx, g.bounds['x'].tolist()) self.assertListAlmostEqual(expected_by, g.bounds['y'].tolist()) def test_to_dict(self): g = LissajousGenerator(["x", "y"], ["mm", "cm"], [0., 0.], [1., 1.], 1) expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/LissajousGenerator:1.0" expected_dict['axes'] = ["x", "y"] expected_dict['units'] = ["mm", "cm"] expected_dict['centre'] = [0., 0.] expected_dict['span'] = [1., 1.] expected_dict['lobes'] = 1 expected_dict['size'] = 250 expected_dict['alternate'] = False d = g.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['axes'] = ["x", "y"] _dict['units'] = ["cm", "mm"] _dict['centre'] = [0.0, 0.0] _dict['span'] = [1., 2.] _dict['lobes'] = 5 _dict['size'] = 250 units_dict = dict() units_dict['x'] = "cm" units_dict['y'] = "mm" gen = LissajousGenerator.from_dict(_dict) self.assertEqual(["x", "y"], gen.axes) self.assertEqual(units_dict, gen.axis_units()) self.assertEqual(5, gen.x_freq) self.assertEqual(0.5, gen.x_max) self.assertEqual(1.0, gen.y_max) self.assertEqual([0.0, 0.0], gen.centre) self.assertEqual(250, gen.size) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
scanpointgenerator/rois/linear_roi.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from math import cos, sin from scanpointgenerator.core import ROI from scanpointgenerator.compat import np with Anno("The start of the line"): AStart = Array[float] UStart = Union[AStart, Sequence[float]] with Anno("The length of the line"): ALength = float with Anno("The angle of the line"): AAngle = float @ROI.register_subclass("scanpointgenerator:roi/LinearROI:1.0") class LinearROI(ROI): def __init__(self, start, length, angle): # type: (UStart, ALength, AAngle) -> None super(LinearROI, self).__init__() if length == 0: raise ValueError("Line must have non-zero length") self.start = AStart(start) self.length = ALength(length) self.angle = AAngle(angle) def contains_point(self, point, epsilon=1e-15): # line's vector is (cphi, sphi) cphi = cos(self.angle) sphi = sin(self.angle) # check if it's within epsilon of end points x = point[0] - (self.start[0] + self.length * cphi) y = point[1] - (self.start[1] + self.length * sphi) if x * x + y * y <= epsilon * epsilon: return True x = point[0] - self.start[0] y = point[1] - self.start[1] if x * x + y * y <= epsilon * epsilon: return True # check that we're not passed the segment end points dp = x * cphi + y * sphi if dp < 0 or dp > self.length: return False # distance is scalar projection (dot product) # of point difference to line normal # normal vector of line vector is (sphi, -cphi) d = abs(x * sphi + y * -cphi) return d < epsilon def mask_points(self, points, epsilon=1e-15): cphi = cos(self.angle) sphi = sin(self.angle) x = points[0] - self.start[0] y = points[1] - self.start[1] # test for being past segment end-points dp = x * cphi + y * sphi mask = np.full(len(x), True, dtype=np.int8) mask &= dp >= 0 mask &= dp <= self.length # distance is scalar projection (dot-product) of # point difference to line normal (normal = (sphi, -cphi)) dp = np.abs(x * sphi + y * -cphi) mask &= dp < epsilon # include all points in an epsilon circle around endpoints x *= x y *= y mask |= x + y <= epsilon * epsilon x = points[0] - (self.start[0] + self.length * cphi) y = points[1] - (self.start[1] + self.length * sphi) x *= x y *= y mask |= x + y <= epsilon * epsilon return mask
dls-controls/scanpointgenerator
tests/test_rois/test_sector_roi.py
<reponame>dls-controls/scanpointgenerator<filename>tests/test_rois/test_sector_roi.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from math import pi from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.sector_roi import SectorROI from scanpointgenerator.compat import np class SectorInitTest(unittest.TestCase): def test_init(self): s = SectorROI([1.1, 2.2], [3.3, 4.4], [pi/2, 2*pi]) self.assertEquals([1.1, 2.2], s.centre) self.assertEquals([3.3, 4.4], s.radii) self.assertEquals([pi/2, 2*pi], s.angles) def test_init_negative_range(self): s = SectorROI([0, 0], [0, 1], [pi/2, -pi/2]) self.assertEquals([pi/2, 3*pi/2], s.angles) def test_invalid_radii_fails(self): with self.assertRaises(ValueError): s = SectorROI([0, 0], [-1, 1], [0, 0]) with self.assertRaises(ValueError): s = SectorROI([0, 0], [1, 0], [0, 0]) with self.assertRaises(ValueError): s = SectorROI([0, 0], [-2, -3], [0, 0]) class SectorDictTest(unittest.TestCase): def test_to_dict(self): s = SectorROI([1.1, 2.2], [3.3, 4.4], [pi/2, pi]) expected = { "typeid":"scanpointgenerator:roi/SectorROI:1.0", "centre":[1.1, 2.2], "radii":[3.3, 4.4], "angles":[pi/2, pi]} self.assertEquals(expected, s.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/SectorROI:1.0", "centre":[0.1, 0.2], "radii":[1, 2], "angles":[0, pi]} s = SectorROI.from_dict(d) self.assertEqual([0.1, 0.2], s.centre) self.assertEqual([1, 2], s.radii) self.assertEqual([0, pi], s.angles) class SectorContainsTest(unittest.TestCase): def test_inner_disc_fails(self): s = SectorROI((0, 0), (1., 2.), (0, 2*pi)) p = (0.9, 0) self.assertFalse(s.contains_point(p)) p = (0, 0.9) self.assertFalse(s.contains_point(p)) p = (0.7, 0.7) # < (sqrt(2)/2, sqrt(2)/2) self.assertFalse(s.contains_point(p)) p = (-0.7, -0.7) self.assertFalse(s.contains_point(p)) def test_outside_disc_fails(self): s = SectorROI((0, 0), (1., 2.), (0, 2*pi)) p = (2.1, 0) self.assertFalse(s.contains_point(p)) p = (0, 2.1) self.assertFalse(s.contains_point(p)) p = (1.5, 1.5) # > (sqrt(2), sqrt(2)) self.assertFalse(s.contains_point(p)) p = (-1.5, 1.5) self.assertFalse(s.contains_point(p)) def test_inside_disc_passes(self): s = SectorROI((0, 0), (1., 2.), (0, 2*pi)) p = (1, 0) self.assertTrue(s.contains_point(p)) p = (2, 0) self.assertTrue(s.contains_point(p)) p = (1, 1) self.assertTrue(s.contains_point(p)) p = (-1, -1) self.assertTrue(s.contains_point(p)) def test_past_sector_fail(self): s = SectorROI((0, 0), (0, 1), (0, pi)) p = (-0.1, -0.1) self.assertFalse(s.contains_point(p)) p = (0.1, -0.1) self.assertFalse(s.contains_point(p)) s = SectorROI((0, 0), (0, 1), (pi, 0)) p = (-0.1, 0.1) self.assertFalse(s.contains_point(p)) p = (0.1, 0.1) self.assertFalse(s.contains_point(p)) def test_in_sector_passes(self): s = SectorROI((0, 0), (0, 1), (0, pi/2)) p = (1, 0) self.assertTrue(s.contains_point(p)) p = (0, 1) self.assertTrue(s.contains_point(p)) p = (0.7, 0.7) self.assertTrue(s.contains_point(p)) s = SectorROI((0, 0), (0, 1), (pi, 3*pi/2)) p = (-1, 0) self.assertTrue(s.contains_point(p)) p = (0, -1) self.assertTrue(s.contains_point(p)) p = (-0.7, -0.7) self.assertTrue(s.contains_point(p)) def test_large_ranges_pass(self): s = SectorROI((0, 0), (0, 1), (-pi, 5*pi)) p = (0.7, 0.7) self.assertTrue(s.contains_point(p)) def test_negative_ranges(self): s = SectorROI((0, 0), (0, 1), (pi/2, -pi/2)) s.angles = (pi/2, -pi/2) p = (0.1, 0) self.assertFalse(s.contains_point(p)) p = (-0.1, 0) self.assertTrue(s.contains_point(p)) s = SectorROI((0, 0), (0, 1), (-pi/2, pi/2)) p = (-0.1, 0) self.assertFalse(s.contains_point(p)) p = (0.1, 0) self.assertTrue(s.contains_point(p)) s = SectorROI((0, 0), (0, 1), (pi, -6*pi)) s.angles = (pi, -6*pi) p = (1, 0) self.assertTrue(s.contains_point(p)) p = (0, 1) self.assertTrue(s.contains_point(p)) p = (-1, 0) self.assertTrue(s.contains_point(p)) p = (0, -1) self.assertTrue(s.contains_point(p)) def test_mask_points(self): s = SectorROI((0, 1), (1, 2), (-pi/2, pi/2)) p = [np.array([0, 1, 0, 2.05, 1, 0.7, -1.5, 0.00]), np.array([0, 0, 1, 0.00, 1, 0.7, 0.00, 2.05])] points_cp = [axis.copy().tolist() for axis in p] expected = [True, True, False, False, True, False, False, True] mask = s.mask_points(p) self.assertEquals(expected, mask.tolist()) s2 = SectorROI((0, 0), (1, 2), (-5*pi/2, -3*pi/2)) #the same sector mask = s.mask_points(p) self.assertEquals(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in p]) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_core/test_dimension.py
<filename>tests/test_core/test_dimension.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator.compat import np from scanpointgenerator.core.dimension import Dimension from pkg_resources import require require("mock") from mock import Mock class DimensionTests(ScanPointGeneratorTest): def test_init(self): g = Mock() g.axes = ["x", "y"] g.positions = {"x":np.array([0, 1, 2]), "y":np.array([10, 11, 12])} g.bounds = {"x":np.array([-0.5, 0.5, 1.5, 2.5]), "y":np.array([9.5, 10.5, 11.5, 12.5])} g.size = 3 d = Dimension([g]) d.prepare() self.assertEqual([g], d.generators) self.assertEqual([], d.excluders) self.assertEqual(["x", "y"], d.axes) self.assertEqual(g.alternate, d.alternate) self.assertEqual(g.size, d.size) self.assertEqual([2, 12], d.upper) self.assertEqual([0, 10], d.lower) def test_two_generators_init(self): g, h = Mock(), Mock() g.axes, h.axes = ["gx", "gy"], ["hx", "hy"] g.size, h.size = 16, 64 g.alternate = False h.alternate = False g.positions = {"gx":np.array([0, 1, 2]), "gy":np.array([10, 11, 12])} g.bounds = {"gx":np.array([-0.5, 0.5, 1.5, 2.5]), "gy":np.array([9.5, 10.5, 11.5, 12.5])} h.positions = {"hx":np.array([0, -1, -2]), "hy":np.array([-10, -11, -12])} h.bounds = {"hx":np.array([0.5, -0.5, -1.5, -2.5]), "hy":np.array([-9.5, -10.5, -11.5, -12.5])} d = Dimension([g, h]) self.assertEqual(False, d.alternate) self.assertEqual(["gx", "gy", "hx", "hy"], d.axes) self.assertEqual([2, 12, 0, -10], d.upper) self.assertEqual([0, 10, -2, -12], d.lower) def test_excluders_init(self): g1, g2, g3 = Mock(), Mock(), Mock() e1, e2 = Mock(), Mock() g1.axes, g2.axes, g3.axes = ["g1"], ["g2"], ["g3"] g1.size, g2.size, g3.size = 3, 4, 5 g1.positions = {"g1":np.array([0, 1, 2])} g1.bounds = {"g1":np.array([-0.5, 0.5, 1.5, 2.5])} g2.positions = {"g2":np.array([-1, 0, 1, 2])} g2.bounds = {"g2":np.array([-1.5, -0.5, 0.5, 1.5, 2.5])} g3.positions = {"g3":np.array([-2, 0, 2, 4, 6])} g3.bounds = {"g3":np.array([-3, -1, 1, 3, 5, 7])} g1.alternate = False g2.alternate = False g3.alternate = False e1.axes = ["g1", "g2"] e2.axes = ["g2", "g3"] d = Dimension([g1, g2, g3], [e1, e2]) self.assertEqual(False, d.alternate) self.assertEqual(["g1", "g2", "g3"], d.axes) self.assertEqual([0, -1, -2], d.lower) self.assertEqual([2, 2, 6], d.upper) def test_positions_non_alternate(self): g1, g2, g3 = Mock(), Mock(), Mock() g1.axes, g2.axes, g3.axes = ["g1"], ["g2"], ["g3"] g1.size, g2.size, g3.size = 3, 4, 5 g1.positions = {"g1":np.array([0, 1, 2])} g1.bounds = {"g1":np.array([-0.5, 0.5, 1.5, 2.5])} g2.positions = {"g2":np.array([-1, 0, 1, 2])} g2.bounds = {"g2":np.array([-1.5, -0.5, 0.5, 1.5, 2.5])} g3.positions = {"g3":np.array([-2, 0, 2, 4, 6])} g3.bounds = {"g3":np.array([-3, -1, 1, 3, 5, 7])} g1.alternate = False g2.alternate = False g3.alternate = False e1, e2 = Mock(), Mock() e1.axes = ["g1", "g2"] e2.axes = ["g2", "g3"] m1 = np.repeat(np.array([0, 1, 0, 1, 1, 0]), 10) m2 = np.tile(np.array([1, 0, 0, 1, 1, 1]), 10) e1.create_mask.return_value = m1 e2.create_mask.return_value = m2 d = Dimension([g1, g2, g3], [e1, e2]) d.prepare() expected_mask = m1 & m2 expected_indices = expected_mask.nonzero()[0] expected_g1 = np.repeat(g1.positions["g1"], 5 * 4)[expected_indices] expected_g2 = np.tile(np.repeat(g2.positions["g2"], 5), 3)[expected_indices] expected_g3 = np.tile(g3.positions["g3"], 3*4)[expected_indices] self.assertEqual(expected_mask.tolist(), d.mask.tolist()) self.assertEqual(expected_indices.tolist(), d.indices.tolist()) self.assertEqual(expected_g1.tolist(), d.positions["g1"].tolist()) self.assertEqual(expected_g2.tolist(), d.positions["g2"].tolist()) self.assertEqual(expected_g3.tolist(), d.positions["g3"].tolist()) def test_multi_axis_per_generator(self): g1, g2 = Mock(), Mock() g1.axes = ["z"] g2.axes = ["x", "y"] g1.positions = {"z":np.array([100, 200, 300, 400])} g1.bounds = {"z":np.array([50, 150, 250, 350, 450])} g2.positions = {"x":np.array([10, 11, 12]), "y":np.array([-1, -2, -3])} g2.bounds = {"x":np.array([9.5, 10.5, 11.5, 12.5]), "y":np.array([-0.5, -1.5, -2.5, -3.5])} g1.size, g2.size = 4, 3 g1.alternate, g2.alternate = False, False e1, e2 = Mock(), Mock() e1.axes = ["x", "y"] e2.axes = ["x", "z"] m1 = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0]) m2 = np.array([1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1]) e1.create_mask.return_value = m1 e2.create_mask.return_value = m2 d = Dimension([g1, g2], [e1, e2]) d.prepare() expected_mask = m1 & m2 expected_indices = expected_mask.nonzero()[0] expected_x = [10, 10, 11, 11] expected_y = [-1, -1, -2, -2] expected_z = [100, 300, 300, 400] self.assertEqual(4, d.size) self.assertEqual(expected_mask.tolist(), d.mask.tolist()) self.assertEqual(expected_indices.tolist(), d.indices.tolist()) self.assertEqual(expected_x, d.positions["x"].tolist()) self.assertEqual(expected_y, d.positions["y"].tolist()) self.assertEqual(expected_z, d.positions["z"].tolist()) def test_single_alternating_generator_with_excluder(self): x_pos = np.array([0, 1, 2, 3, 4, 5]) x_bounds = np.array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]) y_pos = np.array([10, 11, 12, 13, 14, 15]) y_bounds = np.array([9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5]) g = Mock( axes=["x", "y"], positions={"x":x_pos, "y":y_pos}, bounds={"x":x_bounds, "y":y_bounds}, size=6) g.alternate = True mask = np.array([1, 1, 0, 1, 0, 0], dtype=np.int8) e = Mock(axes=["x", "y"], create_mask=Mock(return_value=mask)) d = Dimension([g], [e]) self.assertTrue(d.alternate) d.prepare() expected_x = [0, 1, 3] expected_y = [10, 11, 13] self.assertEqual(expected_x, d.positions["x"].tolist()) self.assertEqual(expected_y, d.positions["y"].tolist()) def test_positions_alternating(self): g1, g2 = Mock(), Mock() g1.axes = ["z"] g2.axes = ["x", "y"] g1.positions = {"z":np.array([100, 200, 300, 400])} g1.bounds = {"z":np.array([50, 150, 250, 350, 450])} g2.positions = {"x":np.array([10, 11, 12]), "y":np.array([-1, -2, -3])} g2.bounds = {"x":np.array([9.5, 10.5, 11.5, 12.5]), "y":np.array([-0.5, -1.5, -2.5, -3.5])} g1.size, g2.size = 4, 3 g1.alternate, g2.alternate = False, True e1, e2 = Mock(), Mock() e1.axes = ["x", "y"] e2.axes = ["x", "z"] m1 = np.array([1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1]) m2 = np.array([1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1]) e1.create_mask.return_value = m1 e2.create_mask.return_value = m2 d = Dimension([g1, g2], [e1, e2]) d.prepare() expected_mask = m1 & m2 expected_indices = expected_mask.nonzero()[0] expected_x = [10, 11, 12, 11, 12, 11, 10] expected_y = [-1, -2, -3, -2, -3, -2, -1] expected_z = [100, 100, 200, 200, 300, 400, 400] self.assertEqual(7, d.size) self.assertEqual(expected_mask.tolist(), d.mask.tolist()) self.assertEqual(expected_indices.tolist(), d.indices.tolist()) self.assertEqual(expected_x, d.positions["x"].tolist()) self.assertEqual(expected_y, d.positions["y"].tolist()) self.assertEqual(expected_z, d.positions["z"].tolist()) def test_single_axis_excluder(self): x_pos = np.array([0, 1, 2, 3, 4, 5]) x_bounds = np.array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]) y_pos = np.array([10, 11, 12, 13, 14, 15]) y_bounds = np.array([9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5]) g = Mock(axes=["x", "y"], positions={"x":x_pos, "y":y_pos}, bounds={"x":x_bounds, "y":y_bounds}, size=len(x_pos)) g.alternate = False e = Mock(axes=["x"], create_mask=lambda x: (2 <= x) & (x < 4) | (x == 5)) d = Dimension([g], [e]) d.prepare() self.assertEqual([2, 3, 5], d.get_positions('x').tolist()) self.assertEqual([12, 13, 15], d.get_positions('y').tolist()) def test_excluder_over_spread_axes(self): gw_pos = np.array([0.1, 0.2]) gw_bounds = np.array([0.05, 0.15, 0.25]) gx_pos = np.array([0, 1, 2, 3]) gy_pos = np.array([10, 11, 12, 13]) gz_pos = np.array([100, 101, 102, 103]) go_pos = np.array([1000, 1001, 1002]) mask_xz_func = lambda px, pz: (px-1)**2 + (pz-102)**2 <= 1 exz = Mock(axes=["gx", "gz"], create_mask=Mock(side_effect=mask_xz_func)) gw = Mock(axes=["gw"], positions={"gw":gw_pos}, bounds={"gw":gw_bounds}, size=2, alternate=False) gx = Mock(axes=["gx"], positions={"gx":gx_pos}, size=4, alternate=False) gy = Mock(axes=["gy"], positions={"gy":gy_pos}, size=4, alternate=False) gz = Mock(axes=["gz"], positions={"gz":gz_pos}, size=4, alternate=False) go = Mock(axes=["go"], positions={"go":go_pos}, size=3, alternate=False) d = Dimension([go, gz, gy, gx, gw], [exz]) d.prepare() x_positions = np.tile(np.array([0, 1, 2, 3]), 16) y_positions = np.repeat(np.tile(np.array([10, 11, 12, 13]), 4), 4) z_positions = np.repeat(np.array([100, 101, 102, 103]), 16) x_positions = np.tile(np.repeat(x_positions, gw.size), go.size) y_positions = np.tile(np.repeat(y_positions, gw.size), go.size) z_positions = np.tile(np.repeat(z_positions, gw.size), go.size) mask = mask_xz_func(x_positions, z_positions) expected_x = x_positions[mask].tolist() expected_y = y_positions[mask].tolist() expected_z = z_positions[mask].tolist() self.assertEqual(expected_x, d.get_positions("gx").tolist()) self.assertEqual(expected_y, d.get_positions("gy").tolist()) self.assertEqual(expected_z, d.get_positions("gz").tolist()) def test_spread_excluder_multi_axes_per_gen(self): gx1_pos = np.array([1, 2, 3, 4, 5]) gx1_bounds = np.array([0.5, 1.5, 2.5, 3.5, 4.5, 5.5]) gx2_pos = np.array([11, 10, 9, 8, 7]) gx2_bounds = np.array([11.5, 10.5, 9.5, 8.5, 7.5, 6.5]) gy_pos = np.array([-1, 0, 1]) gz_pos = np.array([1, 0, -1, -2, -3]) mask_x1z_func = lambda px, pz: (px-4)**2 + (pz+1)**2 <= 1 exz = Mock(axes=["gx1", "gz"], create_mask=Mock(side_effect=mask_x1z_func)) gx = Mock(axes=["gx1", "gx2"], positions={"gx1":gx1_pos, "gx2":gx2_pos}, bounds={"gx1":gx1_bounds, "gx2":gx2_bounds}, size=5, alternate=False) gy = Mock(axes=["gy"], positions={"gy":gy_pos}, size=3, alternate=False) gz = Mock(axes=["gz"], positions={"gz":gz_pos}, size=5, alternate=False) d = Dimension([gz, gy, gx], [exz]) d.prepare() x1_positions = np.tile(gx1_pos, 15) x2_positions = np.tile(gx2_pos, 15) y_positions = np.repeat(np.tile(gy_pos, 5), 5) z_positions = np.repeat(gz_pos, 15) mask = mask_x1z_func(x1_positions, z_positions) expected_x1 = x1_positions[mask].tolist() expected_x2 = x2_positions[mask].tolist() expected_y = y_positions[mask].tolist() expected_z = z_positions[mask].tolist() self.assertEqual(expected_x1, d.get_positions("gx1").tolist()) self.assertEqual(expected_x2, d.get_positions("gx2").tolist()) self.assertEqual(expected_y, d.get_positions("gy").tolist()) self.assertEqual(expected_z, d.get_positions("gz").tolist()) def test_high_dimensional_excluder(self): w_pos = np.array([0, 1, 2, 3, 4, 5]) w_bounds = np.array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]) x_pos = np.array([0, 1, 2, 3, 4, 5]) y_pos = np.array([0, 1, 2, 3, 4, 5]) z_pos = np.array([0, 1, 2, 3, 4, 5]) mask_function = lambda pw, px, py, pz: (pw-2)**2 + (px-2)**2 + (py-1)**2 + (pz-3)**2 <= 1.1 excluder = Mock(axes=["w", "x", "y", "z"], create_mask=Mock(side_effect=mask_function)) gw = Mock(axes=["w"], positions={"w":w_pos}, bounds={"w":w_bounds}, size=len(w_pos), alternate=False) gx = Mock(axes=["x"], positions={"x":x_pos}, size=len(x_pos), alternate=False) gy = Mock(axes=["y"], positions={"y":y_pos}, size=len(y_pos), alternate=False) gz = Mock(axes=["z"], positions={"z":z_pos}, size=len(z_pos), alternate=False) d = Dimension([gz, gy, gx, gw], [excluder]) d.prepare() w_positions = np.tile(w_pos, len(x_pos) * len(y_pos) * len(z_pos)) x_positions = np.repeat(np.tile(x_pos, len(y_pos) * len(z_pos)), len(w_pos)) y_positions = np.repeat(np.tile(y_pos, len(z_pos)), len(w_pos) * len(x_pos)) z_positions = np.repeat(z_pos, len(w_pos) * len(x_pos) * len(y_pos)) mask = mask_function(w_positions, x_positions, y_positions, z_positions) w_expected = w_positions[mask].tolist() x_expected = x_positions[mask].tolist() y_expected = y_positions[mask].tolist() z_expected = z_positions[mask].tolist() self.assertEqual(w_expected, d.get_positions("w").tolist()) self.assertEqual(x_expected, d.get_positions("x").tolist()) self.assertEqual(y_expected, d.get_positions("y").tolist()) self.assertEqual(z_expected, d.get_positions("z").tolist()) def test_get_mesh_map(self): # Set up a generator, with 3x4 grid with alternating x and a circular # excluder such that the four 'corners' of the grid are excluded gx_pos = np.array([0.1, 0.2, 0.3]) gx_bounds = np.array([0.05, 0.15, 0.25, 0.35]) gy_pos = np.array([1.1, 1.2, 1.3, 1.4]) mask_func = lambda px, py: (px - 0.2) ** 2 + (py - 1.25) ** 2 <= 0.0225 gx = Mock(axes=["gx"], positions={"gx": gx_pos}, bounds={"gx":gx_bounds}, size=3, alternate=True) gy = Mock(axes=["gy"], positions={"gy": gy_pos}, size=4, alternate=False) e = Mock(axes=["gx", "gy"], create_mask=Mock(side_effect=mask_func)) d = Dimension([gy, gx], [e]) d.prepare() self.assertEqual([1, 2, 1, 0, 0, 1, 2, 1], d.get_mesh_map("gx").tolist()) self.assertEqual([0, 1, 1, 1, 2, 2, 2, 3], d.get_mesh_map("gy").tolist()) def test_mixed_alternating_generators(self): x_pos = np.array([0, 1, 2]) x_bounds = np.array([-0.5, 0.5, 1.5, 2.5]) y_pos = np.array([10, 11, 12]) z_pos = np.array([20, 21, 22]) w_pos = np.array([30, 31, 32]) gx = Mock(axes=["x"], positions={"x":x_pos}, bounds={"x":x_bounds}, size=3, alternate=True) gy = Mock(axes=["y"], positions={"y":y_pos}, size=3, alternate=True) gz = Mock(axes=["z"], positions={"z":z_pos}, size=3, alternate=False) gw = Mock(axes=["w"], positions={"w":w_pos}, size=3, alternate=False) mask = np.array([1, 1, 0, 1, 1, 1, 1, 0, 1] * 9) indices = np.nonzero(mask)[0] e = Mock(axes=["x", "y", "z", "w"]) e.create_mask.return_value=mask d = Dimension([gw, gz, gy, gx], [e]) d.prepare() expected_x = np.append(np.tile(np.append(x_pos, x_pos[::-1]), 13), x_pos)[indices] expected_y = np.repeat(np.append(np.tile(np.append(y_pos, y_pos[::-1]), 4), y_pos), 3)[indices] expected_z = np.tile(np.repeat(z_pos, 9), 3)[indices] expected_w = np.repeat(w_pos, 27)[indices] self.assertEqual(False, d.alternate) self.assertEqual(expected_x.tolist(), d.get_positions("x").tolist()) self.assertEqual(expected_y.tolist(), d.get_positions("y").tolist()) self.assertEqual(expected_z.tolist(), d.get_positions("z").tolist()) self.assertEqual(expected_w.tolist(), d.get_positions("w").tolist()) def test_dim_alternate_condition(self): g1 = Mock( axes=["x"], positions={"x":np.array([1, 2, 3])}, bounds={"x":np.array([0.5, 1.5, 2.5, 3.5])}, size=3, alternate=True) g2 = Mock( axes=["y"], positions={"y":np.array([1, 2, 3])}, bounds={"y":np.array([0.5, 1.5, 2.5, 3.5])}, size=3, alternate=False) g3 = Mock( axes=["z"], positions={"z":np.array([1, 2, 3])}, bounds={"z":np.array([0.5, 1.5, 2.5, 3.5])}, size=3, alternate=True) d1 = Dimension([g1, g3]) d2 = Dimension([g2, g3]) self.assertEqual(True, d1.alternate) self.assertEqual(False, d2.alternate) d1.prepare() d2.prepare() self.assertEqual(True, d1.alternate) self.assertEqual(False, d2.alternate) def test_dim_invalid_alternating(self): g1 = Mock( axes=["x"], positions={"x":np.array([1, 2, 3])}, bounds={"x":np.array([0.5, 1.5, 2.5, 3.5])}, size=3, alternate=True) g2 = Mock( axes=["y"], positions={"y":np.array([1, 2, 3])}, bounds={"y":np.array([0.5, 1.5, 2.5, 3.5])}, size=3, alternate=False) with self.assertRaises(ValueError): d = Dimension([g1, g2]) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_core/test_random.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from pkg_resources import require require("mock") from mock import patch from test_util import ScanPointGeneratorTest from scanpointgenerator import Random class RandomTest(unittest.TestCase): @patch('scanpointgenerator.core.Random.twist') def test_init(self, twist_mock): self.RNG = Random(1) self.assertEqual(0, self.RNG.index) self.assertEqual(624, len(self.RNG.seeds)) twist_mock.assert_called_once_with() def setUp(self): self.RNG = Random(1) @patch('scanpointgenerator.core.Random.twist') def test_generate_number(self, twist_mock): self.RNG.seeds[0] = 1234567890 response = self.RNG.generate_number() self.assertEqual(1284973367, response) for i in range(624): self.RNG.generate_number() twist_mock.assert_called_once_with() def test_twist(self): self.RNG.seeds = [1, 54235326, 723456923, 23489293] + [0]*620 expected_seeds = [27117663, 2357672210, 2579203417, 0] + [0]*620 self.RNG.twist() for i in range(5): self.assertEqual(expected_seeds[i], self.RNG.seeds[i]) def test_random(self): self.RNG.seeds[0] = 1234567890 response = self.RNG.random() self.assertAlmostEqual(0.633794821, response, places=10) response = self.RNG.random() self.assertAlmostEqual(0.316782824, response, places=10) response = self.RNG.random() self.assertAlmostEqual(-0.789226097, response, places=10) response = self.RNG.random() self.assertAlmostEqual(-0.366964996, response, places=10) response = self.RNG.random() self.assertAlmostEqual(0.948058921, response, places=10) response = self.RNG.random() self.assertAlmostEqual(0.436480924, response, places=10) def test_int32(self): response = self.RNG._int32(0x100000001) self.assertEqual(1, response) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_generators/test_linegenerator.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import LineGenerator class LineGeneratorTest(ScanPointGeneratorTest): def test_init(self): g = LineGenerator("x", "mm", 1.0, 9.0, 5, alternate=True) self.assertEqual(dict(x="mm"), g.axis_units()) self.assertEqual(["x"], g.axes) self.assertEqual(True, g.alternate) def test_init_multi_dim(self): g = LineGenerator(["x", "y"], ["mm", "cm"], [2., -2.], [4., -4.], 3) self.assertEqual(["x", "y"], g.axes) self.assertEqual({"x":"mm", "y":"cm"}, g.axis_units()) self.assertEqual(False, g.alternate) def test_array_positions(self): g = LineGenerator("x", "mm", 1.0, 9.0, 5, alternate=True) positions = [1.0, 3.0, 5.0, 7.0, 9.0] bounds = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0] indexes = [0, 1, 2, 3, 4] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['x'].tolist()) self.assertEqual(bounds, g.bounds['x'].tolist()) def test_negative_direction(self): g = LineGenerator("x", "mm", 2, -2, 5) positions = [2., 1., 0., -1., -2.] bounds = [2.5, 1.5, 0.5, -0.5, -1.5, -2.5] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['x'].tolist()) self.assertEqual(bounds, g.bounds['x'].tolist()) def test_single_point(self): g = LineGenerator("x", "mm", 1.0, 4.0, 1) g.prepare_positions() g.prepare_bounds() self.assertEqual([2.5], g.positions["x"].tolist()) self.assertEqual([1.0, 4.0], g.bounds["x"].tolist()) def test_single_point_exact(self): g = LineGenerator("x", "mm", 1.0, 1.0, 1) g.prepare_positions() g.prepare_bounds() self.assertEqual([1.0], g.positions["x"].tolist()) self.assertEqual([1.0, 1.0], g.bounds["x"].tolist()) def test_duplicate_name_raises(self): with self.assertRaises(AssertionError): LineGenerator(["x", "x"], "mm", 0.0, 1.0, 5) def test_to_dict(self): g = LineGenerator("x", "mm", 1.0, 9.0, 5, alternate=True) expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/LineGenerator:1.0" expected_dict['axes'] = ["x"] expected_dict['units'] = ["mm"] expected_dict['start'] = [1.0] expected_dict['stop'] = [9.0] expected_dict['size'] = 5 expected_dict['alternate'] = True d = g.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['axes'] = ["x"] _dict['units'] = ["mm"] _dict['start'] = [1.0] _dict['stop'] = [9.0] _dict['size'] = 5 _dict['alternate'] = True units_dict = dict() units_dict['x'] = "mm" gen = LineGenerator.from_dict(_dict) self.assertEqual(["x"], gen.axes) self.assertEqual(units_dict, gen.axis_units()) self.assertEqual([1.0], gen.start) self.assertEqual([9.0], gen.stop) self.assertEqual(5, gen.size) self.assertTrue(gen.alternate) class LineGenerator2DTest(ScanPointGeneratorTest): def test_init(self): g = LineGenerator(["x", "y"], ["mm", "mm"], [1.0, 2.0], [5.0, 10.0], 5) self.assertEqual(dict(x="mm", y="mm"), g.axis_units()) self.assertEqual(["x", "y"], g.axes) def test_given_inconsistent_dims_then_raise_error(self): with self.assertRaises(ValueError): LineGenerator("x", "mm", [1.0], [5.0, 10.0], 5) def test_give_one_point_then_step_zero(self): l = LineGenerator(["1", "2", "3", "4", "5"], "mm", [0.0]*5, [10.0]*5, 1) l.prepare_positions() assert list(l.positions.values()) == 5*[5.0] def test_array_positions(self): g = LineGenerator(["x", "y"], "mm", [1.0, 2.0], [5.0, 10.0], 5) g.prepare_positions() g.prepare_bounds() x_positions = [1.0, 2.0, 3.0, 4.0, 5.0] y_positions = [2.0, 4.0, 6.0, 8.0, 10.0] x_bounds = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5] y_bounds = [1, 3, 5, 7, 9, 11] self.assertEqual(x_positions, g.positions['x'].tolist()) self.assertEqual(y_positions, g.positions['y'].tolist()) self.assertEqual(x_bounds, g.bounds['x'].tolist()) self.assertEqual(y_bounds, g.bounds['y'].tolist()) def test_array_positions_single_point(self): g = LineGenerator(["x", "y"], "mm", [1.0, -3.0], [5.0, -4.0], 1) g.prepare_positions() g.prepare_bounds() x_positions = [3.0] y_positions = [-3.5] x_bounds = [1.0, 5.0] y_bounds = [-3.0, -4.0] self.assertEqual(x_positions, g.positions['x'].tolist()) self.assertEqual(y_positions, g.positions['y'].tolist()) self.assertEqual(x_bounds, g.bounds['x'].tolist()) self.assertEqual(y_bounds, g.bounds['y'].tolist()) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
scanpointgenerator/core/roi.py
<filename>scanpointgenerator/core/roi.py<gh_stars>1-10 ### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Serializable class ROI(Serializable): def __init__(self): # type: () -> None pass def contains_point(self, point): raise NotImplementedError
dls-controls/scanpointgenerator
scanpointgenerator/mutators/randomoffsetmutator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### import collections from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.compat import np from scanpointgenerator.core import Mutator with Anno("Seed for random offset generator"): ASeed = int with Anno("Axes to apply random offsets to, " "in the order the offsets should be applied"): AAxes = Array[str] UAxes = Union[AAxes, Sequence[str], str] with Anno("Array of maximum allowed offset in generator-defined units"): AMaxOffset = Array[float] UMaxOffset = Union[AMaxOffset, Sequence[float], float] @Mutator.register_subclass("scanpointgenerator:mutator/RandomOffsetMutator:1.0") class RandomOffsetMutator(Mutator): """Mutator to apply a random offset to the points of an ND ScanPointGenerator""" def __init__(self, seed, axes, max_offset): # type: (ASeed, UAxes, UMaxOffset) -> None self.seed = ASeed(seed) self.axes = AAxes(axes) # Check max_offset isn't a dict, and convert to list if it is if isinstance(max_offset, collections.Mapping): new_max_offset = [] for axis in axes: new_max_offset.append(max_offset[axis]) max_offset = new_max_offset self.max_offset = AMaxOffset(max_offset) # Validate if len(self.max_offset) != len(self.axes): raise ValueError("Dimensions of axes (%s) and max offset (%s) don't" " match" % (len(self.max_offset), len(self.axes))) def calc_offset(self, axis, idx): m = self.max_offset[self.axes.index(axis)] x = (idx << 4) + (0 if len(axis) == 0 else ord(axis[0])) x ^= (self.seed << 12) # Apply hash algorithm to x for pseudo-randomness # <NAME> 32 bit hash (avalanches well) x = (x + 0x7ED55D16) + (x << 12) x &= 0xFFFFFFFF # act as 32 bit unsigned before doing any right-shifts x = (x ^ 0xC761C23C) ^ (x >> 19) x = (x + 0x165667B1) + (x << 5) x = (x + 0xD3A2646C) ^ (x << 9) x = (x + 0xFD7046C5) + (x << 3) x &= 0xFFFFFFFF x = (x ^ 0xB55A4F09) ^ (x >> 16) x &= 0xFFFFFFFF # Jython does not like np.float32(x) r = np.array([x], dtype=np.float32)[0] r /= float(0xFFFFFFFF) # r in interval [0, 1] r = r * 2 - 1 # r in [-1, 1] return m * r def mutate(self, point, idx): ''' In Jython, int bit length conversion does not happen automatically within an array, therefore manually do it Jython bitwise operations overflow not extend, so work with 64 bit then reduce after calculation Jython also does not allow dtype(x), so must wrap in array ''' idx = np.array([idx], dtype=np.int64)[0] for axis in self.axes: point_offset = self.calc_offset(axis, idx) low_offset = (self.calc_offset(axis, idx-1) + point_offset) / 2 high_offset = (self.calc_offset(axis, idx+1) + point_offset) / 2 point.positions[axis] += point_offset # recalculate lower & upper bounds point.lower[axis] += low_offset point.upper[axis] += high_offset return point
dls-controls/scanpointgenerator
scanpointgenerator/excluders/__init__.py
<filename>scanpointgenerator/excluders/__init__.py from scanpointgenerator.excluders.roiexcluder import ROIExcluder from scanpointgenerator.excluders.squashingexcluder import SquashingExcluder
dls-controls/scanpointgenerator
scanpointgenerator/compat.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### import os try: range_ = xrange except NameError: # For Python3 range_ = range import numpy as np
dls-controls/scanpointgenerator
scanpointgenerator/rois/circular_roi.py
<reponame>dls-controls/scanpointgenerator<gh_stars>1-10 ### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.core import ROI import math as m with Anno("The centre of circle"): ACentre = Array[float] UCentre = Union[ACentre, Sequence[float]] with Anno("The radius of the circle"): ARadius = float @ROI.register_subclass("scanpointgenerator:roi/CircularROI:1.0") class CircularROI(ROI): def __init__(self, centre, radius): # type: (UCentre, ARadius) -> None super(CircularROI, self).__init__() if radius <= 0.0: raise ValueError("Circle must have some size") self.radius = ARadius(radius) self.centre = ACentre(centre) def contains_point(self, point): if m.sqrt((point[0] - self.centre[0]) ** 2 + (point[1] - self.centre[1]) ** 2) > self.radius: return False else: return True def mask_points(self, points): x = points[0].copy() x -= self.centre[0] y = points[1].copy() y -= self.centre[1] # use in place operations as much as possible (to save array creation) x *= x y *= y x += y r2 = self.radius * self.radius return x <= r2
dls-controls/scanpointgenerator
scanpointgenerator/core/excluder.py
<filename>scanpointgenerator/core/excluder.py ### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Serializable, Anno, Array, Union, Sequence from scanpointgenerator.compat import np with Anno("Names of axes to exclude points from"): AExcluderAxes = Array[str] UExcluderAxes = Union[AExcluderAxes, Sequence[str], str] class Excluder(Serializable): """Base class for objects that filter points based on their attributes.""" def __init__(self, axes): # type: (UExcluderAxes) -> None self.axes = AExcluderAxes(axes) def create_mask(self, *point_arrays): # type: (np.array) -> np.array raise NotImplementedError("Method must be implemented in child class.")
dls-controls/scanpointgenerator
scanpointgenerator/core/random.py
<gh_stars>1-10 ### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### class Random(object): # See: https://en.wikipedia.org/wiki/Mersenne_Twister - MT19937 w = 32 # Word size n = 624 # Degree of recurrence m = 397 # Middle word offset r = 31 # Lower bit mask length a = 0x9908B0DF # Twist matrix elements f = 1812433253 # Initialisation constant lower_mask = (1 << r) - 1 # Mask of `r` 1s upper_mask = 0xFFFFFFFF & (~lower_mask) # 32 LSB of (NOT lower_mask) s_shift = 7 # Tempering bit shifts and masks t_shift = 15 b_mask = 0x9D2C5680 c_mask = 0xEFC60000 u_shift = 11 # Additional bit shifts and mask l_shift = 18 d_mask = 0xFFFFFFFF def __init__(self, seed): self.index = 0 self.seeds = [seed] # Initialize the initial state to the seed for i in range(1, self.n): self.seeds.append(self._int32( self.f * (self.seeds[i - 1] ^ self.seeds[i - 1] >> 30) + i)) self.twist() def generate_number(self): number = 0 while len(str(number)) != 10: if self.index >= self.n: self.twist() self.index = 0 number = self.seeds[self.index] # Do some bit shifting and XOR-ing number ^= number >> self.u_shift number ^= number << self.s_shift & self.b_mask number ^= number << self.t_shift & self.c_mask number ^= number >> self.l_shift self.index += 1 return self._int32(number) def twist(self): for i in range(self.n): # Get the most significant bit and add it to the less significant # bits of the next number y = self._int32((self.seeds[i] & self.upper_mask) + (self.seeds[(i + 1) % self.n] & self.lower_mask)) self.seeds[i] = self.seeds[(i + self.m) % self.n] ^ y >> 1 if y % 2 != 0: self.seeds[i] ^= self.a def random(self): rand = str(self.generate_number())[::-1] decimal = float(rand[0] + '.' + rand[1:]) # -> 0.0 to 10.0 decimal %= 2 # -> 0.0 to 1.0 decimal -= 1.0 # -> -1.0 to 1.0 return decimal @staticmethod def _int32(number): # Get the 32 least significant bits. return int(0xFFFFFFFF & number) # class Random2(object): # # def __init__(self, seed=1): # self.x = seed # # def random(self): # # self.x ^= self.x >> 12 # self.x ^= self.x << 25 # self.x ^= self.x >> 27 # # rand = str(self.x * 2685821657736338717) # decimal = float(rand[0] + '.' + rand[1:25]) # # while decimal > 1.0: # decimal -= 2.0 # # return decimal
dls-controls/scanpointgenerator
tests/test_rois/test_point_roi.py
<gh_stars>1-10 import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.point_roi import PointROI from scanpointgenerator.compat import np class PointROITest(unittest.TestCase): def test_init(self): roi = PointROI([1.1, 2.2]) self.assertEqual([1.1, 2.2], roi.point) def test_contains_point_exact(self): roi = PointROI([5.4321, 1.2345]) p = [5.4321, 1.2345] self.assertTrue(roi.contains_point(p)) p = [5.4321 + 1e-15, 1.2345] self.assertFalse(roi.contains_point(p)) p = [5.4321, 1.2345 + 1e-15] self.assertFalse(roi.contains_point(p)) def test_contains_point_approx(self): roi = PointROI([1, 1]) p = [1, 1] self.assertTrue(roi.contains_point(p, 1e-14)) p = [1 + 6e-15, 1 + 6e-15] self.assertTrue(roi.contains_point(p, 1e-14)) p = [1 + 1e-14, 1 + 1e-14] self.assertFalse(roi.contains_point(p, 1e-14)) def test_mask_points(self): roi = PointROI([1, 2]) px = [1, 0, 1+1e-15, 1, 1] py = [2, 0, 2, 2+1e-15, 2+1e-14] expected = [True, False, True, True, False] p = [np.array(px), np.array(py)] points_cp = [axis.copy().tolist() for axis in p] mask = roi.mask_points(p, 2e-15) self.assertEqual(expected, mask.tolist()) mask = roi.mask_points([np.array(px), np.array(py)], 0) expected = [True, False, False, False, False] self.assertEqual(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in p]) def test_to_dict(self): roi = PointROI([1.1, 2.2]) expected = { "typeid":"scanpointgenerator:roi/PointROI:1.0", "point":[1.1, 2.2]} self.assertEqual(expected, roi.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/PointROI:1.0", "point":[0.1, 0.2]} roi = PointROI.from_dict(d) self.assertEqual([0.1, 0.2], roi.point) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
scanpointgenerator/core/point.py
<filename>scanpointgenerator/core/point.py<gh_stars>1-10 ### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - Points implementation # ### from scanpointgenerator.compat import np class Point(object): """Contains information about for each scan point Attributes: positions (dict): Dict of str position_name -> float position for each scannable dimension. E.g. {"x": 1, "y": 2.2} lower (dict): Dict of str position_name -> float lower_bound for each scannable dimension. E.g. {"x": 0.95, "y": 2.15} upper (dict): Dict of str position_name -> float upper_bound for each scannable dimension. E.g. {"x": 1.05, "y": 2.25} indexes (list): List of int indexes for each dataset dimension, fastest changing last. E.g. [15] duration (int): Int or None for duration of the point exposure delay_after (float): Float or None. Insert a time delay after every point """ def __init__(self): self.positions = {} self.lower = {} self.upper = {} self.indexes = [] self.duration = None self.delay_after = None def __len__(self): return 1 class Points(object): """Contains information about multiple points Attributes: positions (dict): Dict of str position_name -> float array positions for each scannable dimension. E.g. {"x": [1, 1.1], "y": [2.2, 2.2]} lower (dict): Dict of str position_name -> float array lower_bounds for each scannable dimension. E.g. {"x": [0.95, 1.95]., "y": [2.1, 2.1]} upper (dict): Dict of str position_name -> float array upper_bounds for each scannable dimension. E.g. {"x": [1.05, 2.05], "y": [2.3, 2.3]} indexes (list): List of int array indexes for each dataset dimension, fastest changing last. E.g. [[16, 15], [16,16]] duration (int array): Int array or None for duration of the points exposures delay_after (float array): Float array or None. Insert a time delay after every point """ def __init__(self): self.positions = {} self.lower = {} self.upper = {} self.indexes = [] self.duration = None self.delay_after = None def __len__(self): return len(self.indexes) def __add__(self, other): """ input: other (Point or Points) Appends the positions, bounds, indices, duration, delay of another Points or Point to self Assumes that dimensions are shared, or that either self or other have no positions. returns: self """ if not len(self): if isinstance(other, Points): return other.__copy__() return self.wrap(other) if len(other): self.positions.update({axis: np.append(self.positions[axis], other.positions[axis]) for axis in other.positions}) self.lower.update({axis: np.append(self.lower[axis], other.lower[axis]) for axis in other.lower}) self.upper.update({axis: np.append(self.upper[axis], other.upper[axis]) for axis in other.upper}) if isinstance(other, Point): self.indexes = np.vstack((self.indexes, other.indexes)) elif len(other): self.indexes = np.concatenate((self.indexes, other.indexes), axis=0) self.duration = np.append(self.duration, other.duration) self.delay_after = np.append(self.delay_after, other.delay_after) return self def __getitem__(self, sliced): """ input: sliced (int or slice)- index of a Point or a slice of many Point to consolidate into a Points returns: Point or Points object with each field reduced to the relevant indices """ if isinstance(sliced, int): # Single position point = Point() else: point = Points() point.positions = {axis: self.positions[axis][sliced] for axis in self.positions} point.upper = {axis: self.upper[axis][sliced] for axis in self.upper} point.lower = {axis: self.lower[axis][sliced] for axis in self.lower} point.indexes = self.indexes[sliced] point.duration = self.duration[sliced] point.delay_after = self.delay_after[sliced] return point def extract(self, points): self.positions.update({axis: points.positions[axis].copy() for axis in points.positions}) self.lower.update({axis: points.lower[axis].copy() for axis in points.lower}) self.upper.update({axis: points.upper[axis].copy() for axis in points.upper}) if len(self.indexes): # if indices is not empty: assumption that length of indices is consistent self.indexes = np.column_stack((self.indexes, points.indexes)) else: self.indexes = points.indexes def __copy__(self): points = Points() points.positions.update({self.positions[axis].copy() for axis in self.positions}) points.lower.update({self.lower[axis].copy() for axis in self.lower}) points.upper.update({self.upper[axis].copy() for axis in self.upper}) points.delay_after = self.delay_after.copy() points.duration = self.duration.copy() points.indexes = self.indexes.copy() return points @staticmethod def wrap(point): """ :param point: :return: a Points object wrapping the point """ points = Points() points.positions.update({axis:[point.positions[axis]] for axis in point.positions}) points.lower.update({axis:[point.lower[axis]] for axis in point.lower}) points.upper.update({axis:[point.upper[axis]] for axis in point.upper}) points.delay_after = [point.delay_after] points.duration = [point.duration] points.indexes = [point.indexes] return points @staticmethod def points_from_axis_point(dim, index, length): points = Points() dimension_points = {axis: np.full(length, dim.positions[axis][index]) for axis in dim.positions} lower, upper = dim.get_bounds(index) points.positions.update(dimension_points) points.lower.update({axis: np.full(length, lower[axis]) for axis in lower}) points.upper.update({axis: np.full(length, upper[axis]) for axis in upper}) points.indexes = np.full(length, index) return points
dls-controls/scanpointgenerator
tests/test_rois/test_rectangular_roi.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from math import pi from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.rectangular_roi import RectangularROI from scanpointgenerator.compat import np class InitTest(unittest.TestCase): def test_given_zero_height_then_error(self): with self.assertRaises(ValueError): RectangularROI([0.0, 0.0], 0.0, 5.0) def test_given_zero_width_then_error(self): with self.assertRaises(ValueError): RectangularROI([0.0, 0.0], 5.0, 0.0) def test_given_valid_params_then_set(self): x_start = 1.0 y_start = 4.0 height = 5.0 width = 10.0 angle = pi/4 rectangle = RectangularROI([x_start, y_start], width, height, angle) self.assertEqual(rectangle.width, width) self.assertEqual(rectangle.height, height) self.assertEqual(rectangle.start[0], x_start) self.assertEqual(rectangle.start[1], y_start) self.assertEqual(rectangle.angle, angle) def test_default_angle(self): roi = RectangularROI([0, 0], 1, 1) self.assertEqual(0, roi.angle) class ContainsPointTest(unittest.TestCase): def setUp(self): self.Rectangle = RectangularROI([-2.0, -2.5], 4.0, 5.0, 0) def test_given_valid_point_then_return_True(self): self.point = [1.0, 2.0] self.assertTrue(self.Rectangle.contains_point(self.point)) def test_given_point_high_then_return_False(self): self.point = [5.0, 2.0] self.assertFalse(self.Rectangle.contains_point(self.point)) def test_given_point_low_then_return_False(self): self.point = [-3.0, 2.0] self.assertFalse(self.Rectangle.contains_point(self.point)) def test_given_point_left_then_return_False(self): self.point = [1.0, 4.0] self.assertFalse(self.Rectangle.contains_point(self.point)) def test_given_point_right_then_return_False(self): self.point = [1.0, -6.0] self.assertFalse(self.Rectangle.contains_point(self.point)) def test_rotated_rectangle(self): roi = RectangularROI([1, 2], 1, 1, pi/4) p = [2, 3] self.assertFalse(roi.contains_point(p)) p = [2, 2] self.assertFalse(roi.contains_point(p)) p = [1, 2] self.assertTrue(roi.contains_point(p)) p = [1, 3.4] # (x = 1, y = sqrt(2) + 2 self.assertTrue(roi.contains_point(p)) p = [1.7, 2.7] self.assertTrue(roi.contains_point(p)) p = [0.3, 2.705] # rounding errors cause problems on the line y = -x self.assertTrue(roi.contains_point(p)) p = [1.01, 1.99] self.assertFalse(roi.contains_point(p)) p = [0.99, 1.99] self.assertFalse(roi.contains_point(p)) def test_mask(self): roi = RectangularROI([1, 2], 1, 1, pi/4) points = [np.array([2, 2, 1, 1, 1.7, 0.3, 1.01, 0.99]), np.array([3, 2, 2, 3.4, 2.7, 2.705, 1.99, 1.99])] points_cp = [axis.copy().tolist() for axis in points] expected = [False, False, True, True, True, True, False, False] mask = roi.mask_points(points) self.assertEqual(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in points]) class DictTest(unittest.TestCase): def test_to_dict(self): roi = RectangularROI([1, 2], 3, 4, pi/4) expected = { "typeid":"scanpointgenerator:roi/RectangularROI:1.0", "start":[1, 2], "width":3, "height":4, "angle":pi/4} self.assertEqual(expected, roi.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/RectangularROI:1.0", "start":[1, 2], "width":3, "height":4, "angle":pi/4} roi = RectangularROI.from_dict(d) self.assertEqual([1, 2], roi.start) self.assertEqual(3, roi.width) self.assertEqual(4, roi.height) self.assertEqual(pi/4, roi.angle) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_excluders/test_roiexcluder.py
<filename>tests/test_excluders/test_roiexcluder.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from pkg_resources import require require("mock") from mock import patch, MagicMock from test_util import ScanPointGeneratorTest from scanpointgenerator import ROIExcluder, CircularROI from scanpointgenerator.compat import np roi_patch_path = "scanpointgenerator.core.ROI" class TestCreateMask(ScanPointGeneratorTest): def setUp(self): self.r1 = MagicMock(spec=CircularROI) self.r2 = MagicMock(spec=CircularROI) self.e = ROIExcluder([self.r1, self.r2], ["x", "y"]) def test_create_mask_returns_union_of_rois(self): x_points = np.array([1, 2, 3, 4]) y_points = np.array([10, 10, 20, 20]) self.r1.mask_points.return_value = \ np.array([True, False, False, True]) self.r2.mask_points.return_value = \ np.array([False, False, True, True]) expected_mask = np.array([True, False, True, True]) mask = self.e.create_mask(x_points, y_points) r1_call_list = self.r1.mask_points.call_args_list[0][0][0] r2_call_list = self.r2.mask_points.call_args_list[0][0][0] self.assertEqual(x_points.tolist(), r1_call_list[0].tolist()) self.assertEqual(y_points.tolist(), r1_call_list[1].tolist()) self.assertEqual(x_points.tolist(), r2_call_list[0].tolist()) self.assertEqual(y_points.tolist(), r2_call_list[1].tolist()) self.assertEqual(expected_mask.tolist(), mask.tolist()) class TestSerialisation(unittest.TestCase): def setUp(self): self.r1 = CircularROI([1, 2], 3) self.r2 = CircularROI([4, 5], 6) self.r1_dict = self.r1.to_dict() self.r2_dict = self.r2.to_dict() self.e = ROIExcluder([self.r1, self.r2], ["x", "y"]) def test_to_dict(self): expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:excluder/ROIExcluder:1.0" expected_dict['rois'] = [self.r1_dict, self.r2_dict] expected_dict['axes'] = ["x", "y"] d = self.e.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['rois'] = [self.r1_dict, self.r2_dict] _dict['axes'] = ["x", "y"] e = ROIExcluder.from_dict(_dict) self.assertEqual(["x", "y"], e.axes) self.assertEqual(2, len(e.rois)) self.assertEqual("scanpointgenerator:roi/CircularROI:1.0", e.rois[0].typeid) self.assertEqual([1, 2], e.rois[0].centre) self.assertEqual(3, e.rois[0].radius) self.assertEqual("scanpointgenerator:roi/CircularROI:1.0", e.rois[1].typeid) self.assertEqual([4, 5], e.rois[1].centre) self.assertEqual(6, e.rois[1].radius) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_mutators/test_randomoffsetmutator.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator.compat import range_ from scanpointgenerator.generators import LineGenerator, LissajousGenerator from scanpointgenerator.mutators import RandomOffsetMutator from scanpointgenerator import Point, CompoundGenerator from pkg_resources import require require("mock") from mock import patch, MagicMock class RandomOffsetMutatorTest(ScanPointGeneratorTest): def test_init(self): m = RandomOffsetMutator(1, ["x"], [0.25]) self.assertEqual(1, m.seed) self.assertEqual([0.25], m.max_offset) def test_mutate_simple(self): def point_gen(): for n in range_(10): p = Point() p.indexes = [n] p.positions = {"x":n/10.} p.lower = {"x":(n-0.5)/10.} p.upper = {"x":(n+0.5)/10.} yield p m = RandomOffsetMutator(1, ["x"], [0.01]) original = [p for p in point_gen()] mutated = [m.mutate(p, i) for i, p in enumerate(point_gen())] for o, m in zip(original, mutated): op, mp = o.positions["x"], m.positions["x"] ou, mu = o.upper["x"], m.upper["x"] ol, ml = o.lower["x"], m.lower["x"] self.assertNotEqual(op, mp) self.assertTrue(abs(mp - op) < 0.01) self.assertTrue(abs(mu - ou) < 0.01) self.assertTrue(abs(ml - ol) < 0.01) offsets = [m.positions["x"] - o.positions["x"] for m, o in zip(mutated, original)] for o1, o2 in zip(offsets[:-1], offsets[1:]): self.assertNotEqual(o1, o2) def test_random_access_consistency(self): def point_gen(): for n in range_(10): p = Point() p.indexes = [n] p.positions = {"x":n/10.} p.lower = {"x":(n-0.5)/10.} p.upper = {"x":(n+0.5)/10.} yield p m = RandomOffsetMutator(5025, ["x"], [0.01]) original = [p.positions['x'] for p in point_gen()] mutated1 = [m.mutate(p, i).positions['x'] for i, p in enumerate(point_gen())] mutated2 = [m.mutate(p, i).positions['x'] for i, p in enumerate(point_gen())] mutated3 = [m.mutate(p, i).positions['x'] for i, p in list(enumerate(point_gen()))[::-1]][::-1] self.assertNotEqual(original, mutated1) self.assertEqual(mutated1, mutated2) self.assertEqual(mutated1, mutated3) def test_bounds_consistency(self): def point_gen(): for n in range_(10): p = Point() p.indexes = [n] p.positions = {"x":n/10.} p.lower = {"x":(n-0.5)/10.} p.upper = {"x":(n+0.5)/10.} yield p m = RandomOffsetMutator(1, ["x"], [0.01]) original = [p.positions["x"] for p in point_gen()] mutated = [m.mutate(p, i) for i, p in enumerate(point_gen())] for m1, m2 in zip(mutated[:-1], mutated[1:]): self.assertEqual(m1.upper["x"], m2.lower["x"]) def test_double_line_consistency(self): xg = LineGenerator("x", "mm", 0, 4, 5, True) yg = LineGenerator("y", "mm", 0, 4, 3) m = RandomOffsetMutator(1, ["x", "y"], [0.1, 0.25]) g = CompoundGenerator([yg, xg], [], []) g.prepare() points = list(g.iterator()) ly = [l.upper["y"] for l in points[0:4] + points[5:9] + points[10:14]] ry = [r.lower["y"] for r in points[1:5] + points[6:10] + points[11:15]] self.assertEqual(ly, ry) def test_bounds_consistency_in_compound(self): liss = LissajousGenerator(["x", "y"], ["mm", "mm"], [0., 0.], [2., 2.], 4, 100, True) line = LineGenerator("z", "mm", 0, 1, 3) m = RandomOffsetMutator(1, ["x", "y"], [0.1, 0.1]) g = CompoundGenerator([line, liss], [], []) gm = CompoundGenerator([line, liss], [], [m]) g.prepare() gm.prepare() points = list(gm.iterator()) lx = [l.upper["x"] for l in points[:-1]] rx = [r.lower["x"] for r in points[1:]] self.assertListAlmostEqual(lx, rx) ly = [l.upper["y"] for l in points[:-1]] ry = [r.lower["y"] for r in points[1:]] self.assertListAlmostEqual(ly, ry) def test_consistent_python_jython(self): p = Point() p.indexes = [0] p.positions = {"x":1, "y":2} p.lower = {"x":0.5, "y":1.75} p.upper = {"x":1.5, "y":2.25} m = RandomOffsetMutator(1, ["y"], [0.01]) q = m.mutate(p, 0) # Generated with Python 3.7.3, but should be consistent with all Python/Jython self.assertAlmostEqual(2.00454337, q.positions["y"]) self.assertAlmostEqual(2.25045721, q.upper["y"]) self.assertAlmostEqual(1.74735178, q.lower["y"]) class TestSerialisation(unittest.TestCase): def setUp(self): self.l = MagicMock() self.l_dict = MagicMock() self.max_offset = [0.25] self.m = RandomOffsetMutator(1, ["x"], self.max_offset) def test_to_dict(self): self.l.to_dict.return_value = self.l_dict expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:mutator/RandomOffsetMutator:1.0" expected_dict['seed'] = 1 expected_dict['axes'] = ["x"] expected_dict['max_offset'] = self.max_offset d = self.m.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['seed'] = 1 _dict['axes'] = ["x"] _dict['max_offset'] = self.max_offset units_dict = dict() units_dict['x'] = 'mm' m = RandomOffsetMutator.from_dict(_dict) self.assertEqual(1, m.seed) self.assertEqual(self.max_offset, m.max_offset) def test_from_dict_max_offset_dict(self): _dict = dict() _dict['seed'] = 1 _dict['axes'] = ["x"] _dict['max_offset'] = dict(x=0.25) units_dict = dict() units_dict['x'] = 'mm' m = RandomOffsetMutator.from_dict(_dict) self.assertEqual(1, m.seed) self.assertEqual(self.max_offset, m.max_offset) def test_from_dict_multiple_axes(self): _dict = dict() _dict['seed'] = 1 _dict['axes'] = ["x", "y"] _dict['max_offset'] = [0.25, 0.5] units_dict = dict() units_dict['x'] = 'mm' units_dict['y'] = 'cm' m = RandomOffsetMutator.from_dict(_dict) self.assertEqual(1, m.seed) self.assertEqual(["x", "y"], m.axes) self.assertEqual([0.25, 0.5], m.max_offset) def test_from_dict_multiple_axes_dict_corrects_order(self): _dict = dict() _dict['seed'] = 1 _dict['axes'] = ["x", "y"] _dict['max_offset'] = dict(y=0.5, x=0.25) units_dict = dict() units_dict['x'] = 'mm' units_dict['y'] = 'cm' m = RandomOffsetMutator.from_dict(_dict) self.assertEqual(1, m.seed) self.assertEqual(["x", "y"], m.axes) self.assertEqual([0.25, 0.5], m.max_offset) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_core/test_get_points_performance.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest import time from test_util import ScanPointGeneratorTest from scanpointgenerator import CompoundGenerator from scanpointgenerator import LineGenerator, StaticPointGenerator, LissajousGenerator, SpiralGenerator from scanpointgenerator import CircularROI, RectangularROI, ROIExcluder from scanpointgenerator import RandomOffsetMutator # Jython gets 3x as long TIMELIMIT = 3 if os.name == "java" else 1 # Goal is 10khz, 1s per 10,000(10e4) points class GetPointsPerformanceTest(ScanPointGeneratorTest): def test_90_thousand_time_constraint(self): z = LineGenerator("z", "mm", 0, 1, 300, True) w = LineGenerator("w", "mm", 0, 1, 300, True) g = CompoundGenerator([z, w], [], []) g.prepare() # 9e4 points start_time = time.time() C = g.get_points(0, 90000) end_time = time.time() self.assertLess(end_time - start_time, TIMELIMIT*9) def test_30_thousand_time_constraint_with_outer(self): a = StaticPointGenerator(1) z = LineGenerator("z", "mm", 0, 1, 300, True) w = LineGenerator("w", "mm", 0, 1, 300, True) g = CompoundGenerator([a, z, w], [], []) g.prepare() # 9e4 points start_time = time.time() C = g.get_points(0, 30000) end_time = time.time() self.assertLess(end_time - start_time, TIMELIMIT*3) def test_30_thousand_time_constraint_with_inner(self): a = StaticPointGenerator(1) z = LineGenerator("z", "mm", 0, 1, 300, True) w = LineGenerator("w", "mm", 0, 1, 300, True) g = CompoundGenerator([z, w, a], [], []) g.prepare() # 9e4 points start_time = time.time() C = g.get_points(0, 30000) end_time = time.time() self.assertLess(end_time - start_time, TIMELIMIT*3) @unittest.skip("Unsuitable") def test_1_million_time_constraint_complex(self): a = LineGenerator("a", "mm", 0, 1, 10, True) b = LineGenerator("b", "mm", 0, 1, 10) c = LineGenerator("c", "mm", 0, 1, 10) d = LineGenerator("d", "mm", 0, 1, 10) e = LineGenerator("e", "mm", 0, 1, 10) f = LineGenerator("f", "mm", 0, 1, 10) g = CompoundGenerator([b, c, d, e, f, a], [], []) g.prepare() # 1e6 points start_time = time.time() C = g.get_points(0, 1000000) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*100) @unittest.skip("Unsuitable") def test_small_time_constraint_complex(self): a = LineGenerator("a", "mm", 0, 1, 10, True) b = LineGenerator("b", "mm", 0, 1, 10) c = LineGenerator("c", "mm", 0, 1, 10) d = LineGenerator("d", "mm", 0, 1, 10) e = LineGenerator("e", "mm", 0, 1, 10) f = LineGenerator("f", "mm", 0, 1, 10) g = CompoundGenerator([b, c, d, e, f, a], [], []) g.prepare() # 1e6 points start_time = time.time() C = g.get_points(0, 1) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*1e-4) start_time = time.time() C = g.get_points(0, 10) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*1e-3) start_time = time.time() C = g.get_points(0, 100) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*1e-2) def test_roi_time_constraint(self): a = LineGenerator("a", "mm", 0, 1, 300, True) b = LineGenerator("b", "mm", 0, 1, 300) r1 = CircularROI([0.25, 0.33], 0.1) e1 = ROIExcluder([r1], ["a", "b"]) g = CompoundGenerator([b, a], [e1], []) g.prepare() # ~2,800 points start_time = time.time() C = g.get_points(0, 1000) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*0.1) start_time = time.time() C = g.get_points(0, 2800) end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT*0.28) @unittest.skip("Unsuitable") def test_time_constraint_complex(self): a = LineGenerator("a", "eV", 0, 1, 10) b = LineGenerator("b", "rad", 0, 1, 10) c = LissajousGenerator(["c", "d"], ["mm", "cm"], [0, 0], [5, 5], 3, 10) d = SpiralGenerator(["e", "f"], ["mm", "s"], [10, 5], 7, 0.6) e = LineGenerator("g", "mm", 0, 1, 10) f = LineGenerator("h", "mm", 0, 5, 20) r1 = CircularROI([0.2, 0.2], 0.1) r2 = CircularROI([0.4, 0.2], 0.1) r3 = CircularROI([0.6, 0.2], 0.1) e1 = ROIExcluder([r1, r2, r3], ["a", "b"]) m1 = RandomOffsetMutator(12, ["a"], [0.1]) m2 = RandomOffsetMutator(200, ["c", "f"], [0.01, 0.5]) g = CompoundGenerator([c, d, e, f, b, a], [e1], [m1, m2]) g.prepare() # 1e6 points for i in [1, 2, 3, 4, 5, 6]: p = 10**i start_time = time.time() g.get_points(0, p) end_time = time.time() self.assertLess(end_time - start_time, TIMELIMIT*p/1e4) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_generators/test_concatgenerator.py
import unittest from scanpointgenerator import LineGenerator, ConcatGenerator, ArrayGenerator, \ CompoundGenerator from tests.test_util import ScanPointGeneratorTest class ConcatGeneratorTest(ScanPointGeneratorTest): def test_init(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 13, 20, 5) g = ConcatGenerator([genone, gentwo]) self.assertEqual(["x"], g.axes) self.assertEqual(dict(x="mm"), g.axis_units()) self.assertEqual(10, g.size) def test_init_none(self): with self.assertRaises(AssertionError): ConcatGenerator([]) def test_init_alternate(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 13, 20, 5) g = ConcatGenerator([genone, gentwo], True) self.assertEqual(["x"], g.axes) self.assertEqual(dict(x="mm"), g.axis_units()) self.assertEqual(10, g.size) self.assertEqual(True, g.alternate) def test_init_two_dim(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) gentwo = LineGenerator(["x", "y"], ["mm", "mm"], [6., -6.], [8., -8.], 3) g = ConcatGenerator([genone, gentwo]) self.assertEqual(["x", "y"], g.axes) self.assertEqual({"x": "mm", "y": "mm"}, g.axis_units()) def test_init_alternate_set(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5, alternate=True) gentwo = LineGenerator("x", "mm", 13, 20, 5, alternate=True) with self.assertRaises(AssertionError): ConcatGenerator([genone, gentwo]) def test_array_positions_from_line(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 11, 19, 5) g = ConcatGenerator([genone, gentwo]) positions = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] bounds = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['x'].tolist()) self.assertEqual(bounds, g.bounds['x'].tolist()) def test_array_positions_from_array(self): genone = ArrayGenerator("x", "mm", [1.0, 2.0, 3.0, 4.0, 5.0]) gentwo = ArrayGenerator("x", "mm", [6.0, 7.0, 8.0, 9.0, 0.0]) g = ConcatGenerator([genone, gentwo]) positions = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0] bounds = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, -4.5] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['x'].tolist()) self.assertEqual(bounds, g.bounds['x'].tolist()) def test_array_positions_from_2D_line(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) gentwo = LineGenerator(["x", "y"], ["mm", "mm"], [5., -4.], [7., -2.], 3) g = ConcatGenerator([genone, gentwo]) x_positions = [2.0, 3.0, 4.0, 5.0, 6.0, 7.0] y_positions = [-2.0, -3.0, -4.0, -4.0, -3.0, -2.0] x_bounds = [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5] y_bounds = [-1.5, -2.5, -3.5, -4.5, -3.5, -2.5, -1.5] g.prepare_positions() g.prepare_bounds() self.assertEqual(x_positions, g.positions['x'].tolist()) self.assertEqual(y_positions, g.positions['y'].tolist()) self.assertEqual(x_bounds, g.bounds['x'].tolist()) self.assertEqual(y_bounds, g.bounds['y'].tolist()) def test_array_positions_from_three_(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 11, 19, 5) genthree = LineGenerator("x", "mm", 21, 29, 5) g = ConcatGenerator([genone, gentwo, genthree]) positions = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29] bounds = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['x'].tolist()) self.assertEqual(bounds, g.bounds['x'].tolist()) def test_array_positions_from_line_non_matching_bounds(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 20, 24, 5) g = ConcatGenerator([genone, gentwo]) g.prepare_positions() with self.assertRaises(AssertionError): g.prepare_bounds() def test_array_positions_from_three_line_non_matching_bounds(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 11, 19, 5) genthree = LineGenerator("x", "mm", 22, 30, 5) g = ConcatGenerator([genone, gentwo, genthree]) g.prepare_positions() with self.assertRaises(AssertionError): g.prepare_bounds() def test_to_dict(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 13, 20, 5) g = ConcatGenerator([genone, gentwo]) expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/ConcatGenerator:1.0" expected_dict['generators'] = [{'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [9.0], 'start': [1.0], 'units': ['mm'], 'size': 5}, {'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [20], 'start': [13], 'units': ['mm'], 'size': 5}] expected_dict['alternate'] = False d = g.to_dict() self.assertEqual(expected_dict, d) comp = CompoundGenerator([g], [], []) expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/CompoundGenerator:1.0" expected_dict['generators'] = [{'typeid': 'scanpointgenerator:generator/ConcatGenerator:1.0', 'alternate': False, 'generators': [{'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [9.0], 'start': [1.0], 'units': ['mm'], 'size': 5}, {'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [20], 'start': [13], 'units': ['mm'], 'size': 5}]}] expected_dict['excluders'] = [] expected_dict['mutators'] = [] expected_dict['duration'] = -1.0 expected_dict['continuous'] = True expected_dict['delay_after'] = 0 d = comp.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) g1_dict = genone.to_dict() gentwo = LineGenerator("x", "mm", 13, 20, 5) g2_dict = gentwo.to_dict() _dict = dict() _dict['generators'] = [g1_dict, g2_dict] _dict['alternate'] = False gen = ConcatGenerator.from_dict(_dict) self.assertEqual(gen.generators[0].to_dict(), genone.to_dict()) self.assertEqual(gen.generators[1].to_dict(), gentwo.to_dict()) g = ConcatGenerator([genone, gentwo]) g_dict = g.to_dict() _dict = dict() _dict['generators'] = [g_dict] _dict['excluders'] = [] _dict['mutators'] = [] _dict['duration'] = 10 _dict['continuous'] = False gen = CompoundGenerator.from_dict(_dict) self.assertEqual(gen.generators[0].to_dict(), g.to_dict()) def test_compound_of_two_lines(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 11, 19, 5) lines = ConcatGenerator([genone, gentwo]) g = CompoundGenerator([lines], [], [], duration=0.5) g.prepare() x_positions = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] expected_pos = [] for i in range(len(x_positions)): expected_pos.append({"x": x_positions[i]}) points = list(g.iterator()) self.assertEqual(expected_pos, [p.positions for p in points]) data = [] for vals in expected_pos: data.append(vals["x"]) def test_concat_three_oneD_lines(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 11, 19, 5) genthree = LineGenerator("x", "mm", 19.5, 13.5, 7) lines = ConcatGenerator([genone, gentwo, genthree]) g = CompoundGenerator([lines], [], [], duration=0.5) x_positions = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 19.5, 18.5, 17.5, 16.5, 15.5, 14.5, 13.5] expected_pos = [] for i in range(len(x_positions)): expected_pos.append({"x": x_positions[i]}) g.prepare() points = list(g.iterator()) self.assertEqual(expected_pos, [p.positions for p in points]) def test_concat_three_twoD_lines(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [1.0, 12.0], [9.0, 4.0], 5) gentwo = LineGenerator(["x", "y"], ["mm", "mm"], [11.0, 4.0], [19.0, 12.0], 5) genthree = LineGenerator(["x", "y"], ["mm", "mm"], [19.5, 13.5], [13.5, 19.5], 7) lines = ConcatGenerator([genone, gentwo, genthree]) g = CompoundGenerator([lines], [], [], duration=0.5) x_positions = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 19.5, 18.5, 17.5, 16.5, 15.5, 14.5, 13.5] y_positions = [12, 10, 8, 6, 4, 4, 6, 8, 10, 12, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5] expected_pos = [] for i in range(len(x_positions)): expected_pos.append({"x": x_positions[i], "y": y_positions[i]}) g.prepare() points = list(g.iterator()) self.assertEqual(expected_pos, [p.positions for p in points]) def test_concat_five_twoD_lines(self): lineone = LineGenerator(["x", "y"], ["mm", "mm"], [0, 0], [10, 10], 6) linetwo = LineGenerator(["x", "y"], ["mm", "mm"], [12, 11], [22, 11], 6) linethree = LineGenerator(["x", "y"], ["mm", "mm"], [24, 10], [34, 0], 6) linefour = LineGenerator(["x", "y"], ["mm", "mm"], [32.5, -1], [2.5, -1], 7) linefive = LineGenerator(["x", "y"], ["mm", "mm"], [5, 1], [55, 21], 6) lines = ConcatGenerator([lineone, linetwo, linethree, linefour, linefive]) g = CompoundGenerator([lines], [], [], duration=0.5) x_positions = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 32.5, 27.5, 22.5, 17.5, 12.5, 7.5, 2.5, 5.0, 15.0, 25, 35, 45, 55] y_positions = [0, 2, 4, 6, 8, 10, 11, 11, 11, 11, 11, 11, 10, 8, 6, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, 1, 5, 9, 13, 17, 21] expected_pos = [] for i in range(len(x_positions)): expected_pos.append({"x": x_positions[i], "y": y_positions[i]}) g.prepare() points = list(g.iterator()) self.assertEqual(expected_pos, [p.positions for p in points]) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
plot_check.py
from scanpointgenerator import LineGenerator, CompoundGenerator from scanpointgenerator import RectangularROI from scanpointgenerator import CircularROI from scanpointgenerator import SpiralGenerator from scanpointgenerator import LissajousGenerator from scanpointgenerator import RandomOffsetMutator from scanpointgenerator import ROIExcluder from scanpointgenerator.plotgenerator import plot_generator from pkg_resources import require require('matplotlib') require('numpy') require('scipy') def grid_check(): x = LineGenerator("x", "mm", 0.0, 4.0, 5, alternate=True) y = LineGenerator("y", "mm", 0.0, 3.0, 4) gen = CompoundGenerator([y, x], [], []) plot_generator(gen) def grid_circle_check(): x = LineGenerator("x", "mm", 0.0, 4.0, 5, alternate=True) y = LineGenerator("y", "mm", 0.0, 3.0, 4) circle = ROIExcluder([CircularROI([2.0, 1.0], 2.0)], ['x', 'y']) gen = CompoundGenerator([y, x], [circle], []) plot_generator(gen, circle) def spiral_check(): spiral = SpiralGenerator(['x', 'y'], ["mm", "mm"], [0.0, 0.0], 10.0) gen = CompoundGenerator([spiral], [], []) plot_generator(gen) def spiral_rectangle_check(): spiral = SpiralGenerator(['x', 'y'], ["mm", "mm"], [0.0, 0.0], 10.0) rectangle = ROIExcluder([RectangularROI([0.0, 0.0], 10.0, 10.0)], ['x', 'y']) gen = CompoundGenerator([spiral], [rectangle], []) plot_generator(gen, rectangle) def lissajous_check(): bounding_box = dict(centre=[0.0, 0.0],span=[1.0,1.0], lobes=2) lissajous = LissajousGenerator(['x', 'y'], ["mm", "mm"], **bounding_box) gen = CompoundGenerator([lissajous], [], []) plot_generator(gen) def lissajous_rectangle_check(): bounding_box = dict(centre=[0.0, 0.0],span=[1.0,1.0], lobes=2) lissajous = LissajousGenerator(['x', 'y'], ["mm", "mm"], **bounding_box) rectangle = ROIExcluder([RectangularROI([0.0, 0.0], 0.8, 0.8)], ['x', 'y']) gen = CompoundGenerator([lissajous], [rectangle], []) plot_generator(gen, rectangle) def line_2d_check(): line = LineGenerator(["x", "y"], ["mm", "mm"], [1.0, 2.0], [5.0, 10.0], 5) gen = CompoundGenerator([line], [], []) plot_generator(gen) def random_offset_check(): x = LineGenerator("x", "mm", 0.0, 4.0, 5, alternate=True) y = LineGenerator("y", "mm", 0.0, 3.0, 4) mutator = RandomOffsetMutator(2,['x','y'], dict(x=0.25, y=0.25)) gen = CompoundGenerator([y, x], [], [mutator]) plot_generator(gen) gen = CompoundGenerator([y, x], [], [mutator, mutator]) plot_generator(gen) gen = CompoundGenerator([y, x], [], [mutator, mutator, mutator]) plot_generator(gen) gen = CompoundGenerator([y, x], [], [mutator, mutator, mutator, mutator, mutator]) plot_generator(gen) def serialise_grid_check(): x = LineGenerator("x", "mm", 0.0, 4.0, 5, alternate=True) y = LineGenerator("y", "mm", 0.0, 3.0, 4) gen = CompoundGenerator([y, x], [], []) plot_generator(gen) gen = gen.to_dict() print(gen) gen = CompoundGenerator.from_dict(gen) plot_generator(gen) grid_check() grid_circle_check() spiral_check() spiral_rectangle_check() lissajous_check() lissajous_rectangle_check() line_2d_check() random_offset_check() serialise_grid_check()
dls-controls/scanpointgenerator
tests/test_core/test_mutator.py
<gh_stars>1-10 import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from scanpointgenerator import Mutator from pkg_resources import require require("mock") from mock import MagicMock class MutatorTest(unittest.TestCase): def test_mutate_raises(self): m = Mutator() with self.assertRaises(NotImplementedError): m.mutate(MagicMock(), MagicMock()) class SerialisationTest(unittest.TestCase): def setUp(self): self.m = Mutator() def test_to_dict(self): expected = {} self.assertEqual(expected, self.m.to_dict()) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
scanpointgenerator/generators/lissajousgenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### import math as m from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.compat import np from scanpointgenerator.core import Generator, UAxes, UUnits, ASize, AAlternate with Anno("The centre of the lissajous curve"): ACentre = Array[float] UCentre = Union[ACentre, Sequence[float]] with Anno("The [height, width] of the curve"): ASpan = Array[float] USpan = Union[ASpan, Sequence[float]] with Anno("Number of x-direction lobes for curve; " "will have lobes+1 y-direction lobes"): ALobes = int @Generator.register_subclass( "scanpointgenerator:generator/LissajousGenerator:1.0") class LissajousGenerator(Generator): """Generate the points of a Lissajous curve""" def __init__(self, axes, units, centre, span, lobes, size=None, alternate=False): # type: (UAxes, UUnits, UCentre, USpan, ALobes, ASize, AAlternate) -> None # Default for size is 250 * lobes if not specified self.centre = ACentre(centre) self.span = ASpan(span) self.lobes = ALobes(lobes) if size is None: size = self.lobes * 250 # Validate assert len(self.centre) == len(self.span) == len(axes) == 2, \ "Expected centre %s, span %s and axes %s to be 2 dimensional" % ( list(self.centre), list(self.span), list(axes)) # Phase needs to be 0 for even lobes and pi/2 for odd lobes to start # at centre for odd and at right edge for even self.x_freq = self.lobes self.y_freq = self.lobes + 1 self.x_max, self.y_max = self.span[0]/2, self.span[1]/2 self.phase_diff = m.pi/2 * (self.lobes % 2) self.increment = 2*m.pi/size super(LissajousGenerator, self).__init__(axes, units, size, alternate) def prepare_arrays(self, index_array): arrays = { self.axes[0]: self.centre[0] + self.x_max * np.sin( self.x_freq * self.increment * index_array + self.phase_diff ), self.axes[1]: self.centre[1] + self.y_max * np.sin( self.y_freq * self.increment * index_array ) } return arrays
dls-controls/scanpointgenerator
scanpointgenerator/core/mutator.py
<filename>scanpointgenerator/core/mutator.py ### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Serializable, Union, Array from scanpointgenerator.core import Point, Points UPoint = Union[Point, Points] UInt = Union[int, Array[int]] class Mutator(Serializable): """Abstract class to apply a mutation to point/points of an ND ScanPointGenerator""" def mutate(self, point, index): # type: (UPoint, Uint) -> UPoint """ Abstract method to take a Point or Points, apply a mutation and then return the new point Args: point: Point or Points object to mutate index: ind[ex/ices] of the Point[s] to mutate Returns: Point: Mutated point """ raise NotImplementedError
dls-controls/scanpointgenerator
scanpointgenerator/plotgenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from scanpointgenerator import CompoundGenerator, RectangularROI, CircularROI MARKER_SIZE = 10 def plot_generator(gen, excluder=None, show_indexes=True): from matplotlib.patches import Rectangle, Circle import matplotlib.pyplot as plt import numpy as np from scipy import interpolate if excluder is not None: for roi in excluder.rois: overlay = plt.subplot(111, aspect='equal') if isinstance(roi, RectangularROI): overlay.add_patch(Rectangle(roi.start, roi.width, roi.height, fill=False)) if isinstance(roi, CircularROI): overlay.add_patch(Circle(roi.centre, roi.radius, fill=False)) if not isinstance(gen, CompoundGenerator): excluders = [] if excluder is None else [excluder] gen = CompoundGenerator([gen], excluders, []) gen.prepare() # points for spline generation x, y = [], [] # capture points and indexes capx, capy, capi = [], [], [] # segment start for colour changing starts = [] for point in gen.iterator(): # If lower is different from last then include it xlower = point.lower["x"] ylower = point.lower.get("y", 0) xpos = point.positions["x"] ypos = point.positions.get("y", 0) if len(x) == 0 or x[-1] != xlower or y[-1] != ylower: if len(x) != 0: # add in a tiny fractional distance to extend last point xdiff = (x[-1] - x[-2]) * 0.01 ydiff = (y[-1] - y[-2]) * 0.01 for i in range(3): x.append(x[-1] + xdiff) y.append(y[-1] + ydiff) # add in padding for the next point xdiff = (xpos - xlower) * 0.01 ydiff = (ypos - ylower) * 0.01 for i in reversed(range(3)): x.append(xlower - xdiff * (i + 1)) y.append(ylower - ydiff * (i + 1)) starts.append(len(x)) x.append(xlower) y.append(ylower) # Add in capture points x.append(xpos) y.append(ypos) capx.append(xpos) capy.append(ypos) capi.append(point.indexes) # And upper point starts.append(len(x)) x.append(point.upper["x"]) y.append(point.upper.get("y", 0)) # # Plot labels plt.xlabel("X (%s)" % gen.units["x"]) if "y" in gen.units: plt.ylabel("Y (%s)" % gen.units["y"]) else: plt.tick_params(left='off', labelleft='off') # Define curves parametrically x = np.array(x) y = np.array(y) t = np.zeros(len(x)) t[1:] = np.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2) t = np.cumsum(t) t /= t[-1] tck, _ = interpolate.splprep([x, y], s=0) # Plot each line for i, start in enumerate(starts): if i + 1 < len(starts): end = starts[i+1] else: end = len(x) - 1 tnew = np.linspace(t[start], t[end], num=1001, endpoint=True) sx, sy = interpolate.splev(tnew, tck) plt.plot(sx, sy, linewidth=2) # And the capture points plt.plot(capx, capy, linestyle="", marker="x", color="k", markersize=MARKER_SIZE) # And a start position plt.plot([x[0]], [y[0]], 'bo') plt.annotate("Start", (x[0], y[0]), xytext=(MARKER_SIZE/2, MARKER_SIZE/2), textcoords='offset points') # And the indexes if show_indexes: for i, x, y in zip(capi, capx, capy): plt.annotate(i, (x, y), xytext=(MARKER_SIZE/2, MARKER_SIZE/2), textcoords='offset points') #indexes = ["%s (size %d)" % z for z in zip(gen.index_names, gen.index_dims)] #plt.title("Dataset: [%s]" % (", ".join(indexes))) plt.show()
dls-controls/scanpointgenerator
tests/test_util.py
<gh_stars>1-10 import unittest import os import sys # module import sys.path.append(os.path.join(os.path.dirname(__file__), "..")) class ScanPointGeneratorTest(unittest.TestCase): def assertListAlmostEqual(self, actual, expected, delta=1e-15): self.assertEqual(len(actual), len(expected)) for a, e in zip(actual, expected): if type(a) in (list, tuple): self.assertEqual(type(a), type(e)) self.assertListAlmostEqual(a, e, delta) else: self.assertAlmostEqual(a, e) def assertIteratorProduces(self, iterator, all_expected): for expected in all_expected: actual = iterator.next() if type(actual) in (list, tuple): self.assertListAlmostEqual(actual, expected) else: self.assertAlmostEqual(actual, expected, delta=0.000001) self.assertRaises(StopIteration, iterator.next)
dls-controls/scanpointgenerator
scanpointgenerator/core/dimension.py
<reponame>dls-controls/scanpointgenerator<filename>scanpointgenerator/core/dimension.py ### # Copyright (c) 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### import itertools from scanpointgenerator.compat import np class Dimension(object): """ An unrolled set of generators joined by excluders. Represents a single dimension within a scan. """ def __init__(self, generators, excluders=None): self.generators = list(generators) self.excluders = list(excluders) if excluders is not None else [] self.axes = list(axis for g in self.generators for axis in g.axes) """list(str): Unrolled axes within the dimension""" self.size = None """int: Size of the dimension""" self.upper = [g.positions[a].max((0,)) for g in self.generators for a in g.axes] """list(float): Upper bound for the dimension""" self.lower = [g.positions[a].min((0,)) for g in self.generators for a in g.axes] """list(float): Lower bound for the dimension""" self.alternate = self.generators[0].alternate self._prepared = False self.indices = [] # validate alternating constraints # we currently do not allow a non-alternating generator inside an # alternating one due to potentially "surprising" behaviour of the # non-alternating generator (the dimension itself will be alternating) started_alternating = False for g in self.generators: if started_alternating and not g.alternate: raise ValueError( "Cannot nest non-alternating generators in " "alternating generators within a Dimension " "due to inconsistent output paths") started_alternating = started_alternating or g.alternate def apply_excluder(self, excluder): """Add an excluder to the current Dimension""" if self._prepared: raise ValueError("Dimension already prepared") if not set(excluder.axes) <= set(self.axes): raise ValueError("Excluder axes '%s' do not apply to Dimension axes '%s'" \ % (excluder.axes, self.axes)) self.excluders.append(excluder) def get_positions(self, axis): """ Retrieve the positions for a given axis within the dimension. Args: axis (str): axis to get positions for Returns: Positions (np.array): Array of positions """ # check that this dimension is prepared if not self._prepared: raise ValueError("Must call prepare first") return self.positions[axis] def get_mesh_map(self, axis): """ Retrieve the mesh map (indices) for a given axis within the dimension. Args: axis (str): axis to get positions for Returns: Positions (np.array): Array of mesh indices """ # the points for this axis must be scaled and then indexed if not self._prepared: raise ValueError("Must call prepare first") # scale up points for axis gen = [g for g in self.generators if axis in g.axes][0] points = gen.positions[axis] # just get index of points instead of actual point value points = np.arange(len(points)) if gen.alternate: points = np.append(points, points[::-1]) tile = 0.5 if self.alternate else 1 repeat = 1 for g in self.generators[:self.generators.index(gen)]: tile *= g.size for g in self.generators[self.generators.index(gen) + 1:]: repeat *= g.size points = np.repeat(points, repeat) if tile % 1 != 0: p = np.tile(points, int(tile)) points = np.append(p, points[:int(len(points)//2)]) else: points = np.tile(points, int(tile)) return points[self.indices] def get_point(self, idx): if not self._prepared: raise ValueError("Must call prepare first") axis_points = {axis:self.positions[axis][idx] for axis in self.positions} return axis_points def get_bounds(self, idx, reverse=False): if not self._prepared: raise ValueError("Must call prepare first") if not reverse: axis_upper, axis_lower = self.upper_bounds, self.lower_bounds else: axis_upper, axis_lower = self.lower_bounds, self.upper_bounds lower = {axis:axis_lower[axis][idx] for axis in axis_lower} upper = {axis:axis_upper[axis][idx] for axis in axis_upper} return lower, upper def prepare(self): """ Prepare data structures required to determine size and filtered positions of the dimension. Must be called before get_positions or get_mesh_map are called. """ axis_positions = {} axis_bounds_lower = {} axis_bounds_upper = {} masks = [] # scale up all position arrays # inner generators are tiled by the size of out generators # outer generators have positions repeated by the size of inner generators repeats, tilings, dim_size = 1, 1, 1 for g in self.generators: repeats *= g.size dim_size *= g.size for gen in self.generators: repeats /= gen.size for axis in gen.axes: positions = gen.positions[axis] if gen.alternate: positions = np.append(positions, positions[::-1]) positions = np.repeat(positions, repeats) p = np.tile(positions, (tilings // 2)) if tilings % 2 != 0: positions = np.append(p, positions[:int(len(positions)//2)]) else: positions = p else: positions = np.repeat(positions, repeats) positions = np.tile(positions, tilings) axis_positions[axis] = positions tilings *= gen.size # produce excluder masks for excl in self.excluders: arrays = [axis_positions[axis] for axis in excl.axes] excluder_mask = excl.create_mask(*arrays) masks.append(excluder_mask) # AND all masks together (empty mask is all values selected) mask = masks[0] if len(masks) else np.full(dim_size, True, dtype=np.int8) for m in masks[1:]: mask &= m gen = self.generators[-1] if getattr(gen, "bounds", None): tilings = np.prod(np.array([g.size for g in self.generators[:-1]])) if gen.alternate: tilings /= 2. for axis in gen.axes: upper_base = gen.bounds[axis][1:] lower_base = gen.bounds[axis][:-1] upper, lower = upper_base, lower_base if gen.alternate: upper = np.append(upper_base, lower_base[::-1]) lower = np.append(lower_base, upper_base[::-1]) upper = np.tile(upper, int(tilings)) lower = np.tile(lower, int(tilings)) if tilings % 1 != 0: upper = np.append(upper, upper_base) lower = np.append(lower, lower_base) axis_bounds_upper[axis] = upper axis_bounds_lower[axis] = lower self.mask = mask self.indices = self.mask.nonzero()[0] self.size = len(self.indices) self.positions = {axis:axis_positions[axis][self.indices] for axis in axis_positions} self.upper_bounds = {axis:self.positions[axis] for axis in self.positions} self.lower_bounds = {axis:self.positions[axis] for axis in self.positions} for axis in axis_bounds_lower: self.upper_bounds[axis] = axis_bounds_upper[axis][self.indices] self.lower_bounds[axis] = axis_bounds_lower[axis][self.indices] self._prepared = True @staticmethod def merge_dimensions(dimensions): generators = itertools.chain.from_iterable(d.generators for d in dimensions) excluders = itertools.chain.from_iterable(d.excluders for d in dimensions) return Dimension(generators, excluders)
dls-controls/scanpointgenerator
scanpointgenerator/core/compoundgenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - Points implementation # ### import logging from annotypes import Serializable, Anno, Union, Array, Sequence, \ deserialize_object from scanpointgenerator.compat import range_, np from scanpointgenerator.core.dimension import Dimension from scanpointgenerator.core.generator import Generator from scanpointgenerator.core.point import Point, Points from scanpointgenerator.core.excluder import Excluder from scanpointgenerator.excluders.roiexcluder import ROIExcluder from scanpointgenerator.core.mutator import Mutator from scanpointgenerator.rois import RectangularROI from scanpointgenerator.generators import LineGenerator, StaticPointGenerator with Anno("List of Generators to nest"): AGenerators = Array[Generator] UGenerators = Union[AGenerators, Sequence[Generator], Generator] with Anno("List of Excluders to filter points by"): AExcluders = Array[Excluder] UExcluders = Union[AExcluders, Sequence[Excluder], Excluder] with Anno("List of Mutators to apply to each point"): AMutators = Array[Mutator] UMutators = Union[AMutators, Sequence[Mutator], Mutator] with Anno("Point durations in seconds (-1 for variable)"): ADuration = float with Anno("Make points continuous (set upper/lower bounds)"): AContinuous = bool with Anno("Time delay after each point"): ADelay = float @Generator.register_subclass( "scanpointgenerator:generator/CompoundGenerator:1.0") class CompoundGenerator(Serializable): """Nest N generators, apply exclusion regions to relevant generator pairs and apply any mutators before yielding points""" def __init__(self, generators, # type: UGenerators excluders=(), # type: UExcluders mutators=(), # type: UMutators duration=-1, # type: ADuration continuous=True, # type: AContinuous delay_after=0 # type: ADelay ): # type: (...) -> None self.size = 0 """int: Final number of points to be generated - valid only after calling prepare""" self.shape = None """tuple(int): Final shape of the scan - valid only after calling prepare""" self.dimensions = [] """list(Dimension): Dimension instances - valid only after calling prepare""" self.generators = AGenerators( [deserialize_object(g, Generator) for g in generators]) self.excluders = AExcluders( [deserialize_object(e, Excluder) for e in excluders]) self.mutators = AMutators( [deserialize_object(m, Mutator) for m in mutators]) self.duration = ADuration(duration) self.continuous = AContinuous(continuous) self.axes = [] self.units = {} self._dim_meta = {} self._prepared = False self.delay_after = ADelay(delay_after) if self.delay_after < 0.0: self.delay_after = 0.0 for generator in self.generators: logging.debug("Generator passed to Compound init") logging.debug(generator.to_dict()) self.axes += generator.axes self.units.update(generator.axis_units()) if len(self.axes) != len(set(self.axes)): raise ValueError("Axis names cannot be duplicated") def prepare(self): """ Prepare data structures required for point generation and initialize size, shape, and dimensions attributes. Must be called before get_point or iterator are called. """ if self._prepared: return self.dimensions = [] self._dim_meta = {} # we're going to mutate these structures excluders = list(self.excluders) generators = list(self.generators) # special case if we have rectangular regions on line generators # we should restrict the resulting grid rather than merge dimensions # this changes the alternating case a little (without doing this, we # may have started in reverse direction) for excluder_ in [e for e in excluders if isinstance(e, ROIExcluder)]: if len(excluder_.rois) == 1 \ and isinstance(excluder_.rois[0], RectangularROI) \ and excluder_.rois[0].angle == 0: rect = excluder_.rois[0] axis_1, axis_2 = excluder_.axes[0], excluder_.axes[1] gen_1 = [g for g in generators if axis_1 in g.axes][0] gen_2 = [g for g in generators if axis_2 in g.axes][0] if gen_1 is gen_2: continue if isinstance(gen_1, LineGenerator) \ and isinstance(gen_2, LineGenerator): gen_1.prepare_positions() gen_2.prepare_positions() # Filter by axis 1 valid = np.full(gen_1.size, True, dtype=np.int8) valid &= \ gen_1.positions[axis_1] <= rect.width + rect.start[0] valid &= \ gen_1.positions[axis_1] >= rect.start[0] points_1 = gen_1.positions[axis_1][valid.astype(np.bool)] # Filter by axis 2 valid = np.full(gen_2.size, True, dtype=np.int8) valid &= \ gen_2.positions[axis_2] <= rect.height + rect.start[1] valid &= gen_2.positions[axis_2] >= rect.start[1] points_2 = gen_2.positions[axis_2][valid.astype(np.bool)] # Recreate generators to replace larger generators + ROI new_gen1 = LineGenerator( gen_1.axes, gen_1.units, [points_1[0]], [points_1[-1]], len(points_1), gen_1.alternate) new_gen2 = LineGenerator( gen_2.axes, gen_2.units, [points_2[0]], [points_2[-1]], len(points_2), gen_2.alternate) generators[generators.index(gen_1)] = new_gen1 generators[generators.index(gen_2)] = new_gen2 # Remove Excluder as it is now empty excluders.remove(excluder_) for generator in generators: generator.prepare_positions() self.dimensions.append(Dimension([generator])) # only the inner-most generator needs to have bounds calculated if self.continuous: generators[-1].prepare_bounds() for excluder in excluders: matched_dims = [d for d in self.dimensions if len(set(d.axes) & set(excluder.axes)) != 0] if len(matched_dims) == 0: raise ValueError( "Excluder references axes that have not been provided by generators: %s" % str(excluder.axes)) d_start = self.dimensions.index(matched_dims[0]) d_end = self.dimensions.index(matched_dims[-1]) if d_start != d_end: # merge all excluders between d_start and d_end (inclusive) merged_dim = Dimension.merge_dimensions(self.dimensions[d_start:d_end+1]) self.dimensions = self.dimensions[:d_start] + [merged_dim] + self.dimensions[d_end+1:] dim = merged_dim else: dim = self.dimensions[d_start] dim.apply_excluder(excluder) self.size = 1 for dim in self.dimensions: self._dim_meta[dim] = {} dim.prepare() if dim.size == 0: raise ValueError("Regions would exclude entire scan") self.size *= dim.size self.shape = tuple(dim.size for dim in self.dimensions) repeat = self.size tile = 1 for dim in self.dimensions: repeat /= dim.size # Tile = number of times this dimension is tiled self._dim_meta[dim]["tile"] = tile # Repeat = number of times each point is repeated self._dim_meta[dim]["repeat"] = repeat tile *= dim.size self._prepared = True def iterator(self): """ Iterator yielding generator positions at each scan point Yields: Point: The next point """ if not self._prepared: raise ValueError("CompoundGenerator has not been prepared") it = (self.get_point(n) for n in range_(self.size)) for p in it: yield p def get_point(self, n): """ Retrieve the desired point from the generator Args: n (int): point to be generated Returns: Point: The requested point """ if not self._prepared: raise ValueError("CompoundGenerator has not been prepared") if n >= self.size: raise IndexError("Requested point is out of range") point = Point() # determine which point to extract from each dimension # handling the fact that some dimensions "alternate" for dim in self.dimensions: k = int(n // self._dim_meta[dim]["repeat"]) dim_runs = k // dim.size dim_idx = k % dim.size dim_in_reverse = dim.alternate and dim_runs % 2 == 1 if dim_in_reverse: dim_idx = dim.size - dim_idx - 1 dim_positions = dim.get_point(dim_idx) point.positions.update(dim_positions) if dim is self.dimensions[-1]: lower, upper = dim.get_bounds(dim_idx, dim_in_reverse) point.lower.update(lower) point.upper.update(upper) else: point.lower.update(dim_positions) point.upper.update(dim_positions) point.indexes.append(dim_idx) point.duration = self.duration point.delay_after = self.delay_after for m in self.mutators: point = m.mutate(point, n) return point def get_points(self, start, finish): """ Retrieve a Points object: a wrapper for an array of Point from the generator Args: start (int), finish (int): indices of the first point and final+1th point to include i.e. get_points(1, 5) would return a Points of Point 1, 2, 3 & 4 but not 5. Returns: Points: a wrapper object with the data of the requested Point [plural] """ if not self._prepared: raise ValueError("CompoundGenerator has not been prepared") ''' situations: dim N constant, dim N+1 constant (e.g. 1,1 -> 1,1) dim N constant, dim N+1 increasing: (e.g. n,1->n,5) dim N increasing, dim N+1 increasing: (n,1->n+1,2) N[n],N+1[start]->N[n],N+1[max]->N[n+1],N+1[0]->...->N[K],N+1[finish] dim N increasing, dim N+1 decreasing: (n,2->n+1,1) as above dim N increasing, dim N+1 constant: (n,1->n+1,1) as above for each pair of consecutive dim N, N+1 => must be first dim M where changes (even if it's outermost). => All dimensions outside M must have single point => M must be within single dimension "run" => All dimensions inside M must tile => M behaves like all dimensions within it innermost dim must be moving ''' if finish == start: return Points() indices = np.arange(start, finish, np.sign(finish-start)) indices = np.where(indices < 0, indices + self.size, indices) if max(indices) >= self.size: raise IndexError("Requested points extend out of range") length = len(indices) points = Points() for dim in self.dimensions: point_repeat = int(self._dim_meta[dim]["repeat"]) point_indices = indices // point_repeat # Number of point this step is on found_m = np.any(point_indices != point_indices[0]) # For alternating case if found_m: points.extract(self._points_from_below_m(dim, point_indices)) else: points.extract(self._points_above_m(dim, point_indices[0], length)) points.duration = np.full(length, self.duration) points.delay_after = np.full(length, self.delay_after) for m in self.mutators: points = m.mutate(points, indices) return points @staticmethod def _points_above_m(dim, index, length): if dim.alternate and ((index // dim.size) % 2 == 1): index = dim.size - index - 1 index %= dim.size ''' This dimension does not step, all points are the same point, cannot be the lowest dimension Unless finish = start + 1, in which case all dimensions are treated this way''' return Points.points_from_axis_point(dim, int(index), length) def _points_from_below_m(self, dim, indices): points = Points() ''' This dimension must step and may finish a run through a dimension, alternate. One of these will be the innermost dimension, so must calculate bounds ''' dim_run = indices // dim.size point_indices = indices % dim.size backwards = (dim_run % 2 == 1) & dim.alternate point_indices = (np.where(backwards, dim.size - point_indices - 1, point_indices)) dimension_positions = {axis:dim.positions[axis][point_indices] for axis in dim.axes} points.positions.update(dimension_positions) if dim is self.dimensions[-1]: points.lower.update({axis: np.where(backwards, dim.upper_bounds[axis][point_indices], dim.lower_bounds[axis][point_indices]) for axis in dim.axes}) points.upper.update({axis: np.where(backwards, dim.lower_bounds[axis][point_indices], dim.upper_bounds[axis][point_indices]) for axis in dim.axes}) else: points.lower.update({axis: dimension_positions[axis] for axis in dimension_positions}) points.upper.update({axis: dimension_positions[axis] for axis in dimension_positions}) points.indexes = point_indices return points
dls-controls/scanpointgenerator
tests/test_generators/test_spiralgenerator.py
<filename>tests/test_generators/test_spiralgenerator.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import SpiralGenerator class SpiralGeneratorTest(ScanPointGeneratorTest): def setUp(self): self.g = SpiralGenerator(['x', 'y'], ["cm", "mm"], [0.0, 0.0], 1.4, alternate=True) def test_init(self): self.assertEqual(self.g.axis_units(), dict(x="cm", y="mm")) self.assertEqual(self.g.axes, ["x", "y"]) def test_duplicate_name_raises(self): with self.assertRaises(AssertionError): SpiralGenerator(["x", "x"], ["mm", "mm"], [0.0, 0.0], 1.0) def test_array_positions(self): expected_x = [0.23663214944574582, -0.6440318266552169, -0.5596688286164636, 0.36066957248394327, 1.130650533568409, 1.18586065489788, 0.5428735608675326] expected_y = [-0.3211855677650875, -0.25037538922751695, 0.6946549630820702, 0.9919687803189761, 0.3924587351155914, -0.5868891557832875, -1.332029488076613,] expected_bx = [0.0, -0.2214272368007088, -0.7620433832656455, -0.13948222773063082, 0.8146440851904461, 1.2582363345925418, 0.9334439933089926, 0.06839234794968006] expected_by = [0.0, -0.5189218293602549, 0.23645222432582483, 0.9671992383675001, 0.7807653675717078, -0.09160107657707395, -1.0190886264001306, -1.4911377166541206] self.g.prepare_positions() self.g.prepare_bounds() self.assertListAlmostEqual(expected_x, self.g.positions['x'].tolist()) self.assertListAlmostEqual(expected_y, self.g.positions['y'].tolist()) self.assertListAlmostEqual(expected_bx, self.g.bounds['x'].tolist()) self.assertListAlmostEqual(expected_by, self.g.bounds['y'].tolist()) def test_to_dict(self): expected_dict = dict() expected_dict['typeid'] = "scanpointgenerator:generator/SpiralGenerator:1.0" expected_dict['axes'] = ['x', 'y'] expected_dict['units'] = ['cm', 'mm'] expected_dict['centre'] = [0.0, 0.0] expected_dict['radius'] = 1.4 expected_dict['scale'] = 1 expected_dict['alternate'] = True d = self.g.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['axes'] = ["x", "y"] _dict['units'] = ["mm", "cm"] _dict['centre'] = [0.0, 0.0] _dict['radius'] = 1.4 _dict['scale'] = 1 _dict['alternate'] = True units_dict = dict() units_dict['x'] = "mm" units_dict['y'] = "cm" gen = SpiralGenerator.from_dict(_dict) self.assertEqual(["x", "y"], gen.axes) self.assertEqual(units_dict, gen.axis_units()) self.assertEqual([0.0, 0.0], gen.centre) self.assertEqual(1.4, gen.radius) self.assertEqual(1, gen.scale) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_generators/test_zipgenerator.py
from scanpointgenerator import LineGenerator, ZipGenerator, Generator from tests.test_util import ScanPointGeneratorTest class ZipGeneratorTest(ScanPointGeneratorTest): def test_init(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) g = ZipGenerator([genone]) self.assertEqual(["x"], g.axes) gau = g.axis_units() self.assertEqual(dict(x="mm"), gau) self.assertEqual(5, g.size) self.assertEqual(False, g.alternate) def test_init_alternate(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) g = ZipGenerator([genone], True) self.assertEqual(["x"], g.axes) gau = g.axis_units() self.assertEqual(dict(x="mm"), gau) self.assertEqual(5, g.size) self.assertEqual(True, g.alternate) def test_init_diff_axis(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("y", "mm", 13, 20, 5) g = ZipGenerator([genone, gentwo]) self.assertEqual(["x", "y"], g.axes) self.assertEqual(dict(x="mm", y="mm"), g.axis_units()) self.assertEqual(5, g.size) def test_init_same_axis(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("x", "mm", 13, 20, 5) with self.assertRaises(AssertionError): ZipGenerator([genone, gentwo]) def test_init_diff_size(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("y", "mm", 13, 20, 6) with self.assertRaises(AssertionError): ZipGenerator([genone, gentwo]) def test_init_diff_alternate(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5, alternate=True) gentwo = LineGenerator("y", "mm", 13, 20, 5, alternate=False) with self.assertRaises(AssertionError): ZipGenerator([genone, gentwo]) def test_init_two_dim_line_axis(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) g = ZipGenerator([genone]) self.assertEqual(["x", "y"], g.axes) self.assertEqual(dict(x="mm", y="mm"), g.axis_units()) self.assertEqual(3, g.size) def test_init_two_gen_same_axis(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) gentwo = LineGenerator(["x", "y"], ["mm", "mm"], [6., -6.], [8., -8.], 3) with self.assertRaises(AssertionError): ZipGenerator([genone, gentwo]) def test_init_two_gen_diff_axis(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) gentwo = LineGenerator(["w", "z"], ["mm", "mm"], [6., -6.], [8., -8.], 3) g = ZipGenerator([genone, gentwo]) self.assertEqual(["x", "y", "w", "z"], g.axes) self.assertEqual(dict(x="mm", y="mm", w="mm", z="mm"), g.axis_units()) self.assertEqual(3, g.size) def test_init_two_gen_overlap_axis(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) gentwo = LineGenerator(["y", "z"], ["mm", "mm"], [6., -6.], [8., -8.], 3) with self.assertRaises(AssertionError): ZipGenerator([genone, gentwo]) def test_init_none(self): with self.assertRaises(AssertionError): ZipGenerator([]) def test_array_positions_from_line(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("y", "mm", 11, 19, 5) genthree = LineGenerator("z", "mm", 21, 29, 5) g = ZipGenerator([genone, gentwo, genthree]) g.prepare_positions() g.prepare_bounds() self.assertEqual([1, 3, 5, 7, 9], g.positions['x'].tolist()) self.assertEqual([0, 2, 4, 6, 8, 10], g.bounds['x'].tolist()) self.assertEqual([11, 13, 15, 17, 19], g.positions['y'].tolist()) self.assertEqual([10, 12, 14, 16, 18, 20], g.bounds['y'].tolist()) self.assertEqual([21, 23, 25, 27, 29], g.positions['z'].tolist()) self.assertEqual([20, 22, 24, 26, 28, 30], g.bounds['z'].tolist()) def test_array_positions_from_two_dim_line_axis(self): genone = LineGenerator(["x", "y"], ["mm", "mm"], [2., -2.], [4., -4.], 3) g = ZipGenerator([genone]) g.prepare_positions() g.prepare_bounds() self.assertEqual([2, 3, 4], g.positions['x'].tolist()) self.assertEqual([1.5, 2.5, 3.5, 4.5], g.bounds['x'].tolist()) self.assertEqual([-2, -3, -4], g.positions['y'].tolist()) self.assertEqual([-1.5, -2.5, -3.5, -4.5], g.bounds['y'].tolist()) def test_to_dict(self): genone = LineGenerator("x", "mm", 1.0, 9.0, 5) gentwo = LineGenerator("y", "mm", 11, 19, 5) g = ZipGenerator([genone, gentwo]) expected_dict = dict() expected_dict['typeid'] = \ "scanpointgenerator:generator/ZipGenerator:1.0" expected_dict['generators'] = [{'typeid': 'scanpointgenerator:generator' '/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [9.0], 'start': [1.0], 'units': ['mm'], 'size': 5}, {'typeid': 'scanpointgenerator:generator' '/LineGenerator:1.0', 'alternate': False, 'axes': ['y'], 'stop': [19], 'start': [11], 'units': ['mm'], 'size': 5}] expected_dict['alternate'] = False d = g.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['typeid'] = "scanpointgenerator:generator/ZipGenerator:1.0" _dict['generators'] = [ {'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['x'], 'stop': [9.0], 'start': [1.0], 'units': ['mm'], 'size': 5}, {'typeid': 'scanpointgenerator:generator/LineGenerator:1.0', 'alternate': False, 'axes': ['y'], 'stop': [19], 'start': [11], 'units': ['mm'], 'size': 5}] gen = ZipGenerator.from_dict(_dict) self.assertEqual(["x", "y"], gen.axes) self.assertEqual(dict(x="mm", y="mm"), gen.axis_units()) self.assertEqual(5, gen.size) self.assertEqual(False, gen.alternate) gen.prepare_positions() gen.prepare_bounds() self.assertEqual([1, 3, 5, 7, 9], gen.positions['x'].tolist()) self.assertEqual([0, 2, 4, 6, 8, 10], gen.bounds['x'].tolist()) self.assertEqual([11, 13, 15, 17, 19], gen.positions['y'].tolist()) self.assertEqual([10, 12, 14, 16, 18, 20], gen.bounds['y'].tolist())
dls-controls/scanpointgenerator
tests/test_excluders/test_squashingexcluder.py
<filename>tests/test_excluders/test_squashingexcluder.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import SquashingExcluder from scanpointgenerator.compat import np class TestCreateMask(ScanPointGeneratorTest): def setUp(self): self.e = SquashingExcluder(["x", "y"]) def test_create_mask_returns_all_points(self): x_points = np.array([1, 2, 3, 4]) y_points = np.array([10, 10, 20, 20]) expected_mask = np.array([True, True, True, True]) mask = self.e.create_mask(x_points, y_points) self.assertEqual(expected_mask.tolist(), mask.tolist()) class TestSerialisation(unittest.TestCase): def setUp(self): self.e = SquashingExcluder(["x", "y"]) def test_to_dict(self): expected_dict = dict() expected_dict['typeid'] = \ "scanpointgenerator:excluder/SquashingExcluder:1.0" expected_dict['axes'] = ["x", "y"] d = self.e.to_dict() self.assertEqual(expected_dict, d) def test_from_dict(self): _dict = dict() _dict['axes'] = ["x", "y"] e = SquashingExcluder.from_dict(_dict) self.assertEqual(["x", "y"], e.axes) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_core/test_get_points.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import CompoundGenerator from scanpointgenerator import LineGenerator from scanpointgenerator import CircularROI, ROIExcluder from scanpointgenerator import RandomOffsetMutator from scanpointgenerator import Points from scanpointgenerator.compat import np class GetPointsTest(ScanPointGeneratorTest): def setUp(self): l1 = LineGenerator("x", "mm", 0, 5, 5) l2 = LineGenerator("y", "nm", 0, 5, 5) l3 = LineGenerator("z", "mm", 0, 5, 5) self.comp = CompoundGenerator([l1, l2, l3], [], [], 5, True, 7) self.comp.prepare() def test_simple_points(self): points= self.comp.get_points(7, 12) self.assertEqual(list([[0, 1, 2],[0, 1, 3],[0, 1, 4],[0, 2, 0],[0, 2, 1]]), points.indexes.tolist()) # Lower = Bounds for outer dimension self.assertEqual(list([0., 0., 0., 0., 0.]), points.lower['x'].tolist()) # Lower != bounds for innermost dimension self.assertEqual(list([1.25, 1.25, 1.25, 2.5 , 2.5]), points.lower['y'].tolist()) self.assertEqual(list([1.875, 3.125, 4.375, -0.625, 0.625]), points.lower['z'].tolist()) self.assertTrue(np.all(np.full(5, 5) == points.duration)) self.assertTrue(np.all(np.full(5, 7) == points.delay_after)) def test_bulk(self): points= self.comp.get_points(42, 59) for a in range(42, 59): self.assertListAlmostEqual(self.comp.get_point(a).indexes, points.indexes[a-42]) for axis in ["x", "y", "z"]: self.assertEqual(self.comp.get_point(a).lower[axis], points.lower[axis][a-42]) self.assertEqual(self.comp.get_point(a).upper[axis], points.upper[axis][a-42]) self.assertEqual(self.comp.get_point(a).positions[axis], points.positions[axis][a-42]) def test_alternating(self): l1 = LineGenerator("x", "mm", 0, 5, 5) l2 = LineGenerator("y", "nm", 0, 5, 5, True) l3 = LineGenerator("z", "mm", 0, 5, 5) comp = CompoundGenerator([l1, l2, l3], [], [], 5) comp.prepare() self.assertEqual(list([[0,0,0],[0,0,1],[0,0,2],[0,0,3],[0,0,4],[0,1,0],[0,1,1],[0,1,2],[0,1,3],[0,1,4], [0,2,0]]), comp.get_points(0, 11).indexes.tolist()) self.assertEqual(list([[0,3,1],[0,3,2],[0,3,3],[0,3,4],[0,4,0],[0,4,1],[0,4,2],[0,4,3],[0,4,4],[1,4,0], [1,4,1]]), comp.get_points(16, 27).indexes.tolist()) self.assertEqual(list([[0,3,1],[0,3,2],[0,3,3],[0,3,4],[0,4,0],[0,4,1],[0,4,2],[0,4,3],[0,4,4],[1,4,0], [1,4,1]]), comp.get_points(-109, -98).indexes.tolist()) def test_alternating_bounds(self): l1 = LineGenerator("x", "mm", 0, 0.5, 3, True) l2 = LineGenerator("y", "nm", 0, 0.1, 2) comp = CompoundGenerator([l2, l1], [], []) comp.prepare() points = comp.get_points(0, 6) self.assertEqual(list([0., 0., 0., 0.1, 0.1, 0.1]), points.lower["y"].tolist()) self.assertEqual(list([0., 0., 0., 0.1, 0.1, 0.1]), points.upper["y"].tolist()) # Bounds go in the correct direction for an alternating dimension self.assertEqual(list([-0.125, 0.125, 0.375, 0.625, 0.375, 0.125]), points.lower["x"].tolist()) self.assertEqual(list([0.125, 0.375, 0.625, 0.375, 0.125, -0.125]), points.upper["x"].tolist()) def test_backwards(self): fpoints = self.comp.get_points(0, 6) bpoints = self.comp.get_points(5,-1) for i in range(0,5): point = self.comp.get_point(i) for axis in fpoints.positions: self.assertEqual(fpoints.positions[axis][i], bpoints.positions[axis][5-i]) self.assertEqual(fpoints.lower[axis][i], bpoints.lower[axis][5-i]) self.assertEqual(fpoints.upper[axis][i], bpoints.upper[axis][5-i]) self.assertTrue(np.all(fpoints.indexes[i] == bpoints.indexes[5-i])) self.assertTrue(np.all(point.indexes == fpoints.indexes[i])) def test_adding_points(self): apoints = self.comp.get_points(0, 5) apoints += self.comp.get_points(5, 10) cpoints = self.comp.get_points(0, 10) for i in range(0,10): for axis in apoints.positions: self.assertEqual(apoints.positions[axis][i], cpoints.positions[axis][i]) self.assertEqual(apoints.lower[axis][i], cpoints.lower[axis][i]) self.assertEqual(apoints.upper[axis][i], cpoints.upper[axis][i]) self.assertTrue(np.all(apoints.indexes == cpoints.indexes)) def test_adding_point_to_points(self): # 0, 1, 2, 3, 4 apoints = self.comp.get_points(0, 5) # nothing apoints += self.comp.get_points(5, 5) # 5 apoints += self.comp.get_point(5) # 6, 7 apoints += self.comp.get_points(6, 8) # 0, 1, 2, 3, 4, 5, 6, 7 cpoints = self.comp.get_points(0, 8) for i in range(0,8): for axis in apoints.positions: self.assertEqual(apoints.positions[axis][i], cpoints.positions[axis][i]) self.assertTrue(np.all(apoints.indexes == cpoints.indexes)) def test_roi(self): l1 = LineGenerator("x", "mm", 0.5, 5.5, 6) l2 = LineGenerator("y", "mm", 0.5, 5.5, 6) r1 = CircularROI([2.5, 2.5], 1.01) e = ROIExcluder([r1], ["x", "y"]) self.comp = CompoundGenerator([l1, l2], [e], [], 5, True, 7) self.comp.prepare() # Comp.size = 5, only these points included y = [2.5, 1.5, 2.5, 3.5, 2.5] y_up = [3, 2, 3, 4, 3] y_dn = [2, 1, 2, 3, 2] x = [1.5, 2.5, 2.5, 2.5, 3.5] points= self.comp.get_points(0,5) self.assertTrue(np.all([0,1,2,3,4] == points.indexes)) self.assertTrue(np.all(x == points.positions["x"])) self.assertTrue(np.all(x == points.lower["x"])) self.assertTrue(np.all(x == points.upper["x"])) self.assertTrue(np.all(y == points.positions["y"])) self.assertTrue(np.all(y_dn == points.lower["y"])) self.assertTrue(np.all(y_up == points.upper["y"])) def test_random_offset(self): ''' Also tests consistency between Jython and Cython: all hardcoded values generated with Cython 2.7.13, but should be consistent with all Cython, Jython ''' l1 = LineGenerator("x", "mm", 0.5, 5.5, 6) l2 = LineGenerator("y", "mm", 0.5, 5.5, 6) m1 = RandomOffsetMutator(12, ["x", "y"], [0.1, 0.1]) self.comp = CompoundGenerator([l1, l2], [], [m1], 5, True, 7) self.comp.prepare() pos = self.comp.get_points(0, 8) shortpos = self.comp.get_points(0, 4) rev = self.comp.get_points(7, -1) shortrev = self.comp.get_points(3, -1) positions = [0.438320, 0.430532, 0.462758, 0.540163, 0.585728, 0.565177, 1.402957, 1.461795] uppy = [1.001194, 2.063024, 3.048318, 4.036334, 5.043193, 6.051262, 1.013331, 1.984931] lowx = [0.515187, 0.434426, 0.446645, 0.501460, 0.562946, 0.575453, 1.484067, 1.432376] for i in range(8): point = self.comp.get_point(i) a = (pos.positions["x"][i], pos.lower["x"][i], pos.upper["y"][i]) b = (rev.positions["x"][7-i], rev.lower["x"][7-i], rev.upper["y"][7-i]) c = (point.positions["x"], point.lower["x"], point.upper["y"]) for k in [a, b, c]: self.assertAlmostEqual(positions[i], k[0], delta=0.0001) self.assertAlmostEqual(lowx[i], k[1], delta=0.0001) self.assertAlmostEqual(uppy[i], k[2], delta=0.0001) # Test for when one dimension is stationary and so points = bounds for i in range(3): point = self.comp.get_point(i) a = (shortpos.positions["x"][i], shortpos.lower["x"][i], shortpos.upper["y"][i]) b = (shortrev.positions["x"][3 - i], shortrev.lower["x"][3 - i], shortrev.upper["y"][3 - i]) c = (point.positions["x"], point.lower["x"], point.upper["y"]) for k in [a, b, c]: self.assertAlmostEqual(positions[i], k[0], delta=0.0001) self.assertAlmostEqual(lowx[i], k[1], delta=0.0001) self.assertAlmostEqual(uppy[i], k[2], delta=0.0001) def test_slicing(self): l1 = LineGenerator("x", "mm", 0.5, 5.5, 6) l2 = LineGenerator("y", "mm", 0.5, 5.5, 6) m1 = RandomOffsetMutator(12, ["x", "y"], [0.1, 0.1]) self.comp = CompoundGenerator([l1, l2], [], [m1], 5, True, 7) self.comp.prepare() points = self.comp.get_points(0, 8) self.assertEqual(8, len(points)) self.assertAlmostEqual(0.45867, points[0].positions["y"], delta=0.0001) for i in [0, 1]: self.assertAlmostEqual([0.45867, 1.54371][i], points[0:2].positions["y"][i], delta=0.0001) self.assertAlmostEqual([0.58572, 0.54016][i], points[4:2:-1].positions["x"][i], delta=0.0001) self.assertAlmostEqual(1.46179, points[-1].positions["x"], delta=0.0001) for i in range(4): self.assertAlmostEqual([1.46179, 0.56517, 0.54016, 0.43053][i] , points[-1:0:-2].positions["x"][i], delta=0.0001) def test_consistency(self): ''' Tests the consistency of the random offsetmutator function: a mutated Points should contain the same as the sum of the Point that make it up mutated seperately; as should a Points constructed from multiple Points. ''' l1 = LineGenerator("x", "mm", 0.5, 5.5, 6) l2 = LineGenerator("y", "mm", 0.5, 5.5, 6) m1 = RandomOffsetMutator(12, ["x", "y"], [0.1, 0.1]) self.comp = CompoundGenerator([l1, l2], [], [m1], 5, True, 7) self.comp.prepare() points = self.comp.get_points(5, 12) # get_points apoints = self.comp.get_points(5, 8) # get_points + get_points apoints += self.comp.get_points(8, 12) addi_points = Points() # get_point + get_point for i in range(6): point = self.comp.get_point(i+5) # get_point addi_points += point # a = b, a = c, a = d => a = b = c = d a = (points.positions["x"][i], points.lower["x"][i], "a") b = (point.positions["x"], point.lower["x"], "b") c = (addi_points.positions["x"][i], addi_points.lower["x"][i], "c") d = (apoints.positions["x"][i], apoints.lower["x"][i], "d") for k in [b, c, d]: self.assertAlmostEqual(a[0], k[0]) self.assertAlmostEqual(a[1], k[1]) # One dimension stationary therefore bounds = points apoints = self.comp.get_points(8, 10) apoints += self.comp.get_points(10, 12) mpoints = self.comp.get_points(8, 12) addi_points = Points() for i in range(4): point = self.comp.get_point(8+i) addi_points += point # a = b, a = c, a = d => a = b = c = d a = (points.positions["x"][3+i], points.lower["x"][3+i]) b = (point.positions["x"], point.lower["x"]) c = (addi_points.positions["x"][i], addi_points.lower["x"][i]) d = (apoints.positions["x"][i], apoints.lower["x"][i]) e = (mpoints.positions["x"][i], mpoints.lower["x"][i]) for k in [b, c, d, e]: self.assertAlmostEqual(a[0], k[0]) self.assertAlmostEqual(a[1], k[1]) def test_negative_consistency_and_above_m(self): ''' Also tests "above m" functions as length 1 no dimension moves ''' for a in [-1, -2, -7, -9]: point = self.comp.get_point(a) points = self.comp.get_points(a, a - 1) self.assertEquals(list(point.indexes), list(points.indexes[0])) for b in ["x", "y", "z"]: self.assertAlmostEqual(point.positions[b], points.positions[b][0]) self.assertAlmostEqual(point.lower[b], points.lower[b][0]) self.assertAlmostEqual(point.upper[b], points.upper[b][0]) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_core/test_excluder.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import Excluder from pkg_resources import require require("mock") from mock import MagicMock class ExcluderTest(unittest.TestCase): def test_init(self): Excluder(["x", "y"]) class SimpleFunctionsTest(unittest.TestCase): def setUp(self): self.e = Excluder(["x", "y"]) def test_create_mask(self): with self.assertRaises(NotImplementedError): self.e.create_mask(MagicMock(), MagicMock()) class SerialisationTest(unittest.TestCase): def setUp(self): self.e = Excluder(["x", "y"]) def test_to_dict(self): expected_dict = dict() expected_dict['axes'] = ["x", "y"] d = self.e.to_dict() self.assertEqual(expected_dict, d) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
scanpointgenerator/core/__init__.py
<reponame>dls-controls/scanpointgenerator ### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from .random import Random from .point import Point, Points from .roi import ROI from .mutator import Mutator from .excluder import Excluder, AExcluderAxes, UExcluderAxes from .generator import Generator, AAxes, AUnits, AAlternate, ASize, UAxes, \ UUnits from .compoundgenerator import CompoundGenerator from .dimension import Dimension
dls-controls/scanpointgenerator
scanpointgenerator/generators/arraygenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence, Any from scanpointgenerator.compat import np from scanpointgenerator.core import Generator, UAxes, UUnits, AAlternate with Anno("The array positions"): APoints = Array[float] UPoints = Union[APoints, Sequence[float]] @Generator.register_subclass( "scanpointgenerator:generator/ArrayGenerator:1.0") class ArrayGenerator(Generator): """Generate points from a given list of positions""" def __init__(self, axes=None, units=None, points=[], alternate=False, **kwargs): # type: (UAxes, UUnits, UPoints, AAlternate, **Any) -> None # Check for 'axis' argument in kwargs for backwards compatibility assert {"axis"}.issuperset(kwargs), \ "Unexpected argument found in kwargs %s" % list(kwargs) axes = kwargs.get('axis', axes) super(ArrayGenerator, self).__init__( axes, units, len(points), alternate) # Validation assert len(self.axes) == len(self.units) == 1, \ "Expected 1D, got axes %s and units %s" % (list(self.axes), list(self.units)) self.points = APoints(points) def prepare_arrays(self, index_array): # Get the actual numpy array from the Array class wrapper points = np.array(self.points.seq) # add linear extension to ends of points, representing t=-1 and t=N+1 v_left = points[0] - (points[1] - points[0]) v_right = points[-1] + (points[-1] - points[-2]) shape = points.shape shape = (shape[0] + 2,) + shape[1:] extended = np.empty(shape, dtype=points.dtype) extended[1:-1] = points extended[0] = v_left extended[-1] = v_right points = extended index_floor = np.floor(index_array).astype(np.int32) epsilon = index_array - index_floor index_floor += 1 values = points[index_floor] + epsilon * \ (points[index_floor+1] - points[index_floor]) return {self.axes[0]: values}
dls-controls/scanpointgenerator
scanpointgenerator/generators/zipgenerator.py
from annotypes import Anno, deserialize_object, Array, Sequence, Union from scanpointgenerator.core import Generator, AAlternate with Anno("List of Generators to zip"): AGenerators = Array[Generator] UGenerators = Union[AGenerators, Sequence[Generator], Generator] @Generator.register_subclass( "scanpointgenerator:generator/ZipGenerator:1.0") class ZipGenerator(Generator): """ Zip generators together, combining all generators into one """ def __init__(self, generators, alternate=False): # type: (UGenerators, AAlternate) -> None self.generators = AGenerators([deserialize_object(g, Generator) for g in generators]) assert len(self.generators), "At least one generator needed" units = [] axes = [] size = self.generators[0].size for generator in self.generators: assert generator.axes not in axes, "You cannot zip generators " \ "on the same axes" assert generator.size == size, "You cannot zip generators " \ "of different sizes" assert not generator.alternate, \ "Alternate should not be set on the component generators of a" \ "zip generator. Set it on the top level ZipGenerator only." axes += generator.axes units += generator.units super(ZipGenerator, self).__init__(axes=axes, size=size, units=units, alternate=alternate) def prepare_arrays(self, index_array): # The ZipGenerator gets its positions from its sub-generators zipped_arrays = {} for generator in self.generators: arrays = generator.prepare_arrays(index_array) zipped_arrays.update(arrays) return zipped_arrays
dls-controls/scanpointgenerator
tests/test_generators/test_arraygenerator.py
<reponame>dls-controls/scanpointgenerator import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import ArrayGenerator class ArrayGeneratorTest(ScanPointGeneratorTest): def test_1d_init(self): g = ArrayGenerator("x", "mm", [0, 1, 2, 3]) self.assertEqual({"x":"mm"}, g.axis_units()) self.assertEqual(["x"], g.axes) def test_array_positions(self): points = [0., 1., 2., 2.5, 3.0, 4.0, 4.5] bounds = [-0.5, 0.5, 1.5, 2.25, 2.75, 3.5, 4.25, 4.75] g = ArrayGenerator("x", "mm", points) g.prepare_positions() g.prepare_bounds() self.assertEqual(points, g.positions["x"].tolist()) self.assertEqual(bounds, g.bounds["x"].tolist()) def test_to_dict(self): points = [0., 0., 1., 2., 0.5, 2.7, 1.3, 4.0] expected = {} expected["typeid"] = "scanpointgenerator:generator/ArrayGenerator:1.0" expected['axes'] = ["x"] expected["units"] = ["cm"] expected["points"] = points expected["alternate"] = True g = ArrayGenerator("x", "cm", points, True) self.assertEqual(expected, g.to_dict()) def test_from_dict(self): points = [0., 0., 1., 2., 0.5, 2.7, 1.3, 4.0] d = {} d["axes"] = ["x"] d["units"] = "cm" d["points"] = points d["alternate"] = True g = ArrayGenerator.from_dict(d) self.assertEqual(["x"], g.axes) self.assertEqual({"x":"cm"}, g.axis_units()) self.assertEqual(points, g.points) self.assertEqual(True, g.alternate) def test_from_dict_backwards_compatible(self): points = [0., 0., 1., 2., 0.5, 2.7, 1.3, 4.0] d = {} d["axis"] = ["x"] d["units"] = "cm" d["points"] = points d["alternate"] = True g = ArrayGenerator.from_dict(d) self.assertEqual(["x"], g.axes) self.assertEqual({"x":"cm"}, g.axis_units()) self.assertEqual(points, g.points) self.assertEqual(True, g.alternate) def test_from_dict_extra_args_asserts(self): points = [0., 0., 1., 2., 0.5, 2.7, 1.3, 4.0] d = {} d["axes"] = ["x"] d["units"] = "cm" d["points"] = points d["alternate"] = True d["extra"] = ["extra_argument"] with self.assertRaises(AssertionError): ArrayGenerator.from_dict(d) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_rois/test_circular_roi.py
<filename>tests/test_rois/test_circular_roi.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.circular_roi import CircularROI from scanpointgenerator.compat import np class InitTest(unittest.TestCase): def test_given_zero_radius_then_error(self): with self.assertRaises(ValueError): CircularROI([0.0, 0.0], 0.0) def test_given_valid_params_then_set(self): x_centre = 1.0 y_centre = 4.0 radius = 5.0 circle = CircularROI([x_centre, y_centre], radius) self.assertEqual(circle.radius, radius) self.assertEqual(circle.centre[0], x_centre) self.assertEqual(circle.centre[1], y_centre) class ContainsPointTest(unittest.TestCase): def setUp(self): self.roi = CircularROI([5.0, 15.0], 5.0) def test_given_valid_point_then_return_True(self): point = [7.0, 11.0] self.assertTrue(self.roi.contains_point(point)) def test_given_point_outside_then_return_False(self): point = [9.0, 11.0] self.assertFalse(self.roi.contains_point(point)) def test_mask_points(self): points = [np.array([7., 9.]), np.array([11., 11.])] points_cp = [axis.copy().tolist() for axis in points] expected = [True, False] mask = self.roi.mask_points(points) self.assertEqual(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in points]) class DictTest(unittest.TestCase): def test_to_dict(self): roi = CircularROI([1.1, 2.2], 3.3) expected = { "typeid":"scanpointgenerator:roi/CircularROI:1.0", "centre":[1.1, 2.2], "radius":3.3} self.assertEquals(expected, roi.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/CircularROI:1.0", "centre":[0, 0.1], "radius":1} roi = CircularROI.from_dict(d) self.assertEqual([0, 0.1], roi.centre) self.assertEqual(1, roi.radius) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
tests/test_core/test_roi.py
<filename>tests/test_core/test_roi.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from scanpointgenerator import ROI from pkg_resources import require require("mock") from mock import Mock class ROITest(unittest.TestCase): def test_to_dict(self): roi = ROI() expected = {} self.assertEqual(expected, roi.to_dict()) if __name__ == "__main__": unittest.main()
dls-controls/scanpointgenerator
scanpointgenerator/rois/elliptical_roi.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from math import cos, sin from scanpointgenerator.core import ROI with Anno("The centre of ellipse"): ACentre = Array[float] UCentre = Union[ACentre, Sequence[float]] with Anno("The semiaxes of ellipse"): ASemiaxes = Array[float] USemiaxes = Union[ASemiaxes, Sequence[float]] with Anno("The angle of the ellipse"): AAngle = float @ROI.register_subclass("scanpointgenerator:roi/EllipticalROI:1.0") class EllipticalROI(ROI): def __init__(self, centre, semiaxes, angle=0): # type: (UCentre, USemiaxes, AAngle) -> None super(EllipticalROI, self).__init__() if semiaxes[0] <= 0.0 or semiaxes[1] <= 0.0: raise ValueError("Ellipse semi-axes must be greater than zero") self.centre = ACentre(centre) self.semiaxes = ASemiaxes(semiaxes) self.angle = AAngle(angle) def contains_point(self, point): # transform point to the rotated ellipse frame x = float(point[0]) - float(self.centre[0]) y = float(point[1]) - float(self.centre[1]) if self.angle != 0: phi = -self.angle tx = x * cos(phi) - y * sin(phi) ty = x * sin(phi) + y * cos(phi) x = tx y = ty rx = float(self.semiaxes[0]) ry = float(self.semiaxes[1]) return (x * x) / (rx * rx) + (y * y) / (ry * ry) <= 1 def mask_points(self, points): x = points[0].copy() x -= self.centre[0] y = points[1].copy() y -= self.centre[1] if self.angle != 0: phi = -self.angle tx = x * cos(phi) - y * sin(phi) ty = x * sin(phi) + y * cos(phi) x = tx y = ty rx2 = self.semiaxes[0] * self.semiaxes[0] ry2 = self.semiaxes[1] * self.semiaxes[1] x *= x x /= rx2 y *= y y /= ry2 x += y return x <= 1
dls-controls/scanpointgenerator
scanpointgenerator/excluders/roiexcluder.py
### # Copyright (c) 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence, deserialize_object from scanpointgenerator.core import Excluder, UExcluderAxes, ROI from scanpointgenerator.compat import np with Anno("List of regions of interest"): ARois = Array[ROI] URois = Union[ARois, Sequence[ROI]] @Excluder.register_subclass("scanpointgenerator:excluder/ROIExcluder:1.0") class ROIExcluder(Excluder): """A class to exclude points outside of regions of interest.""" def __init__(self, rois, axes): # type: (URois, UExcluderAxes) -> None super(ROIExcluder, self).__init__(axes) self.rois = ARois([deserialize_object(r, ROI) for r in rois]) def create_mask(self, *point_arrays): """Create a boolean array specifying the points to exclude. The resulting mask is created from the union of all ROIs. Args: *point_arrays (numpy.array(float)): Array of points for each axis Returns: np.array(int8): Array of points to exclude """ l = len(point_arrays[0]) for arr in point_arrays: if len(arr) != l: raise ValueError("Points lengths must be equal") mask = np.zeros_like(point_arrays[0], dtype=np.int8) for roi in self.rois: # Accumulate all True entries # Points outside of all ROIs will be excluded mask |= roi.mask_points(point_arrays) return mask
dls-controls/scanpointgenerator
scanpointgenerator/rois/polygonal_roi.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.core import ROI from scanpointgenerator.compat import np with Anno("x positions for polygon vertices"): APointsX = Array[float] UPointsX = Union[APointsX, Sequence[float]] with Anno("y positions for polygon vertices"): APointsY = Array[float] UPointsY = Union[APointsY, Sequence[float]] @ROI.register_subclass("scanpointgenerator:roi/PolygonalROI:1.0") class PolygonalROI(ROI): def __init__(self, points_x, points_y): # type: (UPointsX, UPointsY) -> None super(PolygonalROI, self).__init__() if len(points_x) != len(points_y): raise ValueError("Point arrays must be the same size") if len(points_x) < 3: raise ValueError("Polygon requires at least 3 vertices") # TODO: check points are not all collinear # (i.e. describe at least a triangle) self.points_x = APointsX(points_x) self.points_y = APointsY(points_y) def contains_point(self, point): # Uses ray-casting algorithm - "fails" for complex (self-intersecting) # polygons, but this is intended behaviour for the moment # Haines 1994 inside = False x = point[0] y = point[1] v1x, v1y = self.points_x[-1], self.points_y[-1] for v2x, v2y in zip(self.points_x, self.points_y): if (v1y <= y and v2y > y) or (v1y > y and v2y <= y): t = float(y - v1y) / float(v2y - v1y) if x < v1x + t * (v2x - v1x): inside = not inside v1x, v1y = v2x, v2y return inside def mask_points(self, points): x = points[0] y = points[1] v1x, v1y = self.points_x[-1], self.points_y[-1] mask = np.full(len(x), False, dtype=np.int8) for v2x, v2y in zip(self.points_x, self.points_y): # skip horizontal edges if (v2y != v1y): vmask = np.full(len(x), False, dtype=np.int8) vmask |= ((y < v2y) & (y >= v1y)) vmask |= ((y < v1y) & (y >= v2y)) t = (y - v1y) / (v2y - v1y) vmask &= x < v1x + t * (v2x - v1x) mask ^= vmask v1x, v1y = v2x, v2y return mask
dls-controls/scanpointgenerator
scanpointgenerator/rois/sector_roi.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from math import hypot, atan2, pi from scanpointgenerator.core import ROI from scanpointgenerator.compat import np with Anno("The centre of sector"): ACentre = Array[float] UCentre = Union[ACentre, Sequence[float]] with Anno("The radii of sector"): ARadii = Array[float] URadii = Union[ARadii, Sequence[float]] with Anno("The angles of sector"): AAngles = Array[float] UAngles = Union[AAngles, Sequence[float]] @ROI.register_subclass("scanpointgenerator:roi/SectorROI:1.0") class SectorROI(ROI): def __init__(self, centre, radii, angles): # type: (UCentre, URadii, UAngles) -> None super(SectorROI, self).__init__() if radii[0] < 0 or radii[1] < radii[0] or radii[1] <= 0.0: raise ValueError("Sector size is invalid") self.centre = ACentre(centre) self.radii = ARadii(radii) self.angles = AAngles(self.constrain_angles(angles)) def constrain_angles(self, angles): # constrain angles such that angles[0] < angles[1], # angles[0] in [0, 2pi), and angles[1] <= angles[0] + 2pi a1 = angles[0] a2 = angles[1] if a2 < a1: a2 += 2 * pi if a2 < a1: # input describes the full circle return [0, 2*pi] # a1 <= a2 diff = a2 - a1 if diff >= 2*pi: return [0, 2*pi] a1 = (a1 + 2*pi) % (2*pi) return [a1, a1+diff] def contains_point(self, point): angles = self.constrain_angles(self.angles) # get polar form (r, phi) x = point[0] - self.centre[0] y = point[1] - self.centre[1] r = hypot(x, y) phi = atan2(y, x) phi = (2*pi + phi) % (2*pi) if r < self.radii[0] or r > self.radii[1]: return False sweep = angles[1] - angles[0] # angle along starting at angles[0] theta = (phi - angles[0] + 2*pi) % (2*pi) return theta <= sweep def mask_points(self, points): x = points[0].copy() y = points[1].copy() x -= self.centre[0] y -= self.centre[1] r2 = (np.square(x) + np.square(y)) phi_0, phi_1 = self.constrain_angles(self.angles) # phi_0 <= phi_1, phi_0 in [0, 2pi), phi_1 < 4pi phi_x = np.arctan2(y, x) # translate phi_x to range [0, 2pi] phi_x = (2*pi + phi_x) % (2*pi) # define phi_s and phi_x "offset from phi_0" phi_s = phi_1 - phi_0 phi_x -= phi_0 + 2*pi phi_x %= 2*pi mask = np.full(len(x), 1, dtype=np.int8) mask &= r2 <= self.radii[1] mask &= r2 >= self.radii[0] mask &= (phi_x <= phi_s) return mask
dls-controls/scanpointgenerator
scanpointgenerator/generators/staticpointgenerator.py
### # Copyright (c) 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### import numpy as np from scanpointgenerator.core import Generator, ASize, UAxes, AAxes @Generator.register_subclass( "scanpointgenerator:generator/StaticPointGenerator:1.0") class StaticPointGenerator(Generator): """Generate 'empty' points with optional axis information""" def __init__(self, size, axes=[]): # type: (ASize, UAxes) -> None axis = AAxes(axes) # Validate assert len(axis) <= 1, \ "Expected 1D or no axes, got axes %s" % ( list(axis)) super(StaticPointGenerator, self).__init__(axes=axis, units=[""] * len(axis), size=size) def prepare_arrays(self, index_array): arrays = {} # If there is an axis in self.axes, produce a 1-indexed array for it for axis in self.axes: arrays[axis] = np.arange(1, len(index_array)+1) return arrays
dls-controls/scanpointgenerator
scanpointgenerator/generators/spiralgenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### import math as m from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.compat import np from scanpointgenerator.core import Generator, UAxes, UUnits, AAlternate with Anno("The centre of the lissajous curve"): ACentre = Array[float] UCentre = Union[ACentre, Sequence[float]] with Anno("Maximum radius of spiral"): ARadius = float with Anno("Gap between spiral arcs; " "higher scale gives fewer points for same radius"): AScale = float @Generator.register_subclass("scanpointgenerator:generator/SpiralGenerator:1.0") class SpiralGenerator(Generator): """Generate the points of an Archimedean spiral""" def __init__(self, axes, units, centre, radius, scale=1.0, alternate=False): # type: (UAxes, UUnits, UCentre, ARadius, AScale, AAlternate) -> None self.centre = ACentre(centre) self.radius = ARadius(radius) self.scale = AScale(scale) # Validate assert len(self.centre) == len(axes) == 2, \ "Expected centre %s and axes %s to be 2 dimensional" % ( list(self.centre), list(axes)) # spiral equation : r = b * phi # scale = 2 * pi * b # parameterise phi with approximation: # phi(t) = k * sqrt(t) (for some k) # number of possible t is solved by sqrt(t) = max_r / b*k self.alpha = m.sqrt(4 * m.pi) # Theta scale factor = k self.beta = scale / (2 * m.pi) # Radius scale factor = b size = int((self.radius / (self.alpha * self.beta)) ** 2) + 1 super(SpiralGenerator, self).__init__(axes, units, size, alternate) def prepare_arrays(self, index_array): # parameterise phi with approximation: # phi(t) = k * sqrt(t) (for some k) phi = self.alpha * np.sqrt(index_array + 0.5) arrays = { self.axes[0]: self.centre[0] + self.beta * phi * np.sin(phi), self.axes[1]: self.centre[1] + self.beta * phi * np.cos(phi) } return arrays
dls-controls/scanpointgenerator
scanpointgenerator/core/generator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Serializable, Anno, Array, Sequence, Union, TYPE_CHECKING from scanpointgenerator.compat import np if TYPE_CHECKING: from typing import Dict with Anno("List of scannable names contributed to each Point"): AAxes = Array[str] UAxes = Union[AAxes, Sequence[str], str] with Anno("The units that the scannables are demanded in"): AUnits = Array[str] UUnits = Union[AUnits, Sequence[str], str] with Anno("The number of Points that this generator will produce"): ASize = int with Anno("Whether to reverse on each alternate run of the generator"): AAlternate = bool class Generator(Serializable): """Base class for all malcolm scan point generators""" def __init__(self, axes, units, size, alternate=False): # type: (UAxes, UUnits, ASize, AAlternate) -> None self.axes = AAxes(axes) assert len(self.axes) == len(set(self.axes)), \ "Axis names cannot be duplicated; given %s" % list(self.axes) self.units = AUnits(units) # If only one set of units given, use those for all axes if len(self.units) == 1: self.units = AUnits(self.units.seq * len(self.axes)) assert len(self.axes) == len(self.units), \ "Units array %s length != axes array %s length" % ( list(self.units), list(self.axes)) self.size = ASize(size) assert self.size > 0, "Expected size > 0, got size = %d" % self.size self.alternate = AAlternate(alternate) # These will be filled in by prepare_* self.positions = None self.bounds = None def axis_units(self): # type: () -> Dict[str, float] """Return the units for each axis in a dict""" return dict(zip(self.axes, self.units)) def prepare_arrays(self, index_array): # type: (np.array) -> Dict[str, np.array] """ Abstract method to create position or bounds array from provided index array. index_array will be np.arange(self.size) for positions and np.arange(self.size + 1) - 0.5 for bounds. Args: index_array (np.array): Index array to produce parameterised points Returns: Positions: Dictionary of axis names to position/bounds arrays """ raise NotImplementedError def prepare_positions(self): self.positions = self.prepare_arrays(np.arange(self.size)) def prepare_bounds(self): self.bounds = self.prepare_arrays(np.arange(self.size + 1) - 0.5)
dls-controls/scanpointgenerator
scanpointgenerator/generators/concatgenerator.py
<reponame>dls-controls/scanpointgenerator<filename>scanpointgenerator/generators/concatgenerator.py<gh_stars>1-10 from annotypes import Anno, deserialize_object, Array from scanpointgenerator.compat import np from scanpointgenerator.core import Generator, AAlternate with Anno("The array containing points"): AGenerator = Array[Generator] @Generator.register_subclass( "scanpointgenerator:generator/ConcatGenerator:1.0") class ConcatGenerator(Generator): """ Concat generators to operate one after each other """ DIFF_LIMIT = 1e-05 def __init__(self, generators, alternate=False): # type: (AGenerator, AAlternate) -> None self.generators = AGenerator([deserialize_object(g, Generator) for g in generators]) assert len(self.generators) > 0, "At least one generator needed" units = self.generators[0].units axes = self.generators[0].axes size = sum(generator.size for generator in self.generators) for generator in self.generators: assert generator.axes == axes, "You cannot Concat generators " \ "on different axes" assert generator.units == units, "You cannot Concat " \ "generators with different units" assert not generator.alternate, \ "Alternate should not be set on the component generators of a" \ "ConcatGenerator. Set it on the top level ConcatGenerator only." super(ConcatGenerator, self).__init__(axes=axes, size=size, units=units, alternate=alternate) def prepare_arrays(self, index_array): # The ConcatGenerator gets its positions from its sub-generators merged_arrays = {} for axis in self.axes: merged_arrays[axis] = np.array first = True if index_array.size == self.size + 1: # getting bounds preparing_bounds = True else: # getting positions preparing_bounds = False for generator in self.generators: if preparing_bounds: # getting bounds arr = generator.prepare_arrays(index_array[:generator.size + 1]) else: # getting positions arr = generator.prepare_arrays(index_array[:generator.size]) for axis in self.axes: axis_array = arr[axis] if first: merged_arrays[axis] = axis_array else: # This avoids appending an ndarray to a list cur_array = merged_arrays[axis] if preparing_bounds: assert np.abs(cur_array[-1] - axis_array[0]) < self.DIFF_LIMIT, \ "Merged generator bounds don't meet" \ " for axis %s (%f, %f)" \ % (str(axis), cur_array[-1], axis_array[0]) cur_array = np.append(cur_array[:-1], axis_array) else: cur_array = np.append(cur_array, axis_array) merged_arrays[axis] = cur_array first = False return merged_arrays
dls-controls/scanpointgenerator
tests/test_rois/test_polygonal_roi.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator.rois.polygonal_roi import PolygonalROI from scanpointgenerator.compat import np class PolygonalROITests(unittest.TestCase): def test_init(self): roi = PolygonalROI([0, 0, 1], [0, 1, 0]) self.assertEquals([0, 0, 1], roi.points_x) self.assertEquals([0, 1, 0], roi.points_y) def test_init_raises_on_few_points(self): with self.assertRaises(ValueError): roi = PolygonalROI([0, 0], [1, 1]) def test_to_dict(self): roi = PolygonalROI([0, 1, 1], [0, 1, 0]) expected = { "typeid":"scanpointgenerator:roi/PolygonalROI:1.0", "points_x":[0, 1, 1], "points_y":[0, 1, 0]} self.assertEquals(expected, roi.to_dict()) def test_from_dict(self): d = { "typeid":"scanpointgenerator:roi/PolygonalROI:1.0", "points_x":[1, 1, 0], "points_y":[2, 3, 5]} roi = PolygonalROI.from_dict(d) self.assertEquals([1, 1, 0], roi.points_x) self.assertEquals([2, 3, 5], roi.points_y) def test_simple_point_contains(self): vertices_x = [0, 1, 2, 2, -1, -1] vertices_y = [0, 0, -1, 1, 1, -1] """ Shape described looks like this: _____ | _ | |/ \| """ roi = PolygonalROI(vertices_x, vertices_y) p = [-0.9, -0.85] self.assertTrue(roi.contains_point(p)) p = [1.9, 0.85] self.assertTrue(roi.contains_point(p)) p = [0.5, -0.5] self.assertFalse(roi.contains_point(p)) p = [0.5, 0.5] self.assertTrue(roi.contains_point(p)) def test_complex_point_contains(self): vertices_x = [0, 0, 2, 2, 1, 1, 3, 3] vertices_y = [0, 2, 2, 1, 1, 3, 3, 0] roi = PolygonalROI(vertices_x, vertices_y) p = [0.5, 0.5] self.assertTrue(roi.contains_point(p)) p = [0.5, 2.5] self.assertFalse(roi.contains_point(p)) # The inner square should be "outside" according to the # ray-cast algorithm, even if traditionally considered "inside" p = [1.5, 1.5] # has winding number -2 self.assertFalse(roi.contains_point(p)) def test_simple_point_contains(self): vertices_x = [0, 1, 2, 2, -1, -1] vertices_y = [0, 0, -1, 1, 1, -1] roi = PolygonalROI(vertices_x, vertices_y) px = [-0.9, 1.9, 0.5, 0.5, 2.2, -1.1] py = [-0.85, 0.85, -0.5, 0.5, 0.5, 0.5] p = [np.array(px), np.array(py)] expected = [True, True, False, True, False, False] mask = roi.mask_points(p) self.assertEquals(expected, mask.tolist()) def test_complex_mask_points(self): vertices_x = [0, 0, 2, 2, 1, 1, 3, 3] vertices_y = [0, 2, 2, 1, 1, 3, 3, 0] roi = PolygonalROI(vertices_x, vertices_y) px = [0.5, 0.5, 1.5, 1.5, 2.5, 2.5, 3.5, -0.5, 3.5, 2, 3, 0] py = [0.5, 2.5, 1.5, 2.5, 2.5, -0.5, 1.5, 0.5, 0.5, 0, 2, 1.5] p = [np.array(px), np.array(py)] points_cp = [axis.copy().tolist() for axis in p] expected = [True, False, False, True, True, False, False, False, False, True, False, True] mask = roi.mask_points(p) self.assertEquals(expected, mask.tolist()) self.assertEqual(points_cp, [axis.tolist() for axis in p]) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
scanpointgenerator/rois/point_roi.py
### # Copyright (c) 2016 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.core import ROI with Anno("The point"): APoint = Array[float] UPoint = Union[APoint, Sequence[float]] @ROI.register_subclass("scanpointgenerator:roi/PointROI:1.0") class PointROI(ROI): def __init__(self, point): # type: (UPoint) -> None super(PointROI, self).__init__() self.point = APoint(point) def contains_point(self, point, epsilon=0): if epsilon == 0: return list(self.point) == list(point) x = point[0] - self.point[0] y = point[1] - self.point[1] return x * x + y * y <= epsilon * epsilon def mask_points(self, points, epsilon=0): x = points[0].copy() x -= self.point[0] y = points[1].copy() y -= self.point[1] x *= x y *= y x += y return x <= epsilon * epsilon
dls-controls/scanpointgenerator
scanpointgenerator/generators/linegenerator.py
### # Copyright (c) 2016, 2017 Diamond Light Source Ltd. # # Contributors: # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # <NAME> - initial API and implementation and/or initial documentation # ### from annotypes import Anno, Union, Array, Sequence from scanpointgenerator.core import Generator, UAxes, UUnits, ASize, AAlternate with Anno("The first position to be generated. e.g. 1.0 or [1.0, 2.0]"): AStart = Array[float] UStart = Union[AStart, Sequence[float], float] with Anno("The final position to be generated. e.g. 5.0 or [5.0, 10.0]"): AStop = Array[float] UStop = Union[AStop, Sequence[float], float] @Generator.register_subclass( "scanpointgenerator:generator/LineGenerator:1.0") class LineGenerator(Generator): """Generate a line of equally spaced N-dimensional points""" def __init__(self, axes, units, start, stop, size, alternate=False): # type: (UAxes, UUnits, UStart, UStop, ASize, AAlternate) -> None super(LineGenerator, self).__init__(axes, units, size, alternate) self.start = AStart(start) self.stop = AStop(stop) # Validate if len(self.axes) != len(self.start) or \ len(self.axes) != len(self.stop): raise ValueError( "Dimensions of axes, start and stop do not match") def prepare_arrays(self, index_array): arrays = {} for axis, start, stop in zip(self.axes, self.start, self.stop): step = float(stop - start) # if self.size == 1 then single point case if self.size > 1: step /= (self.size - 1) else: # Single point, use midpoint as start. Bounds are start and stop start = float(start + stop) / 2.0 arrays[axis] = index_array * step + start return arrays
dls-controls/scanpointgenerator
scanpointgenerator/excluders/squashingexcluder.py
<reponame>dls-controls/scanpointgenerator ### # Copyright (c) 2019 Diamond Light Source Ltd. # # Contributors: # <NAME> - Initial implementation # ### from scanpointgenerator.core import Excluder, UExcluderAxes from scanpointgenerator.compat import np @Excluder.register_subclass("scanpointgenerator:excluder/SquashingExcluder:1.0") class SquashingExcluder(Excluder): """A class that allows every point through. Used to squash generators""" def __init__(self, axes): # type: (UExcluderAxes) -> None super(SquashingExcluder, self).__init__(axes) def create_mask(self, *point_arrays): """Create a boolean array specifying the points to exclude. All points are included, none are excluded for this excluder. Args: *point_arrays (numpy.array(float)): Array of points for each axis Returns: np.array(int8): Array of points to exclude """ length = len(point_arrays[0]) for arr in point_arrays: if len(arr) != length: raise ValueError("Points lengths must be equal") mask = np.ones_like(point_arrays[0], dtype=np.int8) return mask
dls-controls/scanpointgenerator
tests/test_generators/test_staticpointgenerator.py
<filename>tests/test_generators/test_staticpointgenerator.py import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest from test_util import ScanPointGeneratorTest from scanpointgenerator import StaticPointGenerator class StaticPointGeneratorTest(ScanPointGeneratorTest): def test_init(self): g = StaticPointGenerator(7) self.assertEqual([], g.units) self.assertEqual([], g.axes) self.assertEqual(7, g.size) def test_array_positions(self): g = StaticPointGenerator(5) g.prepare_positions() g.prepare_bounds() self.assertEqual({}, g.positions) self.assertEqual({}, g.bounds) def test_array_positions_with_axis(self): g = StaticPointGenerator(5, 'repeats') positions = [1, 2, 3, 4, 5] bounds = [1, 2, 3, 4, 5, 6] g.prepare_positions() g.prepare_bounds() self.assertEqual(positions, g.positions['repeats'].tolist()) self.assertEqual(bounds, g.bounds['repeats'].tolist()) def test_to_dict(self): g = StaticPointGenerator(7) expected_dict = { "typeid":"scanpointgenerator:generator/StaticPointGenerator:1.0", "size": 7, "axes": [], } self.assertEqual(expected_dict, g.to_dict()) def test_to_dict_with_axis(self): g = StaticPointGenerator(7, 'repeats') expected_dict = { "typeid":"scanpointgenerator:generator/StaticPointGenerator:1.0", "size": 7, "axes": ['repeats'], } self.assertEqual(expected_dict, g.to_dict()) def test_from_dict(self): d = {"size":6} g = StaticPointGenerator.from_dict(d) self.assertEqual(6, g.size) self.assertEqual([], g.axes) self.assertEqual([], g.units) if __name__ == "__main__": unittest.main(verbosity=2)
dls-controls/scanpointgenerator
tests/test_core/test_compoundgenerator_performance.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import unittest import time from test_util import ScanPointGeneratorTest from scanpointgenerator import CompoundGenerator from scanpointgenerator import LineGenerator from scanpointgenerator import SpiralGenerator from scanpointgenerator import ROIExcluder from scanpointgenerator.rois import CircularROI from scanpointgenerator.mutators import RandomOffsetMutator # Test 20 million points on Jython (Travis runs out of memory at 200 million) ZSIZE = 10 if os.name == "java" else 100 # Normally this should take CPython ~5 seconds on a reasonable machine for # for 200 million points, but Travis VMs are sometimes quite weak. # Jython gets less time because it's doing fewer points (but around 3 times slower) TIMELIMIT = 8 if os.name == "java" else 16 class CompoundGeneratorPerformanceTest(ScanPointGeneratorTest): @unittest.skip("Unsuitable") def test_200_million_time_constraint(self): start_time = time.time() s = SpiralGenerator( ["x", "y"], "mm", [0, 0], 6, 0.02, True) # ~2e5 points z = LineGenerator("z", "mm", 0, 1, ZSIZE, True) #1e2 points or 1e1 for Jython w = LineGenerator("w", "mm", 0, 1, 10, True) #1e1 points r1 = CircularROI([-0.7, 4], 0.5) r2 = CircularROI([0.5, 0.5], 0.3) r3 = CircularROI([0.2, 4], 0.5) e1 = ROIExcluder([r1], ["x", "y"]) e2 = ROIExcluder([r2], ["w", "z"]) e3 = ROIExcluder([r3], ["z", "y"]) om = RandomOffsetMutator(0, ["x", "y"], [0.2, 0.2]) g = CompoundGenerator([w, z, s], [e1, e3, e2], [om]) g.prepare() # g.size ~3e5 end_time = time.time() # if this test becomes problematic then we'll just have to remove it self.assertLess(end_time - start_time, TIMELIMIT) # we dont care about this right now #start_time = time.time() #for p in g.iterator(): # pass #end_time = time.time() ## point objects are quite expensive to create #self.assertLess(end_time - start_time, 20) if __name__ == "__main__": unittest.main(verbosity=2)
surajmane/Movie_reviews
reviews_import.py
#Keep adding the required imports below from bs4 import BeautifulSoup import urllib import urllib.request import re import sys from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import string import numpy as np import pandas as pd import cufflinks as cf import chart_studio.plotly as py import chart_studio.tools as tls import plotly.graph_objects as go import plotly.express as ex from nltk.probability import FreqDist import matplotlib as plt import argparse from selenium import webdriver from selenium.webdriver.common.keys import Keys
surajmane/Movie_reviews
reviews.py
<reponame>surajmane/Movie_reviews from reviews_import import * """Get the movie about info and the average movie ratings from Rottentomatoes given the movie name Args: url(str) = The name of the movie you'd like the review of returns: A small about info of the movie and the average rating from Rottentomatoes """ def webscraper(): movie_name = sys.argv[1] url = "https://www.rottentomatoes.com" + "/m/" + movie_name print(url) with urllib.request.urlopen(url) as response: html = response.read() soup = BeautifulSoup(html, features='html.parser') # text = soup.get_text() # print(text) tags = soup.find(id="score-details-json") val = str(tags.contents) print('What the movie is about') print(soup.find("meta", {"name":"description"})['content']) # soup_val = BeautifulSoup(val, features='html.parser') val_tknz = word_tokenize(val) #print(val_tknz) rating = val_tknz.index('averageRating') rating_index = rating+4 print(val_tknz[rating], "=", val_tknz[rating_index]) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Word Frequency generator') parser.add_argument('URL', type=str, help='The URL to fetch the word densities from') args = parser.parse_args() info = webscraper()
fruser/video_analysis
video_analysis.py
import argparse import boto3 def extractTextRekognition(source, destination, object_name): client = boto3.client('rekognition') response = client.detect_text(Image={'S3Object': {'Bucket': source, 'Name': object_name}}) text_detection = response['TextDetections'] print(response) print('Detected text') for text in text_detection: print('Detected text: ' + text['DetectedText']) print('Confidence: ' + "{:.2f}".format(text['Confidence']) + "%") print('Id: {}'.format(text['Id'])) if 'ParentId' in text: print('Parent Id: {}'.format(text['ParentId'])) print('Type:' + text['Type']) def main(): a = argparse.ArgumentParser() a.add_argument('--source', required=True, help='S3 bucket containing source image files') a.add_argument('--dest', required=True, help='Destination path for Rekognition result') a.add_argument('--object', required=True, help='Name of the object in S3 bucket that requires text extraction') args = a.parse_args() print(args) extractTextRekognition(args.source, args.dest, args.object) if __name__ == '__main__': main()
fruser/video_analysis
video_split.py
import argparse import cv2 import boto3 import os def extract_image(source, destination, step): count = 0 vidcap = cv2.VideoCapture(source) success, image = vidcap.read() while success: vidcap.set(cv2.CAP_PROP_POS_MSEC, (count * step * 1000)) cv2.imwrite(destination + "/frame%d.jpg" % count, image) success, image = vidcap.read() print('Read a new frame: ', success) count = count + 1 def s3_upload(bucket, source): s3 = boto3.client('s3') bucket_name = bucket for file in os.listdir(source): if file.endswith(".jpg"): print(os.path.join(source, file)) s3.upload_file(os.path.join(source, file), bucket_name, file) def main(): a = argparse.ArgumentParser() a.add_argument('--source', required=True, help='Path to the video source file') a.add_argument('--dest', required=True, help='Destination path for images') a.add_argument('--s3_bucket', required=True, help='Destination S3 bucket') a.add_argument('--step', default=1, help='Step to use in seconds when converting to JPEG. Default is 1 second') args = a.parse_args() print(args) extract_image(args.source, args.dest, args.step) s3_upload(args.s3_bucket, args.dest) if __name__ == '__main__': main()
dpttw/model_calibration
mc.py
<reponame>dpttw/model_calibration # -*- coding: utf-8 -*- import os import time import numpy as np import ctypes import numpy as np import matplotlib.pyplot as plt import matplotlib.colorbar as clb import matplotlib.patches as mpatches import matplotlib.lines as mlines # ++++ Fortran function for plastic deformation ++++ import irreverisble def plotSingle2D(comp,xtitle,ytitle,xscale,yscale): exp = [] # ***** target exp = np.loadtxt('ref/850-30.dat') fig, ax = plt.subplots(figsize=(12, 9)) ax.plot(comp[:,0],comp[:,1],lw=3) ax.scatter(exp[:,0]*100, exp[:,1],s=100,zorder=5) ax.set_xlabel(xtitle, fontsize=35, labelpad=15) ax.set_ylabel(ytitle, fontsize=35, labelpad=15) ax.tick_params(axis='x', labelsize=25, pad = 10) ax.tick_params(axis='y', labelsize=25, pad = 10) ax.set_xscale(xscale, nonposx='clip') ax.set_yscale(yscale, nonposx='clip') ax.grid(True) fig.tight_layout() plt.show() # --------------- material properties T_service = 1123 prec_stress = 50 SS_stress = 400 # -------------- number samples, =1 in this case no_samples = 1 # ============================== objective # optimize these two parameters (model_parameters) # to minimize the error between [exp] and [stress_strain] # ============================== model_parameters = (-180, 3.077) # the function, irreverisble.mechanics, is used to calculate the stress-strain curve in plastic deforamtion region # the outputs are 2D list (stress-strain, stress_strain) and 1 parameter (work to necking, WTN) stress_strain, WTN = irreverisble.mechanics(prec_stress,SS_stress,T_service,model_parameters,no_samples) stress_strain = np.array(np.trim_zeros(stress_strain)).reshape(-1,2) plotSingle2D(stress_strain,'strain','stress','linear','linear')
lordent/hasoffers-api
hasoffers_api/api.py
import aiohttp import ujson import asyncio from multidimensional_urlencode import urlencode class ApiError(Exception): pass class InvalidAuthorization(ApiError): pass class MissingRequiredArgument(ApiError): pass class APIUsageExceededRateLimit(ApiError): pass class FailedToHydrateRows(ApiError): pass class NetworkTokenIsNotAuthenticated(ApiError): pass class IPIsNotWhiteListed(ApiError): pass ERRORS = { 'Invalid Authorization': InvalidAuthorization, 'Missing required argument': MissingRequiredArgument, 'API usage exceeded rate limit': APIUsageExceededRateLimit, 'Failed to hydrate rows': FailedToHydrateRows, 'is not authenticated': NetworkTokenIsNotAuthenticated, 'is not white-listed': IPIsNotWhiteListed, } class ApiRequest: def __init__(self, url, params, proxy=None, auto_retry=False): self.url = url self.params = params or dict() self.auto_retry = auto_retry self.proxy = proxy def __await__(self): return self.api_call(self.url + urlencode(self.params)).__await__() async def __aiter__(self): if 'limit' in self.params: self.params.update(page=0) result = await self yield result['data'] for page in range(1, result['pageCount']): self.params.update(page=page) yield (await self)['data'] else: yield await self async def api_call(self, url): async with aiohttp.ClientSession() as session: async with session.get(url, proxy=self.proxy) as response: result = ujson.loads(await response.read()) if 'response' in result: if result['response']['errorMessage']: for error_type, error_class in ERRORS.items(): if error_type in result['response']['errorMessage']: if error_class is APIUsageExceededRateLimit \ and self.auto_retry: await asyncio.sleep(1) return await self raise error_class(result['response']['errorMessage']) raise ApiError(result['response']['errorMessage']) return result['response']['data'] return result class ApiMethod: def __init__(self, api_controller, name): self.api_controller = api_controller self.name = name def __call__(self, params=None, auto_retry=False): url = 'https://%s/Apiv3/json?' % '%s.api.hasoffers.com' % self.api_controller.api.network params = dict( NetworkToken=self.api_controller.api.apikey, Target=self.api_controller.name, Method=self.name, **(params or dict()) ) return ApiRequest(url, params, proxy=self.api_controller.api.proxy, auto_retry=auto_retry) class ApiController: def __init__(self, api, name): self.api = api self.name = name def __getattr__(self, api_method_name): return ApiMethod(self, api_method_name) class Api: """Async HasOffers Network API driver https://developers.tune.com/network/ Usage examples: - request collection of objects async for results in api.Offer.findAll({ 'filters': { 'status': 'active', }, 'contain': [ 'Goal', 'Country', ], 'limit': 100, # Set `limit` value for paging results }, auto_retry=True): # Use `auto_retry` for continue on API usage limit for res in results.values(): print(res['Offer']['name']) if res['Goal']: print(len(res['Goal'])) - request one object or call method affiliate = await api.Affiliate.findById({'id': 1}) """ def __init__(self, network, apikey, proxy=None): self.network = network self.apikey = apikey self.proxy = proxy def __getattr__(self, api_controller_name): return ApiController(self, api_controller_name)
lordent/hasoffers-api
hasoffers_api/tests/test.py
<filename>hasoffers_api/tests/test.py import pytest from aiohttp import web from hasoffers_api.api import Api, ApiController, ApiMethod, \ ApiRequest, APIUsageExceededRateLimit pytest_plugins = 'aiohttp.pytest_plugin' async def test_api_builder(): network = 'test_network' apikey = 'test_apikey' controller_name = 'test_controller' method_name = 'method_name' builder = Api(network=network, apikey=apikey) controller = getattr(builder, controller_name) assert isinstance(controller, ApiController) is True method = getattr(controller, method_name) assert isinstance(method, ApiMethod) is True payload = { 'filters': { 'id': 1, }, } request = method(payload) assert isinstance(request, ApiRequest) is True assert network in request.url assert request.params == dict( NetworkToken=apikey, Target=controller_name, Method=method_name, **payload, ) async def done_handler(request): return web.json_response({ 'response': { 'data': 'Done', 'errorMessage': '', }, }) async def usagelimit_handler(request): return web.json_response({ 'response': { 'data': '', 'errorMessage': 'API usage exceeded rate limit:', }, }) async def paging_handler(request): return web.json_response({ 'response': { 'data': { 'page': 0, 'pageCount': 10, 'data': [ 'Done', ], }, 'errorMessage': '', }, }) async def test_api_request(loop): builder = Api(network='network', apikey='apikey') request = builder.Controller.Method({}) app = web.Application() app.router.add_route('GET', '/done', done_handler) app.router.add_route('GET', '/usagelimit', usagelimit_handler) app.router.add_route('GET', '/paging', paging_handler) host, port = '127.0.0.1', 8000 server = loop.create_server(app.make_handler(), host, port) loop.create_task(await server) request.url = 'http://{host}:{port}/done?'.format(host=host, port=port) response = await request assert response == 'Done' request.url = 'http://{host}:{port}/usagelimit?'.format(host=host, port=port) with pytest.raises(APIUsageExceededRateLimit): await request request = builder.Controller.Method({ 'limit': 100, }) request.url = 'http://{host}:{port}/paging?'.format(host=host, port=port) pages = 10 async for results in request: pages -= 1 for result in results: assert result == 'Done' assert pages == 0
lordent/hasoffers-api
setup.py
<reponame>lordent/hasoffers-api from setuptools import setup setup( name='hasoffers_api', version='1.0.3', description='Async HasOffers Network API driver', long_description='', author='<NAME>', author_email='<EMAIL>', packages=['hasoffers_api'], url='https://github.com/lordent/hasoffers-api', install_requires=[ 'multidimensional_urlencode', 'aiohttp', 'ujson', ], classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', ] )
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/addapost.py
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ from __future__ import unicode_literals from email.Encoders import encode_base64 from email.MIMENonMultipart import MIMENonMultipart from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from logging import getLogger log = getLogger('addapost') from zope.component import createObject, getMultiAdapter from zExceptions import BadRequest from gs.group.list.store.queries import DuplicateMessageError from gs.group.member.canpost.interfaces import IGSPostingUser from gs.profile.notify.adressee import Addressee from gs.email import send_email from Products.XWFCore.XWFUtils import removePathsFromFilenames def tagProcess(tagsString): # --=mpj17=-- Not the most elegant function, but I did not want to # use the regular-expression library. r = [] if len(tagsString) == 0: return r if ',' in tagsString: r = tagsString.split(',') else: tags = tagsString if (('"' in tags) and (tags.count('"') % 2 == 0)): newTags = '' inQuote = False for c in tags: if (c == '"') and (not inQuote): inQuote = True elif (c == '"') and (inQuote): inQuote = False elif (c == ' ') and inQuote: newTags += '_' else: newTags += c tags = newTags tagsList = tags.split(' ') for tag in tagsList: r.append(tag.replace('_', ' ')) retval = [t.strip() for t in [u for u in r if u != '']] return retval def add_a_post(groupId, siteId, replyToId, topic, message, tags, email, uploadedFiles, context, request): result = { 'error': False, 'message': "Message posted.", 'id': ''} site_root = context.site_root() assert site_root userInfo = createObject('groupserver.LoggedInUser', context) siteObj = getattr(site_root.Content, siteId) groupObj = getattr(siteObj.groups, groupId) messages = getattr(groupObj, 'messages') assert messages listManager = messages.get_xwfMailingListManager() assert listManager groupList = getattr(listManager, groupObj.getId()) assert groupList #audit = WebPostAuditor(groupObj) #audit.info(POST, topic) # Step 1, check if the user can post userPostingInfo = getMultiAdapter((groupObj, userInfo), IGSPostingUser) if not userPostingInfo.canPost: raise 'Forbidden', userPostingInfo.status # --=mpj17-- Bless WebKit. It adds a file, even when no file has # been specified; if the files are empty, do not add the files. uploadedFiles = [f for f in uploadedFiles if f] # Step 2, Create the message # Step 2.1 Body message = message.encode('utf-8') if uploadedFiles: msg = MIMEMultipart() msgBody = MIMEText(message, 'plain', 'utf-8') # As God intended. msg.attach(msgBody) else: msg = MIMEText(message, 'plain', 'utf-8') # Step 2.2 Headers # msg['To'] set below # TODO: Add the user's name. The Header class will be needed # to ensure it is escaped properly. msg['From'] = unicode(Addressee(userInfo, email)).encode('ascii', 'ignore') msg['Subject'] = topic # --=mpj17=-- This does not need encoding. tagsList = tagProcess(tags) tagsString = ', '.join(tagsList) if tagsString: msg['Keywords'] = tagsString if replyToId: msg['In-Reply-To'] = replyToId # msg['Reply-To'] set by the list # Step 2.3 Attachments for f in uploadedFiles: # --=mpj17=-- zope.formlib has already read the data, so we # seek to the beginning to read it all again :) f.seek(0) data = f.read() if data: t = f.headers.getheader('Content-Type', 'application/octet-stream') mimePart = MIMENonMultipart(*t.split('/')) mimePart.set_payload(data) mimePart['Content-Disposition'] = 'attachment' filename = removePathsFromFilenames(f.filename) mimePart.set_param('filename', filename, 'Content-Disposition') encode_base64(mimePart) # Solves a lot of problems. msg.attach(mimePart) # Step 3, check the moderation. # --=mpj17=-- This changes *how* we send the message to the # mailing list. No, really. via_mailserver = False moderatedlist = groupList.get_moderatedUserObjects(ids_only=True) moderated = groupList.getValueFor('moderated') # --=rrw=--if we are moderated _and_ we have a moderatedlist, only # users in the moderated list are moderated if moderated and moderatedlist and (userInfo.id in moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True # --=rrw=-- otherwise if we are moderated, everyone is moderated elif moderated and not(moderatedlist): log.warn('User "%s" posted from web while moderated' % userInfo.id) via_mailserver = True errorM = 'The post was not added to the topic '\ '<code class="topic">%s</code> because a post with the same '\ 'body already exists in the topic.' % topic # Step 4, send the message. for list_id in messages.getProperty('xwf_mailing_list_ids', []): curr_list = listManager.get_list(list_id) msg['To'] = curr_list.getValueFor('mailto') if via_mailserver: # If the message is being moderated, we have to emulate # a post via email so it can go through the moderation # subsystem. mailto = curr_list.getValueFor('mailto') try: send_email(email, mailto, msg.as_string()) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e.encode('ascii', 'ignore')) break result['error'] = True result['message'] = 'Your message has been sent to the '\ 'moderators for approval.' break else: # Send the message directly to the mailing list because # it is not moderated try: request = {'Mail': msg.as_string()} r = groupList.manage_listboxer(request) result['message'] = \ '<a href="/r/topic/%s#post-%s">Message '\ 'posted.</a>' % (r, r) except BadRequest as e: result['error'] = True result['message'] = errorM log.error(e) break except DuplicateMessageError as e: result['error'] = True result['message'] = errorM break if (not r): # --=mpj17=-- This could be lies. result['error'] = True result['message'] = errorM break return result
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/base.py
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ from zope.cachedescriptors.property import Lazy from gs.content.form.base import SiteForm class ListInfoForm(SiteForm): def __init__(self, context, request): SiteForm.__init__(self, context, request) self.map = {} @Lazy def mailingListManager(self): assert self.context retval = self.context.ListManager assert retval return retval def get_siteId_groupId_for_email(self, emailAddr): # TODO: making a nice big cache would be great if emailAddr not in self.map: try: l = self.mailingListManager.get_listFromMailto(emailAddr) except AttributeError: self.map[emailAddr] = (None, None) else: self.map[emailAddr] = (l.getProperty('siteId'), l.getId()) retval = self.map[emailAddr] assert len(retval) == 2 return retval def get_site_id(self, emailAddr): retval = self.get_siteId_groupId_for_email(emailAddr)[0] return retval def get_group_id(self, emailAddr): retval = self.get_siteId_groupId_for_email(emailAddr)[1] return retval
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/adder.py
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ from __future__ import absolute_import, unicode_literals from logging import getLogger log = getLogger('gs.group.messages.add.base.Adder') from zope.cachedescriptors.property import Lazy from Products.XWFMailingListManager.utils import MAIL_PARAMETER_NAME class Adder(object): def __init__(self, context, request, siteId, groupId): assert context, 'No context' self.context = context assert request, 'No request' self.request = request assert siteId, 'No siteId' self.siteId = siteId assert groupId, 'No groupId' self.groupId = groupId @Lazy def list(self): listManager = self.context.ListManager assert hasattr(listManager, self.groupId),\ 'No such list "%s"' % self.groupId retval = listManager.get_list(self.groupId) assert retval return retval def add(self, message): # munge the message into the request. This is priority to remove! self.request.form[MAIL_PARAMETER_NAME] = message retval = self.list.manage_mailboxer(self.request) if not retval: m = 'No post ID returned. This might be normal, or it might '\ 'be a problem if the poster did not exist.' log.warn(m) return retval
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/groupexists.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## from __future__ import unicode_literals, absolute_import from json import dumps as to_json from zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from gs.auth.token import log_auth_error from .base import ListInfoForm from .interfaces import IGSGroupExists class GroupExists(ListInfoForm): label = 'Check if a group exists' pageTemplateFileName = 'browser/templates/groupexists.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) form_fields = form.Fields(IGSGroupExists, render_context=False) def __init__(self, context, request): ListInfoForm.__init__(self, context, request) def get_url_for_site(self, siteId): retval = None if siteId: s = getattr(self.context.Content, siteId) retval = createObject('groupserver.SiteInfo', s).url return retval @form.action(label='Check', failure='handle_check_action_failure') def handle_check(self, action, data): emailAddr = data['email'] siteId = self.get_site_id(emailAddr) d = { 'email': emailAddr, 'siteId': siteId, 'groupId': self.get_group_id(emailAddr), 'siteURL': self.get_url_for_site(siteId), } self.status = 'Done' retval = to_json(d) return retval def handle_check_action_failure(self, action, data, errors): log_auth_error(self.context, self.request, errors) if len(errors) == 1: self.status = '<p>There is an error:</p>' else: self.status = '<p>There are errors:</p>' assert type(self.status) == unicode
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/interfaces.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## from __future__ import unicode_literals from zope.interface.interface import Interface from zope.schema import ASCIILine, Text from gs.auth.token import AuthToken class IGSGroupExists(Interface): # TODO: Create a base email-address type email = ASCIILine(title='Email Address', description='The email address to check', required=True) token = AuthToken(title='Token', description='The authentication token', required=True) class IGSAddEmail(Interface): emailMessage = Text(title='Email Message', description='The email message to add', required=True) groupId = ASCIILine(title='Group Identifier', description='The identifier of the group to add the ' 'message to.', required=True) token = AuthToken(title='Token', description='The authentication token', required=True)
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/addemail.py
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2014, 2015 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ from __future__ import absolute_import, unicode_literals import base64 from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from gs.auth.token import log_auth_error from .adder import Adder from .audit import AddAuditor, ADD_EMAIL from .base import ListInfoForm from .interfaces import IGSAddEmail class AddEmail(ListInfoForm): label = 'Add an email' pageTemplateFileName = 'browser/templates/addemail.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) form_fields = form.Fields(IGSAddEmail, render_context=False) def __init__(self, context, request): super(AddEmail, self).__init__(context, request) @form.action(label='Add', failure='handle_add_action_failure') def handle_add(self, action, data): try: msg = base64.b64decode(data['emailMessage']) except TypeError: # wasn't base64 encoded. Try and proceed anyway! msg = data['emailMessage'] # Audit auditor = AddAuditor(self.context) length = '%d bytes' % len(data['emailMessage']) auditor.info(ADD_EMAIL, length, data['groupId']) # Note the site ID adder = Adder(self.context, self.request, self.siteInfo.id, data['groupId']) adder.add(msg) # Because the text-version of the email message can mess with # the content type self.request.response.setHeader(b'Content-type', b'text/html') self.status = 'Done' def handle_add_action_failure(self, action, data, errors): log_auth_error(self.context, self.request, errors) if len(errors) == 1: self.status = '<p>There is an error:</p>' else: self.status = '<p>There are errors:</p>'
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/audit.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright © 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## from __future__ import unicode_literals from pytz import UTC from datetime import datetime from zope.cachedescriptors.property import Lazy from zope.component import createObject from zope.component.interfaces import IFactory from zope.interface import implements, implementedBy from Products.XWFCore.XWFUtils import munge_date from Products.GSAuditTrail import IAuditEvent, BasicAuditEvent, AuditQuery from Products.GSAuditTrail.utils import event_id_from_data SUBSYSTEM = 'gs.group.messages.add' import logging log = logging.getLogger(SUBSYSTEM) UNKNOWN = '0' # Unknown is always "0" ADD_EMAIL = '1' class AddEmailAuditEventFactory(object): """A Factory for add-email events.""" implements(IFactory) title = 'GroupServer Add-Email Event Factory' description = 'Creates a GroupServer event auditor for add-email events' def __call__(self, context, event_id, code, date, userInfo, instanceUserInfo, siteInfo, groupInfo, instanceDatum='', supplementaryDatum='', subsystem=''): """Create an event""" assert subsystem == SUBSYSTEM, 'Subsystems do not match' if code == ADD_EMAIL: event = AddEvent(context, event_id, date, siteInfo, instanceDatum, supplementaryDatum) else: event = BasicAuditEvent(context, event_id, UNKNOWN, date, userInfo, instanceUserInfo, siteInfo, groupInfo, instanceDatum, supplementaryDatum, SUBSYSTEM) assert event return event def getInterfaces(self): return implementedBy(BasicAuditEvent) class AddEvent(BasicAuditEvent): ''' An audit-trail event representing an email being added to a list.''' implements(IAuditEvent) def __init__(self, context, id, d, siteInfo, instanceDatum, supplementaryDatum): """ Create an event""" BasicAuditEvent.__init__(self, context, id, ADD_EMAIL, d, None, None, siteInfo, None, instanceDatum, supplementaryDatum, SUBSYSTEM) def __unicode__(self): retval = 'Email (%s) added to a list (%s) on %s (%s).' %\ (self.instanceDatum, self.supplementaryDatum, self.siteInfo.name, self.siteInfo.id) return retval def __str__(self): retval = unicode(self).encode('ascii', 'ignore') return retval @property def xhtml(self): cssClass = 'audit-event gs-group-messages-add-base-%s' % self.code retval = '<span class="%s">Added an email (%s) to %s.</span>' % \ (cssClass, self.instanceDaturm, self.supplementaryDatum) retval = '%s (%s)' % \ (retval, munge_date(self.context, self.date)) return retval class AddAuditor(object): """An auditor for adding an email. """ def __init__(self, context): """Create an auditor.""" self.context = context @Lazy def siteInfo(self): retval = createObject('groupserver.SiteInfo', self.context) return retval @Lazy def factory(self): retval = AddEmailAuditEventFactory() return retval @Lazy def queries(self): retval = AuditQuery() return retval def info(self, code, instanceDatum='', supplementaryDatum=''): """Log an info event to the audit trail. * Creates an ID for the new event, * Writes the instantiated event to the audit-table, and * Writes the event to the standard Python log. """ d = datetime.now(UTC) eventId = event_id_from_data(self.siteInfo, self.siteInfo, self.siteInfo, code, instanceDatum, supplementaryDatum + SUBSYSTEM) e = self.factory(self.context, eventId, code, d, None, None, self.siteInfo, None, instanceDatum, supplementaryDatum, SUBSYSTEM) self.queries.store(e) log.info(e) return e
groupserver/gs.group.messages.add.base
gs/group/messages/add/base/__init__.py
<reponame>groupserver/gs.group.messages.add.base<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import absolute_import #lint:disable from .addapost import add_a_post from .base import ListInfoForm #lint:enable
veggiespam/ZocSec.SecurityAsCode.GitHub
GitHub_Inventory_Tool/kyro.py
<gh_stars>1-10 # kyro.py || part of ZocSec.SecurityAsCode.GitHub # # A tool for extracting important informaiton about all repos in an organization. # # Owner: Copyright © 2018-2019 Zocdoc Inc. www.zocdoc.com # Authors: <NAME> @garymalaysia # <NAME> @veggiespam # # from github import Github from github import enable_console_debug_logging from github import GithubException from time import sleep import argparse import datetime import sys from openpyxl import Workbook from openpyxl.utils import get_column_letter from openpyxl import load_workbook from openpyxl.styles import PatternFill, Side, Alignment, Font # Prior running this script do the following # execute "pip3 install -r requirements.txt" if __name__ == "__main__": parser = argparse.ArgumentParser(description='This tool allow user to audit Enterprise Repos.') parser.add_argument("-t", "--token", required=True, help="GitHub User Private Token") parser.add_argument("-a",'--audit',action='store_true',help="Audit github Repo") parser.add_argument("-u",'--update',help="Import Topics to Repo") args = vars(parser.parse_args()) #audit_github(args["token"]) # user token is required count = 0 row = 1 num_of_keys = 1 num_of_topic = 0 human = 0 col = 1 # using an access token user = Github(args["token"]) # use in the tile with month and year month_of_year = datetime.date.today().strftime("%Y-%m-%d") if args["audit"]: # openpyxl at work wb = Workbook() #Creating excel Spreadsheet and initializing title ws = wb.active ws.title = "Github Inventory" filepath = "Github_Audit_"+month_of_year+".xlsx" #Excel spreadsheet name wb.save(filepath) wb=load_workbook(filepath) wb.create_sheet('Repos Deploy keys') # create a second sheet within the same excel spreadsheet deploy_keys_sheet = wb["Repos Deploy keys"] wb.create_sheet('Summary') # create a third sheet within the same excel spreadsheet summary_sheet = wb["Summary"] print ("Gathering all repos.. And apologize for the bootleg progress bar =_=!") # Using authenticated user token to gather all repo from Zocdoc org = user.get_organization("Zocdoc") repos = org.get_repos() for rep in repos: count +=1 # For the bootleg progress bar toolbar_width = count sys.stdout.write("[%s]" % (" " * toolbar_width)) sys.stdout.flush() sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '[' # Coloring for the cell in the excel sheet alignment=Alignment(wrap_text=True) skyFill = PatternFill(start_color='add8e6',end_color='add8e6',fill_type="solid") redFill = PatternFill(start_color='fa8072',end_color='fa8072',fill_type="solid") grassFill = PatternFill(start_color='C1FFC1',end_color='C1FFC1',fill_type="solid") # Writing Columns to first sheet in the excel sheet github_inventory=wb.active github_inventory['a1'] = 'node_id' github_inventory['b1'] = 'Name' github_inventory['c1'] = 'Description' github_inventory['d1'] = 'Archived' github_inventory['e1'] = 'Private' github_inventory['f1'] = 'Languages' github_inventory['g1'] = 'Teams' github_inventory['h1'] = 'Topics' github_inventory['i1'] = 'Topic_add' github_inventory['j1'] = 'Topic_del' github_inventory['k1'] = 'Last Comitter' github_inventory['l1'] = 'Last Comit Date' github_inventory.freeze_panes = 'A2' # Freeze top row github_inventory.column_dimensions['A'].width = 15 # In characters, not pixels github_inventory.column_dimensions['B'].width = 30 # In characters, not pixels github_inventory.column_dimensions['C'].width = 30 # In characters, not pixels github_inventory.column_dimensions['D'].width = 10 # In characters, not pixels github_inventory.column_dimensions['E'].width = 10 # In characters, not pixels github_inventory.column_dimensions['F'].width = 40 # In characters, not pixels github_inventory.column_dimensions['G'].width = 30 # In characters, not pixels github_inventory.column_dimensions['H'].width = 30 # In characters, not pixels github_inventory.column_dimensions['I'].width = 25 # In characters, not pixels github_inventory.column_dimensions['J'].width = 25 # In characters, not pixels github_inventory.column_dimensions['K'].width = 25 # In characters, not pixels github_inventory.column_dimensions['L'].width = 20 # In characters, not pixels # Writing Columns to second sheet in the excel sheet deploy_keys_sheet['a1'] = 'Repository' deploy_keys_sheet['b1'] = 'Deploy Key ID' deploy_keys_sheet.freeze_panes = 'A2' # Freeze top row deploy_keys_sheet.column_dimensions['A'].width = 30 deploy_keys_sheet.column_dimensions['B'].width = 60 # Writing Columns to third sheet in the excel sheet summary_sheet['a1'] = 'Total Repo without Team Topic' summary_sheet['b1'] = 'Percentage' summary_sheet['c1'] = 'Total Repo with last Human Commit' summary_sheet['d1'] = 'Percentage' summary_sheet.freeze_panes = 'A2' # Freeze top row summary_sheet.column_dimensions['A'].width = 25 summary_sheet.column_dimensions['B'].width = 10 summary_sheet.column_dimensions['C'].width = 30 summary_sheet.column_dimensions['D'].width = 10 # Github API is doing work using for loop for repo in user.get_user().get_repos(): row+=1 sys.stdout.write("*") sys.stdout.flush() languages = "" for lang in repo.get_languages(): languages = languages + lang + " " teamlist = "" try: for team in repo.get_teams(): teamlist = teamlist + team.name + "/" + team.permission + " " except: pass topics = "" for topic in repo.get_topics(): topics = topics + " "+ topic # Check to see is the Repo empty. if so, print message to cell try: for commits in repo.get_commits(): if commits.committer : github_inventory['k%d' % row] = commits.committer.login if commits.committer.login.endswith("-zocdoc"): human += 1 break except GithubException as e: github_inventory['k%d' % row] = e.args[1]['message'] # Color the field to light blue id is even row number if row %2 == 0 : github_inventory['a%d' % row].fill = skyFill github_inventory['b%d' % row].fill = skyFill github_inventory['c%d' % row].fill = skyFill github_inventory['d%d' % row].fill = skyFill github_inventory['e%d' % row].fill = skyFill github_inventory['f%d' % row].fill = skyFill github_inventory['g%d' % row].fill = skyFill github_inventory['h%d' % row].fill = skyFill github_inventory['i%d' % row].fill = skyFill github_inventory['j%d' % row].fill = skyFill github_inventory['k%d' % row].fill = skyFill github_inventory['l%d' % row].fill = skyFill # Fetching data with Github API github_inventory['a%d' % row] = repo.id github_inventory['b%d' % row] = repo.name github_inventory['c%d' % row] = repo.description # Highlight archived to green if true if repo.archived == True: github_inventory['d%d' % row].fill = grassFill github_inventory['d%d' % row] = repo.archived else: github_inventory['d%d' % row] = repo.archived # Highlight Private to red if False if repo.private == False: github_inventory['e%d' % row].fill = redFill github_inventory['e%d' % row] = repo.private else: github_inventory['e%d' % row] = repo.private github_inventory['f%d' % row] = languages github_inventory['g%d' % row] = teamlist github_inventory['l%d' % row] = repo.pushed_at # this adds the sort mechanisms to the table. github_inventory.auto_filter.ref = "A:L" github_inventory.auto_filter.add_sort_condition = "A:A" github_inventory.auto_filter.add_sort_condition = "B:B" github_inventory.auto_filter.add_sort_condition = "C:C" github_inventory.auto_filter.add_sort_condition = "D:D" github_inventory.auto_filter.add_sort_condition = "E:E" github_inventory.auto_filter.add_sort_condition = "F:F" github_inventory.auto_filter.add_sort_condition = "G:G" github_inventory.auto_filter.add_sort_condition = "H:H" github_inventory.auto_filter.add_sort_condition = "I:I" github_inventory.auto_filter.add_sort_condition = "J:J" github_inventory.auto_filter.add_sort_condition = "K:K" github_inventory.auto_filter.add_sort_condition = "L:L" # Finding Repo with missing Team Topic if topics.find("team-") > 0: github_inventory['h%d' % row] = topics else: num_of_topic += 1 github_inventory['h%d' % row].fill = redFill github_inventory['h%d' % row] = topics github_inventory['i%d' % row].fill = redFill # Fetching repo deploy keys with Github API try: for key in repo.get_keys(): num_of_keys += 1 deploy_keys_sheet['a%d' % num_of_keys] = repo.full_name deploy_keys_sheet['b%d' % num_of_keys] = str(key) except: num_of_keys = 0 sleep(0.3) # provide some seperation for each Github API call sys.stdout.write("\n") # Boot leg progress bar ending # Calcualting formular to added to the third sheet for all missing team topic repo summary_sheet['a2'] = num_of_topic summary_sheet['b2'] = num_of_topic/count*100 summary_sheet['b2'].fill = redFill summary_sheet['c2'] = human summary_sheet['d2'] = human/count*100 summary_sheet['d2'].fill = skyFill wb.save(filepath) # Saving the excel file # if -u flag is used, execute below script if args["update"]: wb = load_workbook(filename=args["update"],read_only=True) read_github_inventory = wb['Github Inventory'] github_inventory_max_row = read_github_inventory.max_row for columns in range(1,read_github_inventory.max_column+1): # search for column "Topic_add" if read_github_inventory['%s1'% get_column_letter(columns)].value == "Topic_add": for row in range(2,github_inventory_max_row+1): if read_github_inventory['%s%d' % (get_column_letter(columns),row)].value: #if there is a value in the cell of column "Topic_add" topic_add = read_github_inventory['%s%d' % (get_column_letter(columns),row)].value.strip().split(" ") #remove leading and trailing spaces and split each word into a List # search for column "Topics" while read_github_inventory['%s1'% get_column_letter(col)].value != "Topics": col += 1 #iterate from column 1 on to look for "Topics" else: # if "Topics" is found, do next if read_github_inventory['%s%d' % (get_column_letter(col),row)].value:#look for data in the cell under the column "Topics" orginal_topic = read_github_inventory['%s%d' % (get_column_letter(col),row)].value.strip().split(" ") orginal_topic.extend(topic_add)# extending a list with data in "Topic_add" repo_name = read_github_inventory['b%d' % (row)].value # look for repo name in column B repo_events = user.get_repo("Zocdoc/%s" % repo_name) print (repo_name,orginal_topic) repo_events.replace_topics(orginal_topic)# add the extended list to GitHub else:# if no data is found in "Topics" repo_name = read_github_inventory['b%d' % (row)].value repo_events = user.get_repo("Zocdoc/%s" % repo_name) print (repo_name, topic_add) repo_events.replace_topics(topic_add) # add whatever in "topic_add" column to GitHub if read_github_inventory['%s1'% get_column_letter(columns)].value == "Topic_del":# search for column "Topic_del" for row in range(2,github_inventory_max_row+1): if read_github_inventory['%s%d' % (get_column_letter(columns),row)].value:#if there is a value in the cell of column "Topic_del" topic_del = read_github_inventory['%s%d' % (get_column_letter(columns),row)].value.strip().split(" ") #remove leading and trailing spaces and split each word into a List while read_github_inventory['%s1'% get_column_letter(col)].value != "Topics": col += 1 else:# if "Topics" is found, do next if read_github_inventory['%s%d' % (get_column_letter(col),row)].value: #look for data in the cell under the column "Topics" orginal_topic = read_github_inventory['%s%d' % (get_column_letter(col),row)].value.strip().split(" ") #remove leading and trailing spaces and split each word into a List updated_topics = [] #create a new list for i in orginal_topic: # look for element in the list "orginal_topic" if i not in topic_del: # compare List "topic_del" against List "orginal_topic" updated_topics.append(i) # Append what is not in List "topic_del" to List "updated_topics" repo_name = read_github_inventory['b%d' % (row)].value # look for repo name in column B repo_events = user.get_repo("Zocdoc/%s" % repo_name) print (orginal_topic,topic_del,updated_topics ) repo_events.replace_topics(updated_topics) # Update Github with List "updated_topics" else: # if no value is found in column "Topic_del", pass # DON'T WORRY ABOUT IT! # vim ts=4:noexpandtab
veggiespam/ZocSec.SecurityAsCode.GitHub
GitHub_Enable_Vuln_Scan/enable_vuln.py
# enable_vuln.py || part of ZocSec.SecurityAsCode.GitHub # # A tool for extracting important informaiton about all repos in an organization. # # Owner: Copyright © 2018-2019 Zocdoc Inc. www.zocdoc.com # Authors: <NAME> @garymalaysia # <NAME> @veggiespam # from github import Github from github import enable_console_debug_logging from github import GithubException import argparse import requests import json if __name__ == "__main__": parser = argparse.ArgumentParser(description='This tool allow user to audit Enterprise Repos.') parser.add_argument("-t", "--token", required=True, help="GitHub User Private Token") parser.add_argument("-o",'--organization',help="Enter the Organization/Company") args = vars(parser.parse_args()) token = args["token"] org = args["organization"].lower() headers = {'Authorization': 'token ' + token, # https://developer.github.com/changes/2019-04-24-vulnerability-alerts/ 'Accept':'application/vnd.github.dorian-preview+json'} try:# Error checking for user credential user = Github(token) try:# Error checking for organization organization = user.get_organization(org) repos = organization.get_repos() for repo in repos: repo_name = repo.full_name login = requests.put('https://api.github.com/repos/%s/vulnerability-alerts' % repo_name , headers=headers) print (repo_name +": Enabled -> ", login.ok) except GithubException as org_err: print (org_err.data) except GithubException as login_err: print (type(login_err.data))
AugRM/stereo-to-mono
Stereo-to-mono.py
import os def st2mono(arquivo): from pydub import AudioSegment if arquivo.endswith('.wav'): sound=AudioSegment.from_wav(arquivo) sound=sound.set_channels(1) output="[MONO] %s"%(arquivo) print("%s criado."%output) sound.export(output, format="wav") if arquivo.endswith('.mp3'): sound=AudioSegment.from_mp3(arquivo) sound=sound.set_channels(1) output="[MONO] %s"%(arquivo) print("%s criado."%output) sound.export(output, format="mp3") for f in os.listdir(): if (f.endswith('.wav') or f.endswith('.mp3')) and not f.startswith('[MONO]'): st2mono(f)
rezam747/DSCI_522_Spotify_Track_Popularity_Predictor
src/.ipynb_checkpoints/eda_profile-checkpoint.py
<gh_stars>0 # author: UBC MDS Block 3 Group 27 # date: 2021-11-18 """This script output the EDA report of the data. Usage: eda_profile.py <data> <output> Options: <data> Takes any data, remember the path ;) <output> output data, should be *.html """ import pandas as pd from docopt import docopt from pandas_profiling import ProfileReport opt = docopt(__doc__) def main(data, output): df = pd.read_csv(data, encoding="utf-8") profile = ProfileReport(df, title="Pandas Profiling Report") #, minimal=True) profile.to_file(output) if __name__ == "__main__": main(opt["<data>"], opt["<output>"])
rezam747/DSCI_522_Spotify_Track_Popularity_Predictor
src/preprocess_n_model.py
<reponame>rezam747/DSCI_522_Spotify_Track_Popularity_Predictor # author : Group 27 # date : 2021-11-25 """Performs some statistical or machine learning analysis and summarizes the results as a figure(s) and a table(s) Usage: preprocess_n_model.py --file_path=<file_path> --out_file=<out_file> Options: --file_path=<file_path> Path to train processed data file for which to perform preprocessing on --out_file=<out_file> Path (including filename) of where to locally write the file """ import altair as alt import numpy as np import pandas as pd import os from docopt import docopt from sklearn.compose import ColumnTransformer, make_column_transformer from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline, make_pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression, Ridge, RidgeCV from sklearn.preprocessing import ( OneHotEncoder, OrdinalEncoder, StandardScaler, ) from sklearn.model_selection import ( GridSearchCV, RandomizedSearchCV, ShuffleSplit, cross_val_score, cross_validate, train_test_split, ) opt = docopt(__doc__) def main(file_path, out_file): df_train = pd.read_csv(f'{file_path}/train_df.csv') df_test = pd.read_csv(f'{file_path}/test_df.csv') X_train, y_train = df_train.drop(columns=["spotify_track_popularity"]), df_train["spotify_track_popularity"] X_test, y_test = df_test.drop(columns=["spotify_track_popularity"]), df_test["spotify_track_popularity"] numeric_features = [ 'spotify_track_duration_ms', 'danceability', 'energy','key', 'loudness','mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'time_signature'] categorical_features = ['performer'] binary_features = ['spotify_track_explicit'] drop_features = ['song_id', 'spotify_track_id', 'spotify_track_album'] preprocessor = make_column_transformer( (StandardScaler(), numeric_features), (OneHotEncoder(handle_unknown="ignore"), categorical_features), (OneHotEncoder(drop='if_binary', handle_unknown="ignore"), binary_features), (CountVectorizer(max_features = 20000, stop_words="english"), "spotify_genre"), (CountVectorizer(max_features = 20000, stop_words="english"), "song"), ("drop", drop_features) ) pipe = make_pipeline(preprocessor, Ridge()) cv_df = pd.DataFrame(cross_validate(pipe, X_train, y_train, cv=10, return_train_score=True)) try: cv_df.to_csv(f'{out_file}/cv_df.csv', index = False) # save the cv file except: os.makedirs(os.path.dirname(f'{out_file}/cv_df.csv')) cv_df.to_csv(f'{out_file}/cv_df.csv', index = False) #random seach hyperparameters model tunning param_grid = { "ridge__alpha": np.logspace(-3,2,6), "columntransformer__countvectorizer-1__binary": np.array([True, False]), "columntransformer__countvectorizer-1__max_features": np.arange(1000, 10000, 20000), "columntransformer__countvectorizer-2__binary": np.array([True, False]), "columntransformer__countvectorizer-2__max_features": np.arange(1000, 10000, 20000) } random_search = RandomizedSearchCV( pipe, param_distributions=param_grid, n_jobs=-1, n_iter=10, cv=5 ) random_search.fit(X_train, y_train) random_search_results = pd.DataFrame(random_search.cv_results_)[ [ "mean_test_score", "param_ridge__alpha", "param_columntransformer__countvectorizer-1__max_features", "param_columntransformer__countvectorizer-1__binary", "param_columntransformer__countvectorizer-2__max_features", "param_columntransformer__countvectorizer-2__binary", "rank_test_score", ] ].set_index("rank_test_score").sort_index() try: random_search_results.to_csv(f'{out_file}/best_hyperparameters.csv', index = False) # save the random_search results except: os.makedirs(os.path.dirname(f'{out_file}/best_hyperparameters.csv')) random_search_results.to_csv(f'{out_file}/best_hyperparameters.csv', index = False) #Evaluating on the test set y_predicted = random_search.predict(X_test) df = pd.DataFrame({'y_test':y_test, 'y_predicted':y_predicted}) plot = alt.Chart(df, title= "Predicted versus true Spotify popularities").mark_point(filled=True, clip=True).encode( alt.X('y_test', title='Predicted values of Spotify popularities'), alt.Y('y_predicted', title='True values of Spotify popularities', scale=alt.Scale(domain=(0, 100))) ) plot_2 = plot + plot.mark_line(color = 'black').encode( alt.Y('y_test') ) try: plot_2.save(f'{out_file}/predict_vs_test.png') #needs altair_saver package except: os.makedirs(os.path.dirname(f'{out_file}/predict_vs_test.png')) plot_2.to_csv(f'{out_file}/predict_vs_test.png', index = False) if __name__ == "__main__": main(opt["--file_path"], opt["--out_file"])
rezam747/DSCI_522_Spotify_Track_Popularity_Predictor
src/clean_n_split.py
# author : Group 27 # date : 2021-11-25 """"Cleans data csv data from a data file audio_features.csv and save it to a local filepath as csv format" Usage: clean_n_split.py --file_path=<file_path> --out_file=<out_file> Options: --file_path=<file_path> Path to data file for which to perform preprocessing on --out_file=<out_file> Path (including filename) of where to locally write the train and test data """ import numpy as np import pandas as pd import os from docopt import docopt from sklearn.model_selection import cross_val_score, cross_validate, train_test_split opt = docopt(__doc__) def main(file_path, out_file): assert file_path.endswith(".csv"), "file path is not for a .csv document, please enter a .csv file path in --<file_path>" data= pd.read_csv(file_path) data = data.drop(columns = ["spotify_track_preview_url"]) #drop the URL columns as it has so many NA and does not have useful information data['spotify_genre'] = data['spotify_genre'].str[1:-1].str.replace("'","") # convert the spotify_genre to string data.iloc[:,3].replace("", np.NAN, inplace=True) #repalce the blank cells with NA data = data.dropna() #drop the NA rows train_df, test_df = train_test_split(data, test_size=0.2, random_state=123) try: train_df.to_csv(f'{out_file}/train_df.csv', index = False) except: os.makedirs(os.path.dirname(f'{out_file}/train_df.csv')) data.to_csv(f'{out_file}/train_df.csv', index = False) try: test_df.to_csv(f'{out_file}/test_df.csv', index = False) except: os.makedirs(os.path.dirname(f'{out_file}/test_df.csv')) test_df.to_csv(f'{out_file}/test_df.csv', index = False) if __name__ == "__main__": main(opt["--file_path"], opt["--out_file"])
DboraSilva/c-spiffe
integration_test/features/steps/fetch_x509_step.py
<reponame>DboraSilva/c-spiffe import os import sys import json import base64 import subprocess import time PARENT_PATH = os.path.abspath("..") if PARENT_PATH not in sys.path: sys.path.insert(0, PARENT_PATH) from hamcrest import assert_that, is_, is_not from OpenSSL import crypto @when(u'I fetch SVID') def step_impl(context): c_client_bin = os.popen("../build/workload/c_client") result = c_client_bin.read() result = result.splitlines()[0] context.svid = result.replace("Address : ", "") @then(u'I check that the SVID is returned correctly') def step_impl(context): assert_that(context.svid, is_not("(nil)")) @when(u'I fetch bundle') def step_impl(context): c_client_bin = os.popen("../build/workload/c_client_bundle") result = c_client_bin.read() result = result.splitlines()[0] context.bundle = result.replace("Address : ", "") @then(u'I check that the Bundle is returned correctly') def step_impl(context): assert_that(context.bundle, is_not("(nil)")) @when(u'I down the server') def step_impl(context): #List all process processes = os.popen('ps aux | grep spire-agent') result = processes.read() result = result.splitlines()[0] process_id_1 = result[12:-125] process_id_2 = result[12:-155] down_process = subprocess.run(["kill", process_id_1]) down_process = subprocess.run(["kill", process_id_2]) time.sleep(5) @when(u'I up the server') def step_impl(context): path = ["spire-agent"] command = ["run", "-joinToken", "$TOKEN", "-config", "/opt/spire/conf/agent/agent.conf"] process = subprocess.Popen(path + command) time.sleep(5) @then(u'I check that the SVID is not returned') def step_impl(context): assert_that(context.svid, is_("(nil)")) @then(u'I check that the Bundle is not returned') def step_impl(context): assert_that(context.bundle, is_("(nil)"))
DboraSilva/c-spiffe
integration_test/features/utils.py
import os import sys import string from os import chdir from common.constants import Paths PARENT_PATH = os.path.abspath("..") if PARENT_PATH not in sys.path: sys.path.insert(0, PARENT_PATH) def handle_response(response, function_name, expected_status_code): if response.status_code != expected_status_code: print("request: " + function_name + " - status_code: " + str(response.status_code) + " - message: " + response.text) def print_exception(function_name, error): print(function_name + str(error))
DboraSilva/c-spiffe
integration_test/get-entries.py
#!/usr/bin/env python import os import logging import sys logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) def check_entries(): logging.info("Getting Entries from SPIRE server...") bashCommand = "./get-entries.sh"; output = os.system(bashCommand) logging.info("entries:" + str(output)); return output if __name__ == "__main__": j = check_entries() if not j: print("Error: Could not retrieve entries") else: print("Success: found entries %s \n" % j)
DboraSilva/c-spiffe
integration_test/features/environment.py
import os import sys import json import argparse from urllib.parse import unquote def before_all(context): context.spiffe_id = context.config.userdata['spiffe_id']
DboraSilva/c-spiffe
integration_test/common/constants.py
<gh_stars>0 class Paths: ASSETS_PATH = '..\\common\\assets\\'
rushkii/maid_manga_id
maid_manga_id/http.py
from .utils import to_async from bs4 import BeautifulSoup as bsoup import requests, lxml, re BASE = "https://maid.my.id" @to_async def scrape(path:str): if bool(re.match(r'((http|https):\/\/)?(www.)?maid.my.id/(.*)', path)): url = path elif not path.startswith('/'): url = f'{BASE}/{path}' else: url = BASE+path response = requests.get(url) soup = bsoup(response.text, 'lxml') return soup @to_async def api(**kwargs): response = requests.post( f'{BASE}/wp-admin/admin-ajax.php', **kwargs ) soup = bsoup(response.text, 'lxml') return soup @to_async def new(method, url, **kwargs): return requests.request(method, url, **kwargs)
rushkii/maid_manga_id
maid_manga_id/methods/manga/info.py
from bs4 import BeautifulSoup as bsoup from dateutil import parser import re from maid_manga_id.scaffold import Maid from maid_manga_id import types from maid_manga_id import http from maid_manga_id import utils from maid_manga_id.object import Listing class MangaInfo(Maid): async def info(self, title): # cek jika argumennya menggunakan url # jika tidak maka menggunakan jalur endpoint # check if the argument passing the url # else using endpoint path if bool(re.match(r'((http|https):\/\/)?(www.)?maid.my.id/manga/(.*)', title)): url = title else: url = f"/manga/{title.replace(' ', '-')}" manga: bsoup = await http.scrape(url) # request ke url lalu me-return BeautifulSoup objek # requested to the url then return BeautifulSoup object cover = manga.find('div', class_='series-thumb').img.get('src') title = { 'japanese': manga.find('div', class_='series-title').h2.text, 'english': manga.find('div', class_='series-title').span.text } genre = manga.find('div', class_='series-genres') synopsis = manga.find('div', class_='series-synops') published = manga.find('span', class_='published') author = manga.find('span', class_='author') rating = manga.find('div', class_='series-infoz score') chapters = manga.find_all('div', class_='flexch-infoz') if bool(genre): genre = [a.text for a in genre.find_all('a')] else: genre = [] if bool(synopsis): synopsis = synopsis.text else: synopsis = None if bool(published): published = parser.parse(published.text) else: published = None if bool(author): author = author.text else: author = None if bool(rating): rating = float(rating.text) else: rating = float(0) # menguraikan types.Chapter objek agar bekerja dengan baik # parsing types.Chapter object in order to work well if bool(chapters): chapters = Listing(sorted([ await types.Chapters._parse(self, title = title, chapter = a.find("span", class_="ch").text, released = parser.parse(utils.recognize_indo_month( a.find("span", class_="date").text)), url = a.a['href'] ) for a in manga.find_all('div', class_='flexch-infoz')], key=lambda _: list((_).__dict__.values())[-1])) else: chapters = Listing() if url.startswith('/'): url = f'https://maid.my.id/manga{url}' else: url # menguraikan types.Manga object agar bekerja dengan baik # parsing the types.Manga object in order to work well parsed = await types.Manga._parse( self, cover = cover, title = title, genre = genre, synopsis = synopsis, published = published, author = author, rating = rating, url = url, chapters = chapters) return parsed
rushkii/maid_manga_id
maid_manga_id/maid_client.py
from maid_manga_id.scaffold import Maid from maid_manga_id.methods import Methods class MaidManga(Methods, Maid): pass
rushkii/maid_manga_id
maid_manga_id/methods/manga/search.py
from bs4 import BeautifulSoup as bsoup from urllib.parse import quote from urllib.parse import urlparse import re from maid_manga_id.scaffold import Maid from maid_manga_id import types from maid_manga_id import http from maid_manga_id.object import Listing class MangaSearch(Maid): async def search(self, title): html: bsoup = await http.scrape(f'/?s={quote(title)}') result = html.find_all('div', class_='flexbox2-item') listed = Listing() for manga in result: cover = manga.find('div', class_='flexbox2-thumb').img.get('src', '').split('?')[0] title = manga.find('span', class_='title') genre = manga.find_all('a', rel='tag') chapter = manga.find('div', class_='season') author = manga.find('span', class_='studio') rating = manga.find('div', class_='score') url = manga.find('a').get('href') if bool(title): title = title.text else: title = None if bool(genre): genre = [a.text for a in genre] else: genre = [] if bool(chapter): chl = Listing() counted = int(re.findall(r'-?\d+\.?\d*', chapter.text)[0]) for ch in range(1, counted+1): if ch < 10: num = "0" else: num = "" parse = urlparse(url) chl.append(await types.Chapters._parse( self, title = title, chapter = ch, url = f"{parse.scheme}://{parse.netloc}{parse.path.replace('/manga','').rstrip('/')}-chapter-{num}{ch}-bahasa-indonesia/" )) chapters = chl else: chapters = Listing() if bool(author): author = author.text else: author = None if bool(rating): rating = rating.text else: rating = None listed.append(await types.Manga._parse( self, cover = cover, title = title, genre = genre, author = author, rating = rating, chapters = chapters )) return listed
rushkii/maid_manga_id
maid_manga_id/types/__init__.py
<reponame>rushkii/maid_manga_id from .manga import Manga from .chapter import Chapters
rushkii/maid_manga_id
example.py
from maid_manga_id import MaidManga import asyncio if __name__ == '__main__': maid = MaidManga() async def main(): manga = await maid.info('kanojo mo kanojo') print(manga) asyncio.get_event_loop().run_until_complete(main())
rushkii/maid_manga_id
maid_manga_id/types/manga.py
from typing import List, Dict from dataclasses import dataclass from maid_manga_id.object import Object @dataclass class Manga(Object): cover: str = None title: Dict[str, str] = None genre: List[str] = None synopsis: str = None published: int = None author: str = None rating: float = None url: str = None chapters: List[dict] = None async def _parse(self, **kwargs): return Manga(**kwargs)
rushkii/maid_manga_id
old_version/maid_manga/__init__.py
from .api import MaidMangaID __copyright__ = 'Copyright 2020 by https://maid.my.id/' __version__ = '1.0' __author__ = 'Kee' __author_email__ = '<EMAIL>' __url__ = 'https://github.com/rushkii/maid_manga_id' __all__ = ['MaidMangaID']
rushkii/maid_manga_id
maid_manga_id/methods/manga/__init__.py
<reponame>rushkii/maid_manga_id<gh_stars>1-10 from .info import MangaInfo from .search import MangaSearch class Manga( MangaInfo, MangaSearch ): pass
rushkii/maid_manga_id
maid_manga_id/object.py
from typing import cast, List, Any, Union, Dict, Match from datetime import datetime import json, inspect import maid_manga_id class PrettyObject: __slots__: List[str] = [] QUALNAME = "Types" @staticmethod def default(obj: "PrettyObject") -> Union[str, Dict[str, str]]: if isinstance(obj, bytes): return repr(obj) return { "_": obj.QUALNAME, **{ attr: getattr(obj, attr) for attr in obj.__slots__ if getattr(obj, attr) is not None } } def __str__(self) -> str: return json.dumps(self, indent=4, default=PrettyObject.default, ensure_ascii=False) def __repr__(self) -> str: return "types.{}({})".format( self.QUALNAME, ", ".join( f"{attr}={repr(getattr(self, attr))}" for attr in self.__slots__ if getattr(self, attr) is not None ) ) def __eq__(self, other: Any) -> bool: for attr in self.__slots__: try: if getattr(self, attr) != getattr(other, attr): return False except AttributeError: return False return True def __len__(self) -> int: return len(self.write()) def __getitem__(self, item: Any) -> Any: return getattr(self, item) def __setitem__(self, key: Any, value: Any) -> Any: setattr(self, key, value) def __call__(self, *args: Any, **kwargs: Any) -> Any: pass class Meta(type, metaclass=type("", (type,), {"__str__": lambda _: "~hi"})): def __str__(self): return f"<class 'maid_manga_id.types.{self.__name__}'>" class Object(metaclass=Meta): def __init__(self, maid: "maid_manga_id.MaidManga" = None): self._maid = maid def bind(self, maid: "maid_manga_id.MaidManga"): self._maid = maid @staticmethod def default(obj: "Object"): if isinstance(obj, bytes): return repr(obj) if isinstance(obj, Match): return repr(obj) if isinstance(obj, datetime): return str(obj) return { "_": obj.__class__.__name__, **{ attr: ( getattr(obj, attr) ) for attr in filter(lambda x: not x.startswith("_"), obj.__dict__) if getattr(obj, attr) is not None } } def __str__(self) -> str: return json.dumps(self, indent=4, default=Object.default, ensure_ascii=False) def __repr__(self) -> str: return "maid_manga_id.types.{}({})".format( self.__class__.__name__, ", ".join( f"{attr}={repr(getattr(self, attr))}" for attr in filter(lambda x: not x.startswith("_"), self.__dict__) if getattr(self, attr) is not None ) ) def __eq__(self, other: "Object") -> bool: for attr in self.__dict__: try: if getattr(self, attr) != getattr(other, attr): return False except AttributeError: return False return True def __getitem__(self, item): return getattr(self, item) def __setitem__(self, key, value): setattr(self, key, value) def __getstate__(self): new_dict = self.__dict__.copy() new_dict.pop("_maid", None) return new_dict class Listing(list): __slots__ = [] def __str__(self): return Object.__str__(self) def __repr__(self): return f"maid_manga_id.object.Listing([{','.join(Object.__repr__(i) for i in self)}])"
rushkii/maid_manga_id
maid_manga_id/methods/__init__.py
from maid_manga_id.methods.manga import Manga class Methods( Manga ): pass
rushkii/maid_manga_id
maid_manga_id/utils.py
from typing import Any, Callable from functools import wraps, partial from motor.frameworks.asyncio import _EXECUTOR import asyncio def to_async(func: Callable[[Any], Any]) -> Callable[[Any], Any]: @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: loop = asyncio.get_running_loop() return await loop.run_in_executor(_EXECUTOR, partial(func, *args, **kwargs)) return wrapper def recognize_indo_month(month_str): month_str = month_str.split()[0] ID = [ 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember' ] EN = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] for i in range(len(ID)): if month_str == ID[i]:return EN[i]
rushkii/maid_manga_id
setup.py
from setuptools import setup, find_packages def readme(): with open('README.md') as f: return f.read() setup( name='maid_manga_id', version='1.1', description='Maid Manga Indonesia wrapper using Python BeautifulSoup.', long_description=readme(), long_description_content_type='text/markdown', classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], url='https://github.com/rushkii/maid_manga_id', author='Kee', author_email='<EMAIL>', keywords='manga maid_manga maid_manga_id manga_id MaidMangaID', license='MIT', packages=find_packages(exclude=['old_version', 'downloads']), install_requires=[ 'requests', 'bs4', 'lxml', 'img2pdf', 'humanfriendly', 'motor', 'python-dateutil' ], include_package_data=True, zip_safe=False )
rushkii/maid_manga_id
old_version/example.py
<reponame>rushkii/maid_manga_id<filename>old_version/example.py from maid_manga.api import MaidMangaID import json, re if __name__ == '__main__': manga = MaidMangaID() print(json.dumps(manga.top_manga('romance'), indent=4))