Collection of scripts and small programs used by the EVN Support Scientists at JIVE during the regular data processing of EVN observations.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

144 lines
6.1 KiB

  1. #!/usr/bin/env python3
  2. """
  3. Flag visibilities with weights below the provided threshold.
  4. Usage: flag_weights.py msdata threshold
  5. Options:
  6. msdata : str MS data set containing the data to be flagged.
  7. threshold : float Visibilities with a weight below the specified
  8. value will be flagged. Must be positive.
  9. Version: 3.1
  10. Date: Mar 2020
  11. Written by Benito Marcote (marcote@jive.eu)
  12. version 3.1 changes (Mar 2020)
  13. - Progress bar added.
  14. version 3.0 changes (Apr 2019)
  15. - Refactoring code (thanks to Harro).
  16. version 2.0 changes
  17. - Major revision. Now it does not modify the weights anymore. Instead, it
  18. flags those data with weights below the given threshold by modifying the
  19. FLAG table.
  20. - Small change in print messages to show '100%' instead of '1e+02%' in certain
  21. cases.
  22. version 1.4 changes
  23. - Now it also reports the percentage or data that were different from
  24. zero and will be flagged (not only the total data as before).
  25. version 1.3 changes
  26. - Minor fixes (prog name in optparse info).
  27. version 1.2 changes
  28. - Minor fixes.
  29. version 1.1 changes
  30. - Added option -v that allows you to just get how many visibilities will
  31. be flagged (but without actually flagging the data).
  32. """
  33. from pyrap import tables as pt
  34. import numpy as np
  35. import sys
  36. __version__ = 3.0
  37. help_msdata = 'Measurement set containing the data to be corrected.'
  38. help_threshold = 'Visibilities with a weight below this value will be flagged. Must be positive.'
  39. help_v = 'Only checks the visibilities to flag (do not flag the data).'
  40. try:
  41. usage = "%(prog)s [-h] <measurement set> <weight threshold>"
  42. description="""Flag visibilities with weights below the provided threshold.
  43. """
  44. import argparse
  45. parser = argparse.ArgumentParser(description=description, prog='flag_weights.py', usage=usage)
  46. parser.add_argument('msdata', type=str, help=help_msdata)
  47. parser.add_argument('threshold', type=float, help=help_threshold)
  48. parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__))
  49. parser.add_argument("-v", "--verbose", default=True, action="store_false" , help=help_v)
  50. arguments = parser.parse_args()
  51. #print('The arguments ', arguments)
  52. verbose = arguments.verbose
  53. msdata = arguments.msdata[:-1] if arguments.msdata[-1]=='/' else arguments.msdata
  54. threshold = arguments.threshold
  55. except ImportError:
  56. usage = "%prog [-h] [-v] <measurement set> <weight threshold>"
  57. description="""Flag visibilities with weights below the provided threshold.
  58. """
  59. # Compatibility with Python 2.7 in eee
  60. import optparse
  61. parser = optparse.OptionParser(usage=usage, description=description, prog='flag_weights.py', version='%prog 1.3')
  62. parser.add_option("-v", action="store_false", dest="verbose", default=True, help=help_v)
  63. theparser = parser.parse_args()
  64. verbose = theparser[0].verbose
  65. arguments = theparser[1]
  66. #arguments = parser.parse_args()[1]
  67. if len(arguments) != 2:
  68. print('Two arguments must be provided: flag_weights.py [-h] [-v] <measurement set> <weight threshold>')
  69. print('Use -h to get help.')
  70. sys.exit(1)
  71. msdata = arguments[0][:-1] if arguments[0][-1]=='/' else arguments[0]
  72. threshold = float(arguments[1])
  73. assert threshold > 0.0
  74. def chunkert(f, l, cs, verbose=True):
  75. while f<l:
  76. n = min(cs, l-f)
  77. yield (f, n)
  78. f = f + n
  79. def cli_progress_bar(current_val, end_val, bar_length=40):
  80. percent = current_val/end_val
  81. hashes = '#'*int(round(percent*bar_length))
  82. spaces = ' '*(bar_length-len(hashes))
  83. sys.stdout.write("\rProgress: [{0}] {1}%".format(hashes+spaces, int(round(percent*100))))
  84. sys.stdout.flush()
  85. percent = lambda x, y: (float(x)/float(y))*100.0
  86. with pt.table(msdata, readonly=False, ack=False) as ms:
  87. total_number = 0
  88. flagged_before, flagged_after = (0, 0)
  89. flagged_nonzero, flagged_nonzero_before, flagged_nonzero_after = (0, 0, 0)
  90. # WEIGHT: (nrow, npol)
  91. # WEIGHT_SPECTRUM: (nrow, npol, nfreq)
  92. # flags[weight < threshold] = True
  93. weightcol = 'WEIGHT_SPECTRUM' if 'WEIGHT_SPECTRUM' in ms.colnames() else 'WEIGHT'
  94. transpose = (lambda x:x) if weightcol == 'WEIGHT_SPECTRUM' else (lambda x: x.transpose((1, 0, 2)))
  95. for (start, nrow) in chunkert(0, len(ms), 5000):
  96. cli_progress_bar(start, len(ms), bar_length=40)
  97. # shape: (nrow, npol, nfreq)
  98. flags = transpose(ms.getcol("FLAG", startrow=start, nrow=nrow))
  99. total_number += np.product(flags.shape)
  100. # count how much data is already flagged
  101. flagged_before += np.sum(flags)
  102. # extract weights and compute new flags based on threshold
  103. weights = ms.getcol(weightcol, startrow=start, nrow=nrow)
  104. # how many non-zero did we flag
  105. flagged_nonzero_before = np.logical_and(flags, weights > 0)
  106. # join with existing flags and count again
  107. flags = np.logical_or(flags, weights < threshold)
  108. flagged_after += np.sum(flags)
  109. flagged_nonzero_after = np.logical_and(flags, weights > 0)
  110. # Saving the total of nonzero flags (in this and previous runs)
  111. # flagged_nonzero += np.sum(np.logical_xor(flagged_nonzero_before, flagged_nonzero_after))
  112. flagged_nonzero += np.sum(flagged_nonzero_after)
  113. # one thing left to do: write the updated flags to disk
  114. #flags = ms.putcol("FLAG", flags.transpose((1, 0 , 2)), startrow=start, nrow=nrow)
  115. if verbose:
  116. flags = ms.putcol("FLAG", transpose(flags), startrow=start, nrow=nrow)
  117. print("\nGot {0:11} visibilities".format(total_number))
  118. print("Got {0:11} visibilities to flag using threshold {1}\n".format(flagged_after-flagged_before,
  119. threshold))
  120. print("{0:.2f}% total vis. flagged ({2:.2f}% to flag in this execution).\n{1:.2f}% data with non-zero weights flagged.\n".format(percent(flagged_after, total_number), percent(flagged_nonzero, total_number), percent(flagged_after-flagged_before, total_number)))
  121. ms.close()
  122. if verbose:
  123. print('Done.')
  124. else:
  125. print('Flags have not been applied.')