Coverage for /wheeldirectory/casa-6.7.0-12-py3.10.el8/lib/py/lib/python3.10/site-packages/casatasks/private/task_immoments.py: 14%
65 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-10-31 19:10 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-10-31 19:10 +0000
1########################################################################3
2# task_immoments.py
3#
4#
5# Copyright (C) 2008, 2009
6# Associated Universities, Inc. Washington DC, USA.
7#
8# This script is free software; you can redistribute it and/or modify it
9# under the terms of the GNU Library General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or (at your
11# option) any later version.
12#
13# This library is distributed in the hope that it will be useful, but WITHOUT
14# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
16# License for more details.
17#
18# You should have received a copy of the GNU Library General Public License
19# along with this library; if not, write to the Free Software Foundation,
20# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
21#
22# Correspondence concerning AIPS++ should be adressed as follows:
23# Internet email: casa-feedback@nrao.edu.
24# Postal address: AIPS++ Project Office
25# National Radio Astronomy Observatory
26# 520 Edgemont Road
27# Charlottesville, VA 22903-2475 USA
28#
29# <author>
30# Shannon Jaeger (University of Calgary)
31# </author>
32#
33# <summary>
34# CASA task for finding moments along a specified axis of a
35# multi-dimentional CASA image.
36# contents
37# </summary>
38#
39# <reviewed reviwer="" date="" tests="" demos="">
40# </reviewed
42# <etymology>
43# immoments stands for image momemnts
44# </etymology>
45#
46# <synopsis>
47# task_immoments.py is a Python script providing an easy to use task
48# for generating momements along a user specified axis on a CASA image.
49# This is a time-honoured spectral-line analysis technique for discovering
50# spectral line information.
51#
52# In this task, moment, refers to collapsing an axis of the image,
53# the moment axis, to a single pixel.
54#
55# The various moments that can be calculated are described in detail
56# at http://casa.nrao.edu/docs/casaref/image.moments.html#x59-590001.1.1
57#
58# </synopsis>
59#
60# <example>
61# <srcblock>
62# # The following code snippet find the 1-moments, intensity-weighted
63# # coordinate, often used for finding velocity fields.
64# immoments( 'axis='spec', imagename='myimage', moment=1, outfile='velocityfields' )
65#
66# # Finding the spectral mean, -1 moment, on a specified portion of the image.
67# # The region used is defined by the box and stokes parameters
68# immoments( imagename='myimage', axis='spec', stokes='I', box=[55,12,97,32], moment=-1 )
69#
70# # The following example uses a second file to use as a mask.
71# # The 0-moments, integrated values, are created on clean.im, but
72# # the mask is based on all the data in calibrated.im, all values
73# # about the threshold 0.5 are used to create the mask.
74#
75# immoments( 'clean.image', axis='spec', mask='calibrated.im>0.5', outfile='mom_withmask.im' )
76# </srblock>
77# </example>
78#
79# <motivation>
80# To provide a user-friendly method of calculating image moments.
81# </motivation>
82#
83# <todo>
84# </todo>
86import os, sys, time
87from stat import S_ISDIR, ST_MTIME, ST_MODE
88from .ialib import write_image_history
89from casatools import regionmanager, image
90from casatasks import casalog
91from . import cvt
93_rg = regionmanager( )
95def immoments(
96 imagename, moments, axis, region, box, chans, stokes,
97 mask, includepix, excludepix, outfile, stretch
98):
99 retValue=None
100 outia = None
101 casalog.origin('immoments')
102 _myia = image( )
103 _csys = None
104 try:
105 if (len(outfile) == 0):
106 raise ValueError("outfile must be specified")
107 _myia.dohistory(False)
108 # First check to see if the output file exists. If it
109 # does then we abort. CASA doesn't allow files to be
110 # over-written, just a policy.
111 if os.path.exists(outfile):
112 raise ValueError(
113 'Output file, ' + outfile +
114 ' exists. immoment can not proceed, please\n'\
115 'remove it or change the output file name.'
116 )
117 elif ( len( outfile ) == 1 ):
118 raise ValueError( 'outfile is not specified but must be' )
119 _myia.open(imagename)
120 _csys = _myia.coordsys()
121 reg = _rg.frombcs(csys=_csys.torecord(),
122 shape=_myia.shape(), box=box, chans=chans, stokes=stokes,
123 stokescontrol="a", region=region
124 )
125 if isinstance(axis, str):
126 axis = _csys.findaxisbyname(axis)
127 _csys.done()
128 outia = _myia.moments(
129 moments=moments, axis=int(axis), mask=mask,
130 region=reg, includepix=cvt.as_list(includepix),
131 excludepix=cvt.as_list(excludepix), outfile=outfile, drop=False,
132 stretch=stretch
133 )
134 created_images = _immoments_get_created_images(outia.name(), outfile)
135 created_images.append(outia)
137 try:
138 vars = locals( )
139 param_names = immoments.__code__.co_varnames[:immoments.__code__.co_argcount]
140 param_vals = [vars[p] for p in param_names]
141 method = sys._getframe().f_code.co_name
142 for im in created_images:
143 write_image_history(
144 im, method, param_names, param_vals, casalog
145 )
146 except Exception as instance:
147 casalog.post("*** Error \'%s\' updating HISTORY" % (instance), 'WARN')
149 finally:
150 _myia.done()
151 _rg.done()
152 if outia:
153 outia.done()
154 if _csys:
155 _csys.done()
157def _immoments_get_created_images(out1name, outfile):
158 dirpath = os.path.dirname(out1name)
159 target_time = os.path.getmtime(out1name)
160 # get all subdirs in the directory w/ stats
161 subdirs = [
162 os.path.join(dirpath, name) for name in os.listdir(dirpath)
163 if os.path.isdir(os.path.join(dirpath, name))
164 ]
165 entries = []
166 for path in subdirs:
167 try:
168 entries.append((os.stat(path), path))
169 except FileNotFoundError:
170 # CAS-13821 this directory disappeared during the execution of the
171 # task, so it was not created by the task but just a coincidental
172 # delete by some unrelated process, so just skip it
173 pass
174 # insert creation date
175 entries = ((stat.st_mtime, path) for stat, path in entries)
176 # reverse sort by time
177 zz = sorted(entries)
178 zz.reverse()
179 created_images = []
180 for mdate, path in zz:
181 if mdate < target_time:
182 # dirs created before execution of this task, so exit
183 break
184 if path != out1name and os.path.basename(path).startswith(outfile):
185 created_images.append(path)
186 return created_images