=== ISSUE #387 | Move daskms.experimental.zarr to zarr-python 3 | labels: enhancement,dependencies | comments: [] | created: 2026-09-30T09:35:15Z ===
dask-ms pins `zarr >=2.12.0, <3.0.0` (and `numcodecs <0.16.0`). The zarr 2 pin
now also holds xarray back. xarray 2026.9.0 requires `zarr >=3` for zarr I/O,
so pip pairs it with zarr 2.18.7 and xarray's zarr backend fails:

```
TypeError: open_group() got an unexpected keyword argument 'zarr_format'
```

This fails `test_xarray_to_zarr` and `test_xarray_reading_daskms_written_dataset`
on every supported Python version. #384 works around it by capping
`xarray <2026.9.0` in the `xarray`, `katdal` and `complete` extras. `master`
will hit the same failure on its next CI run without that cap.

The lasting fix is to move `daskms.experimental.zarr` to zarr-python 3.

## Writing zarr v2 with zarr-python 3

zarr-python 3 still writes the v2 format when given `zarr_format=2`. Tested
by writing with zarr 3.4.0 and reading back with zarr 2.18.7:

| feature | zarr 3 writing v2 | zarr 2 reads it |
|---|---|---|
| numeric and bool arrays | yes | yes |
| group attributes (incl. `__daskms_partition_schema__`) | yes | yes |
| consolidated metadata | yes | yes |
| fsspec mapper as the store | yes | — |
| strings as `dtype=zarr.dtype.VariableLengthUTF8()` | yes | yes (object array, `VLenUTF8` filter) |
| strings as `dtype=object` + `numcodecs.JSON()` (what dask-ms writes now) | **no** | — |

zarr 3 rejects a bare `object` dtype as ambiguous and has no JSON object codec
in its v2 path.

## Changes needed in `daskms/experimental/zarr/__init__.py`

- Write string columns as `VariableLengthUTF8` in place of
  `dtype=object, object_codec=numcodecs.JSON()`.
- `require_dataset` → `require_array`.
- `zarr.convenience.consolidate_metadata` → `zarr.consolidate_metadata`. The
  `zarr.convenience` module no longer exists.
- Opening a missing store now raises `FileNotFoundError` rather than
  `zarr.errors.GroupNotFoundError`, so the "open, or create if missing"
  fallback in `xds_to_zarr` needs to catch it.
- Drop the `zarr <3`, `numcodecs <0.16` and `xarray <2026.9.0` caps.

## Compatibility with existing stores

zarr 3 cannot read the JSON-encoded object arrays that current dask-ms writes
for string columns:

```
ValueError: No Zarr data type found that matches {'name': '|O', 'object_codec_id': 'json2'}
```

- **With consolidated metadata** (the `xds_to_zarr` default), the error comes
  from parsing `.zmetadata`, so the whole store fails to open, not just the
  string columns.
- **Without consolidation**, the group opens and numeric columns read, but the
  string columns still fail.

Stores written after the move would remain readable with zarr 2, so the
format change is backward compatible; reading older stores is what breaks.

As zarr support is experimental, a full compatibility path (rewriting the
`json2` dtype in the metadata) is probably not warranted. A cheap mitigation
would be to catch this error in `xds_from_zarr` and re-raise with a message
saying the store was written by an older dask-ms with zarr 2 and needs
`zarr <3` to read.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


=== ISSUE #380 | pyarrow test cases segfault flakily | labels: bug | comments: [] | created: 2026-07-20T11:07:15Z ===
The github test suite started failing recently with the release of pyarrow 25.0.0. Likely this is due to:

- https://github.com/apache/arrow/issues/50471#issuecomment-5020675468

=== ISSUE #374 | Fusion failure when using clone | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Please post the error message","createdAt":"2026-06-11T10:00:25Z","id":"IC_kwDOBh8_I88AAAABFum7SA","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/374#issuecomment-4679383880","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"The above was not the full story (although it is related). Selecting out an element of of the cloned array causes the failure from `dask>2024.10.0`. New reproducer:\n```python\nimport dask.array as da\nfrom dask.graph_manipulation import clone\nfrom daskms import xds_from_storage_table\n\nspw = xds_from_storage_table(\n    \"path/to/ms::SPECTRAL_WINDOW\",\n    columns=[\"CHAN_WIDTH\"]\n)[0]\nda.compute(clone(spw.CHAN_WIDTH.data)[0])\n```\n\nFull traceback:\n```python\nValueError                                Traceback (most recent call last)\nCell In[3], line 7\n      3 from daskms import xds_from_storage_table\n      5 spw = xds_from_storage_table(\"/home/jonathan/reductions/3C147/msdir/C147_minimal.MS::SPECTRAL_WINDOW\",\n      6                              columns=[\"CHAN_WIDTH\"])[0]\n----> 7 da.compute(clone(spw.CHAN_WIDTH.data)[0])\n\nFile ~/venvs/tmpenv/lib/python3.13/site-packages/dask/base.py:685, in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs)\n    682     expr = expr.optimize()\n    683     keys = list(flatten(expr.__dask_keys__()))\n--> 685     results = schedule(expr, keys, **kwargs)\n    687 return repack(results)\n\nFile ~/venvs/tmpenv/lib/python3.13/site-packages/dask/_expr.py:1152, in _HLGExprSequence.__dask_graph__(self)\n   1149 def __dask_graph__(self):\n   1150     # This class has to override this and not just _layer to ensure the HLGs\n   1151     # are not optimized individually\n-> 1152     return ensure_dict(self._optimized_dsk)\n\nFile ~/.local/share/uv/python/cpython-3.13.6-linux-x86_64-gnu/lib/python3.13/functools.py:1026, in cached_property.__get__(self, instance, owner)\n   1024 val = cache.get(self.attrname, _NOT_FOUND)\n   1025 if val is _NOT_FOUND:\n-> 1026     val = self.func(instance)\n   1027     try:\n   1028         cache[self.attrname] = val\n\nFile ~/venvs/tmpenv/lib/python3.13/site-packages/dask/_expr.py:1144, in _HLGExprSequence._optimized_dsk(self)\n   1142     dsk = hlgexpr.hlg\n   1143     if (optimizer := hlgexpr.low_level_optimizer) is not None:\n-> 1144         dsk = optimizer(dsk, keys)\n   1145     graphs.append(dsk)\n   1147 return HighLevelGraph.merge(*graphs)\n\nFile ~/venvs/tmpenv/lib/python3.13/site-packages/dask/array/optimization.py:62, in optimize(dsk, keys, **kwargs)\n     59 dsk = ensure_dict(dsk)\n     61 dsk = convert_legacy_graph(dsk)\n---> 62 dsk = fuse_linear_task_spec(dsk, keys=keys)\n     63 dsk = _optimize_slices(dsk)\n     65 return dsk\n\nFile ~/venvs/tmpenv/lib/python3.13/site-packages/dask/_task_spec.py:485, in GraphNode.fuse(key, *tasks)\n    483 leafs = all_keys - all_deps\n    484 if len(leafs) > 1:\n--> 485     raise ValueError(f\"Cannot fuse tasks with multiple outputs {leafs}\")\n    487 outkey = leafs.pop()\n    488 return Task(\n    489     key or outkey,\n    490     _execute_subgraph,\n   (...)    495     _data_producer=any(t.data_producer for t in tasks),\n    496 )\n\nValueError: Cannot fuse tasks with multiple outputs {('read~CHAN_WIDTH~C147_minimal.MS/SPECTRAL_WINDOW-844f25eeda1b978e379db9606893ea79', 0, 0), 'finalize-hlgfinalizecompute-61a9733803ef4763a481d4f879ec667a'}\n\n```","createdAt":"2026-06-11T10:06:05Z","id":"IC_kwDOBh8_I88AAAABFuppNA","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/374#issuecomment-4679428404","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Note that the above is triggered by graph optimization i.e. doing `optimize_graph=False` in the compute call suppresses the error. I can definitely pin to an older dask/dask-ms version if needed for now. Ultimately we want to move away from this approach; I just thought it was worth mentioning as it doesn't seem specific to QC.","createdAt":"2026-06-11T10:08:18Z","id":"IC_kwDOBh8_I88AAAABFuqrNQ","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/374#issuecomment-4679445301","viewerDidAuthor":false}] | created: 2026-06-11T09:56:23Z ===
I ran into this while trying to figure out how far I could relax QuartiCal's dependencies. The following should reproduce (with `dask>=2025.4.0`):
```python
import dask.array as da
from dask.graph_manipulation import clone
from daskms import xds_from_storage_table

spw = xds_from_storage_table(
    "path/to/ms::SPECTRAL_WINDOW",
    columns=["CHAN_WIDTH"]
)[0]
da.compute(clone(spw.CHAN_WIDTH.data))
```
The problem seems to have been introduced in `dask==2025.4.0`. Have not done any digging on the `dask-ms` side to figure out why it is only surfaced in this specific case.

=== ISSUE #373 | xarray datasets derived from the katdal backend are not pickleable | labels:  | comments: [] | created: 2026-05-18T11:24:31Z ===
This follows from the fact that the underlying katdal datasets backing the dask arrays are not pickleable:

- https://github.com/ska-sa/katdal/issues/392

=== ISSUE #371 | Remove low-level graph construction | labels: enhancement | comments: [] | created: 2026-04-21T09:45:23Z ===
dask-ms is showing it's age: Many of the routines for constructing read or write arrays were constructed with low level dictionary task graphs. In particular the use of cached and inlined arrays were built using low level graphs and this lead to compatibility issues with newer dask versions:

- https://github.com/ratt-ru/dask-ms/issues/350

This was resolved by #368, but the core issue of low level graph construction still remains. This issue tracks the requirement to upgrade to newer dask constructs that will be better supported in future. However, thanks to #368, the urgency for this upgrade is reduced.

=== ISSUE #360 | Supplying a ROWID for an empty table should throw a better error message as ROWID implies a table update | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Thanks for the reproducer @miguelcarcamov. \n\nThere is a test case for this behaviour so my initial strategy would be to figure out how the example above differs from that:\n\nhttps://github.com/ratt-ru/dask-ms/blob/f3d32a711b2dfdaafd724977fb7800377faf0785/daskms/tests/test_ms_creation.py#L176-L185\n\nMaybe `chunks='auto'` is causing the issue. I'll start taking a closer look tomorrow. \n\n\n","createdAt":"2025-10-27T15:27:42Z","id":"IC_kwDOBh8_I87Nv6rp","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/360#issuecomment-3451890409","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Thank you for the information. I will keep checking what is going on.\n\nGot this warning when I activated the logs\n\n`WARNING:daskms.writes:Unusual ROWID layer arange-978dd7ae7b264601da0ace2b67530ec2. This is probably OK but could foreshadow incorrect behaviour.`\n\nnot sure if that would help","createdAt":"2025-10-27T16:53:31Z","id":"IC_kwDOBh8_I87NxrN9","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/360#issuecomment-3452351357","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"I took off the ROWID coords in the construction of the xarray datasets and it worked. It seems that dask-ms has a bug when ROWID coords are present :).","createdAt":"2025-10-27T17:07:56Z","id":"IC_kwDOBh8_I87Nx6oo","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/360#issuecomment-3452414504","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I took off the ROWID coords in the construction of the xarray datasets and it worked. It seems that dask-ms has a bug when ROWID coords are present :).\n\nAh! Thanks for figuring that out. That is buggy, could probably throw a nicer error message although this reminded me that it is intended behaviour!\n\nhttps://dask-ms.readthedocs.io/en/latest/tutorial/writes.html#updating-appending-rows\n\n> The presence of ROWID coordinates on each of the datasets provided to [xds_to_table()](https://dask-ms.readthedocs.io/en/latest/api.html#daskms.xds_to_table) governs whether the function will update or append rows to a table.\n\nI'll update the title of the issue","createdAt":"2025-10-27T17:17:30Z","id":"IC_kwDOBh8_I87NyE5s","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/360#issuecomment-3452456556","viewerDidAuthor":false}] | created: 2025-10-24T23:13:28Z ===
When attempting to write subtables (ANTENNA, FIELD, SPECTRAL_WINDOW, etc.) to an existing Measurement Set using xds_to_table(), I encounter a `RuntimeError: TableProxy::TableProxy::putColumn: no such row error`. This occurs even with minimal test cases and appears to be related to row allocation in subtable creation.


Minimal code here:

```python
import dask.array as da
import xarray as xr
from daskms import xds_to_table
import dask


# First, create a minimal main table to establish MS structure
minimal_main = xr.Dataset({
    'DATA': (['row', 'chan', 'corr'], da.zeros((1, 1, 1), chunks='auto')),
    'FLAG': (['row', 'chan', 'corr'], da.zeros((1, 1, 1), dtype=bool, chunks='auto')),
    'ANTENNA1': (['row'], da.zeros(1, dtype='int32', chunks='auto')),
    'ANTENNA2': (['row'], da.zeros(1, dtype='int32', chunks='auto')),
}, coords={'ROWID': (['row'], da.arange(1, chunks='auto'))})

print('Creating MS structure with minimal main table...')
try:
    writes = xds_to_table(minimal_main, 'test_minimal_antenna.ms')
    dask.compute(writes)
    print('MS structure created successfully')

    # Now try to write ANTENNA table
    print('Writing ANTENNA table to existing MS...')
    n_antenna = 3
    minimal_antenna = xr.Dataset({
        'NAME': (['row'], da.from_array(['ANT1', 'ANT2', 'ANT3'], chunks='auto')),
        'POSITION': (['row', 'xyz'], da.zeros((n_antenna, 3), chunks='auto')),
        'DISH_DIAMETER': (['row'], da.ones(n_antenna, chunks='auto')),
        'FLAG_ROW': (['row'], da.zeros(n_antenna, dtype=bool, chunks='auto')),
    }, coords={'ROWID': (['row'], da.arange(n_antenna, chunks='auto'))})

    writes = xds_to_table(minimal_antenna, 'test_minimal_antenna.ms::ANTENNA', columns=["NAME"])
    dask.compute(writes)
    print('ANTENNA table write successful')

except Exception as e:
    print(f'Test failed: {e}')
    import traceback
    traceback.print_exc()
```

Expected behavior: The subtable should be created successfully with the specified number of rows (3 in this case) and data should be written without errors.

Actual behavior:
```python
File "/home/user/.local/share/mamba/envs/env/lib/python3.12/site-packages/daskms/writes.py", line 230, in putter_wrapper
    ).result()
File "/home/user/.local/share/mamba/envs/env/lib/python3.12/site-packages/daskms/writes.py", line 41, in ndarray_putcol
    putcol(column, data[rr : rr + rl], startrow=rs, nrow=rl)
File "/home/user/.local/share/mamba/envs/env/lib/python3.12/site-packages/casacore/tables/table.py", line 1152, in table.putcol
    self._putcol(columnname, startrow, nrow, rowincr, value)
RuntimeError: TableProxy::TableProxy::putColumn: no such row
```

Additional Information

Main table writing works perfectly - The issue is specifically with subtable creation
Occurs with any subtable - ANTENNA, FIELD, SPECTRAL_WINDOW, etc. all fail with the same error
Data structure is correct - The xarray datasets have proper dimensions and dtypes
MS structure exists - The main table write creates the MS directory structure successfully
Minimal test case fails - Even with the simplest possible subtable, the error occurs

Workaround
Currently, I can only write main tables successfully. Subtable writing is completely blocked by this issue.

Questions
1. Is this a known issue with the current version of dask-ms?
2. Are there any specific requirements for subtable creation that I might be missing?
3. Is there a different approach I should use for creating subtables?

Additional Context:
This issue is preventing me from implementing a complete MS creation workflow where I need to write both main tables and subtables. The main table functionality works perfectly, but subtable creation appears to have a fundamental issue with row allocation in the casacore table system.


Python 3.12.11
dask-ms version 0.2.21
OS: Manjaro OS

=== ISSUE #347 | dask-ms seems to ignore per-xds chunking when grouping by `__row__` | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"This could probably be improved in `dask-ms` but is it necessary to supply chunking in the `group_cols=\"__row__\"` case?","createdAt":"2025-06-03T15:22:28Z","id":"IC_kwDOBh8_I86u_ud1","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/347#issuecomment-2935940981","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"I think that in this case it is to ensure that the chunking on the datasets matches that of the frequency axis of the actual data. So the `__row__` entry in the chunking dictionary is almost certainly superfluous, but it shouldn't cause any harm. The real issue is that the frequency with heterogenous SPWs, the above fails. I dislike heterogeneous SPWs as much as the next person, hence asking if this is something that should be supported.","createdAt":"2025-06-03T15:32:00Z","id":"IC_kwDOBh8_I86u_9SX","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/347#issuecomment-2936001687","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":">  So the __row__ entry in the chunking dictionary is almost certainly superfluous, but it shouldn't cause any harm.\n\nAgreed, I suspect I've always historically been using a pattern like:\n\n```\ntable = dask.compute(xds_from_table(\"blah.ms::SPECTRAL_WINDOW\"), group_cols=\"__row__\")\n```\n\nand then manually chunking the resulting numpy arrays, but this shouldn't surprise developers.","createdAt":"2025-06-04T07:50:23Z","id":"IC_kwDOBh8_I86vLWED","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/347#issuecomment-2938986755","viewerDidAuthor":false}] | created: 2025-06-03T14:25:55Z ===
I encountered this while attempting reproduce a different (but possibly related) bug.

Doing the following on an ms with 3 SPWs, containing 11, 4 and 17 channels respectively:
```python
from daskms import xds_from_storage_table

xds = xds_from_storage_table(
    "path/to/ms::SPECTRAL_WINDOW",
    group_cols="__row__",
    chunks=[{'__row__': 1, 'chan': (4, 4, 3)}, {'__row__': 1, 'chan': (4,)}, {'__row__': 1, 'chan': (4, 4, 4, 4, 1)}]
)
```
fails with the following traceback:

![Image](https://github.com/user-attachments/assets/da3f3fc4-6cb6-4cbc-bd01-5a69eb8b395a)

This seems to be due to [this code](https://github.com/ratt-ru/dask-ms/blob/e098821925585b46b30176791ceb1612545c159e/daskms/reads.py#L339-L366). Note that it always takes the first element of `self.chunks` which means the tables grouped on only `__row__` do not honour the chunks option correctly.

Is this behaviour that should be supported? I can make the tiny test dataset I used available if required.

=== ISSUE #346 | w-projection and w-ordering pre-processing | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @miguelcarcamov. This is a complex distributed operation. See\n\n- https://github.com/dask/dask/issues/4368\n\nfor further details on why.\n\nOut of interest, what happens when you use `UVW[:,2]` in `index_cols` in  [xds_from_ms](https://dask-ms.readthedocs.io/en/latest/api.html#daskms.xds_from_ms)? It might \"just\" work, but if not I could have a look at the feasibility making it do so.","createdAt":"2025-06-02T09:55:21Z","id":"IC_kwDOBh8_I86uoL04","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/346#issuecomment-2929769784","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Hi @sjperkins. Thank you for your answer. When use `UVW[:,2]` in index_cols, my reading line is:\n```python\nms = xds_from_ms(\n            self.input_name,\n            taql_where=\"!FLAG_ROW\",\n            group_cols=[\"FIELD_ID\", \"DATA_DESC_ID\"],\n            index_cols=[\"SCAN_NUMBER\", \"TIME\", \"ANTENNA1\", \"ANTENNA2\", \"UVW[:,2]\"],\n            chunks=c\n```\nand I get this:\n\n```python\n---------------------------------------------------------------------------\nKeyError                                  Traceback (most recent call last)\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:164, in TableProxyMetaClass.__call__(cls, *args, **kwargs)\n    [163](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:163) try:\n--> [164](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:164)     return _table_cache[key]\n    [165](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:165) except KeyError:\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/weakref.py:136, in WeakValueDictionary.__getitem__(self, key)\n    [135](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/weakref.py:135)     self._commit_removals()\n--> [136](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/weakref.py:136) o = self.data[key]()\n    [137](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/weakref.py:137) if o is None:\n\nKeyError: 4253198375640035878\n\nDuring handling of the above exception, another exception occurred:\n\nRuntimeError                              Traceback (most recent call last)\nCell In[7], [line 1](vscode-notebook-cell:?execution_count=7&line=1)\n----> [1](vscode-notebook-cell:?execution_count=7&line=1) dataset = x.read(filter_flag_column=False, calculate_psf=True)\n\nFile /hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:178, in DaskMS.read(self, read_flagged_data, filter_flag_column, calculate_psf, taql_query, chunks)\n    [174](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:174) pol_obj = Polarization(dataset=pols)\n    [176](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:176) # Reading MS main table indexing columns such as SCAN_NUMBER, TIME, ANTENNA1, ANTENNA2\n    [177](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:177) # This returns a list of measurement sets partitioned by FIELDS and SPWS\n--> [178](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:178) ms = xds_from_ms(\n    [179](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:179)     self.input_name,\n    [180](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:180)     taql_where=taql_query_read,\n    [181](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:181)     group_cols=[\"FIELD_ID\", \"DATA_DESC_ID\"],\n    [182](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:182)     index_cols=[\"SCAN_NUMBER\", \"TIME\", \"ANTENNA1\", \"ANTENNA2\", \"UVW[:,2]\"],\n    [183](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:183)     chunks=chunks_read\n    [184](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:184) )\n    [186](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:186) ms_list = []\n    [187](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/src/pyralysis/io/daskms.py:187) for ms_id, msds in enumerate(ms):\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:330, in xds_from_ms(ms, columns, index_cols, group_cols, **kwargs)\n    [326](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:326) group_cols = promote_columns(group_cols, _DEFAULT_GROUP_COLUMNS)\n    [328](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:328) kwargs.setdefault(\"table_schema\", \"MS\")\n--> [330](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:330) return xds_from_table(\n    [331](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:331)     ms,\n    [332](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:332)     columns=columns,\n    [333](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:333)     index_cols=index_cols,\n    [334](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:334)     group_cols=group_cols,\n    [335](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:335)     context=\"ms\",\n    [336](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:336)     **kwargs,\n    [337](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:337) )\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:293, in xds_from_table(table_name, columns, index_cols, group_cols, **kwargs)\n    [288](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:288) index_cols = promote_columns(index_cols, [])\n    [289](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:289) group_cols = promote_columns(group_cols, [])\n    [291](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:291) return DatasetFactory(\n    [292](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:292)     table_name, columns, group_cols, index_cols, **kwargs\n--> [293](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/dask_ms.py:293) ).datasets()\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:520, in DatasetFactory.datasets(self)\n    [512](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:512)     datasets = [\n    [513](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:513)         self._single_dataset(\n    [514](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:514)             table_proxy, (row_blocks[r], run_blocks[r]), exemplar_row=er\n    [515](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:515)         )\n    [516](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:516)         for r, er in enumerate(np_sorted_row)\n    [517](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:517)     ]\n    [518](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:518) # Grouping column case\n    [519](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:519) else:\n--> [520](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:520)     order_taql = group_ordering_taql(\n    [521](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:521)         table_proxy, self.group_cols, self.index_cols, self.taql_where\n    [522](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:522)     )\n    [523](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:523)     orders = group_row_ordering(\n    [524](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:524)         order_taql, self.group_cols, self.index_cols, self.chunks\n    [525](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:525)     )\n    [527](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/reads.py:527)     groups = [order_taql.getcol(g).result() for g in self.group_cols]\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:185, in group_ordering_taql(table_proxy, group_cols, index_cols, taql_where)\n    [181](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:181)         taql_where = f\"\\nWHERE\\n\\t{taql_where}\"\n    [183](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:183)     query = f\"{select}\\nFROM\\n\\t$1{taql_where}\\n{groupby}\"\n--> [185](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:185)     return TableProxy(\n    [186](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:186)         taql_factory,\n    [187](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:187)         query,\n    [188](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:188)         tables=[table_proxy],\n    [189](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:189)         __executor_key__=table_proxy.executor_key,\n    [190](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:190)     )\n    [192](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/ordering.py:192) raise RuntimeError(\"Invalid condition in group_ordering_taql\")\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:166, in TableProxyMetaClass.__call__(cls, *args, **kwargs)\n    [164](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:164)     return _table_cache[key]\n    [165](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:165) except KeyError:\n--> [166](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:166)     instance = type.__call__(cls, *args, **kwargs)\n    [167](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:167)     instance._hashvalue = key\n    [168](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:168)     _table_cache[key] = instance\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:347, in TableProxy.__init__(self, factory, *args, **kwargs)\n    [345](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:345) # Private, should be inaccessible\n    [346](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:346) self._write = False\n--> [347](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:347) self._writeable = ex.impl.submit(_iswriteable, table).result()\n    [349](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:349) should_be_writeable = not kwargs.get(\"readonly\", True)\n    [351](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:351) if self._writeable is False and should_be_writeable:\n    [352](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:352)     # NOTE(sjperkins)\n    [353](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:353)     # This seems to happen if you've opened a WSRT.MS with\n   (...)\n    [356](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:356)     # Solution is to open WSRT.MS/SUBTABLE to avoid the locking,\n    [357](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:357)     # which may introduce it's own set of issues\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:456, in Future.result(self, timeout)\n    [454](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:454)     raise CancelledError()\n    [455](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:455) elif self._state == FINISHED:\n--> [456](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:456)     return self.__get_result()\n    [457](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:457) else:\n    [458](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:458)     raise TimeoutError()\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:401, in Future.__get_result(self)\n    [399](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:399) if self._exception:\n    [400](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:400)     try:\n--> [401](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:401)         raise self._exception\n    [402](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:402)     finally:\n    [403](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:403)         # Break a reference cycle with the exception in self._exception\n    [404](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:404)         self = None\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:59, in _WorkItem.run(self)\n     [56](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:56)     return\n     [58](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:58) try:\n---> [59](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:59)     result = self.fn(*self.args, **self.kwargs)\n     [60](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:60) except BaseException as exc:\n     [61](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:61)     self.future.set_exception(exc)\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:243, in _iswriteable(table_future)\n    [242](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:242) def _iswriteable(table_future):\n--> [243](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:243)     return table_future.result().iswritable()\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:449, in Future.result(self, timeout)\n    [447](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:447)     raise CancelledError()\n    [448](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:448) elif self._state == FINISHED:\n--> [449](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:449)     return self.__get_result()\n    [451](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:451) self._condition.wait(timeout)\n    [453](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:453) if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:401, in Future.__get_result(self)\n    [399](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:399) if self._exception:\n    [400](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:400)     try:\n--> [401](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:401)         raise self._exception\n    [402](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:402)     finally:\n    [403](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:403)         # Break a reference cycle with the exception in self._exception\n    [404](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/_base.py:404)         self = None\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:59, in _WorkItem.run(self)\n     [56](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:56)     return\n     [58](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:58) try:\n---> [59](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:59)     result = self.fn(*self.args, **self.kwargs)\n     [60](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:60) except BaseException as exc:\n     [61](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/concurrent/futures/thread.py:61)     self.future.set_exception(exc)\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:196, in taql_factory(query, style, tables, readonly)\n    [193](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:193)     t.lock(write=ro is False)\n    [195](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:195) try:\n--> [196](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:196)     return ct.taql(query, style=style, tables=tables)\n    [197](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:197) finally:\n    [198](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/daskms/table_proxy.py:198)     for t in tables:\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:156, in taql(command, style, tables, globals, locals)\n    [154](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:154) if style:\n    [155](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:155)     cmd = 'using style ' + style + ' ' + cmd\n--> [156](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:156) tab = table(cmd, tabs, _oper=2)\n    [157](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:157) result = tab._getcalcresult()\n    [158](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:158) # If result is empty, it was a normal TaQL command resulting in a table.\n    [159](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:159) # Otherwise it is a record containing calc values.\n\nFile ~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:331, in table.__init__(self, tablename, tabledesc, nrow, readonly, lockoptions, ack, dminfo, endian, memorytable, concatsubtables, _columnnames, _datatypes, _oper, _delete)\n    [326](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:326)     Table.__init__(self, tabname, tabledesc, nrow, readonly,\n    [327](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:327)                    lockoptions, ack, dminfo, endian, memorytable,\n    [328](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:328)                    _columnnames, _datatypes)\n    [329](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:329) elif _oper == 2:\n    [330](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:330)     # This is the query or calc constructor.\n--> [331](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:331)     Table.__init__(self, tablename, tabledesc)\n    [332](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:332)     if len(self._getcalcresult()) != 0:\n    [333](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:333)         # Do not make row object for a calc result\n    [334](https://file+.vscode-resource.vscode-cdn.net/hdd_data/repositories/pyralysis/examples/~/micromamba/envs/pyralysis-env/lib/python3.12/site-packages/casacore/tables/table.py:334)         return\n\nRuntimeError: Error in TaQL command: using style Python SELECT\n\tFIELD_ID,\n\tDATA_DESC_ID,\n\tGAGGR(SCAN_NUMBER) as GROUP_SCAN_NUMBER,\n\tGAGGR(TIME) as GROUP_TIME,\n\tGAGGR(ANTENNA1) as GROUP_ANTENNA1,\n\tGAGGR(ANTENNA2) as GROUP_ANTENNA2,\n\tGAGGR(UVW[:,2]) as GROUP_UVW[:,2],\n\tGROWID() AS __tablerow__,\n\tGCOUNT() as __tablerows__,\n\tGROWID()[0] as __firstrow__\nFROM\n\t$1\nWHERE\n\t!FLAG_ROW\nGROUPBY\n\tFIELD_ID,\n\tDATA_DESC_ID\n  parse error at or near position 207 ','\n```\n\nThe version of dask-ms is 0.2.21\n\nCheers,\nMiguel","createdAt":"2025-06-02T14:51:45Z","id":"IC_kwDOBh8_I86utTiy","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/346#issuecomment-2931112114","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Thanks, that's helpful @miguelcarcamov. I need to upgrade `dask-ms`  in the medium term. I'll try roll this into that effort, but I don't think I'll get to it soon unfortunately.","createdAt":"2025-06-03T07:39:49Z","id":"IC_kwDOBh8_I86u4Eki","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/346#issuecomment-2933934370","viewerDidAuthor":false}] | created: 2025-05-31T00:48:17Z ===
Hi,

I'm implementing w-projection in dask-ms but given that arrays are dask instances. It's been difficult to find a way to pre-processing and re-order the data by 'w' -> uvw[:,2]. I know that it is possible to do this in TaQL, but it is possible to do this from dask-ms? And if not, how can I do this in dask? The main problem is that since data is chunked, that won't give a global ordering of the data in one sub-ms (this is the way I named the sub-parts of the ms file). One way to solve that is rechunking to a single chunk and then sorting, the problem with that is that is not feasible for large arrays.

Any thoughts?

Cheers,
Miguel

=== ISSUE #314 | Capitalised ROWID breaks xarray lowercase coordinate naming convention | labels: bug | comments: [] | created: 2024-03-20T11:16:08Z ===
* dask-ms version: 0.20.0
* Python version: 3.9
* Operating System: Ubuntu

### Description

dask-ms chose to capitalise ROWID, a dask coordinate array. By convention, xarray treats uppercase zarr arrays as data variables and lowercase zarr arrays as coordinates. Thus, when `xarray.open_zarr` is called, `ROWID` is loaded as a data variable.



=== ISSUE #295 | Test suite fails on pyarrow 13.0.0 due to new dependency on Pandas | labels:  | comments: [] | created: 2023-10-27T07:13:18Z ===
* dask-ms version: 0.2.18
* Python version: 3.10
* Operating System: Ubuntu 20.04

A dependency on pandas has been introduced in pyarrow 13.0.0 which caused the test suite to fail

- https://github.com/apache/arrow/issues/38428

=== ISSUE #293 | Performance issue in bispectrum method and gradient | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @Hackasteroid142. Thanks for the very detailed issue. I think it may be an easy fix. Try changing the following in your blockwise call: `adjust_chunks={\"t\": tuple(utime_size)}`.","createdAt":"2023-10-09T06:01:02Z","id":"IC_kwDOBh8_I85oc1E8","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1752387900","viewerDidAuthor":false},{"author":{"login":"Hackasteroid142"},"authorAssociation":"NONE","body":"Hi @sjperkins, thank you for replying. I followed your advice, but unfortunately, it didn't resolve the issue. However, another error has become more frequent than the one I mentioned before, and it is related to adjust_chunks. Here are the details of that error:\r\n```\r\nDimension 1 has 56 blocks, adjust_chunks specified with 1 blocks\r\n```\r\nThis error appears when i set a size different of -1 for the chunks when i read the dataset. Do you think there is a error in my implementation? or something is missing?\r\n","createdAt":"2023-10-10T02:31:17Z","id":"IC_kwDOBh8_I85oj2Hq","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1754227178","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Hi @Hackasteroid142. The following code should work. Note that I am using `NaN` chunk sizes as we do not know the number of unique times in each chunk until the graph executes. There is another way of doing this if you need those chunks to be of known size - let me know if that fits your use-case. Regarding memory usage, the bispectrum result is large - if you hold them all in memory (as is done by calling compute on `results` below), it will likely cause memory issues on larger datasets. The solution will be implementation specific, but typically involves either writing results to disk so that there is no need to hang onto the result in memory, or doing further processing on the chunks such that they become smaller/unnecessary to hold in memory. \r\n\r\n```python\r\nimport dask.array as da\r\nimport numpy as np\r\nfrom numba import njit\r\nfrom daskms import xds_from_ms\r\nimport itertools\r\n\r\n\r\n@njit(cache=True, nogil=True)\r\ndef get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):\r\n    cnt = np.zeros(data_shape, dtype=np.int8)\r\n    data_bis = np.ones(data_shape, dtype=data.dtype)\r\n\r\n    for row in range(n_row):\r\n\r\n        ut = utime_inv[row]\r\n\r\n        a1 = ant1[row]\r\n        a2 = ant2[row]\r\n\r\n        for ic, c in enumerate(comb):\r\n            if (a1 == c[0]) and (a2 == c[1]):\r\n                data_bis[ic, ut, 0] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[1]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 1] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[0]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 2] = data[row].conjugate()\r\n                cnt[ic, ut, :] += 1\r\n\r\n    return data_bis, cnt\r\n\r\n\r\ndef get_bispectrum(data, ant1, ant2, comb, time, type):\r\n\r\n    utime, utime_inv = np.unique(time, return_inverse=True)\r\n    n_utime = utime.size\r\n    n_comb = len(comb)\r\n\r\n    n_row, n_chan, n_corr = data.shape\r\n    shape_data = (n_comb, n_utime, 3, n_chan, n_corr)\r\n\r\n    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)\r\n\r\n    bis[cnt != 3] = 0\r\n\r\n    return bis\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    input_name = \"path/to/ms\"\r\n\r\n    xdsl = xds_from_ms(\r\n        input_name,\r\n        group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n        index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n        chunks={'row': 10000}\r\n    )\r\n    n_ant = 28\r\n    antenna_reference = 0\r\n    comb = itertools.combinations(range(n_ant), 3)\r\n    filter_comb = np.array([i for i in comb if antenna_reference in i])\r\n\r\n    results = []\r\n\r\n    for xds in xdsl:\r\n        bis = da.blockwise(\r\n            get_bispectrum,\r\n            ('triangle', 't', 'p', 'f', 'c'),\r\n            xds.DATA.data,\r\n            ('t', 'f', 'c'),\r\n            xds.ANTENNA1.data, ('t'),\r\n            xds.ANTENNA2.data, ('t'),\r\n            filter_comb,\r\n            None,\r\n            xds.TIME.data, ('t'),\r\n            type,\r\n            None,\r\n            align_arrays=False,\r\n            adjust_chunks={'t': (np.nan,)*xds.DATA.data.numblocks[0]},\r\n            new_axes={\r\n                'triangle': len(filter_comb),\r\n                'p': 3\r\n            },\r\n            dtype=xds.DATA.data.dtype\r\n        )\r\n        results.append(bis)\r\n\r\n    results = da.compute(results)\r\n\r\n```","createdAt":"2023-10-10T07:31:28Z","id":"IC_kwDOBh8_I85olMoB","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1754581505","viewerDidAuthor":false},{"author":{"login":"Hackasteroid142"},"authorAssociation":"NONE","body":"Hi @sjperkins, I apologize for the delay in my response. I attempted the solution you provided, but as you mentioned, I need to be aware of the chunk sizes. In later operations, when I use `nan` values, it results in an error. I also experimented with `compute_chunk_sizes()` to overcome the error,  but it significantly slowed down the operations compared to the normal execution time.\r\n\r\nAlso, I attempted to modify your solution slightly by using `(1, ) * xds.DATA.data.numblocks[0]`, but in subsequent operations, this approach led to errors such as\r\n\r\n```\r\nnon-broadcastable output operand with shape (6903,1,3,1,2) doesn't match the broadcast shape (6903,3,3,1,2)\r\n```","createdAt":"2023-10-13T03:09:23Z","id":"IC_kwDOBh8_I85o8hYI","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1760695816","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"The following will make sure that the chunks on the bispectrum are correct. However, this will not guarantee that all rows associated with a single time will be in the same chunk. That is also possible but requires a fair amount of additional code. You can see an example of the approach [here](https://github.com/ratt-ru/QuartiCal/blob/fe1a23d96828b9eaa7200dff39cc5fe051b792a3/quartical/data_handling/chunking.py#L145).\r\n\r\n```python\r\nimport dask.array as da\r\nimport numpy as np\r\nfrom numba import njit\r\nfrom daskms import xds_from_ms\r\nimport itertools\r\n\r\n\r\n@njit(cache=True, nogil=True)\r\ndef get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):\r\n    cnt = np.zeros(data_shape, dtype=np.int8)\r\n    data_bis = np.ones(data_shape, dtype=data.dtype)\r\n\r\n    for row in range(n_row):\r\n\r\n        ut = utime_inv[row]\r\n\r\n        a1 = ant1[row]\r\n        a2 = ant2[row]\r\n\r\n        for ic, c in enumerate(comb):\r\n            if (a1 == c[0]) and (a2 == c[1]):\r\n                data_bis[ic, ut, 0] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[1]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 1] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[0]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 2] = data[row].conjugate()\r\n                cnt[ic, ut, :] += 1\r\n\r\n    return data_bis, cnt\r\n\r\n\r\ndef get_bispectrum(data, ant1, ant2, comb, time, type):\r\n\r\n    utime, utime_inv = np.unique(time, return_inverse=True)\r\n    n_utime = utime.size\r\n    n_comb = len(comb)\r\n\r\n    n_row, n_chan, n_corr = data.shape\r\n    shape_data = (n_comb, n_utime, 3, n_chan, n_corr)\r\n\r\n    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)\r\n\r\n    bis[cnt != 3] = 0\r\n\r\n    return bis\r\n\r\n\r\ndef compute_utime_chunks(xdsl):\r\n\r\n    utime_chunks = []\r\n\r\n    for xds in xdsl:\r\n        time = xds.TIME.data\r\n        utimes_per_chunk = da.blockwise(\r\n            lambda t: np.array(len(np.unique(t))), \"t\",\r\n            time, \"t\",\r\n            adjust_chunks={'t': (np.nan,)*time.numblocks[0]}\r\n        )\r\n        utime_chunks.append(utimes_per_chunk)\r\n\r\n    return [tuple(utc) for utc in da.compute(utime_chunks)[0]]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    input_name = \"path/to/ms\"\r\n\r\n    xdsl = xds_from_ms(\r\n        input_name,\r\n        group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n        index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n        chunks={'row': 10000}\r\n    )\r\n    n_ant = 28\r\n    antenna_reference = 0\r\n    comb = itertools.combinations(range(n_ant), 3)\r\n    filter_comb = np.array([i for i in comb if antenna_reference in i])\r\n\r\n    utime_chunks = compute_utime_chunks(xdsl)\r\n\r\n    results = []\r\n\r\n    for xds, utc in zip(xdsl, utime_chunks):\r\n        bis = da.blockwise(\r\n            get_bispectrum,\r\n            ('triangle', 't', 'p', 'f', 'c'),\r\n            xds.DATA.data,\r\n            ('t', 'f', 'c'),\r\n            xds.ANTENNA1.data, ('t'),\r\n            xds.ANTENNA2.data, ('t'),\r\n            filter_comb,\r\n            None,\r\n            xds.TIME.data, ('t'),\r\n            type,\r\n            None,\r\n            align_arrays=False,\r\n            adjust_chunks={'t': utc},\r\n            new_axes={\r\n                'triangle': len(filter_comb),\r\n                'p': 3\r\n            },\r\n            dtype=xds.DATA.data.dtype\r\n        )\r\n        results.append(bis)\r\n\r\n    results = da.compute(results)\r\n```","createdAt":"2023-10-13T07:32:27Z","id":"IC_kwDOBh8_I85o92Xh","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1761043937","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"@Hackasteroid142 I took the liberty of adding the chunking functionality as it may be useful to other users. Here is the example, which now allows chunking by unique time.\r\n```python\r\nimport dask.array as da\r\nimport numpy as np\r\nfrom numba import njit\r\nfrom daskms import xds_from_ms\r\nimport itertools\r\n\r\n\r\n@njit(cache=True, nogil=True)\r\ndef get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):\r\n    cnt = np.zeros(data_shape, dtype=np.int8)\r\n    data_bis = np.ones(data_shape, dtype=data.dtype)\r\n\r\n    for row in range(n_row):\r\n\r\n        ut = utime_inv[row]\r\n\r\n        a1 = ant1[row]\r\n        a2 = ant2[row]\r\n\r\n        for ic, c in enumerate(comb):\r\n            if (a1 == c[0]) and (a2 == c[1]):\r\n                data_bis[ic, ut, 0] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[1]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 1] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[0]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 2] = data[row].conjugate()\r\n                cnt[ic, ut, :] += 1\r\n\r\n    return data_bis, cnt\r\n\r\n\r\ndef get_bispectrum(data, ant1, ant2, comb, time, type):\r\n\r\n    utime, utime_inv = np.unique(time, return_inverse=True)\r\n    n_utime = utime.size\r\n    n_comb = len(comb)\r\n\r\n    n_row, n_chan, n_corr = data.shape\r\n    shape_data = (n_comb, n_utime, 3, n_chan, n_corr)\r\n\r\n    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)\r\n\r\n    bis[cnt != 3] = 0\r\n\r\n    return bis\r\n\r\n\r\ndef utime_and_row_chunks(time, req_utime=1):\r\n    \"\"\"Internals of compute_utime_and_row_chunks.\"\"\"\r\n\r\n    utime, utime_counts = np.unique(time, return_counts=True)\r\n    n_utime = utime.size\r\n    req_utime = req_utime or n_utime  # Catch zero.\r\n\r\n    chunk_starts = np.arange(0, n_utime, req_utime)\r\n\r\n    utime_chunks = np.array(\r\n        [\r\n            req_utime if i + req_utime < n_utime else n_utime - i\r\n            for i in chunk_starts\r\n        ]\r\n    )\r\n\r\n    row_chunks = np.add.reduceat(utime_counts, chunk_starts)\r\n\r\n    return np.stack([utime_chunks, row_chunks], axis=0)\r\n\r\n\r\n\r\ndef compute_utime_and_row_chunks(indexing_xdsl, req_utime=1):\r\n    \"\"\"Figure out the chunking in unique time and row. Triggers compute.\"\"\"\r\n\r\n    chunking = []\r\n\r\n    for xds in indexing_xdsl:\r\n\r\n        chunking.append(\r\n            xds.TIME.data.map_blocks(\r\n                utime_and_row_chunks,\r\n                req_utime,\r\n                chunks=((2,), (np.nan,)),\r\n                new_axis=0,\r\n                dtype=int\r\n            )\r\n        )\r\n\r\n    result = da.compute(chunking)[0]\r\n\r\n    utime_chunks = [tuple(arr[0]) for arr in result]\r\n    row_chunks = [tuple(arr[1]) for arr in result]\r\n\r\n    return utime_chunks, row_chunks\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n    input_name = \"~/reductions/3C147/msdir/C147_unflagged.MS\"\r\n\r\n    # Set up TIME only datasets which we can use to establish chunking. Note\r\n    # that we use only a single chunk per dataset.\r\n    indexing_xdsl = xds_from_ms(\r\n        input_name,\r\n        group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n        index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n        columns=(\"TIME\",),\r\n        chunks={'row': -1}\r\n    )\r\n\r\n    # req_utime controls the number of unique times that you want in a\r\n    # single chunk. This triggers some early but very lightweight compute\r\n    # to figure out the required chunking - much cheaper than\r\n    # compute_chunk_sizes.\r\n    utime_chunks_list, row_chunks_list = compute_utime_and_row_chunks(\r\n        indexing_xdsl, req_utime=30\r\n    )\r\n\r\n    # Now that we know the desired chunking, load the data we want to\r\n    # manipulate with the required chunking.\r\n    xdsl = xds_from_ms(\r\n        input_name,\r\n        group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n        index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n        columns=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\", \"DATA\"),\r\n        chunks=[{'row': rcs} for rcs in row_chunks_list]\r\n    )\r\n\r\n    n_ant = 28\r\n    antenna_reference = 0\r\n    comb = itertools.combinations(range(n_ant), 3)\r\n    filter_comb = np.array([i for i in comb if antenna_reference in i])\r\n\r\n    results = []\r\n\r\n    for xds, utc in zip(xdsl, utime_chunks_list):\r\n        bis = da.blockwise(\r\n            get_bispectrum,\r\n            ('triangle', 't', 'p', 'f', 'c'),\r\n            xds.DATA.data,\r\n            ('t', 'f', 'c'),\r\n            xds.ANTENNA1.data, ('t'),\r\n            xds.ANTENNA2.data, ('t'),\r\n            filter_comb,\r\n            None,\r\n            xds.TIME.data, ('t'),\r\n            type,\r\n            None,\r\n            align_arrays=False,\r\n            adjust_chunks={'t': utc},\r\n            new_axes={\r\n                'triangle': len(filter_comb),\r\n                'p': 3\r\n            },\r\n            dtype=xds.DATA.data.dtype\r\n        )\r\n        results.append(bis)\r\n\r\n    results = da.compute(results)\r\n```","createdAt":"2023-10-13T08:17:46Z","id":"IC_kwDOBh8_I85o-E6B","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1761103489","viewerDidAuthor":false},{"author":{"login":"Hackasteroid142"},"authorAssociation":"NONE","body":"Thank you for the previous code; it was very helpful for working with different chunk sizes in the Bispectrum. However, I've been trying to use this to improve the performance of my Bispectrum method and the optimization method I'm working on. Despite implementing the code you provided, I haven't seen any improvement in time or memory usage. I'm working with an extract of the HD163296 dataset and a dirty image of this extract, which are available at this link: https://we.tl/t-R4nVGgd2vN. The image is used to calculate the model visibilities for the dataset.\r\n\r\nIn the optimization method, I use the gradient of the chi-square Bispectrum as shown in this [article](https://arxiv.org/pdf/1803.07088.pdf)  (Equation 3 of the appendix) by Andrew A. Chael et al. Based on this code and the dataset I mentioned earlier, is there something I should take into consideration? Is there any way to further optimize my code?\r\n\r\nAs background information, I conducted a small experiment to measure the time it takes to compute the gradient. It takes a few minutes to execute the gradient function thanks to Dask, but if I compute the result, it can take up to 2 days. Also, in the code, there is a class named \"Mask\" that aims to calculate only a portion of the image to improve execution time. It's like a matrix with zeros around it, representing the areas where calculations are not needed. I hope I have explained myself clearly, and the code is understandable. If you have any questions, I'd be happy to answer them.\r\n\r\n\r\n```python\r\nimport astropy.units as un\r\nimport dask.array as da\r\nimport numpy as np\r\nfrom numba import njit, prange    \r\n    \r\ndef gradient(dataset, mask):\r\n\r\n    if mask is None:\r\n        dchi2_1d = __gradient_no_mask(dataset)\r\n    else:\r\n        dchi2_1d = __gradient_mask(dataset, mask=mask)\r\n\r\n    _grad_value = gradient_image_reconstruction(dchi2_1d, mask)\r\n\r\n    return _grad_value\r\n\r\ndef gradient_image_reconstruction(image, mask):\r\n    # Array full with zeros to assign only valid indices with the values of the gradient\r\n    dchi2_1d = da.zeros((np.prod(image.data.shape), ), dtype=np.float32)\r\n    # Get ravel indices of the mask where its values are True\r\n    ravel_mask_idx = da.where(mask.data.data.ravel())[0]\r\n    ravel_mask_idx.compute_chunk_sizes()\r\n    # In the array, assign only valid indices (ravel_mask_idx) with the gradient\r\n    dchi2_1d[(ravel_mask_idx, )] = image\r\n    # Reshape gradient (transposed because indices are in F order)\r\n    image_2d = dchi2_1d.reshape_grad_value.shape).T\r\n    # Flip needed from fft\r\n    flipped = da.flip(image_2d, axis=[0, 1])\r\n    return flipped.rechunk(_grad_value.chunksize)\r\n\r\ndef __gradient_no_mask(dataset):\r\n    delta_x, delta_y = image.cellsize.to(un.rad).value\r\n\r\n    x_ind_2d, y_ind_2d, *z_ind_2d = da.indices(\r\n        image.data.data.shape, dtype=np.int32, chunks=image.data.data.chunksize\r\n    )\r\n\r\n    x_ind = x_ind_2d.ravel()\r\n    y_ind = y_ind_2d.ravel()\r\n\r\n    x_cell = __cell_index_delta(x_ind, delta_x, np.float32)\r\n    y_cell = __cell_index_delta(y_ind, delta_y, np.float32)\r\n\r\n    dchi2_1d = da.zeros_like(x_cell, dtype=np.float32, chunks=x_cell.chunks)\r\n    for i, ms in enumerate(dataset.ms_list):\r\n        dchi2_1d += __ms_gradient(ms, x_cell, y_cell, delta_x, delta_y)\r\n\r\n    return dchi2_1d\r\n\r\ndef __gradient_mask(dataset, mask):\r\n\r\n    delta_x, delta_y = image.cellsize.to(un.rad).value\r\n\r\n    x_ind, y_ind, *z_ind = mask.indices\r\n\r\n    x_cell = __cell_index_delta(x_ind, delta_x, np.float32)\r\n    y_cell = __cell_index_delta(y_ind, delta_y, np.float32)\r\n\r\n    dchi2_1d_masked = da.zeros_like(x_cell, dtype=np.float32, chunks=x_cell.chunks)\r\n    for i, ms in enumerate(dataset.ms_list):\r\n        dchi2_1d_masked += __ms_gradient(ms, x_cell, y_cell, delta_x, delta_y)\r\n\r\n    return dchi2_1d_masked\r\n\r\ndef __ms_gradient(ms, x_cell, y_cell, delta_x, delta_y, *, mask):\r\n    bis_obs = ms.visibilities.cal_data  # (ncomb, ntime, nchans, ncorrs)\r\n    bis_model = ms.visibilities.cal_model\r\n    bis_weight = ms.visibilities.cal_weight\r\n\r\n    bis_r = bis_obs - bis_model  # Calculando visibilidad residuo\r\n    vis = ms.visibilities.bis_data.data  # (ncomb, ntime, nant, nchans, ncorrs)\r\n    uvw = ms.visibilities.bis_uvw.data.astype(np.float32) * un.m  # (ncomb, ntime, nant, uvw)\r\n\r\n    pol_id = ms.polarization_id\r\n    corr_names = dataset.polarization.corrs_string[pol_id]\r\n    corr_idx = [x in _corr for x in corr_names]\r\n    bis_weight = bis_weight[:, :, :, corr_idx]  # Filter by correlation\r\n    bis_r = bis_r[:, :, :, corr_idx]  # Filter by correlation\r\n\r\n    spw_id = ms.spw_id\r\n    nchans = dataset.spws.nchans[spw_id]\r\n    chans = (dataset.spws.dataset[spw_id].CHAN_FREQ.data.squeeze(axis=0) *\r\n                un.Hz).rechunk(bis_obs.chunksize[-2])\r\n\r\n    uvw_lambdas = _uvw_lambdas(uvw, chans, nchans)\r\n\r\n    uv_lambdas = uvw_lambdas[:, :, :, :, :2]\r\n    uv_lambdas = uv_lambdas.map_blocks(\r\n        lambda x: x.value if isinstance(x, un.Quantity) else x, dtype=np.float32\r\n    )\r\n\r\n    phase_dirs_x = (image.data.shape[0] // 2) * delta_x\r\n    phase_dirs_y = (image.data.shape[1] // 2) * delta_y\r\n\r\n    x = x_cell - np.float32(phase_dirs_x)\r\n    y = y_cell - np.float32(phase_dirs_y)\r\n\r\n    chans = chans.map_blocks(lambda x: x.value if isinstance(x, un.Quantity) else x)\r\n    beam = __primary_beam(\r\n        chans,\r\n        image.data.shape,\r\n        chunks=mask.data.chunks if mask is not None else image.data.data.chunksize\r\n    )\r\n\r\n    return _array_gradient(\r\n        x, y, uv_lambdas, bis_weight, vis, bis_r, beam, bis_model, mask=mask\r\n    )\r\n\r\ndef _uvw_lambdas(uvw, chans, nchans):\r\n\r\n    chans_broadcast = chans[np.newaxis, :, np.newaxis]\r\n    uvw_broadcast = da.repeat(uvw[:, :, :, np.newaxis, :], nchans, axis=3)\r\n    uvw_lambdas = array_unit_conversion(\r\n        array=uvw_broadcast,\r\n        unit=un.lambdas,\r\n        equivalencies=lambdas_equivalencies(restfreq=chans_broadcast),\r\n    )\r\n    return uvw_lambdas\r\n\r\ndef _array_gradient(x, y, uv, w, vis, vr, pb, bm, *, mask):\r\n\r\n    data_br = da.blockwise(\r\n        _block_gradient,\r\n        (\"ncomb\", \"chan\", \"corr\", \"idx\"),\r\n        x,\r\n        (\"idx\", ),\r\n        y,\r\n        (\"idx\", ),\r\n        uv,\r\n        (\"ncomb\", \"nutime\", \"nant\", \"chan\", \"corr\"),\r\n        w,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        vis,\r\n        (\"ncomb\", \"nutime\", \"nant\", \"chan\", \"corr\"),\r\n        vr,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        bm,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        adjust_chunks={\r\n            \"ncomb\": 1,\r\n            \"corr\": 1\r\n        },\r\n        dtype=np.float64,\r\n    )\r\n\r\n    data = data_br.sum(axis=(0, 2))\r\n\r\n    if mask is not None:\r\n        # Broadcast mask to match the shape of the PB, and obtain the masked primary beam values\r\n        # via bool indexing\r\n        broadcasted_mask = da.broadcast_to(mask.data.data, pb.shape)\r\n        # Get the Primary Beam masked values\r\n        pb_fitted = pb[broadcasted_mask]\r\n        pb_fitted.compute_chunk_sizes()\r\n    else:\r\n        pb_fitted = pb  # If there is no mask, there is no need to filter the primary beam\r\n\r\n    # Reshape to 2-d where the second dim is the cell idx and the first dim is the channel\r\n    # (frequency) dim\r\n    pb_2d = pb_fitted.reshape((-1, x.shape[0]))\r\n\r\n    data = da.einsum('in,in->n', data, pb_2d)\r\n\r\n    return data\r\n\r\ndef _block_gradient(x, y, uv, w, vis, vr, bm):\r\n    uv = uv[0][0].astype(np.float64)\r\n    dchi2_broad = _ms_memory_gradient(x, y, uv, w[0], vis[0][0], vr[0], bm[0])\r\n    return dchi2_broad[None, :, None, :]\r\n\r\n@staticmethod\r\n@njit(nogil=True, cache=True, parallel=True)\r\ndef _ms_memory_gradient(x, y, uv, w, vis, vr, bm):\r\n    nidx = x.shape[0]\r\n    out_dtype = vis.real.dtype\r\n\r\n    ncomb, utime, nant, nchan, ncorr = vis.shape\r\n\r\n    ms_gradient = np.zeros((nchan, nidx), dtype=out_dtype)\r\n    for i in prange(nidx):\r\n        for c in range(ncomb):\r\n            for t in range(utime):\r\n                for a in range(nant):\r\n                    for f in range(nchan):\r\n                        u, v = uv[c, t, a, f]\r\n                        uv_r = u * x[i] + v * y[i]\r\n                        uv_r *= 2 * np.pi * 1j\r\n                        a_ij = np.exp(uv_r)\r\n\r\n                        for r in range(ncorr):\r\n                            vm = vis[c, t, a, f, r].conjugate()\r\n                            ed = a_ij / vm if vm != 0 else 0\r\n\r\n                            i_sum = vr[c, t, f, r] * bm[c, t, f, r].conjugate() * ed\r\n\r\n                            s_sum = -w[c, t, f, r] * i_sum.real\r\n\r\n                            data = s_sum / ncomb\r\n\r\n                            ms_gradient[f, i] += data\r\n    return ms_gradient\r\n\r\ndef __cell_index_delta(index_array, delta, dtype=np.float32):\r\n    \"\"\"\r\n    Scale an array by a delta, so that each cell/pixel has the increment in radians specified\r\n    by delta.\r\n    \"\"\"\r\n    return (index_array * delta).astype(dtype)\r\n\r\ndef __primary_beam(chans, shape, antenna=np.array([0]), chunks=\"auto\"):\r\n    \"\"\"\r\n    Get the primary beam image for every frequency.\r\n    \"\"\"\r\n    beam = dataset.antenna.primary_beam.beam(\r\n        chans, shape, antenna=antenna, imchunks=chunks\r\n    )\r\n    beam = beam[0].astype(np.float32)  # temporal indexing\r\n    return beam\r\n\r\ninput_name = \"/home/datasets/ms_name.ms\"\r\n\r\nms = xds_from_ms(\r\n            input_name,\r\n            group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n            index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n            chunks={'row': 1500}\r\n        )\r\n\r\nmask = Mask()\r\n\r\nres = gradient(ms, mask)\r\n\r\n```\r\n\r\n","createdAt":"2023-10-18T02:25:27Z","id":"IC_kwDOBh8_I85pWhU5","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1767511353","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Hi @Hackasteroid142! This problem is now beginning to enter the more general territory of optimising dask code. Doing so requires in depth understanding of dask graphs (https://docs.dask.org/en/latest/graphs.html). A good starting point is to inspect the graph (https://docs.dask.org/en/stable/graphviz.html). This can show you whether your implementation contains problematic many-to-many mappings which dask is known to struggle with. \r\n\r\nRegarding performance, be sure to remember that dask does few/no computations until `compute` is called i.e. graph construction should be fast. Most performance problems will manifest after calling compute.\r\n\r\nIn general, while it is useful to see your code, I would encourage you to post code which can be run. This makes it much easier for us to provide useful feedback. As it stands, I cannot give you more precise advice.   ","createdAt":"2023-10-18T06:50:54Z","id":"IC_kwDOBh8_I85pXj6z","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1767784115","viewerDidAuthor":false},{"author":{"login":"Hackasteroid142"},"authorAssociation":"NONE","body":"Hello, I've been reviewing what you advised me, but I haven't achieved good results. I still have a very high runtime. As you instructed, here's a functional code that includes the chi-squared bispectrum, and I've also added the necessary components to calculate the bispectrum and the code you give me for the chunks. Any advice or help to improve my code would be greatly appreciated. If there's any issue with the code, I'll be attentive to help.\r\n\r\n\r\n```python\r\nfrom daskms import xds_from_ms\r\nfrom numba import njit, prange \r\nimport astropy.units as un\r\nimport dask.array as da\r\nimport numpy as np\r\nimport itertools\r\n\r\ndef gradient(dataset, imageshape):\r\n    delta_x, delta_y = [-2.42406841e-08,  2.42406841e-08]\r\n    x_ind_2d, y_ind_2d, *z_ind_2d = da.indices(\r\n            imageshape, dtype=np.int32\r\n    )\r\n\r\n    x_ind = x_ind_2d.ravel()\r\n    y_ind = y_ind_2d.ravel()\r\n\r\n    x_cell = x_ind * delta_x\r\n    y_cell = y_ind * delta_y\r\n\r\n    grad = da.zeros_like(x_cell, dtype=np.float32)\r\n    for i, ms in enumerate(dataset):\r\n        grad += ms_gradient(ms, x_cell, y_cell, delta_x, delta_y, imageshape)\r\n\r\n    grad_2d = grad.reshape(imageshape).T\r\n    image = da.flip(grad_2d, axis=[0, 1])\r\n    return image\r\n\r\ndef ms_gradient(ms, x_cell, y_cell, delta_x, delta_y, imageshape):\r\n    bis_obs = ms.CAL_DATA.data  # (ncomb, ntime, nchans, ncorrs)\r\n    bis_model = ms.CAL_MODEL.data\r\n    bis_weight = ms.CAL_WEIGHT.data\r\n\r\n    bis_r = bis_obs - bis_model \r\n    vis = ms.BIS_DATA.data  # (ncomb, ntime, nant, nchans, ncorrs)\r\n    uvw = ms.BIS_UVW.data.astype(np.float32) * un.m  # (ncomb, ntime, nant, uvw)\r\n\r\n    nchans = ms.DATA.shape[1]\r\n    uvw_lambdas = da.repeat(uvw[:, :, :, np.newaxis, :], nchans, axis=3)\r\n\r\n    uv_lambdas = uvw_lambdas[:, :, :, :, :2]\r\n    uv_lambdas = uv_lambdas.map_blocks(\r\n        lambda x: x.value if isinstance(x, un.Quantity) else x, dtype=np.float32\r\n    )\r\n\r\n    phase_dirs_x = (imageshape[0] // 2) * delta_x\r\n    phase_dirs_y = (imageshape[1] // 2) * delta_y\r\n\r\n    x = x_cell - np.float32(phase_dirs_x)\r\n    y = y_cell - np.float32(phase_dirs_y)\r\n\r\n   \r\n    data_br = da.blockwise(\r\n        _block_gradient,\r\n        (\"ncomb\", \"chan\", \"corr\", \"idx\"),\r\n        x,\r\n        (\"idx\", ),\r\n        y,\r\n        (\"idx\", ),\r\n        uv_lambdas,\r\n        (\"ncomb\", \"nutime\", \"nant\", \"chan\", \"corr\"),\r\n        bis_weight,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        vis,\r\n        (\"ncomb\", \"nutime\", \"nant\", \"chan\", \"corr\"),\r\n        bis_r,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        bis_model,\r\n        (\"ncomb\", \"nutime\", \"chan\", \"corr\"),\r\n        dtype=np.float64,\r\n    )\r\n\r\n    data = data_br.sum(axis=(0, 2))\r\n\r\n    pb = da.ones_like(data)\r\n\r\n    data = da.einsum('in,in->n', data, pb)\r\n\r\n    return data\r\n\r\ndef _block_gradient(x, y, uv, w, vis, vr, bm):\r\n    uv = uv[0][0].astype(np.float64)\r\n    dchi2_broad = _ms_memory_gradient(x, y, uv, w[0], vis[0][0], vr[0], bm[0])\r\n    return dchi2_broad[None, :, None, :]\r\n\r\n@staticmethod\r\n@njit(nogil=True, cache=True, parallel=True)\r\ndef _ms_memory_gradient(x, y, uv, w, vis, vr, bm):\r\n    nidx = x.shape[0]\r\n    out_dtype = vis.real.dtype\r\n\r\n    ncomb, utime, nant, nchan, ncorr = vis.shape\r\n\r\n    ms_gradient = np.zeros((nchan, nidx), dtype=out_dtype)\r\n    for i in prange(nidx):\r\n        for c in range(ncomb):\r\n            for t in range(utime):\r\n                for a in range(nant):\r\n                    for f in range(nchan):\r\n                        u, v = uv[c, t, a, f]\r\n                        uv_r = u * x[i] + v * y[i]\r\n                        uv_r *= 2 * np.pi * 1j\r\n                        a_ij = np.exp(uv_r)\r\n\r\n                        for r in range(ncorr):\r\n                            vm = vis[c, t, a, f, r].conjugate()\r\n                            ed = a_ij / vm if vm != 0 else 0\r\n\r\n                            i_sum = vr[c, t, f, r] * bm[c, t, f, r].conjugate() * ed\r\n\r\n                            s_sum = -w[c, t, f, r] * i_sum.real\r\n\r\n                            data = s_sum / ncomb\r\n\r\n                            ms_gradient[f, i] += data\r\n    return ms_gradient\r\n\r\n\r\ndef utime_and_row_chunks(time, req_utime=1):\r\n    \"\"\"Internals of compute_utime_and_row_chunks.\"\"\"\r\n\r\n    utime, utime_counts = np.unique(time, return_counts=True)\r\n    n_utime = utime.size\r\n    req_utime = req_utime or n_utime  # Catch zero.\r\n\r\n    chunk_starts = np.arange(0, n_utime, req_utime)\r\n\r\n    utime_chunks = np.array(\r\n        [\r\n            req_utime if i + req_utime < n_utime else n_utime - i\r\n            for i in chunk_starts\r\n        ]\r\n    )\r\n\r\n    row_chunks = np.add.reduceat(utime_counts, chunk_starts)\r\n\r\n    return np.stack([utime_chunks, row_chunks], axis=0)\r\n\r\n\r\n\r\ndef compute_utime_and_row_chunks(indexing_xdsl, req_utime=1):\r\n    \"\"\"Figure out the chunking in unique time and row. Triggers compute.\"\"\"\r\n\r\n    chunking = []\r\n\r\n    for xds in indexing_xdsl:\r\n\r\n        chunking.append(\r\n            xds.TIME.data.map_blocks(\r\n                utime_and_row_chunks,\r\n                req_utime,\r\n                chunks=((2,), (np.nan,)),\r\n                new_axis=0,\r\n                dtype=int\r\n            )\r\n        )\r\n\r\n    result = da.compute(chunking)[0]\r\n\r\n    utime_chunks = [tuple(arr[0]) for arr in result]\r\n    row_chunks = [tuple(arr[1]) for arr in result]\r\n\r\n    return utime_chunks, row_chunks\r\n\r\n@njit(cache=True, nogil=True)\r\ndef get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):\r\n    cnt = np.zeros(data_shape, dtype=np.int8)\r\n    data_bis = np.ones(data_shape, dtype=data.dtype)\r\n\r\n    for row in range(n_row):\r\n\r\n        ut = utime_inv[row]\r\n\r\n        a1 = ant1[row]\r\n        a2 = ant2[row]\r\n\r\n        for ic, c in enumerate(comb):\r\n            if (a1 == c[0]) and (a2 == c[1]):\r\n                data_bis[ic, ut, 0] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[1]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 1] = data[row]\r\n                cnt[ic, ut, :] += 1\r\n            elif (a1 == c[0]) and (a2 == c[-1]):\r\n                data_bis[ic, ut, 2] = data[row].conjugate()\r\n                cnt[ic, ut, :] += 1\r\n\r\n    return data_bis, cnt\r\n\r\ndef get_bispectrum(data, ant1, ant2, comb, time, type):\r\n\r\n    utime, utime_inv = np.unique(time, return_inverse=True)\r\n    n_utime = utime.size\r\n    n_comb = len(comb)\r\n\r\n    if type == 'UVW':\r\n        n_row, n_id = data.shape\r\n        shape_data = (n_comb, n_utime, 3, n_id)\r\n    else:\r\n        n_row, n_chan, n_corr = data.shape\r\n        shape_data = (n_comb, n_utime, 3, n_chan, n_corr)\r\n\r\n    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)\r\n\r\n    bis[cnt != 3] = 0\r\n\r\n    return bis\r\n\r\ndef bispectrum_data(data, antenna1, antenna2, filter_comb, time, type, utime_chunks_list):\r\n    utime_size = np.unique(time).size\r\n\r\n    if type == 'UVW':\r\n        bis_shape = ('triangle', 't', 'p', 'id')\r\n        data_shape = ('t', 'id')\r\n    else:\r\n        bis_shape = ('triangle', 't', 'p', 'f', 'c')\r\n        data_shape = ('t', 'f', 'c')\r\n\r\n    bis = da.blockwise(\r\n        get_bispectrum,\r\n        bis_shape,\r\n        data,\r\n        data_shape,\r\n        antenna1, ('t'),\r\n        antenna2, ('t'),\r\n        filter_comb,\r\n        None,\r\n        time.data, ('t'),\r\n        type,\r\n        None,\r\n        adjust_chunks={'t': utime_chunks_list},\r\n        new_axes={\r\n            'triangle': len(filter_comb),\r\n            'p': 3\r\n        },\r\n        dtype=data.dtype\r\n    )\r\n\r\n    return bis\r\n\r\ndef bispectrum(dataset, utime_chunks_list):\r\n    n_ant = 28\r\n    antenna_reference = 0\r\n    comb = itertools.combinations(range(n_ant), 3)\r\n    filter_comb = np.array([i for i in comb if antenna_reference in i])    \r\n\r\n    for i, xds in enumerate(dataset):\r\n        data = xds.DATA.data\r\n        model = xds.MODEL.data\r\n        weight = xds.WEIGHT.data\r\n        time = xds.TIME\r\n        antenna1 = xds.ANTENNA1.data\r\n        antenna2 = xds.ANTENNA2.data\r\n        uvw = xds.UVW.data\r\n\r\n        flags = xds.FLAG.data\r\n\r\n        data = data * ~flags\r\n        model = model * ~flags\r\n        weight = weight * ~flags\r\n\r\n        bm = bispectrum_data(model, antenna1, antenna2, filter_comb, time, 'DATA', utime_chunks_list[i])\r\n        uvw_bis = bispectrum_data(uvw, antenna1, antenna2, filter_comb, time, 'UVW', utime_chunks_list[i])\r\n        bw = bispectrum_data(weight, antenna1, antenna2, filter_comb, time, 'DATA', utime_chunks_list[i])\r\n        bo = bispectrum_data(data, antenna1, antenna2, filter_comb, time, 'DATA', utime_chunks_list[i])\r\n\r\n        cal_data = da.prod(bo, axis=2)\r\n        cal_model = da.prod(bm, axis=2)\r\n\r\n        weighted_vis = (da.absolute(bm)**2) * bw\r\n        aux = da.divide(\r\n            1, weighted_vis, out=da.zeros_like(weighted_vis), where=weighted_vis != 0\r\n        )\r\n        bis_sigma_squared = (da.absolute(cal_data)**2) * da.sum(aux, axis=2)\r\n        bis_weight = da.divide(\r\n            1,\r\n            bis_sigma_squared,\r\n            out=da.zeros_like(bis_sigma_squared),\r\n            where=bis_sigma_squared != 0\r\n        )\r\n\r\n        uvw_bis[:, :, 2] *= -1\r\n\r\n        dataset[i] = xds.assign({\r\n            \"BIS_MODEL\": (('triangle', 't', 'p', 'f', 'c'), bm),\r\n            \"BIS_DATA\": (('triangle', 't', 'p', 'f', 'c'), bo),\r\n            \"BIS_WEIGHT\": (('triangle', 't', 'p', 'f', 'c'), bw),\r\n            \"BIS_UVW\" : (('triangle', 't', 'p', 'id'), uvw_bis),\r\n            \"CAL_DATA\": (('triangle', 't', 'f', 'c'), cal_data),\r\n            \"CAL_MODEL\": (('triangle', 't', 'f', 'c'), cal_model),\r\n            \"CAL_WEIGHT\": (('triangle', 't', 'f', 'c'), bis_weight),\r\n        })\r\n\r\n    return dataset\r\n\r\n\r\nif __name__ == \"__main__\":\r\n  \r\n    input_name = \"/home/datasets/ms_name.ms\"\r\n\r\n    dataset = xds_from_ms(\r\n                input_name,\r\n                group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n                index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n                chunks={'row': -1}\r\n            )\r\n\r\n    utime_chunks_list, row_chunks_list = compute_utime_and_row_chunks(\r\n            dataset, req_utime=30\r\n        )\r\n\r\n    xdsl = xds_from_ms(\r\n            input_name,\r\n            group_cols=(\"SCAN_NUMBER\", \"FIELD_ID\", \"DATA_DESC_ID\"),\r\n            index_cols=(\"TIME\", \"ANTENNA1\", \"ANTENNA2\"),\r\n            chunks=[{'row': rcs} for rcs in row_chunks_list]\r\n        )\r\n\r\n    xdsl = [\r\n        xds.assign(\r\n            {\r\n                \"MODEL\": (\r\n                    xds.DATA.dims,\r\n                    da.ones(\r\n                        xds.DATA.data.shape,\r\n                        dtype=np.complex64,\r\n                        chunks=xds.DATA.data.chunksize\r\n                    ) / 2\r\n                ), \r\n                \"WEIGHT\": (\r\n                    xds.DATA.dims,\r\n                    da.tile(xds.WEIGHT.data, xds.DATA.shape[1]).reshape(len(xds.WEIGHT.data),xds.DATA.shape[1], xds.DATA.shape[2])\r\n                )\r\n            }\r\n        ) for xds in xdsl\r\n    ] \r\n\r\n    dataset_bis = bispectrum(xdsl, utime_chunks_list)\r\n    grad = gradient(dataset_bis, (512,512))\r\n\r\n```\r\n\r\n","createdAt":"2023-10-25T04:19:13Z","id":"IC_kwDOBh8_I85qAXqk","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1778481828","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @Hackasteroid142. I had an offline chat with @JSKenyon regarding the above code. Running it seems to take all available cores, so without fully understanding the optimality of the code for the individual chunks, the dask part seems to be doing its job. Additionally, it seems to be some variant of the DFT which is always going to be much slower than an FFT.\r\n\r\nFor example, https://github.com/caracal-pipeline/crystalball does a DFT predict of a WSClean sky model using dask\r\n\r\n- https://codex-africanus.readthedocs.io/en/latest/rime-api.html?highlight=wsclean#africanus.rime.dask.wsclean_predict\r\n\r\nThis can take up to a week for large Measurement Sets and sources.\r\n\r\nDFT's tend to be embarrasingly parallel, so your algorithm will probably benefit from distributing the problem on a compute cluster. Unfortunately we don't have the resources to help set this up and debug -- I suggest you consult some of the dask resources available on the internet.","createdAt":"2023-10-25T09:07:42Z","id":"IC_kwDOBh8_I85qBtv8","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-1778834428","viewerDidAuthor":false},{"author":{"login":"Maxahup"},"authorAssociation":"NONE","body":"Hi, I'm new to using Dask to parallelize operations and take advantage of its lazy computing model. I'm currently validating an implementation of the bispectrum calculation, but I have an important question related to the use of da.blockwise().\n\nIn particular, in the line where adjust_chunks={'t': (utime_size,)} is specified, I understand that this forces the time axis 't' to have a single chunk. Wouldn't this prevent the data from being properly parallelized?\n\nWhat I notice is that if I define a chunk size smaller than the total amount of data read (for example, data.shape[0] > chunk_size), Dask does generate multiple blocks correctly. However, when running bispectrum_data, an error occurs because it apparently expects a single block, but receives multiple blocks.\n\nIs this restriction actually forcing serialization, which negates the benefits of using Dask in this case? Or is there a recommended way to reword this so that the bispectrum calculation remains distributed across time blocks?\n\nThese are the current versions of the functions mentioned:\n```python\nimport dask.array as da\nimport numpy as np\nfrom numba import njit\n\n\n@njit(cache=True, nogil=True)\ndef get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):\n    cnt = np.zeros(data_shape, dtype=np.int8)\n    data_bis = np.ones(data_shape, dtype=data.dtype)\n\n    for row in range(n_row):\n\n        ut = utime_inv[row]\n\n        a1 = ant1[row]\n        a2 = ant2[row]\n\n        for ic, c in enumerate(comb):\n            if (a1 == c[0]) and (a2 == c[1]):\n                data_bis[ic, ut, 0] = data[row]\n                cnt[ic, ut, :] += 1\n            elif (a1 == c[1]) and (a2 == c[-1]):\n                data_bis[ic, ut, 1] = data[row]\n                cnt[ic, ut, :] += 1\n            elif (a1 == c[0]) and (a2 == c[-1]):\n                data_bis[ic, ut, 2] = data[row].conjugate()\n                cnt[ic, ut, :] += 1\n\n    return data_bis, cnt\n\ndef get_bispectrum(data, ant1, ant2, comb, time, type):\n\n    utime, utime_inv = np.unique(time, return_inverse=True)\n    n_utime = utime.size\n    n_comb = len(comb)\n\n    if type == 'UVW':\n        n_row, n_id = data.shape\n        shape_data = (n_comb, n_utime, 3, n_id)\n    else:\n        n_row, n_chan, n_corr = data.shape\n        shape_data = (n_comb, n_utime, 3, n_chan, n_corr)\n\n    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)\n\n    bis[cnt != 3] = 0\n\n    return bis\n\n\ndef bispectrum_data(data, antenna1, antenna2, filter_comb, time, type):\n    utime_size = np.unique(time).size\n    if type == 'UVW':\n        bis_shape = ('triangle', 't', 'p', 'id')\n        data_shape = ('t', 'id')\n    else:\n        bis_shape = ('triangle', 't', 'p', 'f', 'c')\n        data_shape = ('t', 'f', 'c')\n\n    bis = da.blockwise(\n        get_bispectrum,\n        bis_shape,\n        data,\n        data_shape,\n        antenna1, ('t'),\n        antenna2, ('t'),\n        filter_comb,\n        None,\n        time.data, ('t'),\n        type,\n        None,\n        align_arrays=False,\n        adjust_chunks={'t': (utime_size, )},\n        new_axes={\n            'triangle': len(filter_comb),\n            'p': 3\n        },\n        dtype=data.dtype\n    )\n\n    return bis\n```\n","createdAt":"2025-05-16T16:23:53Z","id":"IC_kwDOBh8_I86sFsUp","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-2887173417","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Hi @Maxahup!\n\n> In particular, in the line where adjust_chunks={'t': (utime_size,)} is specified, I understand that this forces the time axis 't' to have a single chunk. Wouldn't this prevent the data from being properly parallelized?\n\nThis is effectively telling Dask that the size of the output chunks will be equal to `utime_size`. This may not be what you want but I am slightly unsure of the desired output. In principle, this should be set to match the intended output i.e. for each input chunk which includes dimension `t` what is the expected chunk size of the output. \n \n> What I notice is that if I define a chunk size smaller than the total amount of data read (for example, data.shape[0] > chunk_size), Dask does generate multiple blocks correctly. However, when running bispectrum_data, an error occurs because it apparently expects a single block, but receives multiple blocks.\n\nIf there is a reduction over a dimension, Dask will pass arrays wrapped in lists. This can happen for axes which only include a single chunk. Sometimes the (somewhat dodgy) fix is just setting `concatenate=True` in the `blockwise` call. Otherwise, you need to adjust `get_bispectrum` to correctly process lists of input (even if those lists only contain a single element). There should be examples of this in the Dask documentation.\n\n> Is this restriction actually forcing serialization, which negates the benefits of using Dask in this case? Or is there a recommended way to reword this so that the bispectrum calculation remains distributed across time blocks?\n\nI suspect that this is a fixable problem which will require you to mess around with `blockwise` a little more. ","createdAt":"2025-05-19T07:26:33Z","id":"IC_kwDOBh8_I86sQIXa","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/293#issuecomment-2889909722","viewerDidAuthor":false}] | created: 2023-10-04T18:22:25Z ===
* dask-ms version: 0.2.16
* Python version: 3.10
* Operating System: 18.04.6

### Description

Hello, some time ago I opened an [issue](https://github.com/ratt-ru/dask-ms/issues/276)  where I asked for help with the implementation of the bispectrum. Taking into account the responses I received, I started developing a gradient and an optimizer for obtaining images using this method. However, I've encountered some issues in terms of memory and time. I've tried to address this by changing the default chunk size in dataset reading, but I've run into problems with shape values.

Currently, I am reading the dataset using the `xds_from_ms` function from Dask. However, if I change the chunk size to another value, such as 1500, I get the following error.

```
operands could not be broadcast together with shapes () (6903,2,3,1,2) (6903,1500,3,1,2) (6903,2,3,1,2)
```

Based on the tests I've conducted, I believe the issue may be related to the `adjust_chunks` parameter in the `blockwise` function that I'm using for the bispectrum. However, I've tried editing this parameter to solve the problem, but none of my attempts have been successful. Is there a way to resolve this? Additionally, do you think working with the dataset in this manner and performing the bispectrum calculation like this could lead to performance problems?

Here's an excerpt from the code I'm using. If anything is unclear, I'd be happy to provide additional information, and any help is greatly appreciated. Thank you in advance!

```python

import dask.array as da
import numpy as np
from numba import njit


@njit(cache=True, nogil=True)
def get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, data_shape):
    cnt = np.zeros(data_shape, dtype=np.int8)
    data_bis = np.ones(data_shape, dtype=data.dtype)

    for row in range(n_row):

        ut = utime_inv[row]

        a1 = ant1[row]
        a2 = ant2[row]

        for ic, c in enumerate(comb):
            if (a1 == c[0]) and (a2 == c[1]):
                data_bis[ic, ut, 0] = data[row]
                cnt[ic, ut, :] += 1
            elif (a1 == c[1]) and (a2 == c[-1]):
                data_bis[ic, ut, 1] = data[row]
                cnt[ic, ut, :] += 1
            elif (a1 == c[0]) and (a2 == c[-1]):
                data_bis[ic, ut, 2] = data[row].conjugate()
                cnt[ic, ut, :] += 1

    return data_bis, cnt


def get_bispectrum(data, ant1, ant2, comb, time, type):

    utime, utime_inv = np.unique(time, return_inverse=True)
    n_utime = utime.size
    n_comb = len(comb)

    n_row, n_chan, n_corr = data.shape
    shape_data = (n_comb, n_utime, 3, n_chan, n_corr)

    bis, cnt = get_bispectrum_data(data, ant1, ant2, comb, utime_inv, n_row, shape_data)

    bis[cnt != 3] = 0

    return bis


input_name = "/home/datasets/ms_name.ms"

ms = xds_from_ms(
            input_name,
            group_cols=("SCAN_NUMBER", "FIELD_ID", "DATA_DESC_ID"),
            index_cols=("TIME", "ANTENNA1", "ANTENNA2"),
            chunks={'row': 1500}
        )
comb = itertools.combinations(range(antennas.shape[0]), 3)
 filter_comb = np.array([i for i in comb if antenna_reference in i])
utime_size = np.unique(time).size

bis = da.blockwise(
    get_bispectrum,
    ('triangle', 't', 'p', 'f', 'c'),
    data,
    ('t', 'f', 'c'),
    antenna1, ('t'),
    antenna2, ('t'),
    filter_comb,
    None,
    time.data, ('t'),
    type,
    None,
    align_arrays=False,
    adjust_chunks={'t': (utime_size, )},
    new_axes={
        'triangle': len(filter_comb),
        'p': 3
    },
    dtype=data.dtype
)

```


=== ISSUE #285 | Experimental clean-up release | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"/cc @JSKenyon @landmanbester @o-smirnov ","createdAt":"2023-08-29T11:01:01Z","id":"IC_kwDOBh8_I85lKZh8","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1697224828","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"It all looks good to me! Will gladly help out where necessary. ","createdAt":"2023-08-30T08:46:21Z","id":"IC_kwDOBh8_I85lQOPE","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1698751428","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"I've been thinking a bit about xarray as a first class dependency and the fact that xarray doesn't support nan chunks. Here's the xarray issue:\r\n\r\n- https://github.com/pydata/xarray/issues/2801\r\n\r\nIn the case of standard averaging this will require reification of `TIME`, `INTERVAL`, `ANTENNA1` and `ANTENNA2` columns (and probably `CHAN_FREQ` and `CHAN_WIDTH` too).\r\n\r\n```python\r\ndef row_mapper(time, interval, antenna1, antenna2,\r\n               flag_row=None, time_bin_secs=1):\r\n```\r\n\r\nIn the more complex BDA case this requires reification of `TIME`, `INTERVAL`, `ANTENNA1`, `ANTENNA2`, `UVW`, `CHAN_WIDTH` and `CHAN_FREQ`.\r\n\r\n```python\r\ndef bda_mapper(time, interval, ant1, ant2, uvw,  chan_width, chan_freq,\r\n                           max_uvw_dist, flag_row=None, max_fov=3.0,\r\n                           decorrelation=0.98,\r\n                           time_bin_secs=None,\r\n                           min_nchan=1):\r\n```\r\n\r\nI can broadly see two approaches\r\n\r\n# Place reified coordinates on Datasets\r\n\r\nThe obvious way of handlng this (which I've avoided up until now due to memory concerns) would be to make the following fully reified coordinates on the resultant xarray datasets:\r\n\r\n- [MSv2.0 indexing columns](https://casa.nrao.edu/Memos/229.html#SECTION00061000000000000000) \r\n- `SPECTRAL_WINDOW` `CHAN_FREQ` and `CHAN_WIDTH` .\r\n- `POLARIZATION` `CORR_PRODUCT`\r\n- Perhaps some relevant `FEED` columns.\r\n\r\nPros:\r\n\r\n- We can reason about the grid in-memory, and produce accurately chunked dask arrays\r\n- Following on from the point above, it would also give us the ability to check for regularity in the grid\r\n\r\nCons:\r\n\r\n- The memory overhead of fully reified columns in the driver program, and this will increase as dump rates and antennas do too.\r\n- For the BDA case, we'd need to reify `UVW` coordinates further compounding driver program memory costs. These are 3xTIME, but it would still be preferable not to.\r\n  - Maybe UVW can be made an optional coordinate\r\n  - Or use `TIME_CENTROID` and `ANTENNA::POSITION` to generate UVW on the fly.\r\n\r\n\r\n# Compute chunk sizes in the indexing columns in as a pre-compute step\r\n\r\nWe tend to do this in our applications in any case (@JSKenyon in Quartical, myself in xova, @landmanbester ?).\r\n\r\nPros:\r\n\r\n- Not memory-intensive\r\n\r\nCons:\r\n\r\n- Read the indexing columns twice just to get properly chunked dask arrays.\r\n- This may become more problematic as data sizes increase.\r\n\r\n\r\n\r\n\r\n","createdAt":"2023-08-30T13:47:11Z","id":"IC_kwDOBh8_I85lSByB","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1699224705","viewerDidAuthor":false},{"author":{"login":"landmanbester"},"authorAssociation":"COLLABORATOR","body":"> We tend to do this in our applications in any case (@JSKenyon in Quartical, myself in xova, @landmanbester ?).\r\n\r\nYup, I read the indexing columns to set things up as well. It would be nice to have them reified. Maybe don't go as far as reifying uvw's but having access to time and frequency without calling compute is very handy ","createdAt":"2023-09-02T12:15:44Z","id":"IC_kwDOBh8_I85lji3O","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1703816654","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"> I've been thinking a bit about xarray as a first class dependency and the fact that xarray doesn't support nan chunks.\r\n\r\nWholeheartedly agree with making it a first class dependency. The nan chunk problem is irritating but as you mentioned, there are ways around it. \r\n\r\n> In the case of standard averaging this will require reification of `TIME`, `INTERVAL`, `ANTENNA1` and `ANTENNA2` columns (and probably `CHAN_FREQ` and `CHAN_WIDTH` too).\r\n\r\nThis is certainly possible. As you say, it will make things more memory intensive in the driver, but also gives us access to a a fair amount of powerful xarray functionality.\r\n \r\n> In the more complex BDA case this requires reification of `TIME`, `INTERVAL`, `ANTENNA1`, `ANTENNA2`, `UVW`, `CHAN_WIDTH` and `CHAN_FREQ`.\r\n\r\nI think if we add this functionality, we do it in such a way that a user may optionally specify which elements are coordinates and which ones should be read/exposed. That way you don't get reified UVW unless you need it. \r\n\r\n>     * [MSv2.0 indexing columns](https://casa.nrao.edu/Memos/229.html#SECTION00061000000000000000)\r\n> \r\n>     * `SPECTRAL_WINDOW` `CHAN_FREQ` and `CHAN_WIDTH` .\r\n> \r\n>     * `POLARIZATION` `CORR_PRODUCT`\r\n> \r\n>     * Perhaps some relevant `FEED` columns.\r\n\r\nI would say that I want to seriously discourage bolting every indexing column into the coordinates - I think that we need some sort of mechanism for getting what we need in an application specific way. That said, even with all of the above, it is still probably manageable for current problem sizes (although I agree that it could become a problem). Some of the above could be compressed substantially in memory if there was RLE or something of the like in the xarray coordinates (not sure if this exists/could exist).\r\n\r\n> Pros:\r\n> \r\n>     * We can reason about the grid in-memory, and produce accurately chunked dask arrays\r\n> \r\n>     * Following on from the point above, it would also give us the ability to check for regularity in the grid\r\n\r\nJust reiterating that this gives us a great deal more power in xarray land.\r\n\r\n> Cons:\r\n> \r\n>     * The memory overhead of fully reified columns in the driver program, and this will increase as dump rates and antennas do too.\r\n>     * For the BDA case, we'd need to reify `UVW` coordinates further compounding driver program memory costs. These are 3xTIME, but it would still be preferable not to.\r\n\r\nThere will still be a disconnect in the chunking problem i.e. users would still need to use the time and channel information to decide on appropriate chunks and then do another `xds_from_*` call to produce the relevant dask arrays.\r\n \r\n> # Compute chunk sizes in the indexing columns in as a pre-compute step\r\n> \r\n> We tend to do this in our applications in any case (@JSKenyon in Quartical, myself in xova, @landmanbester ?).\r\n> \r\n> Pros:\r\n> \r\n>     * Not memory-intensive\r\n\r\n> Cons:\r\n> \r\n>     * Read the indexing columns twice just to get properly chunked dask arrays.\r\n> \r\n>     * This may become more problematic as data sizes increase.\r\n\r\nI don't really see the indexing columns ever becoming a problem relative to the actual data. I guess one can argue that the driver may end up with a fair amount of data in memory when doing graph construction. \r\n\r\nApologies, I think that this may be a difficult reply to read due to all the quoting. I do think that there are two separate problems to consider here. \r\n\r\nThe first is that we currently limit xarray functionality due to the absence of true coordinate values. This could be solved by allowing users to optionally request certain data_vars (columns) as coordinates during the read. The tricky part is how we attach those coordinates to the other data_vars e.g. if we require both CHAN_FREQ and CHAN_WIDTH, which one is the proper coordinate? We could also opt to establish a CHAN_ID which would be a global integer index over all channels in a spectral window (or optionally over all spectral windows?). Then each CHAN_ID could be associated with a CHAN_FREQ and CHAN_WIDTH. This would pave the way for more easily splitting and combining datasets in frequency.\r\n\r\nThe second problem is the chunking. The reason that many of our applications have this two-step process is that dask-ms is not currently aware of the way in which we typically chunk our data i.e. in blocks of complete time and channel. If dask-ms had a more elaborate chunking mechanism, it may be possible to skip this step in user code e.g. in `xds_from_*` support passing a function and column names to the chunk argument such that the desired chunking can be ensured on the first read.\r\n","createdAt":"2023-09-05T07:43:11Z","id":"IC_kwDOBh8_I85lsR1S","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1706106194","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Another point in favour of reified coordinates/extending the ROWID behaviour to other common axes is that we could support partial updates (see #93). This would make writing data after selection much easier (at present it requires a fair amount of wrangling downstream). ","createdAt":"2023-09-26T07:19:22Z","id":"IC_kwDOBh8_I85naYdB","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/285#issuecomment-1734969153","viewerDidAuthor":false}] | created: 2023-08-29T10:56:10Z ===
### Description

We've been experimenting with a number of features in dask-ms for a while now. Now that we better understand how these features operate in a distributed environment, its worth consolidating these into a list for a release. This may involve breaking some experimental functionality and hopefully less of the existing non-experimental functionality.

## TODO

- [ ] Remove the vendored xarray dataset and make xarray a first class dependency.
  - The original reason for this was that xarray didn't handle nan chunks, which we used in averaging code because it was thought that it wasn't possible to determine the number of output rows (especially in the case of BDA data).
  - This is doable (use the Quartical approach of keeping the index in memory) by applying the averaging mapping functions.
  - This will effect https://github.com/ratt-ru/xova and possibly pfb-clean
- [ ] Use xarray's `open_zarr` and `to_zarr` methods
  - We wrote our own zarr accessors due to root task overproduction in the original xarray zarr implementation creating suboptimal graphs
  - See root task overproduction. https://www.coiled.io/blog/better-shuffling-in-dask-a-proof-of-concept
  - Inspection of dask and xarray code show that these root nodes have been removed.
  - Also might be mitigated by https://www.coiled.io/blog/reducing-dask-memory-usage
- [ ] Consolidate metadata into a single xarray `__daskms_metadata__`. Metadata such as the following should be placed within it:
  - Partitioning schema
  - Casa Descriptors
  - Original MS Opening Parameters
- [ ] #273
  - Originally, `xds_to_table` handled writes to any CASA table, while `xds_from_ms` existed to interpret a CASA table (and subtables) as a MS-specific, adding appropriate coordinates to the MS columns.
  - It's probably more ergonomic to consolidate this into `xds_{from/to}_ms` accessors.
  - Also review what's strictly necessary in these interfaces.
- [ ] Swap out `python-casacore` for https://github.com/ratt-ru/arcae for CASA table access:
   - At minimum this should give us thread-safe distributed reads
   - It's not clear if we can get distributed writes through this approach and whether this is worthwhile.
     - Determine whether this is worth the effort
- [ ] Incorporate fragments #282

=== ISSUE #283 | `daskms.experimental.xds_to_zarr` may fail due to large chunks | labels:  | comments: [] | created: 2023-08-14T13:47:07Z ===
* dask-ms version: master
* Python version: 3.10.12
* Operating System: Ubuntu 20.04 LTS

### Description

When attempting to write an `xarray.Dataset` with large chunks to zarr, I got the following error:

```bash
ValueError: Column FLAG has a chunk of dimension (132750, 4096, 4) that will exceed zarr's 2GiB chunk limit
```

### What I Did

```python
xds_to_zarr([xds_with_large_chunks], "test.zarr", rechunk=True)
```

### Possible solution
This problem can be solved in a number of ways:

1. In user code: I could manually figure out and rechunk before writing.
2. As part of `maybe_rechunk` in `xds_to_zarr`: This functionality currently forces chunks to match those already on disk. It would not be a stretch to extend this to include the case where a new zarr output is being written.
3. As a utility function: A function could be added e.g. `rechunk_for_disk`, which a user could call prior to writing an `xarray.Dataset` to disk.

Practically, a combination of 2 and 3 will likely be best i.e. write a utility function and then call it as part of `xds_to_zarr`. I will take a stab at this this week.


=== ISSUE #277 | Parallelize or map chunks of an MS and an image to compute chi2 gradient | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @valegui. Thanks for the issue. I need some more time to think about what you're asking.\r\n\r\nInitially, I would say that the fact that the code is mapping every visibility to every pixel means that there is a many-to-many communication pattern which is very challenging for dask schedulers. This is probably what leads to the Out of Memory situations.\r\n\r\nOne way of \"solving\" this might be to assume that the image is small enough such that it can [cloned](https://docs.dask.org/en/stable/graph_manipulation.html#dask.graph_manipulation.clone) and fed into each visibility chunk.\r\n\r\nBut I'll try find some more time to think about your code in more detail.","createdAt":"2023-04-04T13:12:18Z","id":"IC_kwDOBh8_I85ZKl9Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/277#issuecomment-1495949145","viewerDidAuthor":false},{"author":{"login":"landmanbester"},"authorAssociation":"COLLABORATOR","body":"Computing the gradient (also the negative of the residual image) using a direct Fourier transform (DFT) is never going to be fast or memory efficient. Have you considered using a degridder (eg. the wgridder)? There are some utilities in codex-africanus that will do this for you, especially the residual function \r\n\r\nhttps://github.com/ratt-ru/codex-africanus/blob/master/africanus/gridding/wgridder/im2residim.py\r\n\r\nYou can see how to call it by looking at this test\r\n\r\nhttps://github.com/ratt-ru/codex-africanus/blob/7a756a9bd3fe8bfadb2a02add9b3f180be42696d/africanus/gridding/wgridder/tests/test_wgridder.py#L159\r\n\r\nBasically the idea is that, since the image is usually much smaller than the visibilities, you hold the full image in memory and chunk over the visibilities along row and chan axes (the latter needs to be aligned with the number of imaging bands you are using). You can get almost arbitrarily accurate (up to 1e-12) results with this approach as long as your pixels lie on a grid. If they do not, I would compute the residual visibilities and just apply the DFT to those. You can use the vis_to_im function (also in codex-africanus)\r\n\r\nhttps://github.com/ratt-ru/codex-africanus/blob/7a756a9bd3fe8bfadb2a02add9b3f180be42696d/africanus/dft/dask.py#L60\r\n\r\nfor that. All the for loops for this implementation are in the numba layer so you shouldn't be afraid of them. It is still going to be very slow compared to the gridded version ","createdAt":"2023-04-04T13:35:14Z","id":"IC_kwDOBh8_I85ZKvm2","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/277#issuecomment-1495988662","viewerDidAuthor":false},{"author":{"login":"valegui"},"authorAssociation":"NONE","body":"Hi @landmanbester , thank you for your answer. \r\nI believe your answer is not exactly what I need, as I'm looking to compute the gradient with respect to the image using every pixel. I do not want to apply gridding.\r\nThis is similar to what is done in the `vis_to_im` function. It's not exactly the same, but the code you suggested to use has served as a guide to continue looking at what can be done with `blockwise`.\r\nTo provide further context, I've already used a degridder to obtain the residual visibilities. The degridding is done using `map_blocks` over the uv array, with the entire image in memory. As you know, this does not cause memory nor time problems due to only indexing/using a minimal slice of the image for each uv pair. The problem starts in the `ms_gradient` function (in the op code) when uv is broadcasted, especially if the image has a number of pixels equal to or greater than 1024x1024.","createdAt":"2023-04-17T16:22:10Z","id":"IC_kwDOBh8_I85aGqZc","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/277#issuecomment-1511695964","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> The degridding is done using `map_blocks` over the uv array, with the entire image in memory. As you know, this does not cause memory nor time problems due to only indexing/using a minimal slice of the image for each uv pair.\r\n\r\nYou've managed to solve the problem in the degridding step by passing the image in to each chunk, now we just need to apply the same idea in the other direction.\r\n\r\n>The problem starts in the `ms_gradient` function (in the op code) when uv is broadcasted, especially if the image has a number of pixels equal to or greater than 1024x1024.\r\n\r\nWhen broadcasting, far more memory is allocated than is strictly needed for computing the result. I've tried to re-express the general outline of your problem by:\r\n\r\n1. Minimising the amount of broadcasting in the dask layer\r\n2. And in the blockwise function layer by implementing it as a numba function with nested loops, rather than NumPy array broadcasting syntax.\r\n\r\nThe following keeps 16 cores busy adding 1's at a fairly stable 8GB of memory usage, but you'll probably want to make it do the actual gradient calculation. If you want to increase your image size, you may need to correspondingly decrease your row chunk size in order to keep the total amount of  used memory stable. Experimenting with chunk sizes is somewhat of an art.\r\n\r\n```python\r\nimport astropy.units as un\r\nimport dask.array as da\r\nimport numba\r\nimport numpy as np\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    chunks = {\r\n        \"row\": (50,) * 2000,\r\n        \"chan\": (64,) * 8,\r\n        \"corr\": (4,),\r\n        \"uvw\": (3,),\r\n    }\r\n\r\n    shapes = {k: sum(v) for k, v in chunks.items()}\r\n    shape = lambda dims: tuple(shapes[d.strip()] for d in dims.split(\",\"))\r\n    chunk = lambda dims: tuple(chunks[d.strip()] for d in dims.split(\",\"))\r\n\r\n    uvw = da.random.random(shape(\"row,uvw\"), chunks=chunk(\"row,uvw\")) * 10_000\r\n    flag = da.random.choice([0, 1], shape(\"row,chan,corr\"), chunks=chunk(\"row,chan,corr\"))\r\n    model = (da.random.random(shape(\"row,chan,corr\"), chunks=chunk(\"row,chan,corr\")) +\r\n             da.random.random(shape(\"row,chan,corr\"), chunks=chunk(\"row,chan,corr\"))*1j)\r\n    observed = (da.random.random(shape(\"row,chan,corr\"), chunks=chunk(\"row,chan,corr\")) +\r\n                da.random.random(shape(\"row,chan,corr\"), chunks=chunk(\"row,chan,corr\"))*1j)\r\n\r\n    image = np.zeros((1024, 1024))\r\n\r\n    @numba.njit(nogil=True)\r\n    def block_gradient(uvw, model, observed, flag, image, deltax=None, deltay=None):\r\n        assert uvw.ndim == 2\r\n        assert flag.ndim == model.ndim == observed.ndim == 3\r\n        assert image.ndim == 2\r\n        nrow, nchan, ncorr = model.shape\r\n        nx, ny = image.shape\r\n\r\n        gradient = np.zeros((nrow, nx, ny))\r\n\r\n        for r in range(nrow):\r\n            u = uvw[r, 0]\r\n            v = uvw[r, 1]\r\n            w = uvw[r, 2]\r\n\r\n            for c in range(nchan):\r\n                for co in range(ncorr):\r\n                    residual = model[r, c, co] - observed[r, c, co]\r\n\r\n                    for yi in range(ny):\r\n                        y = deltay * (yi - ny // 2)\r\n                        for xi in range(nx):\r\n                            x = deltax * (xi - nx // 2)\r\n                            ux = u * x\r\n                            vy = v * y\r\n                            uv = ux + vy\r\n\r\n                            gradient[r, xi, yi] += 1\r\n\r\n        return gradient\r\n\r\n\r\n    grad = da.blockwise(block_gradient, (\"row\", \"x\", \"y\"),\r\n                        uvw, (\"row\", \"uvw\"),\r\n                        model, (\"row\", \"chan\", \"corr\"),\r\n                        observed, (\"row\", \"chan\", \"corr\"),\r\n                        flag, (\"row\", \"chan\", \"corr\"),\r\n                        image, (\"x\", \"y\"),\r\n                        deltax=(-1*un.rad).value,\r\n                        deltay=(-1*un.rad).value,\r\n                        concatenate=True,\r\n                        meta=np.empty((0,)*3, np.complex64))\r\n\r\n    grad.sum().compute()\r\n```\r\n\r\nI hope this bare outline captures your idea and is enough of a base for you to take the solution further.\r\n","createdAt":"2023-04-19T12:45:34Z","id":"IC_kwDOBh8_I85aSBD5","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/277#issuecomment-1514672377","viewerDidAuthor":false}] | created: 2023-04-01T00:38:34Z ===
- dask 2022.12.1
- dask-ms 0.2.15
- numba 0.56.4
- Python 3.10.9
- Ubuntu 18.04.6

Hi there, I'm working with Dask Array and numba to implement the gradient of $\chi²$ in a chunked/parallel way, but I'm having some memory related problems when working with a "big" image.
The $\chi²$ gradient equation is:
```math
[\nabla\chi^2]_i = \sum_{k=0}^{Z-1} w * \left( Re(V_k^R \cos(2\pi (x_i \cdot u_k + y_i \cdot v_k))) - Im(V_k^R \sin(2\pi (x_i \cdot u_k + y_i \cdot v_k))) \right)
```
, where $V_k^R$ is the $k$ -th residual visibility, $(x_i, y_i)$ is the image coordinate of the $i$ -th pixel according to the direction cosines of the phase tracking center, and $(u_k, v_k)$ is the sampling coordinate of the $k$ -th visibility.
The current version that works for images of size 256x256, uses `blockwise` over blocks of data that are aligned on the ROW coordinate. While the image (or its indices which are the ones really used) can be a dask array, it's treated as an in-memory numpy array, and the data from the MS is broadcasted to add the 2 dimensions of the image. That is why this version does not work for bigger images, like 2048x2048 or 1024x1024. While working in a jupyter notebook, the kernel just dies because it runs out of memory.
One of the problems faced to parallelize the proposed solution (with a chunked image) is that for every pixel/cell of the image array, we have to compute the gradient with every visibility, but the blocks of the data from the MS are not aligned to those of the image. This is a problem because we cannot use `map_blocks`or `blockwise` to work in every chunk of the image per every chunk of the data.
From the current state of the solution, I need to find a way to divide the load per chunks of the MS arrays but also per chunk of image, **ideally without falling back to the use of a for-loop** to iterate in every chunk of the image.

## What I have tried until now

Here's a simplified version of the strategy that has been working without problems for images of size 256x256. The steps are the following:

1. Broadcast and multiply the u/v arrays with the index array, so the first two dimensions are from the visibility and freq channel.
2. Use blockwise to map the calculation on every block.
3. Use a numba vectorized function for a faster and parallelized computation.

This works because the size of each block of the broadcasted array is small enough to fit in memory. Changing the size of the image with this version does not work due to memory limits  (the process gets killed).

```python
import astropy.units as un
import dask
import dask.array as da
import numpy as np
import xarray as xr
from dask.diagnostics import ProgressBar
from daskms import xds_from_ms
from numba import float32, guvectorize

def block_gradient(uv, w, vis):
    wvis_r = w[0] * vis[0].real
    wvis_i = w[0] * vis[0].imag
    dchi2_broad = dchi2_row_chan(uv, wvis_r, wvis_i)
    return dchi2_broad

@guvectorize(
    [(float32[:, :], float32[:], float32[:], float32[:, :])],
    '(n,m),(i),(i)->(n,m)',
    nopython=True,
)
def dchi2_row_chan(uv, wvis_r, wvis_i, res):
    uv_pi = 2 * np.pi * uv
    cos_uv = np.cos(uv_pi)
    sin_uv = np.sin(uv_pi)
    for i in range(wvis_r.shape[0]):
        res += wvis_r[i] * cos_uv - wvis_i[i] * sin_uv

def ms_gradient(ms, delta, imshape):
    uvw = ms.UVW.data.astype(np.float32)
    w = ms.WEIGHT.data
    flag = ms.FLAG.data
    vm = ms.MODEL.data
    vo = ms.DATA.data
    vr = vm - vo

    nchan = ms.DATA.shape[1]

    w_broadcast = da.repeat(w[:, np.newaxis, :], nchan, axis=1)
    w_broadcast *= ~flag

    uvw_broadcast = da.repeat(uvw[:, np.newaxis, :], nchan, axis=1)
    u = uvw_broadcast[:, :, 0]
    v = uvw_broadcast[:, :, 0]

    x_ind, y_ind = da.indices(imshape)

    x = (x_ind - imshape[0] // 2) * delta[0].to(un.rad).value
    y = (y_ind - imshape[1] // 2) * delta[1].to(un.rad).value

    ux = u[:, :, None, None] * x[None, None, :, :]
    vy = v[:, :, None, None] * y[None, None, :, :]
    uv = (ux + vy).astype(np.float32)

    # Equivalent to Re(Vr * exp(2j*pi*uv))
    data = da.blockwise(
        block_gradient,
        'ijnm',
        uv,
        'ijnm',
        w_broadcast,
        'ijk',
        vr,
        'ijk',
        dtype=np.float32,
    )

    res = da.sum(data, axis=[0, 1])
    return res


def dchi2(ms_list, imshape):
    dchi2 = da.zeros(imshape, dtype=np.float32)
    for ms in ms_list:
        dchi2 += ms_gradient(ms, [-1, 1]*un.rad, imshape)
    return dchi2

ms = "/home/datasets/ms0/ms0.ms"

data_xdsl = xds_from_ms(
        ms,
        group_cols=["FIELD_ID", "DATA_DESC_ID"],
        index_cols=["SCAN_NUMBER", "TIME", "ANTENNA1", "ANTENNA2"],
        columns=["UVW", "WEIGHT", "FLAG", "DATA"],
        chunks={'row': 1000}
    )

# Replace data with ones
# Create model with 0.5
data_xdsl = [
    xds.assign(
        {
            "DATA": (
                xds.DATA.dims,
                da.ones(
                    xds.DATA.data.shape,
                    dtype=np.complex64,
                    chunks=xds.DATA.data.chunksize
                )
            ),
            "MODEL": (
                xds.DATA.dims,
                da.ones(
                    xds.DATA.data.shape,
                    dtype=np.complex64,
                    chunks=xds.DATA.data.chunksize
                ) / 2
            )
        }
    ) for xds in data_xdsl
]

# Call the gradient function

dchi2_arr = dchi2(data_xdsl, (256, 256))

# Get results

with ProgressBar():
    result, *_ = da.compute(dchi2_arr, scheduler="threads", n_workers=20)

print(result)
```

## What do I  need

The expected result is to get the resulting image, without memory problems.
One option is to modify what has been working with smaller images, but as I mentioned before, the idea is to avoid a for-loop over the image/image-chunks, and I don't know how to do it without the loop.
Any suggestion or modification on the existing code is greatly appreciated.

=== ISSUE #273 | Consolidate MS support into xds_{from,to}_ms | labels: enhancement | comments: [{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"I had had a similar thought and I am all for it. This would likely be a breaking change, but I think it would be worth it. It means that we can abandon MS-like syntax in `xds_{to,from}_table` (i.e. don't introduce a MAIN table for no reason) and remove the unintuitive double colon syntax that it necessitated. This functionality can be retained/added in `xds_{to,from}_ms` to make it \"equivalent\" with MS access via `python-casacore`. I think that `xds_{to,from}_table` should be sufficient for all other use-cases.","createdAt":"2022-12-05T08:22:54Z","id":"IC_kwDOBh8_I85PsCFI","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/273#issuecomment-1336942920","viewerDidAuthor":false}] | created: 2022-12-05T08:14:32Z ===
* dask-ms version: 0.2.15
* Python version: 3.8
* Operating System: Ubuntu 20.04

In #272, @caseyjlaw tried to use `xds_from_ms` to open a sub-table of the MS. This didn't work because `xds_from_ms` adds some default values (grouping and indexing columns) for opening the MAIN table of an MS. Due to this, we currently use `xds_from_table` to access sub-tables in our applications.

However, it occurs to me that @caseyjlaw was trying to do the most obvious thing, given the [affordance](https://uxplanet.org/ux-design-glossary-how-to-use-affordances-in-user-interfaces-393c8e9686e4). It could be that split is unnecessary and confusing and that `xds_{from,to}_ms` should be the interface for dealing with all Measurement Set-like datastores (CASA/zarr/parquet), as well as their sub-tables.

Then, `xds_{from,to}_table` can be used for *general* undefined table types, and we could define `xds_{from,to}_xxx` methods to handle some `xxx` specification (calibration methods for example).

Any opinions on this @JSKenyon, @landmanbester, @o-smirnov ?



=== ISSUE #272 | read, join, and write MS | labels:  | comments: [{"author":{"login":"landmanbester"},"authorAssociation":"COLLABORATOR","body":"I think you may just need a double colon for the subtable i.e. try with\r\n```\r\nds = xds_from_ms('20221129_034113_15MHz.ms::SPECTRAL_WINDOW', group_cols=\"__row__\")\r\n```","createdAt":"2022-12-02T07:03:41Z","id":"IC_kwDOBh8_I85PkALC","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1334837954","viewerDidAuthor":false},{"author":{"login":"caseyjlaw"},"authorAssociation":"NONE","body":"Thanks for the quick reply. Sorry, but I actually pasted the wrong error. Below is what I get when using the proper syntax.\r\nPerhaps our MS is not valid somehow. Do you have a way to verify that the MS file meets the specification?\r\n\r\n```\r\nIn [2]: ds = xds_from_ms('20221129_034113_15MHz.ms::SPECTRAL_WINDOW', group_cols=\"__row__\")\r\n---------------------------------------------------------------------------\r\nKeyError                                  Traceback (most recent call last)\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/table_proxy.py in __call__(cls, *args, **kwargs)\r\n    158             try:\r\n--> 159                 return _table_cache[key]\r\n    160             except KeyError:\r\n\r\n~/.conda/envs/development/lib/python3.6/weakref.py in __getitem__(self, key)\r\n    136             self._commit_removals()\r\n--> 137         o = self.data[key]()\r\n    138         if o is None:\r\n\r\nKeyError: -316058696854364970\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nRuntimeError                              Traceback (most recent call last)\r\n<ipython-input-2-ed052d620bc7> in <module>\r\n----> 1 ds = xds_from_ms('20221129_034113_15MHz.ms::SPECTRAL_WINDOW', group_cols=\"__row__\")\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/dask_ms.py in xds_from_ms(ms, columns, index_cols, group_cols, **kwargs)\r\n    397                           index_cols=index_cols,\r\n    398                           group_cols=group_cols,\r\n--> 399                           **kwargs)\r\n    400 \r\n    401 \r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/dask_ms.py in xds_from_table(table_name, columns, index_cols, group_cols, **kwargs)\r\n    324     dask_datasets = DatasetFactory(table_name, columns,\r\n    325                                    group_cols, index_cols,\r\n--> 326                                    **kwargs).datasets()\r\n    327 \r\n    328     # Return dask datasets if xarray is not available\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/reads.py in datasets(self)\r\n    397         elif len(self.group_cols) == 1 and self.group_cols[0] == \"__row__\":\r\n    398             order_taql = ordering_taql(table_proxy, self.index_cols,\r\n--> 399                                        self.taql_where)\r\n    400             sorted_rows, row_runs = row_ordering(order_taql,\r\n    401                                                  self.index_cols,\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/ordering.py in ordering_taql(table_proxy, index_cols, taql_where)\r\n     74 \r\n     75     return TableProxy(taql_factory, query, tables=[table_proxy],\r\n---> 76                       __executor_key__=table_proxy.executor_key)\r\n     77 \r\n     78 \r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/table_proxy.py in __call__(cls, *args, **kwargs)\r\n    159                 return _table_cache[key]\r\n    160             except KeyError:\r\n--> 161                 instance = type.__call__(cls, *args, **kwargs)\r\n    162                 _table_cache[key] = instance\r\n    163                 return instance\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/table_proxy.py in __init__(self, factory, *args, **kwargs)\r\n    341         # Private, should be inaccessible\r\n    342         self._write = False\r\n--> 343         self._writeable = ex.impl.submit(_iswriteable, table).result()\r\n    344 \r\n    345         should_be_writeable = not kwargs.get('readonly', True)\r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)\r\n    430                 raise CancelledError()\r\n    431             elif self._state == FINISHED:\r\n--> 432                 return self.__get_result()\r\n    433             else:\r\n    434                 raise TimeoutError()\r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/_base.py in __get_result(self)\r\n    382     def __get_result(self):\r\n    383         if self._exception:\r\n--> 384             raise self._exception\r\n    385         else:\r\n    386             return self._result\r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/thread.py in run(self)\r\n     54 \r\n     55         try:\r\n---> 56             result = self.fn(*self.args, **self.kwargs)\r\n     57         except BaseException as exc:\r\n     58             self.future.set_exception(exc)\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/table_proxy.py in _iswriteable(table_future)\r\n    236 \r\n    237 def _iswriteable(table_future):\r\n--> 238     return table_future.result().iswritable()\r\n    239 \r\n    240 \r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)\r\n    423                 raise CancelledError()\r\n    424             elif self._state == FINISHED:\r\n--> 425                 return self.__get_result()\r\n    426 \r\n    427             self._condition.wait(timeout)\r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/_base.py in __get_result(self)\r\n    382     def __get_result(self):\r\n    383         if self._exception:\r\n--> 384             raise self._exception\r\n    385         else:\r\n    386             return self._result\r\n\r\n~/.conda/envs/development/lib/python3.6/concurrent/futures/thread.py in run(self)\r\n     54 \r\n     55         try:\r\n---> 56             result = self.fn(*self.args, **self.kwargs)\r\n     57         except BaseException as exc:\r\n     58             self.future.set_exception(exc)\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/daskms/table_proxy.py in taql_factory(query, style, tables, readonly)\r\n    189 \r\n    190     try:\r\n--> 191         return pt.taql(query, style=style, tables=tables)\r\n    192     finally:\r\n    193         for t in tables:\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/casacore/tables/table.py in taql(command, style, tables, globals, locals)\r\n    152     if style:\r\n    153         cmd = 'using style ' + style + ' ' + cmd\r\n--> 154     tab = table(cmd, tabs, _oper=2)\r\n    155     result = tab._getcalcresult()\r\n    156     # If result is empty, it was a normal TaQL command resulting in a table.\r\n\r\n~/.conda/envs/development/lib/python3.6/site-packages/casacore/tables/table.py in __init__(self, tablename, tabledesc, nrow, readonly, lockoptions, ack, dminfo, endian, memorytable, concatsubtables, _columnnames, _datatypes, _oper, _delete)\r\n    327         elif _oper == 2:\r\n    328             # This is the query or calc constructor.\r\n--> 329             Table.__init__(self, tablename, tabledesc)\r\n    330             if len(self._getcalcresult()) != 0:\r\n    331                 # Do not make row object for a calc result\r\n\r\nRuntimeError: Error in TaQL command: 'using style Python SELECT\r\n\tROWID() as __tablerow__\r\nFROM\r\n\t$1\r\nORDERBY\r\n\tTIME'\r\n  Error in select expression: TIME is an unknown column (or keyword) in table /fast/claw/20221129_034113_15MHz.ms/SPECTRAL_WINDOW\r\n```","createdAt":"2022-12-02T15:03:25Z","id":"IC_kwDOBh8_I85PmEqi","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1335380642","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Try using `xds_from_table` instead of `xds_from_ms`?\r\n\r\n```python\r\nds = xds_from_table('20221129_034113_15MHz.ms::SPECTRAL_WINDOW', group_cols=\"__row__\")\r\n```","createdAt":"2022-12-02T15:29:00Z","id":"IC_kwDOBh8_I85PmO46","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1335422522","viewerDidAuthor":false},{"author":{"login":"caseyjlaw"},"authorAssociation":"NONE","body":"Ok, that is working for me.\r\nI am running into other issues when I try to reproduce the tutorials from the documentation. I think my difficulty is that the docs assume a \"TEST.MS\" with a specific structure (esp that it has two datasets).\r\nEach of my MS files has one integration and one spectral window. I'd like an easy way to merge them together into a file with multiple spectral windows. Is that something that dask-ms can do easily?\r\n","createdAt":"2022-12-02T19:08:22Z","id":"IC_kwDOBh8_I85PnQxW","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1335692374","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"`dask-ms` can certainly do it as a virtual operation i.e. by concatenating the `xarray.Dataset` objects in memory. If your aim is to write a new ms that contains multiple spectral windows, that is probably doable but not necessarily simple. I think @sjperkins will be able to advise; I have limited experience with using `dask-ms` to author new measurement sets. The path of least resistance may be for @sjperkins or myself to add this functionality to `dask-ms convert`, as that should be guaranteed to have all the necessary metadata/subtables for writing a new measurement set - adding it as part of the `xds_to_*` functionality will likely be a bit fraught.","createdAt":"2022-12-05T06:43:19Z","id":"IC_kwDOBh8_I85PrkZJ","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1336821321","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Ok, that is working for me. I am running into other issues when I try to reproduce the tutorials from the documentation. I think my difficulty is that the docs assume a \"TEST.MS\" with a specific structure (esp that it has two datasets).\r\n\r\nThere are three sources of information here that could be useful\r\n\r\n- https://github.com/ratt-ru/dask-ms/blob/482873a41f2d79a4c26d5e1816fb433bf28351ce/daskms/example_data.py#L9-L115 calls `example_ms` which crafts a minimal multi-SPW, multi-POL test MS using python-casacore. This was probably the `TEST.MS` that the docs where referring to (Apologies, its been a while).\r\n- https://github.com/ratt-ru/dask-ms/blob/482873a41f2d79a4c26d5e1816fb433bf28351ce/daskms/tests/test_ms_creation.py#L45 accomplishes similar but using the `xarray` and `dask` interface.\r\n\r\n> Each of my MS files has one integration and one spectral window. I'd like an easy way to merge them together into a file with multiple spectral windows. Is that something that dask-ms can do easily?\r\n\r\nIt's doable but you need to do some book-keeping, particularly with respect to the:\r\n\r\n- DATA_DESC_ID column in the main table\r\n- SPECTRAL_WINDOW_ID and POLARIZATION_ID columns in the DATA_DESCRIPTION sub-tables\r\n- The relevant SPECTRAL_WINDOW and POLARIZATION sub-tables.\r\n\r\nAn example of how this can be accomplished in an actual application is available [here](https://github.com/ratt-ru/xova/blob/08e090855b31cb8691531c02c8b2731359bcd70f/xova/apps/xova/averaging.py#L550-L722) in our averaging application, xova which handles the SPW case as generally as possible.\r\n\r\nIf the structure of your input MS's are well-defined, you may want to exploit that instead of going with the above approach.\r\n\r\n","createdAt":"2022-12-05T07:38:40Z","id":"IC_kwDOBh8_I85Prwtb","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/272#issuecomment-1336871771","viewerDidAuthor":false}] | created: 2022-12-01T20:33:31Z ===
* dask-ms version: 0.2.6
* Python version: 3.8
* Operating System: RHEL 8.6

### Description

I'd like to read multiple MS files and write one that joins along spectral window. Each MS file represents a single integration with a different spectral window and data have identical structure in each MS.

### What I Did

I tried to follow the suggestion in the docs, but I may have an issue with the MS.

```
> ds = xds_from_ms('20221129_034113_15MHz.ms:SPECTRAL_WINDOW', group_cols="__row__")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-75-b6c8fc404ff8> in <module>
----> 1 ds = xds_from_ms('20221129_034113_15MHz.ms:SPECTRAL_WINDOW', group_cols="__row__")

~/.conda/envs/development/lib/python3.6/site-packages/daskms/dask_ms.py in xds_from_ms(ms, columns, index_cols, group_cols, **kwargs)
    397                           index_cols=index_cols,
    398                           group_cols=group_cols,
--> 399                           **kwargs)
    400
    401

~/.conda/envs/development/lib/python3.6/site-packages/daskms/dask_ms.py in xds_from_table(table_name, columns, index_cols, group_cols, **kwargs)
    324     dask_datasets = DatasetFactory(table_name, columns,
    325                                    group_cols, index_cols,
--> 326                                    **kwargs).datasets()
    327
    328     # Return dask datasets if xarray is not available

~/.conda/envs/development/lib/python3.6/site-packages/daskms/reads.py in __init__(self, table, select_cols, group_cols, index_cols, **kwargs)
    279     def __init__(self, table, select_cols, group_cols, index_cols, **kwargs):
    280         if not table_exists(table):
--> 281             raise ValueError("'%s' does not appear to be a CASA Table" % table)
    282
    283         chunks = kwargs.pop('chunks', [{'row': _DEFAULT_ROW_CHUNKS}])

ValueError: '20221129_034113_15MHz.ms:SPECTRAL_WINDOW' does not appear to be a CASA Table

```

However, the file can be read at some level:

```
> ds = xds_from_ms('20221129_034113_15MHz.ms', group_cols=["FIELD_ID", "DATA_DESC_ID"])
> ds
[<xarray.Dataset>
 Dimensions:         (chan: 192, corr: 4, flagcat: 1, row: 62128, uvw: 3)
 Coordinates:
     ROWID           (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
 Dimensions without coordinates: chan, corr, flagcat, row, uvw
 Data variables:
     ANTENNA1        (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     ANTENNA2        (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     ARRAY_ID        (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     DATA            (row, chan, corr) complex64 dask.array<chunksize=(10000, 192, 4), meta=np.ndarray>
     EXPOSURE        (row) float64 dask.array<chunksize=(10000,), meta=np.ndarray>
     FEED1           (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     FEED2           (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     FLAG            (row, chan, corr) bool dask.array<chunksize=(10000, 192, 4), meta=np.ndarray>
     FLAG_CATEGORY   (row, flagcat, chan, corr) bool dask.array<chunksize=(10000, 1, 192, 4), meta=np.ndarray>
     FLAG_ROW        (row) bool dask.array<chunksize=(10000,), meta=np.ndarray>
     INTERVAL        (row) float64 dask.array<chunksize=(10000,), meta=np.ndarray>
     OBSERVATION_ID  (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     PROCESSOR_ID    (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     SCAN_NUMBER     (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     SIGMA           (row, corr) float32 dask.array<chunksize=(10000, 4), meta=np.ndarray>
     STATE_ID        (row) int32 dask.array<chunksize=(10000,), meta=np.ndarray>
     TIME            (row) float64 dask.array<chunksize=(10000,), meta=np.ndarray>
     TIME_CENTROID   (row) float64 dask.array<chunksize=(10000,), meta=np.ndarray>
     UVW             (row, uvw) float64 dask.array<chunksize=(10000, 3), meta=np.ndarray>
     WEIGHT          (row, corr) float32 dask.array<chunksize=(10000, 4), meta=np.ndarray>
 Attributes:
     FIELD_ID:      0
     DATA_DESC_ID:  0]
```

=== ISSUE #235 | Dataset versioning | labels: enhancement | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Three approaches thus far\r\n\r\n# 1. Store Link to parent dataset in metadata\r\n\r\nEach dataset can store a link to the parent dataset in metadata\r\n\r\n# 2. Store links to all previous datasets in metadata\r\n\r\nSlight modification to 1. I prefer this as it provides a less brittle way to specify dataset concatenation.\r\n\r\n# 3. Store all datasets in a single directory.\r\n\r\nEach dataset is stored in a sub-directory of a parent directory. The advantage of this approach is that there's less conceptual fragmentation compared to the first two approaches where url links may or may not exist.","createdAt":"2022-07-20T10:21:12Z","id":"IC_kwDOBh8_I85G73PF","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1190097861","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Something to watch out for, if we're creating multiple Measurement Sets we may end up creating empty required columns (TIME, ANTENNA1, ANTENNA2, UVW) when we only want to store a new version of for e.g. CORRECTED_DATA and FLAG.\r\n\r\n/cc @o-smirnov @JSKenyon @landmanbester","createdAt":"2022-07-20T10:24:12Z","id":"IC_kwDOBh8_I85G737f","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1190100703","viewerDidAuthor":false},{"author":{"login":"o-smirnov"},"authorAssociation":"CONTRIBUTOR","body":"I vote #2!\r\n\r\n> Something to watch out for, if we're creating multiple Measurement Sets we may end up creating empty required columns (TIME, ANTENNA1, ANTENNA2, UVW) when we only want to store a new version of for e.g. CORRECTED_DATA and FLAG.\r\n\r\nWell that's exactly the idea, isn't it... new columns live in the \"new\" version, and all other columns live in the \"old\" version. So the \"new\" version is not self-contained without the old dataset also available, but that's by design.\r\n\r\nThere's another use case for this that feels very related, and that is SSD caching. We've garnered new appreciation recently for how slow MS reads are (see https://github.com/ratt-ru/systems/issues/82), and I'll add SSD scratch filesystems to a few nodes to address this. The problem then is managing the scratch space, since it is necessarily much smaller. I think dask-ms-based tools can be made to be much more cache-friendly by implementing the following logic:\r\n\r\n* A \"fast new\" version of the MS is created on SSD space, with all columns empty, linking back to the \"old slow\" MS on HDD. Some columns (e.g. DATA, CORRECTED_DATA) are marked as \"caching\". There should a command-line tool for this.\r\n\r\n* When dask-ms reads the fast MS, non-caching columns are pulled straight from the slow version, while caching columns are first copied from the slow version to the fast version.\r\n\r\n* Likewise for writes -- caching columns are written to the fast version only, non-caching columns go straight back to the slow version.\r\n\r\n* A command-line tool can look for \"caching columns older than X days\" or \"caching columns not accessed for Y days\", write them back to the slow version, and delete them from the fast version. This can be put in a cron job.\r\n\r\nI think this can provide a very smooth user experience for dask-ms-based tools. If you have access to fast disk, you create your \"fast MS\" linking back to your original slow MS, and as long as you're actively using it, it stays on fast disk -- and if you stop molesting the data for a while, it makes its way back to slow storage eventually without you or the sysadmin worrying too much about it.\r\n\r\n(This will also be very useful in the cloud context -- I think things like S3 storage come in hierarchies of access speed...)\r\n\r\nThoughts?","createdAt":"2022-08-09T11:03:41Z","id":"IC_kwDOBh8_I85IE3hU","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1209235540","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I vote https://github.com/ratt-ru/dask-ms/pull/2!\r\n\r\nYep that's my vote too\r\n\r\n>> Something to watch out for, if we're creating multiple Measurement Sets we may end up creating empty required columns (TIME, ANTENNA1, ANTENNA2, UVW) when we only want to store a new version of for e.g. CORRECTED_DATA and FLAG.\r\n\r\n> Well that's exactly the idea, isn't it... new columns live in the \"new\" version, and all other columns live in the \"old\" version. So the \"new\" version is not self-contained without the old dataset also available, but that's by design.\r\n\r\nI more concerned by the nature of the CASA Measurement Set in the sense that if you create an MS, say with `pyrap.tables.default_ms`, all the other required columns are also created with zeros if columns have a Tiled Storage Manager, or empty otherwise. Thus, creating a secondary MS holding new CORRECTED_DATA and FLAG columns will also create empty/zeroed TIME, ANTENNA1, ANTENNA2, UVW  columns which will, annoyingly, override the correct values in the previous MS.\r\n\r\nTo work around this, it should be possible to just create the new versions as plain CASA tables (which won't have required columns). Or perhaps modify the MS descriptor to just require the new columns... This is all workable but I also don't want things to get too complex.","createdAt":"2022-08-09T13:00:48Z","id":"IC_kwDOBh8_I85IFUCg","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1209352352","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"The zarr and parquet formats don't have these issues because there no distinction between a plain dataset and an MS dataset.","createdAt":"2022-08-09T13:06:57Z","id":"IC_kwDOBh8_I85IFVmt","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1209358765","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> (This will also be very useful in the cloud context -- I think things like S3 storage come in hierarchies of access speed...)\r\n\r\nYep, these are all exciting suggestions. In fact, one thought that comes to mind is datasets composed of CASA tables for the original and zarr/parquet tables for the deltas (fast versions).\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n> There's another use case for this that feels very related, and that is SSD caching. We've garnered new appreciation recently for how slow MS reads are (see [ratt-ru/systems#82](https://github.com/ratt-ru/systems/issues/82)), and I'll add SSD scratch filesystems to a few nodes to address this. The problem then is managing the scratch space, since it is necessarily much smaller. I think dask-ms-based tools can be made to be much more cache-friendly by implementing the following logic:\r\n> \r\n> * A \"fast new\" version of the MS is created on SSD space, with all columns empty, linking back to the \"old slow\" MS on HDD. Some columns (e.g. DATA, CORRECTED_DATA) are marked as \"caching\". There should a command-line tool for this.\r\n> * When dask-ms reads the fast MS, non-caching columns are pulled straight from the slow version, while caching columns are first copied from the slow version to the fast version.\r\n> * Likewise for writes -- caching columns are written to the fast version only, non-caching columns go straight back to the slow version.\r\n> * A command-line tool can look for \"caching columns older than X days\" or \"caching columns not accessed for Y days\", write them back to the slow version, and delete them from the fast version. This can be put in a cron job.\r\n> \r\n> I think this can provide a very smooth user experience for dask-ms-based tools. If you have access to fast disk, you create your \"fast MS\" linking back to your original slow MS, and as long as you're actively using it, it stays on fast disk -- and if you stop molesting the data for a while, it makes its way back to slow storage eventually without you or the sysadmin worrying too much about it.\r\n\r\nYep, this is all sensible stuff. I would point that this is the kind of functionality that a datalake implements -- I'm somewhat wary of reinventing the wheel here, even though it may be fun to roll our own stuff.\r\n\r\n","createdAt":"2022-08-09T13:18:00Z","id":"IC_kwDOBh8_I85IFYhJ","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1209370697","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"One strategy that occurred to me was to introduce a new MS indexing column (PROVENANCE_ID or repurposing an existing column) storing an integer for each row. Each entry would index a list of previous on-disk datasets, stored in a separate PROVENANCE subtable or in table/column metadata.\r\n\r\n/cc @JSKenyon @landmanbester @bennahugo ","createdAt":"2022-10-31T08:57:59Z","id":"IC_kwDOBh8_I85NS2Z6","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296787066","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"I also think that averaging should result in the discarding previous provenance information, because a one-to-one mapping no longer exists.","createdAt":"2022-10-31T08:59:33Z","id":"IC_kwDOBh8_I85NS2yx","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296788657","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Posting @o-smirnov's chat discussion here:\r\n\r\n> From a user's PoV, the simplest thing for flagversions would be:\r\n>\r\n> 1. QuartiCal writes to the FLAG column (of the current delta-set)\r\n> 2. A command-line tool is used to say \"I would like to save this version of FLAG content under the name 'foo'\"\r\n> 3. The next time QuartiCal writes to FLAG, the current content of FLAG is tucked away under the label \"foo\" somehow, and new content is written in. So copy-on-write semantics\r\n>\r\n> Then the restore operation is as simple as saying \"restore FLAG:foo\"\r\n","createdAt":"2022-10-31T10:25:18Z","id":"IC_kwDOBh8_I85NTOf6","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296885754","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Here is my current thoughts for a row-granularity data provenance mechanism:\r\n\r\n# Provenance Sub-table\r\n\r\n| id  | name | url |\r\n| ------------- | ------------- |-----------|\r\n| 0 | archive | s3://ratt-public-data/ESO137/archive.zarr | \r\n| 1 | 1gc | s3://ratt-public-data/ESO137/1gc .zarr | \r\n| 2 | 3gc | s3://ratt-public-data/ESO137/1gc .zarr |\r\n| 3 | imaging | s3://ratt-public-data/ESO137/imaging .zarr |\r\n\r\n# PROVENANCE_ID column\r\n\r\n- Through this column, partial derivation of a dataset from multiple datasets can be supported at row granularity.\r\n- Add to MAIN table\r\n- Added to all sub-tables. This could be potentially messy.\r\n- One of my concerns with this approach is that creating dask arrays from many partial sources\r\n   can end up being messy and interfere with chunking mechanisms.\r\n\r\n# Add `provenance` keyword to `xds_from_` and `xds_to_` methods\r\n\r\n- If provenance, not specified, then latest provenance is the default in `xds_from_` and `xds_to_` methods\r\n- Otherwise provenance name must be supplied by application.","createdAt":"2022-10-31T11:04:09Z","id":"IC_kwDOBh8_I85NTYhC","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296926786","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"I'm leaning towards ditching the `PROVENANCE_ID` column and making it a requirement that provenance `chains` must have a one-to-one mapping in terms of data sizes. Would this be too restrictive for data processing purposes?","createdAt":"2022-10-31T11:16:12Z","id":"IC_kwDOBh8_I85NTbpE","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296939588","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I'm leaning towards ditching the `PROVENANCE_ID` column and making it a requirement that provenance `chains` must have a one-to-one mapping in terms of data sizes. Would this be too restrictive for data processing purposes?\r\n\r\nIf a new data size is produced (by averaging) for example, a completely  new provenance `chain`, and hence, sub-table would be created.","createdAt":"2022-10-31T11:18:30Z","id":"IC_kwDOBh8_I85NTcR_","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296942207","viewerDidAuthor":false},{"author":{"login":"o-smirnov"},"authorAssociation":"CONTRIBUTOR","body":"\r\n> I'm leaning towards ditching the `PROVENANCE_ID` column and making it a requirement that provenance `chains` must have a one-to-one mapping in terms of data sizes. Would this be too restrictive for data processing purposes?\r\n\r\nYes. A very common procedure is to split out calibrators and targets (different FIELD_IDs). It would be very nice if chains supported this, making this split-out effectively a no-op (in terms of storage used). \r\n\r\n> If a new data size is produced (by averaging) for example, a completely new provenance chain, and hence, sub-table would be created.\r\n\r\nI think averaging makes a completely new dataset anyway, no, so there's no chain to speak of?","createdAt":"2022-10-31T11:41:08Z","id":"IC_kwDOBh8_I85NTiGu","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296966062","viewerDidAuthor":false},{"author":{"login":"o-smirnov"},"authorAssociation":"CONTRIBUTOR","body":"> * One of my concerns with this approach is that creating dask arrays from many partial sources\r\ncan end up being messy and interfere with chunking mechanisms.\r\n\r\nYes I see that concern. My current feeling is that a per-row ``PROVENANCE_ID`` is certainly the most generic way, but is also overkill for most applications.\r\n\r\nI think what would be sufficient would be for a delta-column to represent a **fixed** (row-based) subset of the parent column. Can we do it without full-on row-level granularity somehow? Let's keep on thinking...\r\n\r\n","createdAt":"2022-10-31T11:49:55Z","id":"IC_kwDOBh8_I85NTkM3","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296974647","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Yes. A very common procedure is to split out calibrators and targets (different FIELD_IDs). It would be very nice if chains supported this, making this split-out effectively a no-op (in terms of storage used).\r\n\r\nYes, we'd need data subsets you describe below to support the above case, because the split data would be derived from completely different rows.\r\n\r\n> I think what would be sufficient would be for a delta-column to represent a fixed (row-based) subset of the parent column. Can we do it without full-on row-level granularity somehow? Let's keep on thinking...\r\n\r\nWill do. In fact, am doing some reading under the wikpedia [Data Lineage](https://en.wikipedia.org/wiki/Data_lineage) which seems to fall squarely into what we're planning.","createdAt":"2022-10-31T12:09:05Z","id":"IC_kwDOBh8_I85NTo0X","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1296993559","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"https://discourse.pangeo.io/t/tracking-provenance-in-xarray/1510","createdAt":"2022-10-31T12:27:43Z","id":"IC_kwDOBh8_I85NTtzR","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1297013969","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"- @JSKenyon previously mentioned https://docs.xarray.dev/en/stable/generated/xarray.merge.html as a mechanism for reconciling a series of Datasets.\r\n- We'd probably need to reify coordinates in order to do so.\r\n- Disparate Dataset chunking might still be an issue\r\n  - in the most pathological case, say we need one row from a dask array in a previous Dataset that represents a load of 10,000 rows.\r\n\r\n","createdAt":"2022-10-31T13:25:30Z","id":"IC_kwDOBh8_I85NT_qp","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1297087145","viewerDidAuthor":false},{"author":{"login":"o-smirnov"},"authorAssociation":"CONTRIBUTOR","body":"If performance in pathological edge cases is the only issue, then I wouldn't worry about it too much... ","createdAt":"2022-10-31T13:56:58Z","id":"IC_kwDOBh8_I85NUK1T","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[{"content":"THUMBS_UP","users":{"totalCount":1}}],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1297132883","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"TileDB supports dataset versioning and time travelling natively.\n\nhttps://docs.tiledb.com/main/background/key-concepts-and-data-format","createdAt":"2022-10-31T14:00:59Z","id":"IC_kwDOBh8_I85NUMFw","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1297138032","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> If performance in pathological edge cases is the only issue, then I wouldn't worry about it too much...\r\n\r\nAgreed that this is unlikely","createdAt":"2022-10-31T14:01:55Z","id":"IC_kwDOBh8_I85NUMXj","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/235#issuecomment-1297139171","viewerDidAuthor":false}] | created: 2022-07-20T10:17:04Z ===
Support Dataset Versioning. Briefly:

1. Datasets should provide a unified view over multiple datasets on disk.
2. This will allow users to iteratively reduce their data.

=== ISSUE #227 | Document experimental Zarr and Apache Arrow formats | labels: documentation | comments: [] | created: 2022-07-04T10:42:11Z ===
### Description

dask-ms contains experimental support for Zarr and Apache Arrow (parquet formats). These should be documented.

xref:
- #226

=== ISSUE #226 | Document dask-ms convert | labels: documentation | comments: [] | created: 2022-07-04T10:41:09Z ===
### Description

`dask-ms convert` converts Measurement Sets between CASA, Zarr and Apache Arrow (Parquet) formats. This should be documented.


=== ISSUE #225 | Document performance tuning | labels: documentation | comments: [] | created: 2022-07-04T10:38:06Z ===
# Description

Currently, there are a number of parameters that can affect performance in multiple formats. It would be useful to document them.

## CASA

1. Choice of storage manager. Tiled Storage Managers have better performance than Standard Storage Managers. Data can be tiled (chunked) on multiple dimensions.
2. Grouping, indexing columns and TAQL where queries can produce non-contiguous row ordering patterns.
4.  Chunk Sizes specified in `xds_from_*(chunks={"row": 10000})` affect performance:

    - Larger chunk sizes generally perform better as requests for larger quantities of data can be issued in one call (although this is affected by (2)).
    - Functions that process larger chunk sizes can drop the GIL (especially if written in numba or C++). This is useful in a dask environment.
    - Matching some multiple of TiledStorageManager chunks would also  probably improve performance.


## Zarr

1. Can specify on disk chunk sizes, similar to TiledStorageManager

## Arrow/Parquet

1. Arrow datasets are composed of multiple Arrow tables, partitioned by row. Thus, can only chunk on row.

=== ISSUE #223 | Reintroduce warnings for non-contiguous data | labels:  | comments: [] | created: 2022-06-28T10:52:27Z ===
### Description

Historically we used to warn about highly fragmented row runs, but this was removed as it spammed the log.

However, it would be better to reintroduce this in a more limited form to enable faster debugging of disk performance issues.

cc @JSKenyon @o-smirnov


=== ISSUE #213 | How to map correlations to Stokes parameters without looping the correlations? | labels:  | comments: [{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Hi @miguelcarcamov! Apologies for the delay - I was on vacation. I am not entirely sure what you are trying to accomplish. Could you possibly provide more details/a code snippet?\r\n\r\nAre you trying to map [XX, XY, YX, YY] to [I, Q, U V] on the xarray datasets?","createdAt":"2022-05-03T09:44:41Z","id":"IC_kwDOBh8_I85Cg38P","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/213#issuecomment-1115913999","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Hi @JSKenyon well it depends of the feed really. If you see [this code](https://gitlab.com/miguelcarcamov/pyralysis/-/blob/development/pyralysis/transformers/dirty_mapper.py) that tries to do a dirty map from data using dask, you can see that in line 120 I loop the correlations in order to map them to I,Q,U,V depending on the feed. In the code, `gridded_data` and `gridded_weights` have a shape of (m,n,ncorrs), and to sum them to I,Q,U,V uv-grids depending on the feed it costs me a loop through all correlations for each one of the subms. I want to get rid of that for loop, but I'm not so sure of how to do it yet. It might be difficult to follow this, but let me know if you have questions :) ","createdAt":"2022-05-05T16:49:19Z","id":"IC_kwDOBh8_I85Cr87G","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/213#issuecomment-1118817990","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"If you are doing all your operations on dask arrays, I am not sure why the loop itself would be slow (unless you have a huge number of datasets). You can likely simplify the code by just having a mapping stored somewhere so that you don't have to check so many conditions.\r\n\r\nIf your code is pure dask, that loop over correlations isn't doing any real work - it is just setting up a graph. If, however, your arrays have already been reified to numpy at that point, I can imagine that that is slow. \r\n\r\nWould you be willing to run [line_profiler](https://github.com/pyutils/line_profiler) on the function? That may make it a bit clearer to me. ","createdAt":"2022-05-09T08:13:07Z","id":"IC_kwDOBh8_I85CzdHq","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/213#issuecomment-1120784874","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"You may also want to consider: https://codex-africanus.readthedocs.io/en/latest/model-api.html#africanus.model.coherency.dask.convert","createdAt":"2022-07-04T10:47:43Z","id":"IC_kwDOBh8_I85F9L2v","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/213#issuecomment-1173667247","viewerDidAuthor":false}] | created: 2022-04-30T11:34:42Z ===
* dask-ms version: 0.2.6
* Python version: 3.9.7
* Operating System: Manjaro

Hello, I am trying to calculate the psf/dirtybeam analytically with dask-ms and also gridding the data. However, to calculate the psf analytically for each stokes parameter, or the dirty image for each stokes parameter it has been inevitable to loop the correlations to match the data of the correlations to each Stokes. This additional loop inside the loop of list of subms makes the code considerably slow. Has anyone found a way to map the correlations to each stokes without looping the correlations? Is there a way to do this with dask?

If what I just wrote above does not make sense to you, please ask :).


=== ISSUE #212 | Add quiet mode to `xds_from_storage*` functions | labels: enhancement | comments: [] | created: 2022-04-26T08:07:26Z ===
### Description

These functions can raise a large number of `UserWarnings` due to slight discrepancies in the supported features. Canny developers may want to silence these warnings if they are aware of the repercussions and don't want the messages confusing users.

=== ISSUE #211 | Support rechunking of non-row axes in `xds_from_parquet`. | labels: enhancement | comments: [] | created: 2022-04-26T07:56:58Z ===
### Description

Parquet does not allow for on-disk chunking of non-row dimensions. In the interests of providing as uniform an interface as possible to the casa, zarr and parquet backends, I propose that we support chunking in non-row dimensions using `dask.Array.rechunk` functionality. This will have some obvious limitations, as we will still end up with a row-only chunked array in memory i.e. we will read all channels for a number of rows, even if we subsequently process them in smaller chunks. This will will also introduce a shared root in resulting graph (although we may be able to circumvent this with inlining/caching).

An alternative would be to re-read and slice the data for non-row chunks. This would result in a large amount of memory and disk overhead as we would need to repeatedly allocate memory and read from disk.

My instinct is to go with the first option for now as this is still highly experimental functionality.

=== ISSUE #206 | Make xarray a default dependency | labels:  | comments: [{"author":{"login":"bennahugo"},"authorAssociation":"COLLABORATOR","body":"No, I can't think of any good reason not to simplify this to just use\nxarray -- it is a stable package.\n\nOn Thu, Apr 21, 2022 at 9:23 AM JSKenyon ***@***.***> wrote:\n\n> Description\n>\n> I believe that the time may have come to make xarray a core dependency\n> rather than an extra. At present, it is optional as dask-ms implements\n> its own stripped down Dataset. Unfortunately, this is introducing more\n> and more maintenance as these stripped down Dataset objects do not\n> implement a host of xarray.Dataset functionality. This means that writing\n> tests can become frustrating as you have to write the tests anticipating\n> two different Dataset implementations (or skip the tests entirely in the\n> absence of xarray, somewhat defeating the point of writing tests). I am\n> personally of the opinion that the xarray.Dataset representation should\n> be fundamental to dask-ms, even if it is less lightweight.\n>\n> The purpose of this issue is discussion - does anyone object?\n>\n> —\n> Reply to this email directly, view it on GitHub\n> <https://github.com/ratt-ru/dask-ms/issues/206>, or unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AB4RE6SVRBAXAWFPOEOBVCDVGD66VANCNFSM5T6JGJFA>\n> .\n> You are receiving this because you are subscribed to this thread.Message\n> ID: ***@***.***>\n>\n\n\n-- \n--\nBenjamin Hugo\n\nPhD. student,\nCentre for Radio Astronomy Techniques and Technologies\nDepartment of Physics and Electronics\nRhodes University\n\nJunior software developer\nRadio Astronomy Research Group\nSouth African Radio Astronomy Observatory\nBlack River Business Park\nObservatory\nCape Town\n","createdAt":"2022-04-21T08:14:17Z","id":"IC_kwDOBh8_I85B2rg0","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/206#issuecomment-1104853044","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"From offline discussion with Simon I now know that xova relies on the `daskms.Dataset`. I will continue to think about this as we don't want to break anything. ","createdAt":"2022-04-22T11:28:31Z","id":"IC_kwDOBh8_I85B8qiW","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/206#issuecomment-1106421910","viewerDidAuthor":false}] | created: 2022-04-21T07:23:11Z ===
### Description

I believe that the time may have come to make `xarray` a core dependency rather than an extra. At present, it is optional as `dask-ms` implements its own stripped down `Dataset`. Unfortunately, this is introducing more and more maintenance as these stripped down `Dataset` objects do not implement a host of `xarray.Dataset` functionality. This means that writing tests can become frustrating as you have to write the tests anticipating two different `Dataset` implementations (or skip the tests entirely in the absence of `xarray`, somewhat defeating the point of writing tests). I am personally of the opinion that the `xarray.Dataset` representation should be fundamental to `dask-ms`, even if it is less lightweight.

The purpose of this issue is discussion - does anyone object?

=== ISSUE #193 | xds_from_storage_* functions need documentation | labels:  | comments: [] | created: 2022-03-30T08:05:23Z ===
### Description
Nothing complicated, these functions simply lack documentation. This will likely only be added once I have fixed the tiny issues limiting their usefulness.

=== ISSUE #190 | How to deal with file locks properly in a distributed environment | labels:  | comments: [] | created: 2022-03-24T06:59:55Z ===
Just plotting down ideas for discussion for now:

From what I can tell in my browse of this there are the following existing issues:
- In the distributed case casacore::tables rely on OS-supported flocks (sysctl) which are not guaranteed to be safe to use in shared storage between machines (there is no awareness of node IP or other identifying criteria. Looking at this: https://github.com/ratt-ru/dask-ms/blob/master/daskms/table_executor.py#L38-L54 if multiple dask processes each backed with a threadpool and queue pointing to a database on a shared filesystem are started on multiple nodes there is no guarantee that the flocks will hold.
-  One possibility (since dask is being used here) is to implement something like: https://github.com/pydata/xarray/blob/main/xarray/backends/locks.py with spinning locks to block until the lock becomes available as a wrapper around the entire table system to make it distribution-safe.
- The same "user-style" read and write locking will need to be applied for xarray-backed datasets as far as I can tell via context management, although I'm not sure how finely the arrays are "bucketed" in the array specification for this to work.

=== ISSUE #167 | Transforming dataset to a gridded dataset | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @miguelcarcamov. I'll be back in the office next week and will reply in more detail then. In the meantime, you may want to take a look at pfb-clean https://github.com/ratt-ru/pfb-clean/blob/master/pfb/operators/gridder.py. /cc @landmanbester ","createdAt":"2021-10-05T07:29:55Z","id":"IC_kwDOBh8_I843reNN","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/167#issuecomment-934142797","viewerDidAuthor":false},{"author":{"login":"landmanbester"},"authorAssociation":"COLLABORATOR","body":"I guess the short answer here is no. All the gridding actually happens inside the wgridder in [ducc0](https://gitlab.mpcdf.mpg.de/mtr/ducc) which does not expose the grids. From the user's perspective you have images going in and visibilities coming out. All w-corrections, padding, oversampling etc. is taken care of under the hood. If I understand correctly, what you are suggesting might not actually give you a smaller data product in the end because you will have to store a grid roughly the size of the image per baseline. Note that the gridder operator above is a bit outdated, I keep it there for legacy reasons. All gridding related operations now happen [here](https://github.com/ratt-ru/pfb-clean/tree/stokes_products/pfb/workers/grid) but I am not sure if that is useful to you because these workers really just do the data handling. There are dask wrappers for the wgridder in codex-africanus [here](https://github.com/ska-sa/codex-africanus/tree/master/africanus/gridding/wgridder) ","createdAt":"2021-10-05T09:05:28Z","id":"IC_kwDOBh8_I843rvru","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/167#issuecomment-934214382","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@landmanbester  I disagree with this - I mean, the size of the product will depend on the size of the grid and your pixel size (in Fourier space), but also on the size of your convolution kernels. The worst case would be to have a really big kernel and then... Yes, you can end up with a grid with the size of the image per baseline. Although if we are using dask, there is no much to be worried about that. To get to some point I have two questions:\r\n\r\n1) It is possible to loop baselines in a faster way? - Take into account that we are not using the gridding to use it in clean but also to reduce data so it can be used in other optimization algorithms - This algorithms might take non-gridded or gridded data. If not, I guess we might need to lose the baseline information on gridded data and recover it once degridding is done.\r\n\r\n2) Can I use joblib to loop the baselines? If dask data can be accessed in parallel, that would speed up things and I could end up doing the gridding on parallel per each baseline.\r\n\r\n3) As I said, if this is not possible then I will just drop the baseline info for gridded data and then recover if a degridding process is made.\r\n\r\nCheers, \r\n","createdAt":"2021-10-05T19:04:19Z","id":"IC_kwDOBh8_I843tj0Q","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/167#issuecomment-934690064","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":" >     1. It is possible to loop baselines in a faster way? - Take into account that we are not using the gridding to use it in clean but also to reduce data so it can be used in other optimization algorithms - This algorithms might take non-gridded or gridded data. If not, I guess we might need to lose the baseline information on gridded data and recover it once degridding is done.\r\n\r\nMuch of the performance impact of handling each baseline's data separately is that data for each baseline is not contiguously ordered in a monotically increasing TIME ordered Measurement Set, which is the order that newer interferometers will almost certainly choose. Instead, each baseline's data is striped over the entire Measurement Set which leads to poor Disk I/O performance. If I recall correctly, WSClean performs a reordering step where data is separated out into separate baselines in order to avoid these issues. This reordering step should be efficient because the data can be read and written contiguously.\r\n\r\nThe other alternative, as @landmanbester points out is, for each dask chunk, to maintain grids for each baseline separately. Obviously, the dominant issues here are the size of the grid and the number of baselines. E.g. for single precision complex valued MeerKAT data: `8192 x 8192 x 2016 x 8 = ~1TB` per chunk of data and one would need at least 2 of those in memory (and probably a few more) to perform a parallel reduction.\r\n\r\nBut, I'm interested in your intention behind gridding -- it sounds as if you're gridding data with the intention of degridding it again to produce data with a higher time resolution. Is this the case? Perhaps you may be intending to average complex visibility data instead? We have some experience with this too and have an application called xova which performs this process:\r\n\r\n- https://github.com/ska-sa/xova\r\n- It wraps averaging routines from [codex-africanus](https://codex-africanus.readthedocs.io/en/latest/averaging-api.html)\r\n\r\n>     2. Can I use joblib to loop the baselines? If dask data can be accessed in parallel, that would speed up things and I could end up doing the gridding on parallel per each baseline.\r\n\r\nI haven't tried using joblib, but this should, in principle, be possible.\r\n \r\n>     3. As I said, if this is not possible then I will just drop the baseline info for gridded data and then recover if a degridding process is made.\r\n\r\nI think the answer to this question will lie in your response to my response in (1) :-)\r\n","createdAt":"2021-10-11T14:38:31Z","id":"IC_kwDOBh8_I844CKaI","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/167#issuecomment-940091016","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Hi @sjperkins , I have just come back from holidays.\r\n\r\n> Much of the performance impact of handling each baseline's data separately is that data for each baseline is not contiguously ordered in a monotically increasing TIME ordered Measurement Set, which is the order that newer interferometers will almost certainly choose. Instead, each baseline's data is striped over the entire Measurement Set which leads to poor Disk I/O performance. If I recall correctly, WSClean performs a reordering step where data is separated out into separate baselines in order to avoid these issues. This reordering step should be efficient because the data can be read and written contiguously.\r\n\r\nIs it possible to do this reordering using dask-ms? Maybe I can test doing this reordering and trying to check if the gridding per baseline goes faster....\r\n\r\n> The other alternative, as @landmanbester points out is, for each dask chunk, to maintain grids for each baseline separately. Obviously, the dominant issues here are the size of the grid and the number of baselines. E.g. for single precision complex valued MeerKAT data: 8192 x 8192 x 2016 x 8 = ~1TB per chunk of data and one would need at least 2 of those in memory (and probably a few more) to perform a parallel reduction.\r\n\r\nCorrect. Although this would decrease a bit since not all pixels in the grid will have non-zero values (some of them will be zero) - and that's what I am planning to store. So also depends on the convolution kernel and your pixel size in uv-space - I am trying to replicate the original dataset structure but with gridded data instead of ungridded data. Obviously those zero value data points in the grid won't be part of the gridded dataset.\r\n\r\n> But, I'm interested in your intention behind gridding -- it sounds as if you're gridding data with the intention of degridding it again to produce data with a higher time resolution.\r\n\r\nNot exactly... I am planning to grid to decrease the size of the original data - As I said the amount of this decrease depends on the convolution kernels and the pixel-size in uv-space. But let's say that we will end up with a smaller dataset. \r\n\r\nThis dataset then will pass through a reconstruction algorithm, which will give us the image/s and will add a model column to the dataset.\r\n\r\nThis dataset will still be gridded, but it will be possible to apply a degridding in order to obtain data points of the data columns (data and model) in the original (non-gridded) uv points.\r\n\r\nHope that this explains better what I am trying to do.\r\n\r\nCheers!","createdAt":"2021-11-03T18:29:17Z","id":"IC_kwDOBh8_I845NYVO","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/167#issuecomment-959808846","viewerDidAuthor":false}] | created: 2021-10-03T12:13:43Z ===
* dask-ms version:0.2.6
* Python version: 3.9.7
* Operating System: Manjaro LInux

### Description

Hello, is anyone working on transforming the dask-ms dataset to a gridded dataset? I am working on it using dask and the function bincount which works well. However, I would like to have the same structure as the original MS - or Dask-ms dataset. Say, less rows (due to the gridding) but per baseline and per spw.

Is not a problem looping the ms inside and ms_list. However, the problem is when trying to loop the baselines inside that ms_list (this takes a lot of computing time, because I guess each time that I do a compute(), the file is opened and read). I will share my code to see if you can give me a hand.
```
from .transformer import Transformer
from ..reconstruction.convolution import CKernel
from ..reconstruction import Image
from ..units import lambdas_equivalencies
from typing import List, Union
import astropy.units as un
import xarray as xr
import dask.array as da
from astropy.units import Quantity
from ..base import MS
import numpy as np
from abc import ABC


def bincount(weights, x):
    return np.bincount(x, weights)


def complex_bincount(weights, x):
    real_w = weights.real
    imag_w = weights.imag
    return np.bincount(x, real_w) + 1j * np.bincount(x, imag_w)


def calculate_pix(uvw, uvcellsize, imsize, ref_freq):
    m = imsize[0]
    n = imsize[1]
    duv = uvcellsize.to(un.m, equivalencies=lambdas_equivalencies(ref_freq))
    uv = uvw[:, 0:2] / duv
    uv = xr.apply_ufunc(lambda x: x.value, uv, dask="parallelized", output_dtypes=[uv.dtype]).round().astype(np.int32)
    u_pix = uv[:, 0] + m // 2
    v_pix = uv[:, 1] + n // 2
    idx = n * v_pix + u_pix
    return idx


class Gridding(Transformer, ABC):
    def __init__(self, image: Image = None, imsize: Union[List[int], int] = None, uvcellsize: Quantity = None,
                 ckernel_object: CKernel = None, **kwargs):
        """
        Class that represents the interferometric gridding
        :param imsize: Image size
        :param uvcellsize: Cell size in Fourier-space
        :param ckernel_object: Convolution Kernel
        :param kwargs: Transformer arguments
        """
        super().__init__(**kwargs)
        self.ckernel_object = ckernel_object
        self.image = image
        if image is None:
            if isinstance(imsize, int):
                self.imsize = [imsize, imsize]
            else:
                self.imsize = imsize

            if isinstance(uvcellsize, Quantity):
                if uvcellsize.shape[0] > 1:
                    self.uvcellsize = uvcellsize
                else:
                    self.uvcellsize = Quantity([uvcellsize, uvcellsize, uvcellsize])
            else:
                raise TypeError("uvcellsize must be a Quantity instance")
        else:
            self.imsize = image.imsize
            self.uvcellsize = image.cellsize.to(un.lambdas, equivalencies=lambdas_equivalencies()) / self.imsize

    def grid_weights(self, ms: MS = None):
        if ms is not None:

            ref_freq = ms.spectral_window.ref_frequency
            uvw = ms.visibilities.uvw
            weight = ms.visibilities.weight
            idx = calculate_pix(uvw, self.uvcellsize, self.imsize, ref_freq)
            bincount_m = idx.data.max().compute() + 1
            bin_count = da.apply_along_axis(bincount, 0, weight.data, idx.data, shape=(bincount_m,),
                                            dtype=weight.data.dtype)
            w_k = bin_count[idx]  # Gridded weight for each non-gridded u,v coordinate
            return idx, bin_count, w_k

        else:
            raise ValueError("MS cannot be Nonetype")

    # This does the convolutional gridding
    def transform(self) -> None:

        for ms in self.input_data.ms_list:
            ref_freq = ms.spectral_window.ref_frequency
            uvw = ms.visibilities.uvw
            weight = ms.visibilities.weight
            data = ms.visibilities.data
            flag = ms.visibilities.flag

            idx = calculate_pix(uvw, self.uvcellsize, self.imsize, ref_freq)
            ncorrs = ms.polarization.ncorrs
            nchans = ms.spectral_window.nchans
            # chans = ms.spectral_window.chans.compute()
            baselines = da.unique(ms.visibilities.baseline.data).compute()
            weight_list = []
            data_list = []
            for baseline_id in baselines:
                row_id = da.argwhere(ms.visibilities.baseline.data == baseline_id).squeeze().compute()
                idx_per_baseline = idx[row_id]
                weight_per_baseline = weight[row_id]
                flag_per_baseline = flag[row_id]  # (rows, nchans, ncorrs)
                data_per_baseline = data[row_id]
                bincount_m = idx_per_baseline.data.max().compute() + 1
                # Grid the weights (rows, ncorrs)
                bin_count_weights = da.apply_along_axis(bincount, 0, weight_per_baseline.data, idx_per_baseline.data,
                                                        shape=(bincount_m,),
                                                        dtype=weight_per_baseline.data.dtype)
                gridded_weights = bin_count_weights[idx_per_baseline]

                # Grid the complex data (rows, nchans, ncorrs) (w * data)
                weight_broadcast = da.tile(weight_per_baseline, nchans).reshape(
                    (len(weight_per_baseline), nchans, ncorrs))
                weight_broadcast = da.where(~flag_per_baseline, weight_broadcast, 0.0)
                visibility_data_per_baseline = weight_broadcast * data_per_baseline
                bin_count_visibilities = da.apply_along_axis(complex_bincount, 0, visibility_data_per_baseline.data,
                                                             idx_per_baseline.data,
                                                             shape=(bincount_m,),
                                                             dtype=visibility_data_per_baseline.data.dtype)

                bin_count_weight_broadcast = da.apply_along_axis(bincount, 0, weight_broadcast,
                                                             idx_per_baseline.data,
                                                             shape=(bincount_m,),
                                                             dtype=weight_broadcast.dtype)
                gridded_data = bin_count_visibilities[idx_per_baseline] / bin_count_weight_broadcast[idx_per_baseline]
                weight_list.append(gridded_weights)
                data_list.append(gridded_data)
            break # This break is here because we have just tested with one ms from the ms-list
```

=== ISSUE #159 | Baseline information | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @miguelcarcamov, I think it depends on how far you want to take it.\r\n\r\n# 1. The easy, but probably less efficient approach\r\n\r\n\r\nYou could set up your datasets with the following:\r\n\r\n```python\r\ndatasets = xds_from_ms(ms, group_cols=[\"FIELD_ID\", \"DATA_DESC_ID\", \"ANTENNA1\", \"ANTENNA2\"])\r\n```\r\n\r\nThis will create a unique dataset per combination of FIELD_ID, DATA_DESC_ID and BASELINE. Unfortunately, Measurement Sets are frequently monotonically ordered in TIME, rather than ANTENNA1, ANTENNA2, so the resulting datasets will be backed by reads of non-contiguous rows, which results in inefficient disk read patterns. But it should be fairly easy to calculate the max baseline length per dataset as follows:\r\n\r\n```python\r\nimport dask\r\nimport dask.array\r\ndatasets = xds_from_ms(ms, group_cols=[\"FIELD_ID\", \"DATA_DESC_ID\", \"ANTENNA1\", \"ANTENNA2\"])\r\n\r\nbl_lengths = []\r\n\r\nfor ds in datasets:\r\n  ant1 = da.full_like(ds.TIME.data, ds.ANTENNA1, dtype=np.int32)\r\n  ant2 = da.full_like(ds.TIME.data, ds.ANTENNA2, dtype=np.int32)\r\n  bl_lengths.append(da.sqrt((ds.UVW.data[ant2, : ] - ds.UVW.data[ant1, :])**2).max())\r\n\r\ndask.compute(bl_lengths)\r\n```\r\n\r\nIf you want to do more with the baseline length (i.e. process visibility data), then non-contiguous disk access will hurt performance.\r\n\r\n# 2. The harder, but more efficient approach\r\n\r\nA second approach requires (1) some knowledge of dask internals (2) the ability to process your baseline data on a per-chunk basis. \r\n\r\n```python\r\nfrom __future__ import print_function\r\n\r\nimport argparse\r\n\r\nimport dask\r\nimport dask.array as da\r\nfrom daskms import xds_from_ms\r\nimport numpy as np\r\n\r\ndef create_parser():\r\n    p = argparse.ArgumentParser()\r\n    p.add_argument(\"ms\")\r\n    return p\r\n\r\ndef _process(ant1, ant2, uvw):\r\n    uvw = uvw[0]  # Contraction over the uvw3 axis\r\n    # Identify unique  baselines in this chunk\r\n    baselines = np.stack((ant1, ant2), axis=1)\r\n    ubl, inv = np.unique(baselines, return_inverse=True, axis=0)\r\n\r\n   # Determine their lengths\r\n    bl_length = np.empty(ubl.shape[0], dtype=uvw.dtype)\r\n\r\n    for i, (a1, a2) in enumerate(ubl):\r\n        bl_length[i] = np.sqrt(uvw[i == inv, :]**2).max()\r\n\r\n    print(bl_length)\r\n    # Further processing required beyond this point\r\n\r\nif __name__ == \"__main__\":\r\n    args = create_parser().parse_args()\r\n    ds = xds_from_ms(args.ms)\r\n    ds = ds[0]    # Just demonstrate on the first dataset\r\n\r\n    # Map _process function on input arrays to produce an output arrow\r\n    # A good understanding of dask.array.blockwise is advised\r\n    process = da.blockwise(_process, (\"row\",),\r\n                           ds.ANTENNA1.data, (\"row\",),\r\n                           ds.ANTENNA2.data, (\"row\",),\r\n                           ds.UVW.data, (\"row\", \"uvw3\"),\r\n                           concatenate=False,\r\n                           meta=np.empty((), np.object))\r\n\r\n    dask.compute(process)\r\n```\r\n\r\n## Conclusion\r\n\r\nI suspect the approach you take will depend on whether you want to crunch the larger visibility data. What are your thoughts?\r\n```\r\n\r\n\r\n","createdAt":"2021-05-10T09:08:37Z","id":"MDEyOklzc3VlQ29tbWVudDgzNjQzOTc0Nw==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-836439747","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"I ended up using itertools.combinations. Although since I am very new on using dask it might be less efficient than your approach. I would like you to tell me what you think.\r\n\r\n```python\r\nantennas = xds_from_table(self.ms_name_dask + \"ANTENNA\", taql_where=taql_query)[0]\r\nantenna_obj = Antenna(dataset=antennas)\r\n```\r\nWhen creating the object antennas it runs this:\r\n```python\r\nself.max_diameter = 0.0 * u.m\r\nself.min_diameter = 0.0 * u.m\r\n        if dataset is not None:\r\n            self.max_diameter = self.dataset.DISH_DIAMETER.data.max().compute() * u.m\r\n            self.min_diameter = self.dataset.DISH_DIAMETER.data.min().compute() * u.m\r\n```\r\nThen I run:\r\n\r\n```python\r\n# Creating baseline object\r\nbaseline_obj = antenna_obj.create_baseline_dataset()\r\n```\r\nThis function runs:\r\n   ```python\r\n def create_baseline_dataset(self):\r\n        ids = self.dataset.ROWID.data.compute()\r\n        combs = np.array(list(combinations(ids, 2)))\r\n\r\n        antenna1 = self.dataset.sel(row=combs[:, 0])\r\n        antenna2 = self.dataset.sel(row=combs[:, 1])\r\n\r\n        baseline = antenna1.POSITION - antenna2.POSITION\r\n        baseline_length = xarrfunc.sqrt(\r\n            xarrfunc.square(baseline[:, 0]) + xarrfunc.square(baseline[:, 1]) + xarrfunc.square(baseline[:, 2]))\r\n        baseline_length = baseline_length.data.persist()\r\n\r\n        row_id = np.arange(len(combs[:, 0]))\r\n        ant1_id = da.from_array(combs[:, 0])\r\n        ant2_id = da.from_array(combs[:, 1])\r\n        row_id = da.from_array(row_id)\r\n\r\n        ds = xarray.Dataset(\r\n            data_vars=dict(\r\n                ANTENNA1=([\"row\"], ant1_id),\r\n                ANTENNA2=([\"row\"], ant2_id),\r\n                BASELINE_LENGTH=([\"row\"], baseline_length)\r\n            ),\r\n            coords=dict(\r\n                ROWID=([\"row\"], row_id)\r\n            ))\r\n\r\n        return Baseline(dataset=ds)\r\n```\r\nSince the baseline lengths are in a xarray dataset we can get the maximum using:\r\n\r\n```python\r\nself.max_baseline = self.dataset.BASELINE_LENGTH.max().data.compute() * u.m\r\nself.min_baseline = self.dataset.BASELINE_LENGTH.min().data.compute() * u.m\r\n```\r\n\r\nLet me know if this is not efficient, I would like to use the blockwise function though\r\n\r\nCheers","createdAt":"2021-06-05T12:31:19Z","id":"MDEyOklzc3VlQ29tbWVudDg1NTIzMzY3MA==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-855233670","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@sjperkins Ok, I have tested your code and the only downside is that the dask array returned from process is bigger than what we should expect. For example, if we are returning an array of dimensions for the baselines, like (id, antenna1_id, antenna2_id) if we pass row as the first dimension we would end up with a much more bigger dask array. Btw, what do you mean with crunching the visibility data? Well, I would like two things - One of them I have seen it as an issue - which is have antenna1 and antenna2 + baseline_id as a coordinate in the datasets. But also I would like to loop my datasets per baselines and work on each one of them. My idea is to make a function that takes a non-gridded datasets and returns a gridded dataset. For that we need to do the gridding for each field, spw and baseline, so all the ids in the main table fit.","createdAt":"2021-08-06T19:38:51Z","id":"IC_kwDOBh8_I841UKnr","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-894478827","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"A follow up to this @sjperkins: I've seen the documentation of [CASA ngi](https://cngi-prototype.readthedocs.io/en/latest/visibilities.html), and I was wondering how they get to order their data by baseline if the data is not contiguous by baseline... If you convert the data to zarr then you don't get any problem ordering the data by baseline?","createdAt":"2022-07-08T18:09:08Z","id":"IC_kwDOBh8_I85GSdse","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1179245342","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> A follow up to this @sjperkins: I've seen the documentation of [CASA ngi](https://cngi-prototype.readthedocs.io/en/latest/visibilities.html), and I was wondering how they get to order their data by baseline if the data is not contiguous by baseline... If you convert the data to zarr then you don't get any problem ordering the data by baseline?\r\n\r\nI don't want to speak too much for the casangi team, but it looks like they enforce a `(time, baseline, chan, corr)` shape for their zarr representation.\r\n\r\nThe MSv2.0 (and Ms3.0) spec specifies a `(row, chan, corr)` shape but there is no constraint that the data should be ordered by `TIME, ANTENNA1, ANTENNA2` i.e. `(time,baseline,chan,corr)`. This ordering is optimal for certain applications like calibration but `ANTENNA1,ANTENNA2,TIME` i.e. `(baseline,time,chan,corr)`can be more optimal for imaging and flagging. I believe wsclean orders data like this prior to imaging.\r\n\r\nThus, in my opinion, enforcing a`(time, baseline, chan, corr)` order deviates form the full generality of the MSv{2,3} spec if we're being very precise and splitting hairs, but in practice, most instruments will output data in this ordering.\r\n\r\nI've also only mentioned the `TIME,ANTENNA1` and `ANTENNA2` coluns in this comment. Technically all the columns in the MAIN Table key are used to impose an ordering: https://casa.nrao.edu/Memos/229.html#SECTION00061000000000000000, so columns like `FEED1` and `FEED2` are also relevant here.","createdAt":"2022-07-11T13:45:44Z","id":"IC_kwDOBh8_I85GW-8d","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1180430109","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@sjperkins right, makes sense. Although I think that for self-calibration which can be considered as calibration+imaging ordering by `(time,baseline,chan,corr)` is also useful.\r\n\r\nHowever, what I want to do is this: let's say I calculate a baseline_id for each row in my dask-ms dataset which has already been grouped by `[\"DATA_DESC\"]`. Let's say that now I want to regroup the datasets such that they are ordered by `[\"BASELINE_ID\", \"FIELD_ID\", \"DATA_DESC_ID\"]`.  Then my questions are:\r\n\r\n1. It is possible to do this? Is it done using xarray groupby? or is there a more efficient way to do this?\r\n2. Does this order would cause not contiguous performance issues? I guess not if using zarr?\r\n\r\nCheers","createdAt":"2022-07-11T14:12:09Z","id":"IC_kwDOBh8_I85GXGsD","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1180461827","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> @sjperkins right, makes sense. Although I think that for self-calibration which can be considered as calibration+imaging ordering by `(time,baseline,chan,corr)` is also useful.\r\n> \r\n> However, what I want to do is this: let's say I calculate a baseline_id for each row in my dask-ms dataset which has already been grouped by `[\"DATA_DESC\"]`. Let's say that now I want to regroup the datasets such that they are ordered by `[\"BASELINE_ID\", \"FIELD_ID\", \"DATA_DESC_ID\"]`. Then my questions are:\r\n> \r\n> 1. It is possible to do this? Is it done using xarray groupby? or is there a more efficient way to do this?\r\n\r\nIt may be possible to do this via xarray groupby but I'm wary of this approach since it'll create a dask graph for each group (baseline) with a lot of cross-communication between chunks. I think this'll work but will either require:\r\n\r\n1. evaluating each group separately with dask, resulting in accessing the entire dataset multiple times.\r\n \r\n    - This might be avoided by persisting each dataset into cluster memory, but then you'll need\r\n      sufficient memory to hold each dataset on your single node/cluster...\r\n\r\n2. or expecting the dask  (distributed?) scheduler to perfectly handle cross-communication when work for all groups is submitted at once.  This is hard: https://coiled.io/blog/better-shuffling-in-dask-a-proof-of-concept/\r\n\r\nHaving said that I haven't tried this approach in a long time, so the underlying functionality might have improved.\r\n\r\n> 2. Does this order would cause not contiguous performance issues? I guess not if using zarr?\r\n\r\nOne can't really get around this issue, regardless of the storage backend: its a matter of [Spatial Locality](https://en.wikipedia.org/wiki/Locality_of_reference). If I were to use database terminology, accessing data on the primary key is always more optimal than accessing data via a secondary key because data is usually ordered by primary key on disk.\r\n\r\nYou might want to try reordering your MS as follows:\r\n\r\n```bash\r\ndask-ms convert ~/data/input.ms -g \"FIELD_ID,DATA_DESC_ID,SCAN_NUMBER\" -i \"ANTENNA1,ANTENNA2,TIME,FEED1,FEED2\" -o ~/data/output.ms --format ms --force\r\n```\r\nIf you've created a `BASELINE_ID` column, you could probably substitute that for `ANTENNA1,ANTENNA2`.","createdAt":"2022-07-11T16:54:14Z","id":"IC_kwDOBh8_I85GXzHK","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1180643786","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Thank you very much @sjperkins. I will try what you have suggested and I will let you know. Last question - Is the convert function part of the dask-ms? That is, can I call it as a function from a python file?\n\nCheers","createdAt":"2022-07-12T17:50:18Z","id":"IC_kwDOBh8_I85Gdama","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1182116250","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Thank you very much @sjperkins. I will try what you have suggested and I will let you know.\r\n\r\nNote there were some fixes pushed to master this morning, but I don't think there would have been an issue with MS to MS conversion.\r\n\r\n> Last question - Is the convert function part of the dask-ms? That is, can I call it as a function from a python file?\r\n\r\nIt's a class in `daskms/apps/convert.py`. There are no plans to make this into a generic function.","createdAt":"2022-07-13T08:03:55Z","id":"IC_kwDOBh8_I85GgZ21","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1182899637","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@sjperkins Hi again! quick question - How can I use convert from a piece of code directly with the `Convert` class and without using `os.system`?  or would I need to program my own wrapper in order to use it as a function to convert a measurement set file? I want to do this because I guess depending on the stage of the software that I'm currently building I will need different orderings (an specific ordering for imaging, gridding and de-gridding, and other ordering for calibration and self-cal). Since I know which ordering I need to use for each case, I would really like to call convert inside my code as a function rather than using `os.system`. I was wondering if you could please help with that.","createdAt":"2022-10-12T16:31:54Z","id":"IC_kwDOBh8_I85MFQzr","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1276447979","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> @sjperkins Hi again! quick question - How can I use convert from a piece of code directly with the `Convert` class and without using `os.system`? or would I need to program my own wrapper in order to use it as a function to convert a measurement set file? I want to do this because I guess depending on the stage of the software that I'm currently building I will need different orderings (an specific ordering for imaging, gridding and de-gridding, and other ordering for calibration and self-cal). Since I know which ordering I need to use for each case, I would really like to call convert inside my code as a function rather than using `os.system`. I was wondering if you could please help with that.\r\n\r\nI'd just instantiate [Convert](https://github.com/ratt-ru/dask-ms/blob/bccef2a81aa08c14c6642f7c299b155f9b2df7cf/daskms/apps/convert.py#L322\r\n) with the relevant command line arguments and a python logger. Something like the following (I haven't run this!)\r\n\r\n\r\n```python\r\nimport logging\r\nlog = logging.getLogger(__file__)\r\n\r\nargs = [\"input.ms\", \"--output\", \"output.ms\", \"--group-cols\", \"FIELD_ID,DATA_DESC_ID\", \"--index-cols\", \"TIME,ANTENNA1,ANTENNA2\"]\r\n\r\nconvert = Convert(args, log)\r\nconvert.execute()\r\n```\r\n","createdAt":"2022-10-13T07:18:48Z","id":"IC_kwDOBh8_I85MH6IX","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1277141527","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"I'm getting this error when running the command @sjperkins :\r\n```python\r\n2022-11-02 10:34:29,585 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21032324 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,592 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21037373 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,597 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21037373 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,602 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21042422 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,607 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21042422 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,613 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21047471 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,617 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21047471 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,624 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21088424 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,629 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21088424 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,634 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21092912 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,640 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21092912 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,646 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21097400 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,651 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21097400 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,657 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21101888 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,661 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21101888 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,666 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21160232 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,672 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21160232 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,678 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21164720 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,683 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21164720 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,689 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21169208 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,694 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21169208 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,699 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21173696 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,704 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21173696 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,711 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21232040 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,716 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21232040 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,721 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21236528 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,726 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21236528 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,732 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21241016 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,736 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21241016 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,743 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21245504 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,748 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21245504 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,753 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21303848 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,758 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21303848 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,764 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21308336 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,769 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21308336 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,775 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21312824 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,780 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21312824 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:29,786 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21317312 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n2022-11-02 10:34:29,792 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n'Table DataManager error: Invalid operation: TSM: no array in row 21317312 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n2022-11-02 10:34:31,247 - dask-ms - INFO - Input: 'measurementset' file:///home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg\r\n2022-11-02 10:34:31,247 - dask-ms - INFO - Output: 'measurementset' file:///home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg_time\r\n2022-11-02 10:35:21,005 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,011 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,015 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,021 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,025 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,031 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,036 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,042 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n2022-11-02 10:35:21,521 - dask-ms - WARNING - Ignoring SOURCE\r\n2022-11-02 10:35:21,525 - dask-ms - WARNING - Ignoring 'TARGET': Unable to infer shape of column 'TARGET' due to:\r\n'TableProxy::getCell: no such row'\r\n2022-11-02 10:35:21,526 - dask-ms - WARNING - Ignoring 'ENCODER': Unable to infer shape of column 'ENCODER' due to:\r\n'TableProxy::getCell: no such row'\r\n2022-11-02 10:35:21,527 - dask-ms - WARNING - Ignoring 'POINTING_OFFSET': Unable to infer shape of column 'POINTING_OFFSET' due to:\r\n'TableProxy::getCell: no such row'\r\n2022-11-02 10:35:21,527 - dask-ms - WARNING - Ignoring 'DIRECTION': Unable to infer shape of column 'DIRECTION' due to:\r\n'TableProxy::getCell: no such row'\r\nTraceback (most recent call last):\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/bin/dask-ms\", line 8, in <module>\r\n    sys.exit(main())\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/entrypoint.py\", line 9, in main\r\n    return EntryPoint(sys.argv[1:]).execute()\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/entrypoint.py\", line 33, in execute\r\n    cmd.execute()\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/convert.py\", line 415, in execute\r\n    writes = self.convert_table(self.args)\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/convert.py\", line 500, in convert_table\r\n    writes.append(writer(datasets, out_store))\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/dask_ms.py\", line 102, in xds_to_table\r\n    out_ds = write_datasets(\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/writes.py\", line 760, in write_datasets\r\n    tp = _updated_table(table, datasets, columns, descriptor)\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/writes.py\", line 338, in _updated_table\r\n    table_proxy.addcols(_table_desc, dminfo=_dminfo).result()\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/_base.py\", line 444, in result\r\n    return self.__get_result()\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/_base.py\", line 389, in __get_result\r\n    raise self._exception\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/thread.py\", line 57, in run\r\n    result = self.fn(*self.args, **self.kwargs)\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/table_proxy.py\", line 114, in _impl\r\n    return getattr(table, method)(*args, **kwargs)\r\n  File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/casacore/tables/table.py\", line 1226, in addcols\r\n    self._addcols(tdesc, dminfo, addtoparent)\r\nRuntimeError: Invalid Table operation: Data manager name StandardStMan is already used in table /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg_time/POINTING\r\n```","createdAt":"2022-11-02T14:10:55Z","id":"IC_kwDOBh8_I85Ng9--","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1300488126","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"I'm worried that this is not working and that casang can re-order their xarray dataset by (time,baseline). I have noticed that this has a very high impact at least for self-calibration.","createdAt":"2022-11-03T18:11:24Z","id":"IC_kwDOBh8_I85Nont4","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1302494072","viewerDidAuthor":false},{"author":{"login":"bennahugo"},"authorAssociation":"COLLABORATOR","body":"Actually I think this ordering is possibly only good for calibration itself. For imaging one would need to repack by baseline x time instead (like wsclean does when it reorders by w or when ddfacet computes bda ordering). Typically imaging takes a lot longer than the calibration routines so I wonder if it should not be packed like that instead?","createdAt":"2022-11-04T07:07:47Z","id":"IC_kwDOBh8_I85NqwKj","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1303052963","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@bennahugo Yes, ordering time, baseline is only good for calibration. For imaging the best ordering is baseline, time. I agree. Here is where self-cal enters and it needs both ordering - time, baseline when calibrating and baseline, time when imaging. Given that I'm developing software that will do both, my idea would be to re-order the dataset given what the code is doing (calibration, imaging, self-cal (needs both)). However, the convert script is not able to do that as you can see above, so I haven't been able to test anything at the moment.","createdAt":"2022-11-04T12:48:59Z","id":"IC_kwDOBh8_I85NsW-C","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1303474050","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I'm getting this error when running the command @sjperkins :\r\n\r\n> ```python\r\n> 2022-11-02 10:34:29,585 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21032324 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,592 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21037373 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,597 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21037373 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,602 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21042422 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,607 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21042422 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,613 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21047471 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,617 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21047471 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,624 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21088424 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,629 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21088424 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,634 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21092912 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,640 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21092912 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,646 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21097400 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,651 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21097400 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,657 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21101888 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,661 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21101888 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,666 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21160232 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,672 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21160232 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,678 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21164720 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,683 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21164720 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,689 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21169208 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,694 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21169208 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,699 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21173696 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,704 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21173696 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,711 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21232040 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,716 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21232040 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,721 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21236528 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,726 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21236528 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,732 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21241016 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,736 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21241016 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,743 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21245504 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,748 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21245504 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,753 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21303848 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,758 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21303848 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,764 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21308336 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,769 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21308336 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,775 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21312824 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,780 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21312824 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:29,786 - dask-ms - WARNING - Ignoring 'WEIGHT_SPECTRUM': Unable to infer shape of column 'WEIGHT_SPECTRUM' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21317312 of column WEIGHT_SPECTRUM in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f19'\r\n> 2022-11-02 10:34:29,792 - dask-ms - WARNING - Ignoring 'FLAG_CATEGORY': Unable to infer shape of column 'FLAG_CATEGORY' due to:\r\n> 'Table DataManager error: Invalid operation: TSM: no array in row 21317312 of column FLAG_CATEGORY in /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg/table.f18'\r\n> 2022-11-02 10:34:31,247 - dask-ms - INFO - Input: 'measurementset' file:///home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg\r\n> 2022-11-02 10:34:31,247 - dask-ms - INFO - Output: 'measurementset' file:///home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg_time\r\n> 2022-11-02 10:35:21,005 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,011 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,015 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,021 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,025 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,031 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,036 - dask-ms - WARNING - The shape of column 'ASSOC_SPW_ID' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,042 - dask-ms - WARNING - The shape of column 'ASSOC_NATURE' is unconstrained (ndim == -1). Assuming shape is (31,) from exemplar\r\n> 2022-11-02 10:35:21,521 - dask-ms - WARNING - Ignoring SOURCE\r\n> 2022-11-02 10:35:21,525 - dask-ms - WARNING - Ignoring 'TARGET': Unable to infer shape of column 'TARGET' due to:\r\n> 'TableProxy::getCell: no such row'\r\n> 2022-11-02 10:35:21,526 - dask-ms - WARNING - Ignoring 'ENCODER': Unable to infer shape of column 'ENCODER' due to:\r\n> 'TableProxy::getCell: no such row'\r\n> 2022-11-02 10:35:21,527 - dask-ms - WARNING - Ignoring 'POINTING_OFFSET': Unable to infer shape of column 'POINTING_OFFSET' due to:\r\n> 'TableProxy::getCell: no such row'\r\n> 2022-11-02 10:35:21,527 - dask-ms - WARNING - Ignoring 'DIRECTION': Unable to infer shape of column 'DIRECTION' due to:\r\n> 'TableProxy::getCell: no such row'\r\n> Traceback (most recent call last):\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/bin/dask-ms\", line 8, in <module>\r\n>     sys.exit(main())\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/entrypoint.py\", line 9, in main\r\n>     return EntryPoint(sys.argv[1:]).execute()\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/entrypoint.py\", line 33, in execute\r\n>     cmd.execute()\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/convert.py\", line 415, in execute\r\n>     writes = self.convert_table(self.args)\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/apps/convert.py\", line 500, in convert_table\r\n>     writes.append(writer(datasets, out_store))\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/dask_ms.py\", line 102, in xds_to_table\r\n>     out_ds = write_datasets(\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/writes.py\", line 760, in write_datasets\r\n>     tp = _updated_table(table, datasets, columns, descriptor)\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/writes.py\", line 338, in _updated_table\r\n>     table_proxy.addcols(_table_desc, dminfo=_dminfo).result()\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/_base.py\", line 444, in result\r\n>     return self.__get_result()\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/_base.py\", line 389, in __get_result\r\n>     raise self._exception\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/concurrent/futures/thread.py\", line 57, in run\r\n>     result = self.fn(*self.args, **self.kwargs)\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/daskms/table_proxy.py\", line 114, in _impl\r\n>     return getattr(table, method)(*args, **kwargs)\r\n>   File \"/home/vicente/anaconda3/envs/pyralysis2/lib/python3.8/site-packages/casacore/tables/table.py\", line 1226, in addcols\r\n>     self._addcols(tdesc, dminfo, addtoparent)\r\n> RuntimeError: Invalid Table operation: Data manager name StandardStMan is already used in table /home/vicente/Documentos/Ayudantia/complete_data/HLTau_B6cont.calavg_time/POINTING\r\n> ```\r\n\r\nI can't tell exactly what's happening from your stack trace. Which command line arguments are you using?\r\n\r\nIt looks like you're writing to an existing table due to the call to `_updated_table`? This probably won't work. The `--force` argument will remove any exiting output dataset.","createdAt":"2022-11-08T07:48:26Z","id":"IC_kwDOBh8_I85N46_N","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1306767309","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I'm worried that this is not working and that casang can re-order their xarray dataset by (time,baseline). I have noticed that this has a very high impact at least for self-calibration.\r\n\r\nAs discussed earlier in https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1180430109, we don't impose specific orderings on data because different applications benefit from different orderings.\r\n\r\nIt's the user's responsibility to reorder their dataset into a format that is convenient for their application. This is possible via `dask-ms convert` although this is still undocumented: #226.","createdAt":"2022-11-08T08:29:21Z","id":"IC_kwDOBh8_I85N5IZR","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1306822225","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"@sjperkins \r\n\r\nMaybe if I add the link to the ms [here](https://we.tl/t-EmIF6z6DJW) you can traceback the error?\r\n\r\nThe command line that I'm currently using is:\r\n\r\n```python\r\ndask-ms convert HLTau_B6cont.calavg.tav300s -g \"FIELD_ID,DATA_DESC_ID,SCAN_NUMBER\" -i \"ANTENNA1,ANTENNA2,TIME,FEED1,FEED2\" -o output.ms --format ms --force\r\n```\r\n\r\nI'm not creating any folder before that.","createdAt":"2022-11-08T10:31:37Z","id":"IC_kwDOBh8_I85N5wt5","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1306987385","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> @sjperkins\r\n> \r\n> Maybe if I add the link to the ms [here](https://we.tl/t-EmIF6z6DJW) you can traceback the error?\r\n> \r\n> The command line that I'm currently using is:\r\n> \r\n> ```python\r\n> dask-ms convert HLTau_B6cont.calavg.tav300s -g \"FIELD_ID,DATA_DESC_ID,SCAN_NUMBER\" -i \"ANTENNA1,ANTENNA2,TIME,FEED1,FEED2\" -o output.ms --format ms --force\r\n> ```\r\n> \r\n> I'm not creating any folder before that.\r\n\r\nThanks for the linked MS.\r\n\r\nI *can* reproduce this error on my side. I'll try block off some time to look at the issue this week.","createdAt":"2022-11-09T07:40:23Z","id":"IC_kwDOBh8_I85N-6gF","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[{"content":"THUMBS_UP","users":{"totalCount":1}}],"url":"https://github.com/ratt-ru/dask-ms/issues/159#issuecomment-1308338181","viewerDidAuthor":false}] | created: 2021-05-05T20:28:47Z ===
* dask-ms version: 0.2.6
* Python version: 3.9
* Operating System: manjaro Linux

### Description

Hello everyone, I would like to partition or group my ms dataset based on FIELD_ID, DATA_DESC_ID and BASELINE (which is not a column, but can be calculated using ANTENNA1 and ANTENNA2).  It is possible to do this? Also, for each of the baselines I would like to get the length of them. However, for that we would need to do a query for the entire dataset instead of the list of partitions.

Anyone know how to do this?

This library is awesome, keep the good work, best regards!


=== ISSUE #153 | xds_from_table | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Hi there, I'm just starting to play with daskms and I run into an error if I do the following (if I use e.g. FIELD that works). I'm currently working on a multi-source MS dataset.\r\n> \r\n> xds_from_table(MSFN+'::SOURCE',group_cols='**row**')\r\n> \r\n> ValueError: No known conversion from CASA Table type 'record' to python/numpy type. Perhaps it needs to be added to _TABLE_TO_PY?:\r\n> {'BOOL': 'bool',\r\n> 'BOOLEAN': 'bool',\r\n> 'BYTE': 'uint8',\r\n> 'COMPLEX': 'complex64',\r\n> 'DCOMPLEX': 'complex128',\r\n> 'DOUBLE': 'float64',\r\n> 'FCOMPLEX': 'complex64',\r\n> 'FLOAT': 'float32',\r\n> 'INT': 'int32',\r\n> 'INTEGER': 'int32',\r\n> 'SHORT': 'int16',\r\n> 'SMALLINT': 'int16',\r\n> 'STRING': 'object',\r\n> 'UCHAR': 'uint8',\r\n> 'UINT': 'uint32',\r\n> 'UINTEGER': 'uint32',\r\n> 'USHORT': 'uint16',\r\n> 'USMALLINT': 'uint16'}\r\n\r\nThanks for the report @hrkloeck. I note that the in the [definition of the SOURCE table](https://casa.nrao.edu/Memos/229.html#SECTION000615000000000000000), the optional SOURCE_MODEL column has a TableRecord type. I've never encountered an MS with this type of data in it, but it is still a valid case. dask-ms attempts to reproduce CASA columns as dask arrays and TableRecords are dictionaries, so some thought would be required to support this edge case.\r\n\r\nQuestions:\r\n\r\n1. Does your SOURCE table have a SOURCE_MODEL column in it?\r\n2. Do you need to access this column?\r\n3. If not, could you specify only the columns you are interested in via the columns keyword argument?\r\n\r\nDoes (3) solve your problem?","createdAt":"2021-03-19T14:01:57Z","id":"MDEyOklzc3VlQ29tbWVudDgwMjg1NTY2Ng==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/153#issuecomment-802855666","viewerDidAuthor":false},{"author":{"login":"hrkloeck"},"authorAssociation":"NONE","body":"Hi Simon,\r\n\r\n\tthank’s for coming back. \r\n\r\nQ1: I don’t know I need to check (via CASA I guess)\r\nQ2: Not necessary yet, but maybe in the future. I just have started the dask-ms and CASA-MS endeavour, coming from AIPS and ParselTongue.\r\nQ3: ddids,cckey = xds_from_table(MSFN+'::SOURCE',column_keywords=True)\r\n\thave tried this but get the same error.\r\n\r\nSo I guess there is no urgency to this, currently my first approach is to extract the information out of the data to get a first understanding and how that all \r\nworks. However since the MS definition https://casa.nrao.edu/casadocs/casa-5.1.1/reference-material/measurement-set <https://casa.nrao.edu/casadocs/casa-5.1.1/reference-material/measurement-set>\r\nmentioned the SOURCE table I thought to be consistent it might be useful to raise it.\r\n\r\nJust for your info, my idea is that I would like to write something to plot the DATA and DATA_MODEL  versus time for a given baseline to understand the modelling (coming from VLBI) to learn\r\ndask-ms. I know of Oleg’s shadeMS (which I really like), but this is slightly different and I want to learn how to do it. \r\n\r\n\r\nCheers, Hans \r\n\r\n--------------------------------------------------------\r\nHans-Rainer Klöckner\r\n--------------------------------------------------------\r\nMax-Planck-Institut für Radioastronomie\r\nAuf dem Hügel 69\r\n53121 Bonn\r\nGermany\r\n+49 (0)228 525-338\r\n***@***.***\r\n--------------------------------------------------------\r\n\r\n> On 19. Mar 2021, at 15:02, Simon Perkins ***@***.***> wrote:\r\n> \r\n> \r\n> Hi there, I'm just starting to play with daskms and I run into an error if I do the following (if I use e.g. FIELD that works). I'm currently working on a multi-source MS dataset.\r\n> \r\n> xds_from_table(MSFN+'::SOURCE',group_cols='row')\r\n> \r\n> ValueError: No known conversion from CASA Table type 'record' to python/numpy type. Perhaps it needs to be added to _TABLE_TO_PY?:\r\n> {'BOOL': 'bool',\r\n> 'BOOLEAN': 'bool',\r\n> 'BYTE': 'uint8',\r\n> 'COMPLEX': 'complex64',\r\n> 'DCOMPLEX': 'complex128',\r\n> 'DOUBLE': 'float64',\r\n> 'FCOMPLEX': 'complex64',\r\n> 'FLOAT': 'float32',\r\n> 'INT': 'int32',\r\n> 'INTEGER': 'int32',\r\n> 'SHORT': 'int16',\r\n> 'SMALLINT': 'int16',\r\n> 'STRING': 'object',\r\n> 'UCHAR': 'uint8',\r\n> 'UINT': 'uint32',\r\n> 'UINTEGER': 'uint32',\r\n> 'USHORT': 'uint16',\r\n> 'USMALLINT': 'uint16'}\r\n> \r\n> Thanks for the report @hrkloeck <https://github.com/hrkloeck>. I note that the in the definition of the SOURCE table <https://casa.nrao.edu/Memos/229.html#SECTION000615000000000000000>, the optional SOURCE_MODEL column has a TableRecord type. I've never encountered an MS with this type of data in it, but it is still a valid case. dask-ms attempts to reproduce CASA columns as dask arrays and TableRecords are dictionaries, so some thought would be required to support this edge case.\r\n> \r\n> Questions:\r\n> \r\n> Does your SOURCE table have a SOURCE_MODEL column in it?\r\n> Do you need to access this column?\r\n> If not, could you specify only the columns you are interested in via the columns keyword argument?\r\n> Does (3) solve your problem?\r\n> \r\n> —\r\n> You are receiving this because you were mentioned.\r\n> Reply to this email directly, view it on GitHub <https://github.com/ska-sa/dask-ms/issues/153#issuecomment-802855666>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/ALCUM5N7MSEFW62VQ6AP3U3TENKOXANCNFSM4ZOZNK3Q>.\r\n> \r\n\r\n","createdAt":"2021-03-19T15:19:43Z","id":"MDEyOklzc3VlQ29tbWVudDgwMjkxMDAzOA==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/153#issuecomment-802910038","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Hi Simon, thank’s for coming back. Q1: I don’t know I need to check (via CASA I guess) Q2: Not necessary yet, but maybe in the future. I just have started the dask-ms and CASA-MS endeavour, coming from AIPS and ParselTongue. Q3: ddids,cckey = xds_from_table(MSFN+'::SOURCE',column_keywords=True) have tried this but get the same error.\r\n\r\nAh should have mentioned the [docs](https://dask-ms.readthedocs.io/en/latest/api.html#daskms.xds_from_ms), I meant something like:\r\n\r\n```python\r\nxds_from_table(\"BLAH.MS::SOURCE\", columns=[\"TIME\", \"INTERVAL\", \"NAME\", \"CODE\"])\r\n```\r\n\r\n> So I guess there is no urgency to this, currently my first approach is to extract the information out of the data to get a first understanding and how that all works. However since the MS definition https://casa.nrao.edu/casadocs/casa-5.1.1/reference-material/measurement-set <https://casa.nrao.edu/casadocs/casa-5.1.1/reference-material/measurement-set> mentioned the SOURCE table I thought to be consistent it might be useful to raise it.\r\n\r\nYes, this is definitely something to keep track of, so I'll keep this issue open for now. I  would bump the priority if the SOURCE\\_MODEL column was important to a number of people.","createdAt":"2021-03-19T15:35:47Z","id":"MDEyOklzc3VlQ29tbWVudDgwMjkyMDk1Nw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/153#issuecomment-802920957","viewerDidAuthor":false}] | created: 2021-03-19T13:27:46Z ===

Hi there, I'm just starting to play with daskms and I run into an error if I do the following (if I use e.g. FIELD that works). I'm currently working on a multi-source MS dataset.

xds_from_table(MSFN+'::SOURCE',group_cols='__row__')

ValueError: No known conversion from CASA Table type 'record' to python/numpy type. Perhaps it needs to be added to _TABLE_TO_PY?:
{'BOOL': 'bool',
 'BOOLEAN': 'bool',
 'BYTE': 'uint8',
 'COMPLEX': 'complex64',
 'DCOMPLEX': 'complex128',
 'DOUBLE': 'float64',
 'FCOMPLEX': 'complex64',
 'FLOAT': 'float32',
 'INT': 'int32',
 'INTEGER': 'int32',
 'SHORT': 'int16',
 'SMALLINT': 'int16',
 'STRING': 'object',
 'UCHAR': 'uint8',
 'UINT': 'uint32',
 'UINTEGER': 'uint32',
 'USHORT': 'uint16',
 'USMALLINT': 'uint16'}





=== ISSUE #121 | Improve multi-ms functionality | labels:  | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> As it stands, dask-ms will treat a multi-ms as a single monolithic ms. This means it is interpreted as having only a single main table which in turn sacrifices some potential parallelism. It would be ideal if dask-ms understood the multi-ms and handled some of its intricacies for the user.\r\n\r\nI understand that your perspective here is from a performance POV, especially in light of https://github.com/casacore/casacore/issues/1038 and https://github.com/casacore/python-casacore/pull/209.\r\n\r\nHowever, I do want to point out that (as I understand it)  the entire point of the Multi-MS  is to present multiple MS's as a monolithic MS. This is also related to the virtual tables created by TAQL queries -- they're actually reference tables pointing back to an original table.\r\n\r\n> The reason why I believe this belongs in dask-ms is that doing this in an application then requires having an additional layer of pyrap.table calls in order to disentangle the internal partitioning. This just seems error prone/messy on the user end.\r\n\r\nI'm concerned that this request is asking dask-ms to reverse engineer the **intended** virtual interface provided by CASA Tables in order to resolve performance problems. This would likely involve reproducing substantial internal CASA table logic, correctly.\r\n\r\nPut differently, a multi-ms is baking a cake. To unbake the cake would be a Herculean task. I'd be interested in seeing the casacore maintainer's response to https://github.com/casacore/python-casacore/pull/209. ","createdAt":"2020-08-12T10:02:56Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjc3OTAzNw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672779037","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"/cc @IanHeywood who was also interested in multi-ms's","createdAt":"2020-08-12T10:03:12Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjc3OTE1MQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672779151","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"> However, I do want to point out that (as I understand it) the entire point of the Multi-MS is to present multiple MS's as a monolithic MS. This is also related to the virtual tables created by TAQL queries -- they're actually reference tables pointing back to an original table.\r\n\r\nI don't 100% agree on this point. The aim was to allow for MMS aware casa tasks to make use of parallelism whilst everything else could treat it as a monolithic MS. [See this PDF on the subject](http://www.eso.org/~jagonzal/CASA-Documentation/HPC/mpi4casa/CASAMultiMsStructure.pdf).\r\n\r\nEssentially my request would be to make dask-ms MMS aware. I have tried an application-end test (very ugly, not perfect, almost certain there are some threading related things to work out) and see a decent (factor of x3) improvement in performance by reading in the sub-MSs directly. \r\n\r\nI don't really believe that this even constitutes unbaking the cake - all it means is that a given row range lies in a specific subms. Whether the backing getcol points at the subms vs the monolithic ms seems like a relatively minor detail. Of course, I know that it is not that simple, and keeping track of all the subms tables could get difficult. \r\n\r\nThis is by no means a requirement, just thought it was worth putting my thoughts together in an issue.","createdAt":"2020-08-12T10:24:08Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjc4ODgyOQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672788829","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"The performance factor is best taken with a pinch of salt as I think there are some discrepancies in my tests. But there definitely is an improvement.","createdAt":"2020-08-12T10:27:29Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjc5MDIyNQ==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672790225","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> I don't 100% agree on this point. The aim was to allow for MMS aware casa tasks to make use of parallelism whilst everything else could treat it as a monolithic MS. See this PDF on the subject.\r\n\r\nAh thanks for pointing that, I haven't worked with MMS much so my experience of them is limited.\r\n\r\nI guess something like the following is currently possible (although python-casacore and the GIL is still an issue...)\r\n\r\n```python\r\nfrom itertools import chain\r\nfrom daskms import xds_from_ms\r\n\r\nmms = [\"ms01.ms\", \"ms02.ms\", \"ms03.m3\"]\r\n\r\ndatasets = list(chain(map(xds_from_ms, mms)))\r\n```\r\n\r\nWhat exactly distinguishes a normal MS from a multi-MS?\r\n\r\n> This is by no means a requirement, just thought it was worth putting my thoughts together in an issue.\r\n\r\nYes, lets keep the discussion going.","createdAt":"2020-08-12T12:34:04Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjg0MzY1NA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672843654","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> What exactly distinguishes a normal MS from a multi-MS?\r\n\r\nNo need to reply, I'm reading the PDF which seems to describe it well.","createdAt":"2020-08-12T12:36:25Z","id":"MDEyOklzc3VlQ29tbWVudDY3Mjg0NDcwOQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-672844709","viewerDidAuthor":false},{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Hi everyone, is there any news on this? I am also interested on using mms files on dask-ms. Although I think that since dask-ms groups the columns by FIELD_ID and DATA_DESC_ID is not much different from using a MMS file. And the \"partitioned\" dask-ms dataset also can be processed in parallel, so what would be the big difference between reading a mms file and reading the non-mms file using dask-ms?","createdAt":"2021-05-05T19:50:35Z","id":"MDEyOklzc3VlQ29tbWVudDgzMjk2MzMwNQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-832963305","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> Hi everyone, is there any news on this? I am also interested on using mms files on dask-ms. Although I think that since dask-ms groups the columns by FIELD_ID and DATA_DESC_ID is not much different from using a MMS file. And the \"partitioned\" dask-ms dataset also can be processed in parallel, so what would be the big difference between reading a mms file and reading the non-mms file using dask-ms?\r\n\r\nHi @miguelcarcamov. I think the issue here is that:\r\n\r\n1. CASA Tables aren't thread safe and must therefore be accessed from a single thread. https://github.com/casacore/casacore/issues/1038\r\n2. python-casacore doesn't drop the Global Interpreter Lock (GIL) when accessing CASA Table data. https://github.com/casacore/python-casacore/pull/209. This is probably the most painful as it means that no compute happens while waiting for data.\r\n\r\nI've done some work on a new pybind11 wrapper for CASA Tables to solve the above issues, but haven't touched it recently. https://github.com/ratt-ru/futurecasapy\r\n\r\nIn the long term, we're exploring newer formats for the Measurement Set v{2,3} spec. Earlier this year, zarr and parquet support for CASA Table-like data was added to dask-ms master branch -- these have proven highly performant on a supercomputer -- orders of magnitude faster compared to the current CASA Table system, although it is possible that it hasn't been optimally compiled.\r\n\r\n\r\n\r\n\r\n\r\n","createdAt":"2021-05-07T15:48:51Z","id":"MDEyOklzc3VlQ29tbWVudDgzNDU1NTgxMQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/121#issuecomment-834555811","viewerDidAuthor":false}] | created: 2020-08-12T09:10:16Z ===
* dask-ms version: master
* Python version: 3.6.9
* Operating System: Ubuntu 18.04 LTS

### Description

This is very much a non-urgent, wish list feature. As it stands, dask-ms will treat a multi-ms as a single monolithic ms. This means it is interpreted as having only a single main table which in turn sacrifices some potential parallelism. It would be ideal if dask-ms understood the multi-ms and handled some of its intricacies for the user. The reason why I believe this belongs in dask-ms is that doing this in an application then requires having an additional layer of `pyrap.table` calls in order to disentangle the internal partitioning. This just seems error prone/messy on the user end. That being said, it is possible to do this on the application side, so if that is going to be the paradigm, I can make it happen.


=== ISSUE #111 | Track column slicing improvements in casacore | labels: enhancement | comments: [] | created: 2020-04-24T14:48:39Z ===
* dask-ms version: 0.2.4
* Python version: 3.6
* Operating System: Ubuntu 18.04

### Description

#107 disabled column slice caching to avoid excessive memory growith during column slicing (#92).

This issue serves to track any changes dask-ms needs to make in reponse to to casacore improvements, especially with respect to https://github.com/casacore/casacore/issues/1018.

=== ISSUE #109 | what's the best way to apply a channel slice? | labels: question | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"To do this with maximal efficiency, you' have to use a pre-process to figure out the optimal chunking strategy for the channel dimensions\r\n\r\n```python\r\n# Initial dataset partition on FIELD_ID and DATA_DESC_ID\r\nddids = [ds.DATA_DESC_ID for ds in xds_from_ms(\"3C286.ms\")]\r\n# Read in very small DATA_DESCRIPTION table into memory\r\nddid = xds_from_table(\"3C286.ms::DATA_DESCRIPTION\").compute()\r\n# Create a dataset per row from SPECTRAL_WINDOW\r\nspws = xds_from_table(\"3C286.ms::SPECTRAL_WINDOW\", group_cols=\"__row__\")\r\n# Number of channels for each dataset\r\nnchan = [spws[ddid[i].SPECTRAL_WINDOW_ID[0]].CHAN_FREQ.shape[0] for i in ddids]\r\n# Channel chunking schema for each dataset\r\nchan_chunks = [(chanslice.start - 0, chanslice.end - chanslice.start, nc - chanslice.end)\r\n                          for nc in nchan]\r\n\r\n# Chunking schema for each dataset\r\nchunks = [{'row': 100000, 'chan': cc} for cc in chan_chunks]\r\n\r\n# Re-open exact same datasets with a different chunking strategy\r\ndatasets = xds_from_ms(\"3C286.ms\", chunks=chunks)\r\n\r\n# This should slice the channel selection optimally without dask block overlap\r\ndatasets[0].DATA[:, chanslice, :]\r\n```\r\n\r\nI typed this out without running it, but it should illustrate the idea.\r\n\r\nThe above is clunky, I'm thinking about general improvements for the process in https://github.com/ska-sa/dask-ms/pull/86","createdAt":"2020-04-24T13:56:44Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTAyNjE5OA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619026198","viewerDidAuthor":false},{"author":{"login":"Mulan-94"},"authorAssociation":"CONTRIBUTOR","body":"@sjperkins , I'm unable to follow properly. I usually just do `dataset[0].sel(chan=slice(start, end))` . And the chunking for the channel seems to be reconstructed automatically by `dask`. \r\nIs this the wrong way :( ?","createdAt":"2020-04-24T15:27:11Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTA4MDA2NA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619080064","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"> @sjperkins , I'm unable to follow properly. I usually just do `dataset[0].sel(chan=slice(start, end))` . And the chunking for the channel seems to be reconstructed automatically by `dask`.\r\n> Is this the wrong way :( ?\r\n\r\nIt's not wrong, but that way will end up reading more data from the MS than necessary. What the example is trying to demonstrate is that to prevent this behaviour the dask chunking must be correctly set up in `xds_from_ms(..., chunks={...})`.\r\n\r\nI agree that it's not necessarily easy to follow, I simply haven't found a reasonable way of making this easy yet. https://github.com/ska-sa/dask-ms/pull/86 should probably form the nucleus for dealing with this.","createdAt":"2020-04-24T15:33:55Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTA4Mzk3Nw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[{"content":"THUMBS_UP","users":{"totalCount":1}}],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619083977","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Lets look at this with a concrete example\r\n\r\n```python\r\nnchan = 64\r\nchanslice = slice(37, 56)\r\nchan_chunks = (37, 19, 8) = (37 - 0, 56 - 37, 64 - 56)\r\n\r\ndatasets = xds_from_ms(..., chunks={..., 'chan': chan_chunks})\r\nds.DATA.data[:, chanslice, :]\r\n```\r\nthat will create DATA dask arrays with channel chunks of (37, 19, 8). Each channel chunk will read that channel chunk from the MS exactly using [getcolslice](https://casacore.github.io/python-casacore/casacore_tables.html#casacore.tables.table.getcolslice).\r\n\r\nIf by contrast, we don't ask for channel chunking:\r\n\r\n```python\r\ndatasets = xds_from_ms(...)\r\nds.DATA.data[:, chanslice, :]\r\n```\r\nthere'll be a single channel chunk for the dask DATA arrays containing the full  64 channels. So there'll be a [getcol](https://casacore.github.io/python-casacore/casacore_tables.html#casacore.tables.tablecolumn.getcol) operation behind that reads all the channel data followed by a slice that returns the channel subset.\r\n\r\n","createdAt":"2020-04-24T15:53:16Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTA5NTI5Mg==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619095292","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"I also want to say its good that people are pointing this out as a conceptually difficult thing, because I do want to make things easier and reduce the cognitive overhead.","createdAt":"2020-04-24T15:54:20Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTA5NTg5MQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619095891","viewerDidAuthor":false},{"author":{"login":"o-smirnov"},"authorAssociation":"CONTRIBUTOR","body":"As an aging professor, I can only applaud the sentiment. My cognitive is all overhead!","createdAt":"2020-04-24T16:03:53Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTEwMTQyOQ==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619101429","viewerDidAuthor":false},{"author":{"login":"Mulan-94"},"authorAssociation":"CONTRIBUTOR","body":"> that will create DATA dask arrays with channel chunks of (37, 19, 8). Each channel chunk will read that channel chunk from the MS exactly using `getcolslice`.\r\n\r\nThis makes it clearer, thanks :) !","createdAt":"2020-04-24T17:08:43Z","id":"MDEyOklzc3VlQ29tbWVudDYxOTEzNjY2MA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/109#issuecomment-619136660","viewerDidAuthor":false}] | created: 2020-04-24T13:49:25Z ===
Been asking [elsewhere](https://github.com/ratt-ru/shadeMS/issues/31), but it occurs to me it's a general enough question to be usefully asked here....

So, what's the best way to read a subset of channels? I can apply a slice to the array objects of course, but is there a way to do this up front? Or a better way?

=== ISSUE #106 | Add dask-ms profiling functionality | labels: enhancement | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Hi @smasoka. See above the outline of the profiling functionality for dask-ms. Let me know if there's anything that needs expanding.","createdAt":"2020-04-21T15:08:34Z","id":"MDEyOklzc3VlQ29tbWVudDYxNzI0MDE5Mw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/106#issuecomment-617240193","viewerDidAuthor":false},{"author":{"login":"smasoka"},"authorAssociation":"NONE","body":"Hi @sjperkins,  I have a branch that I am working on [dask-ms-profiling](https://github.com/smasoka/dask-ms/tree/dask-ms-profiling)\r\n\r\nThe variable `DASK_MS_PROFILE` should hold `True` or `False` right? \r\nThe wrappers by default will profile, but the variable will control if the user wants to have the run times info or not.\r\n\r\nalso, am I in the right direction here?","createdAt":"2020-05-05T15:12:57Z","id":"MDEyOklzc3VlQ29tbWVudDYyNDExNTI0OA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/106#issuecomment-624115248","viewerDidAuthor":false}] | created: 2020-04-21T15:05:57Z ===
It would be helpful to profile where dask-ms is spending it's time. dask-ms submits operations to a CASA table object from a ThreadPoolExecutor containing a single thread.

There are two sets of function wrappers that are executed within the thread:

- [Wrappers around existing CASA Table methods](https://github.com/ska-sa/dask-ms/blob/0d401f234ccbcafbaa419003d199518c7f11981d/daskms/table_proxy.py#L84-L122)
- [Wrappers around user constructed functions which access the CASA Table](https://github.com/ska-sa/dask-ms/blob/0d401f234ccbcafbaa419003d199518c7f11981d/daskms/table_proxy.py#L196-L233)

Profiling should be done as follows:

1. For now, turn on profiling with a DASK_MS_PROFILE environment variable, checked
   with `os.environ("DASK_MS_PROFILE")`. In future I'd like to configure functionality with [donfig](https://github.com/pytroll/donfig), but this can be a future PR.
2. swap out these wrappers for profiling wrappers. Something like https://stackoverflow.com/a/27737385 as a mechanism would be a good start.
3. Store the run times as a `{function_name: Profiling(accumulated_time, accumulated_counts)}`
dictionary that gets printed `atexit`.  @o-smirnov you may have further ideas on what you want to see here.

One interesting thing that's also worth checking here is the effect that table locking has on performance. If all table access is mediated through a single thread, then locking shouldn't strictly be necessary, *for a single node*.

Unfortunately, if multiple nodes are accessing the same table then that table lock is probably necessary, although I see there are options for turning it off completely in casacore, presumably for the cases where the access patterns are non-overlapping reads and writes.




=== ISSUE #101 | Leverage complete MS table and sub-table definitions | labels: enhancement | comments: [] | created: 2020-04-16T12:09:55Z ===
It looks like python-casacore 3.3.0 will contain [Expose complete MS and subtable definitions](https://github.com/casacore/python-casacore/pull/183).

This paves the way for providing proper definitions for non-required MS columns to the end-user.

Low priority until users start creating some of the more obscure sub-table and main table columns

=== ISSUE #99 | Documentation improvements | labels: documentation | comments: [] | created: 2020-04-15T09:57:04Z ===
* dask-ms version: 0.2.3
* Python version: 3.6
* Operating System: Ubuntu 18.04

### Description

- There are many grammatical and spelling errors
- group_cols columns being placed on datasets as integers is not documented in the API (but is in the tutorial). The tutorial could demonstrate a subtable join.

=== ISSUE #93 | Writing data with fewer correlations than are present in the MS | labels: enhancement | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Temporary work-around is to use ``xarray.Dataset.reindex``","createdAt":"2020-03-24T12:26:06Z","id":"MDEyOklzc3VlQ29tbWVudDYwMzIwOTExMw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/93#issuecomment-603209113","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Just a brief follow-up here. `xarray.Dataset.reindex` does work (and is awesome) but there is a slight problem. `reindex` uses a fill value for the added elements. This can lead to on-disk data being overwritten (e.g. writing two correlations, reindexed to four, back to a column will overwrite values with the fill-value). There are other approaches:\r\n- Slice the data rather than selecting it. This increases code complexity as the slices then need to be used everywhere. \r\n- Re-read the data and combine. This will lead to more data being in memory, perhaps unnecessarily.   \r\n- Support writing of slices back to disk. This will make writes slower but is likely the \"easiest\" from a user perspective. I do not know how tractable this is for other formats.","createdAt":"2021-06-10T09:36:53Z","id":"MDEyOklzc3VlQ29tbWVudDg1ODQ3MTM4OA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/93#issuecomment-858471388","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"Just checking in here - this is becoming increasingly necessary. I might have to start considering option two above which is really inelegant. @sjperkins How much work do you think would be involved in making the writes aware of the correlation axis and using `putcolslice` appropriately?","createdAt":"2021-08-27T09:21:18Z","id":"IC_kwDOBh8_I842EJ_H","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/93#issuecomment-907059143","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Following on from our online conversation\r\n\r\n1. Currently dask-ms supports ranged writes on the `row` dimension only.\r\n2. In principle, supporting this would require ranged writes on `corr`, for instance. `chan` might also be useful.\r\n3. Under the hood, in CASA Tables, the actual operation would be performed using a `putcolslice(column, data[rr:rr + rl], blc, trc, startrow=rs, nrow=rl)` command.\r\n4. Thus, instead of merely slicing out rows for writing, dask-ms would have to support slicing out arbitrary dimensions for writing (particularly `corr`).\r\n\r\nA way forward may be possible by passing in `blc`, `trc` ranges into the blockwise call, rather than individual values, as is presently done here https://github.com/ska-sa/dask-ms/blob/55c987e5f00c24a82c16363f681a966e45590e06/daskms/writes.py#L629-L635","createdAt":"2021-12-14T13:19:27Z","id":"IC_kwDOBh8_I847OBcK","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/93#issuecomment-993531658","viewerDidAuthor":false}] | created: 2020-03-10T09:29:23Z ===
* dask-ms version: 0.2.3
* Python version: 3.6.9
* Operating System: Pop!_OS 18.04 LTS

This is feature request, not a bug.

xarray offers the following awesome functionality:
```
updated_xds = xds.sel(corr=[0, 3])
```
which in this example instantly makes a new xds using only some of the correlations. This is great because it is applied to the entire xds, which means all the fields remain consistent. The only drawback comes when attempting to write MS columns, as a field with two correlations on the xds cannot be written to a column containing four correlations. It would be really cool if dask-ms could support this.

My instinct is that this might become simple if the corr dimension is given a coordinate. That way there is a paper trail showing the correlations which have been selected out, and consequently a way to determine how to store them.


=== ISSUE #82 | Tutorial needs updating | labels: bug | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Thanks for the report @marcinglowacki. \r\n\r\nRegarding your first issue, dask arrays are required on the write dataset. dask-ms is falling over because a numpy array has been provided.\r\n\r\nRegarding your second issue, xarray is an optional dask-ms dependency. dask-ms has its own \"poor man's Dataset\" for use in cases where xarray is not installed. This is a case where the interaction between their internal types conflicted.\r\n\r\nI've merged a fix in https://github.com/ska-sa/dask-ms/pull/83 into master. Could you confirmm whether this fixes your second issue (and complains on the first).","createdAt":"2019-12-12T11:56:23Z","id":"MDEyOklzc3VlQ29tbWVudDU2NDk3NjkzOA==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/82#issuecomment-564976938","viewerDidAuthor":false}] | created: 2019-12-12T10:31:11Z ===
* dask-ms version: 0.2.3
* Python version: 3.6.8
* Operating System: Ubuntu

### Description

I am trying to write to a new .ms file via xds_to_table, but encounter errors regardless of the file name or the column_keywords. I also am unable to run the examples given on the https://dask-ms.readthedocs.io/en/latest/tutorial/writes.html page involving example_ms.

### What I Did

```
from daskms import xds_from_table, xds_from_ms, xds_to_table

import numpy as np
import datashader as ds
import datashader.transfer_functions as tf
import dask.array as da

xds = xds_from_ms("/data/scratchtmp/marcin/laduma_reduction/reflagged/1539630057_sdp_l0.full_1284.full_pol.ms/")

for i in range(3):
    xds[i]['FLAG'] = False#da.zeros((xds[i].FLAG.values.shape),dtype=bool)

writes = xds_to_table(xds, '/data/scratchtmp/marcin/laduma_reduction/reflagged/TEST.MS','ALL')
```

This gives:

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-c4f9a7e71f2d> in <module>()
----> 1 writes = xds_to_table(xds, '/data/scratchtmp/marcin/laduma_reduction/reflagged/test.ms','ALL')

/anaconda3/lib/python3.6/site-packages/daskms/dask_ms.py in xds_to_table(xds, table_name, columns, descriptor, table_keywords, column_keywords)
    108                             descriptor=descriptor,
    109                             table_keywords=table_keywords,
--> 110                             column_keywords=column_keywords)
    111
    112     # No xarray available assume dask datasets

/anaconda3/lib/python3.6/site-packages/daskms/writes.py in write_datasets(table, datasets, columns, descriptor, table_keywords, column_keywords)
    557
    558     if not table_exists(table):
--> 559         table_proxy = _create_table(table, datasets, columns, descriptor)
    560     else:
    561         table_proxy = _updated_table(table, datasets, columns, descriptor)

/anaconda3/lib/python3.6/site-packages/daskms/writes.py in _create_table(table_name, datasets, columns, descriptor)
    179 def _create_table(table_name, datasets, columns, descriptor):
    180     builder = descriptor_builder(table_name, descriptor)
--> 181     table_desc, dminfo = builder.execute(datasets)
    182
    183     root, table, subtable = table_path_split(table_name)

/anaconda3/lib/python3.6/site-packages/daskms/descriptors/builder.py in execute(self, datasets)
     72         default_desc = self.default_descriptor()
     73         variables = self.dataset_variables(datasets)
---> 74         table_desc = self.descriptor(variables, default_desc)
     75         dminfo = self.dminfo(table_desc)
     76

/anaconda3/lib/python3.6/site-packages/daskms/descriptors/ms.py in descriptor(self, variables, default_desc)
    101
    102         if self.fixed:
--> 103             ms_dims = self.infer_ms_dims(variables)
    104             desc = self.fix_columns(variables, desc, ms_dims)
    105

/anaconda3/lib/python3.6/site-packages/daskms/descriptors/ms.py in infer_ms_dims(variables)
    110
    111         # Create a dictionary of all variables in all datasets
--> 112         expanded_vars = {v.data.name: v for k, lv in variables.items()
    113                          for v in lv}
    114

/anaconda3/lib/python3.6/site-packages/daskms/descriptors/ms.py in <dictcomp>(.0)
    111         # Create a dictionary of all variables in all datasets
    112         expanded_vars = {v.data.name: v for k, lv in variables.items()
--> 113                          for v in lv}
    114
    115         # Now try find consistent dimension sizes across all variables

AttributeError: 'numpy.ndarray' object has no attribute 'name'
```

If trying to write to the same .ms file path:
```
writes = xds_to_table(xds, '/data/scratchtmp/marcin/laduma_reduction/reflagged/1539630057_sdp_l0.full_1284.full_pol.ms/','ALL')
```
I get instead:

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-34-1fab1502fc51> in <module>()
----> 1 writes = xds_to_table(xds, '/data/scratchtmp/marcin/laduma_reduction/reflagged/1539630057_sdp_l0.full_1284.full_pol.ms/','ALL')

/anaconda3/lib/python3.6/site-packages/daskms/dask_ms.py in xds_to_table(xds, table_name, columns, descriptor, table_keywords, column_keywords)
    108                             descriptor=descriptor,
    109                             table_keywords=table_keywords,
--> 110                             column_keywords=column_keywords)
    111
    112     # No xarray available assume dask datasets

/anaconda3/lib/python3.6/site-packages/daskms/writes.py in write_datasets(table, datasets, columns, descriptor, table_keywords, column_keywords)
    564                            descriptor=descriptor,
    565                            table_keywords=table_keywords,
--> 566                            column_keywords=column_keywords)

/anaconda3/lib/python3.6/site-packages/daskms/writes.py in _write_datasets(table, table_proxy, datasets, columns, descriptor, table_keywords, column_keywords)
    479             # there is more than one chunk in any of the non-row columns.
    480             # In that case, we can putcol, otherwise putcolslice is required
--> 481             if not all(len(c) == 1 for c in array.chunks[1:]):
    482                 # Add extent arrays
    483                 for d, c in zip(full_dims[1:], array.chunks[1:]):

AttributeError: 'numpy.ndarray' object has no attribute 'chunks'
```

As for the tutorial page, I get errors for Dataset commands, e.g. running
```
import dask
from daskms import xds_from_ms, Dataset
from daskms.example_data import example_ms

# Create example Measurement Set and read datasets
ms = example_ms()
datasets = xds_from_ms(ms)
# Add last Dataset to table using variables only (no ROWID coordinate)
new_ds = Dataset(datasets[-1].data_vars)
datasets.append(new_ds)

# Write datasets back to Measurement Set
writes = xds_to_table(datasets, ms, "ALL")
dask.compute(writes)
```
gives
```
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-1c7fed1cd01e> in <module>()
      7 datasets = xds_from_ms(ms)
      8 # Add last Dataset to table using variables only (no ROWID coordinate)
----> 9 new_ds = Dataset(datasets[-1].data_vars)
     10 datasets.append(new_ds)
     11

/anaconda3/lib/python3.6/site-packages/daskms/dataset.py in __init__(self, data_vars, coords, attrs)
    230         """
    231         self._data_vars = {k: _convert_to_variable(k, v)
--> 232                            for k, v in data_vars.items()}
    233
    234         if coords is not None:

/anaconda3/lib/python3.6/site-packages/daskms/dataset.py in <dictcomp>(.0)
    230         """
    231         self._data_vars = {k: _convert_to_variable(k, v)
--> 232                            for k, v in data_vars.items()}
    233
    234         if coords is not None:

/anaconda3/lib/python3.6/site-packages/daskms/dataset.py in _convert_to_variable(k, v)
    201         raise ValueError("'%s' must be a size 2 to 5 tuple of the form"
    202                          "(dims, array[, attrs[, encoding[, fastpath]]]) "
--> 203                          "tuple. Got '%s' instead," % (k, type(v)))
    204
    205     return as_variable(v)

ValueError: 'ANTENNA1' must be a size 2 to 5 tuple of the form(dims, array[, attrs[, encoding[, fastpath]]]) tuple. Got '<class 'xarray.core.dataarray.DataArray'>' instead,
```

=== ISSUE #77 | Support dask's process scheduler | labels: enhancement | comments: [] | created: 2019-12-09T15:11:03Z ===
The problem
----------------

1. A ThreadPoolExecutor is used to make access to CASA tables threadsafe in a threaded environment.
2. The ThreadPoolExecutor is created and embedded in TableProxy objects during graph creation.
3. Processes are forked during dask.compute leading to the issues well-described here: https://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them

The solution
----------------

1. User configures dask-ms to use processes in some fashion, possibly as a keyword to xds_from_{ms,table} or via some global configuration option.
2. Instead of creating a ThreadPoolExecutor a DummyExecutor can be created.

```python
class DummyFuture(object):
    __slots__ = ("result",)

    def __init__(self, result):
        self.result = result

    def result(self):
        return self.result

class DummyExecutor(object):
    def submit(self, fn, *args, **kwargs):
         return DummyFuture(fn(*args, **kwargs))
```

Comments
-------------

As supporting processes is not currently a high priority, this feature is also not a high priority but exists to describe how it might be supported.

As an aside **test_multiprocess_table** shows that it's possible to spin up xds_from_ms once Processes have been forked and a fair amount of effort is taken to shutdown any threads that are started in the main Process before this happens


=== ISSUE #69 | Incorrect data type used for column keyword | labels: enhancement | comments: [{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"This may have been a false alarm - I have managed to fix the problem by manually removing and re-adding the keywords using pyrap. I will leave this open for now as I am not sure what caused the original problem (an interrupted write perhaps?).","createdAt":"2019-11-05T06:33:46Z","id":"MDEyOklzc3VlQ29tbWVudDU0OTY4MjQ1Mg==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/69#issuecomment-549682452","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"As per our discussion, the likely cause of this is updating an existing keyword with a value of a different type.","createdAt":"2019-11-05T08:16:54Z","id":"MDEyOklzc3VlQ29tbWVudDU0OTcxMjA5Mw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/69#issuecomment-549712093","viewerDidAuthor":false},{"author":{"login":"JSKenyon"},"authorAssociation":"COLLABORATOR","body":"This just bit me again. I now have a better understanding of why. The issue stems from the fact that `ms.getcolkeyword` does not preserve underlying dtype. By that I mean that if you read a column keyword which is say an `int32`, it will be loaded as a standard Python `int` (64-bit). This means that if you read a keyword and then try to write it back, it can fail as the dtype may have changed. This is difficult to keep track of as you cannot query the dtype of a column keyword.  ","createdAt":"2020-07-24T08:44:44Z","id":"MDEyOklzc3VlQ29tbWVudDY2MzQxNTUxNQ==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/69#issuecomment-663415515","viewerDidAuthor":false},{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"For future me's edification, a possible solution might be casting python types to numpy types before column keyword writes. ","createdAt":"2020-07-24T08:50:14Z","id":"MDEyOklzc3VlQ29tbWVudDY2MzQyMDM0Nw==","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/69#issuecomment-663420347","viewerDidAuthor":false}] | created: 2019-11-05T06:15:22Z ===
* dask-ms version: 0.2.2
* Python version: 3.6.8
* Operating System: Ubuntu via WSL

### Description

I updated all my dependencies to the latest versions today and I now get the following error message when attempting to set up a write to column keywords.

```
RuntimeError: TableRecordRep::defineDataField - incorrect data type used for field FLAGSET_legacy.
```

The value currently in that field is an int, as is the value I am attempting to write to it.

### What I Did

I get the same behaviour outside of my project. I ran the following via iPython:

```python
from daskms import xds_from_ms, xds_to_table

xds, kwrds = xds_from_ms("C147_unflagged.MS/", columns=("BITFLAG"), column_keywords=True)
xds_to_table(xds, "C147_unflagged.MS/", columns="BITFLAG", column_keywords={"BITFLAG": kwrds["BITFLAG"]})
```
Note that the above example does not edit the keywords - it just attempts to rewrite the existing keywords but it still falls over. This seems to happen whenever I attempt to write to a keyword which already exists and contains an integer value, or when I attempt to change the type of the value in an existing keyword.


=== ISSUE #67 | force_write option for xds_to_table | labels: enhancement | comments: [] | created: 2019-10-21T11:48:51Z ===
* dask-ms version: 0.2.0
* Python version: 3.6.8
* Operating System: Ubuntu 18.04 under WSL

Sometimes it is possible to end up with a partially added/incorrect column in the MS. Whilst testing, I accidentally wrote a column as complex128 which is not understood by wsclean. I was forced to remove the column in question manually using pyrap. It would be useful to have the option to force a write in situations where the column being written to exists but is not consistent with the data we want to write to it. This could be as simple as removing the old column before readding the new.



=== ISSUE #32 | casacore exception thrown at end of test suite if temporary MS is deleted at the end of the session | labels: bug,wontfix | comments: [{"author":{"login":"sjperkins"},"authorAssociation":"MEMBER","body":"Solve this for the moment by not deleting the temporary MS in https://github.com/ska-sa/xarray-ms/pull/31/commits/262625ec4a82c62bbf12c5c3927a4d19e028b173","createdAt":"2019-05-21T14:31:43Z","id":"MDEyOklzc3VlQ29tbWVudDQ5NDQxNjk0NA==","includesCreatedEdit":true,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/32#issuecomment-494416944","viewerDidAuthor":false}] | created: 2019-05-21T14:30:17Z ===
* xarray-ms version: 1.4
* Python version: 3.6
* Operating System: Ubuntu 18.04

### Description

The ms fixture deletes the measurement set directory once the session closes.

```python
@pytest.fixture(scope="session")
def ms(tmp_path_factory):
    msdir = tmp_path_factory.mktemp("msdir", numbered=False)
    fn = os.path.join(str(msdir), "test.ms")
   ...
    yield fn

    # Remove the temporary directory
    shutil.rmtree(str(msdir))
```

This seems to interact badly with casacore on python3. It may be hanging on to some references internally.

```traceback
$ py.test -s -v xarrayms/
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.6.7, pytest-4.5.0, py-1.8.0, pluggy-0.11.0 -- /home/sperkins/venv/xms-py3/bin/python3.6
cachedir: .pytest_cache
rootdir: /home/sperkins/work/ska/code/xarray-ms, inifile: setup.cfg
collected 47 items

xarrayms/tests/test_ms.py::test_ms_read[index_cols=['ANTENNA2', 'ANTENNA1', 'TIME']-
...
xarrayms/tests/test_table_executor.py::test_table_wrapper_locks[lockseq6] PASSED

================================================================================================ warnings summary =================================================================================================
/home/sperkins/venv/xms-py3/lib/python3.6/site-packages/_pytest/mark/structures.py:324
  /home/sperkins/venv/xms-py3/lib/python3.6/site-packages/_pytest/mark/structures.py:324: PytestUnknownMarkWarning: Unknown pytest.mark.slow - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/latest/mark.html
    PytestUnknownMarkWarning,

-- Docs: https://docs.pytest.org/en/latest/warnings.html
================================================================================ 45 passed, 2 xfailed, 1 warnings in 20.64 seconds ================================================================================
terminate called after throwing an instance of 'casacore::AipsError'
  what():  RegularFile: /tmp/pytest-of-sperkins/pytest-3/msdir/test.ms/table.dat does not exist and cannot be created
Aborted (core dumped)
```



=== ISSUE #19 | Consider setting MS index arrays to be coordinates | labels: enhancement | comments: [{"author":{"login":"miguelcarcamov"},"authorAssociation":"NONE","body":"Hi,\r\n\r\nI have a suggestion also. It would be cool if the baselines could have an ID as well. So the index columns could be like TIME, ANTENNA1, ANTENNA2, DATA_DESC_ID and BASELINE_ID :) ","createdAt":"2021-08-07T12:29:01Z","id":"IC_kwDOBh8_I841U0FN","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/ratt-ru/dask-ms/issues/19#issuecomment-894648653","viewerDidAuthor":false}] | created: 2018-09-01T11:20:31Z ===
1. xarray supports the idea of coordinate arrays to support indexing and selection of data.
2. The MS index columns (TIME, ANTENNA1, ANTENNA2, DATA_DESC_ID) etc. are appropriate to use as coordinate arrays.
3. It's trivial to convert them from standard xarray arrays to xarray coordinates via [Dataset.set_coords](http://xarray.pydata.org/en/stable/generated/xarray.Dataset.set_coords.html#xarray.Dataset.set_coords)
4. It might useful to support this as standard practice on the xarray-ms, but at some point a decision may need to be made as to whether to support this via numpy or dask arrays.

    - dask arrays are good for distributed problems and lazy loading, but care must be taken when using them for indices for e.g. http://dask.pydata.org/en/latest/array-chunks.html?highlight=nan#unknown-chunks
    - numpy arrays avoid the above issues but could be very large given the data volumes we are now encountering.

@bennahugo and @mulan-94, before deciding that 4. is a good idea, I'd be interested in hearing your experiences with 1, 2 and 3, if you have the need to use the xarray coordinate functionality for performing selections..
