Esempio n. 1
0
def test_all_with_dim():
    var = sc.Variable(['x', 'y'],
                      values=np.array([True, True, True, False]).reshape(2, 2))
    assert sc.is_equal(sc.all(var, 'x'),
                       sc.Variable(dims=['y'], values=[True, False]))
    assert sc.is_equal(sc.all(var, 'y'),
                       sc.Variable(dims=['x'], values=[True, False]))
Esempio n. 2
0
def test_simple_case_any_naming():
    ds = _make_simple_dataset(u=2, v=10, w=10)
    grouped = groupby2D(ds, nx_target=5, ny_target=5, x='w', y='v', z='u')
    assert grouped['a'].shape == [2, 5, 5]
    projection = sc.array(dims=['v', 'w'], values=np.ones((5, 5))) * 4
    expected_data = sc.concat([projection, projection], dim='u')
    assert sc.all(
        sc.isclose(grouped['a'].data, expected_data,
                   atol=1e-14 * sc.units.one)).value
Esempio n. 3
0
 def test_inelastic_unit_conversion(self):
     import mantid.simpleapi as mantid
     eventWS = self.base_event_ws
     ws_deltaE = mantid.ConvertUnits(eventWS,
                                     Target='DeltaE',
                                     EMode='Direct',
                                     EFixed=3)
     ref = scn.from_mantid(ws_deltaE)
     da = scn.from_mantid(eventWS)
     # Boost and Mantid use CODATA 2006. This test passes if we manually
     # change the implementation to use the old constants. Alternatively
     # we can correct for this by scaling L1^2 or L2^2, and this was also
     # confirmed in C++. Unfortunately only positions are accessible to
     # correct for this here, and due to precision issues with
     # dot/norm/sqrt this doesn't actually fix the test. We additionally
     # exclude low TOF region, and bump relative and absolute accepted
     # errors from 1e-8 to 1e-5.
     m_n_2006 = 1.674927211
     m_n_2018 = 1.67492749804
     e_2006 = 1.602176487
     e_2018 = 1.602176634
     scale = (m_n_2006 / m_n_2018) / (e_2006 / e_2018)
     da.coords['source_position'] *= np.sqrt(scale)
     da.coords['position'] *= np.sqrt(scale)
     low_tof = da.bins.constituents['data'].coords[
         'tof'] < 49000.0 * sc.units.us
     da.coords['incident_energy'] = 3.0 * sc.units.meV
     da = scn.convert(da, 'tof', 'energy_transfer', scatter=True)
     assert sc.all(
         sc.isnan(da.coords['energy_transfer'])
         | sc.isclose(da.coords['energy_transfer'],
                      ref.coords['energy_transfer'],
                      atol=1e-8 * sc.units.meV,
                      rtol=1e-8 * sc.units.one)).value
     assert sc.all(
         low_tof
         | sc.isnan(da.bins.constituents['data'].coords['energy_transfer'])
         | sc.isclose(
             da.bins.constituents['data'].coords['energy_transfer'],
             ref.bins.constituents['data'].coords['energy_transfer'],
             atol=1e-5 * sc.units.meV,
             rtol=1e-5 * sc.units.one)).value
Esempio n. 4
0
def mask_from_adj_pixels(mask):
    """
    Checks if the adjacent pixels (in 8 directions) are masked to remove
    any noisy pixels which are erroneously masked or unmasked compared to
    it's neighbours

    If all adj. pixels are then the pixel considered is set to True
    If no adj. pixels are then the pixel considered is set to False
    If surrounding pixels have a mix of True/False the val is left as-is

    This function handles border pixels as if they aren't there. So that
    the following happens:
    ------------------------
    |F|T|     ->      |T|T|
    |T|T|             |T|T|
    -----------------------

    Parameters
    ----------
    mask: Existing mask with some positions masked

    Returns
    -------
    mask: Mask copy after completing the op. described above

    """

    mask = mask.copy()

    def make_flip(fill):
        flip = sc.empty(dims=['neighbor', 'y', 'x'],
                        shape=[
                            8,
                        ] + mask.shape,
                        dtype=bool)
        flip['neighbor', 0] = _shift(mask, "x", True, fill)
        flip['neighbor', 1] = _shift(mask, "x", False, fill)
        flip['neighbor', 2] = _shift(mask, "y", True, fill)
        flip['neighbor', 3] = _shift(mask, "y", False, fill)
        flip['neighbor', 4:6] = _shift(flip['neighbor', 0:2], "y", True, fill)
        flip['neighbor', 6:8] = _shift(flip['neighbor', 0:2], "y", False, fill)
        return flip

    # mask if all neighbors masked
    mask = mask | sc.all(make_flip(True), 'neighbor')
    # unmask if no neighbor masked
    mask = mask & sc.any(make_flip(False), 'neighbor')
    return mask
Esempio n. 5
0
def convert_Workspace2D_to_data_array(ws,
                                      load_run_logs=True,
                                      advanced_geometry=False,
                                      **ignored):

    dim, unit = validate_and_get_unit(ws.getAxis(0).getUnit())
    spec_dim, spec_coord = init_spec_axis(ws)

    coords_labs_data = _convert_MatrixWorkspace_info(
        ws, advanced_geometry=advanced_geometry, load_run_logs=load_run_logs)
    _, data_unit = validate_and_get_unit(ws.YUnit(), allow_empty=True)
    if ws.id() == 'MaskWorkspace':
        coords_labs_data["data"] = sc.Variable(dims=[spec_dim],
                                               unit=data_unit,
                                               values=ws.extractY().flatten(),
                                               dtype=sc.DType.bool)
    else:
        stddev2 = ws.extractE()
        np.multiply(stddev2, stddev2, out=stddev2)  # much faster than np.power
        coords_labs_data["data"] = sc.Variable(dims=[spec_dim, dim],
                                               unit=data_unit,
                                               values=ws.extractY(),
                                               variances=stddev2)
    array = sc.DataArray(**coords_labs_data)

    if ws.hasAnyMaskedBins():
        bin_mask = sc.zeros(dims=array.dims,
                            shape=array.shape,
                            dtype=sc.DType.bool)
        for i in range(ws.getNumberHistograms()):
            # maskedBinsIndices throws instead of returning empty list
            if ws.hasMaskedBins(i):
                set_bin_masks(bin_mask, dim, i, ws.maskedBinsIndices(i))
        common_mask = sc.all(bin_mask, spec_dim)
        if sc.identical(common_mask, sc.any(bin_mask, spec_dim)):
            array.masks["bin"] = common_mask
        else:
            array.masks["bin"] = bin_mask

    # Avoid creating dimensions that are not required since this mostly an
    # artifact of inflexible data structures and gets in the way when working
    # with scipp.
    if len(spec_coord.values) == 1:
        if 'position' in array.coords:
            array.coords['position'] = array.coords['position'][spec_dim, 0]
        array = array[spec_dim, 0].copy()
    return array
Esempio n. 6
0
def test_extract_energy_final():
    # Efinal is often stored in a non-default parameter file
    parameters = {
        'IN16B': 'IN16B_silicon_311_Parameters.xml',
        'IRIS': 'IRIS_mica_002_Parameters.xml',
        'OSIRIS': 'OSIRIS_graphite_002_Parameters.xml',
        'BASIS': 'BASIS_silicon_311_Parameters.xml'
    }
    unsupported = [
        'ZEEMANS', 'MARS', 'IN10', 'IN13', 'IN16', 'VISION', 'VESUVIO'
    ]
    for instr in _all_indirect(blacklist=unsupported):
        out = _load_indirect_instrument(instr, parameters)
        ds = scn.from_mantid(out)
        efs = ds.coords["final_energy"]
        assert not sc.all(sc.isnan(efs)).value
        assert efs.unit == sc.Unit("meV")
Esempio n. 7
0
def test_convert_tof_to_energy_transfer_indirect():
    tof = make_test_data(coords=('tof', 'L1', 'L2'), dataset=True)
    with pytest.raises(RuntimeError):
        scn.convert(tof, origin='tof', target='energy_transfer', scatter=True)
    ef = 25.0 * sc.units.meV
    tof.coords['final_energy'] = ef
    indirect = scn.convert(tof,
                           origin='tof',
                           target='energy_transfer',
                           scatter=True)
    check_tof_conversion_metadata(indirect, 'energy_transfer', sc.units.meV)

    t = tof.coords['tof']
    t0 = sc.to_unit(tof.coords['L2'] * sc.sqrt(m_n / 2 / ef), t.unit)
    assert sc.all(t0 < t).value  # only test physical region here
    ref = sc.to_unit(m_n / 2 * (tof.coords['L1'] / (t - t0))**2,
                     ef.unit).rename_dims({'tof': 'energy_transfer'}) - ef
    assert sc.allclose(indirect.coords['energy_transfer'],
                       ref,
                       rtol=sc.scalar(1e-13))
Esempio n. 8
0
def test_all():
    var = sc.Variable(['x'], values=[True, False, True])
    assert sc.all(var, 'x') == sc.Variable(value=False)
Esempio n. 9
0
def test_all():
    var = sc.Variable(['x', 'y'],
                      values=np.array([True, True, True, False]).reshape(2, 2))
    assert sc.is_equal(sc.all(var), sc.Variable(value=False))
Esempio n. 10
0
    def test_center_false(self):
        input_data = [[False, False, False], [False, True, False],
                      [False, False, False]]

        returned = self._run_test(input_data)
        self.assertFalse(sc.all(returned).value)
Esempio n. 11
0
    def test_center_true(self):
        input_data = [[True, True, True], [True, False, True],
                      [True, True, True]]

        returned = self._run_test(input_data)
        self.assertTrue(sc.all(sc.all(returned, "x"), "y").value)
Esempio n. 12
0
def test_all():
    var = sc.Variable([Dim.X], values=[True, False, True])
    assert sc.all(var, Dim.X) == sc.Variable(value=False)