| 1 |
""" |
| 2 |
Writing data as plain text. |
| 3 |
|
| 4 |
Currently, we only do TSV. It would probably be nice to support "formatted |
| 5 |
ASCII as well, though that may be a bit tricky given that we do not |
| 6 |
really store sane formatting hints for most columns. |
| 7 |
""" |
| 8 |
|
| 9 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 10 |
#c |
| 11 |
#c This program is free software, covered by the GNU GPL. See the |
| 12 |
#c COPYING file in the source distribution. |
| 13 |
|
| 14 |
|
| 15 |
import io |
| 16 |
import datetime |
| 17 |
|
| 18 |
from gavo import base |
| 19 |
from gavo import rsc |
| 20 |
from gavo import stc |
| 21 |
from gavo import utils |
| 22 |
from gavo.formats import common |
| 23 |
from gavo.utils import serializers |
| 24 |
|
| 25 |
# A mapper function registry for formats directed at humans |
| 26 |
displayMFRegistry = serializers.ValueMapperFactoryRegistry() |
| 27 |
registerDisplayMF = displayMFRegistry.registerFactory |
| 28 |
|
| 29 |
def _defaultMapperFactory(colDesc): |
| 30 |
def coder(val): |
| 31 |
if val is None: |
| 32 |
return "N/A" |
| 33 |
return str(val) |
| 34 |
return coder |
| 35 |
registerDisplayMF(_defaultMapperFactory) |
| 36 |
|
| 37 |
|
| 38 |
floatTypes = set(["real", "float", "double", "double precision"]) |
| 39 |
|
| 40 |
def _sfMapperFactory(colDesc): |
| 41 |
if colDesc["dbtype"] not in floatTypes: |
| 42 |
return |
| 43 |
if colDesc["displayHint"].get("sf"): |
| 44 |
fmtStr = "%%.%df"%int(colDesc["displayHint"].get("sf")) |
| 45 |
def coder(val): |
| 46 |
if val is None: |
| 47 |
return "N/A" |
| 48 |
else: |
| 49 |
return fmtStr%val |
| 50 |
return coder |
| 51 |
registerDisplayMF(_sfMapperFactory) |
| 52 |
|
| 53 |
|
| 54 |
def _hmsMapperFactory(colDesc): |
| 55 |
if colDesc["displayHint"].get("type")!="hms": |
| 56 |
return |
| 57 |
assert colDesc["unit"]=="deg", "hms display hint only works with deg so far" |
| 58 |
colDesc["unit"] = "h:m:s" |
| 59 |
sepChar = colDesc["displayHint"].get("sepChar", " ") |
| 60 |
sf = int(colDesc["displayHint"].get("sf", 2)) |
| 61 |
def coder(val): |
| 62 |
if val is None: |
| 63 |
return "N/A" |
| 64 |
else: |
| 65 |
return utils.degToHms(val, sepChar, sf) |
| 66 |
return coder |
| 67 |
registerDisplayMF(_hmsMapperFactory) |
| 68 |
|
| 69 |
|
| 70 |
def _dmsMapperFactory(colDesc): |
| 71 |
if colDesc["displayHint"].get("type")!="dms": |
| 72 |
return |
| 73 |
colDesc["unit"] = "d:m:s" |
| 74 |
sepChar = colDesc["displayHint"].get("sepChar", " ") |
| 75 |
sf = int(colDesc["displayHint"].get("sf", 2)) |
| 76 |
def coder(val): |
| 77 |
if val is None: |
| 78 |
return "N/A" |
| 79 |
return utils.degToDms(val, sepChar, sf) |
| 80 |
return coder |
| 81 |
registerDisplayMF(_dmsMapperFactory) |
| 82 |
|
| 83 |
|
| 84 |
def _specUnitMapperFactory(colDesc): |
| 85 |
"""returns a factory that converts between spectral units based |
| 86 |
on a spectralUnit displayHint. |
| 87 |
|
| 88 |
In contract to unitMapperFactory, this supports non-linear conversions. |
| 89 |
""" |
| 90 |
spUnit = colDesc["displayHint"].get("spectralUnit") |
| 91 |
if spUnit and spUnit!=colDesc["unit"]: |
| 92 |
fmtStr = "'%%.%df'"%int(colDesc["displayHint"].get("sf", 2)) |
| 93 |
expr = base.getSpecExpr(colDesc["unit"], spUnit).format("val") |
| 94 |
code = ("def coder(val):\n if val is None:\n return 'N/A'\n" |
| 95 |
f" else:\n return {fmtStr}%({expr})") |
| 96 |
colDesc["unit"] = spUnit |
| 97 |
return utils.compileFunction(code, "coder") |
| 98 |
|
| 99 |
|
| 100 |
registerDisplayMF(_specUnitMapperFactory) |
| 101 |
|
| 102 |
|
| 103 |
def _unitMapperFactory(colDesc): |
| 104 |
"""returns a factory that converts between units for fields that have |
| 105 |
a displayUnit displayHint. |
| 106 |
|
| 107 |
The stuff done here has to be done for all factories handling unit-based |
| 108 |
floating point values. Maybe we want to do "decorating" meta-factories? |
| 109 |
""" |
| 110 |
if colDesc["displayHint"].get("displayUnit") and \ |
| 111 |
colDesc["displayHint"]["displayUnit"]!=colDesc["unit"]: |
| 112 |
try: |
| 113 |
factor = base.computeConversionFactor(colDesc["unit"], |
| 114 |
colDesc["displayHint"]["displayUnit"]) |
| 115 |
except base.BadUnit: |
| 116 |
# bad unit somewhere; ignore display hint |
| 117 |
base.ui.notifyError("Bad unit while computing conversion factor.") |
| 118 |
return None |
| 119 |
|
| 120 |
colDesc["unit"] = colDesc["displayHint"]["displayUnit"] |
| 121 |
fmtStr = "%%.%df"%int(colDesc["displayHint"].get("sf", 2)) |
| 122 |
|
| 123 |
if "[" in colDesc["dbtype"]: |
| 124 |
def coder(val): |
| 125 |
if val is None: |
| 126 |
return "N/A" |
| 127 |
return "[%s]"%", ".join("N/A" if item is None else fmtStr%(item*factor) |
| 128 |
for item in val) |
| 129 |
|
| 130 |
else: |
| 131 |
def coder(val): |
| 132 |
return "N/A" if val is None else fmtStr%(val*factor) |
| 133 |
|
| 134 |
return coder |
| 135 |
registerDisplayMF(_unitMapperFactory) |
| 136 |
|
| 137 |
|
| 138 |
def _stringWrapMF(baseMF): |
| 139 |
"""returns a factory that that stringifies floats and makes N/A from |
| 140 |
Nones coming out of baseMF and passes everything else through. |
| 141 |
""" |
| 142 |
def factory(colDesc): |
| 143 |
handler = baseMF(colDesc) |
| 144 |
if colDesc["displayHint"].get("sf", None): |
| 145 |
fmtstr = "%%.%df"%int(colDesc["displayHint"]["sf"]) |
| 146 |
fmtstr = "%s" |
| 147 |
if handler: |
| 148 |
def realHandler(val): |
| 149 |
res = handler(val) |
| 150 |
if isinstance(res, float): |
| 151 |
return fmtstr%res |
| 152 |
else: |
| 153 |
if res is None: |
| 154 |
return "N/A" |
| 155 |
else: |
| 156 |
return res |
| 157 |
return realHandler |
| 158 |
return factory |
| 159 |
|
| 160 |
registerDisplayMF(_stringWrapMF(stc.datetimeMapperFactory)) |
| 161 |
|
| 162 |
|
| 163 |
def humanDatesFactory(colDesc): |
| 164 |
format, unit = {"humanDate": ("%Y-%m-%d %H:%M:%S", ""), |
| 165 |
"humanDay": ("%Y-%m-%d", "") }.get( |
| 166 |
colDesc["displayHint"].get("type"), (None, None)) |
| 167 |
if format and colDesc["dbtype"] in ("date", "timestamp"): |
| 168 |
colDesc["unit"] = unit |
| 169 |
def coder(val): |
| 170 |
if val is None: |
| 171 |
return "N/A" |
| 172 |
else: |
| 173 |
colDesc["datatype"], colDesc["arraysize"] = "char", "*" |
| 174 |
colDesc["xtype"] = "timestamp" |
| 175 |
colDesc["unit"] = "" |
| 176 |
try: |
| 177 |
return val.strftime(format) |
| 178 |
except ValueError: # probably too old a date, fall back to a hack |
| 179 |
return val.isoformat() |
| 180 |
return coder |
| 181 |
registerDisplayMF(humanDatesFactory) |
| 182 |
|
| 183 |
|
| 184 |
def humanTimesFactory(colDesc): |
| 185 |
if colDesc["displayHint"].get("type")=="humanTime": |
| 186 |
sf = int(colDesc["displayHint"].get("sf", 0)) |
| 187 |
fmtStr = "%%02d:%%02d:%%0%d.%df"%(sf+3, sf) |
| 188 |
def coder(val): |
| 189 |
if val is None: |
| 190 |
return "N/A" |
| 191 |
else: |
| 192 |
if isinstance(val, (datetime.time, datetime.datetime)): |
| 193 |
return fmtStr%(val.hour, val.minute, val.second) |
| 194 |
elif isinstance(val, datetime.timedelta): |
| 195 |
hours = val.seconds//3600 |
| 196 |
minutes = (val.seconds-hours*3600)//60 |
| 197 |
seconds = (val.seconds-hours*3600-minutes*60)+val.microseconds/1e6 |
| 198 |
return fmtStr%(hours, minutes, seconds) |
| 199 |
return coder |
| 200 |
registerDisplayMF(humanTimesFactory) |
| 201 |
|
| 202 |
|
| 203 |
def jdMapperFactory(colDesc): |
| 204 |
"""maps JD, MJD, unix timestamp, and julian year columns to |
| 205 |
human-readable datetimes. |
| 206 |
""" |
| 207 |
if (colDesc["displayHint"].get("type")=="humanDate" |
| 208 |
and colDesc["dbtype"] in ("double precision", "real")): |
| 209 |
|
| 210 |
if colDesc["unit"]=="d": |
| 211 |
if stc.isMJD(colDesc.original): |
| 212 |
converter = stc.mjdToDateTime |
| 213 |
else: |
| 214 |
converter = stc.jdnToDateTime |
| 215 |
elif colDesc["unit"]=="s": |
| 216 |
converter = datetime.datetime.utcfromtimestamp |
| 217 |
elif colDesc["unit"]=="yr": |
| 218 |
converter = stc.jYearToDateTime |
| 219 |
else: |
| 220 |
return None |
| 221 |
|
| 222 |
def fun(val): |
| 223 |
if val is None: |
| 224 |
return "N/A" |
| 225 |
return utils.formatISODT(converter(val)) |
| 226 |
colDesc["datatype"], colDesc["arraysize"] = "char", "*" |
| 227 |
colDesc["xtype"] = "timestamp" |
| 228 |
colDesc["unit"] = "" |
| 229 |
return fun |
| 230 |
registerDisplayMF(jdMapperFactory) |
| 231 |
|
| 232 |
|
| 233 |
def _sizeMapperFactory(colDesc): |
| 234 |
"""is a factory for formatters for file sizes and similar. |
| 235 |
""" |
| 236 |
if colDesc["unit"]!="byte": |
| 237 |
return |
| 238 |
sf = int(colDesc["displayHint"].get("sf", 1)) |
| 239 |
def coder(val): |
| 240 |
if val is None: |
| 241 |
return "N/A" |
| 242 |
else: |
| 243 |
return utils.formatSize(val, sf) |
| 244 |
return coder |
| 245 |
registerDisplayMF(_sizeMapperFactory) |
| 246 |
|
| 247 |
|
| 248 |
registerDisplayMF(serializers._pgSphereMapperFactory) |
| 249 |
|
| 250 |
|
| 251 |
def _makeString(val): |
| 252 |
if val is None: |
| 253 |
return "N/A" |
| 254 |
elif isinstance(val, str): |
| 255 |
# a cheaty way of making sure we get hex escapes for non-printable stuff |
| 256 |
return repr(val)[1:-1] |
| 257 |
elif isinstance(val, bytes): |
| 258 |
return repr(val)[2:-1] |
| 259 |
elif isinstance(val, (list, tuple)): |
| 260 |
return "[%s]"%" ".join("%s"%v for v in val) |
| 261 |
return str(val) |
| 262 |
|
| 263 |
|
| 264 |
def renderAsColumns(table, target, acquireSamples=False): |
| 265 |
"""writes a fixed-column representation of table to target. |
| 266 |
""" |
| 267 |
if isinstance(table, rsc.Data): |
| 268 |
table = table.getPrimaryTable() |
| 269 |
sm = base.SerManager(table, acquireSamples=acquireSamples, |
| 270 |
mfRegistry=displayMFRegistry) |
| 271 |
target.write(utils.bytify( |
| 272 |
utils.formatSimpleTable( |
| 273 |
(_makeString(s) for s in row) for row in sm.getMappedTuples()))) |
| 274 |
|
| 275 |
|
| 276 |
def renderAsText(table, target, acquireSamples=True): |
| 277 |
"""writes a text (TSV) rendering of table to the file target. |
| 278 |
""" |
| 279 |
if isinstance(table, rsc.Data): |
| 280 |
table = table.getPrimaryTable() |
| 281 |
sm = base.SerManager(table, acquireSamples=acquireSamples) |
| 282 |
for row in sm.getMappedTuples(): |
| 283 |
target.write( |
| 284 |
utils.bytify("\t".join([_makeString(s) for s in row])+"\n")) |
| 285 |
|
| 286 |
|
| 287 |
def getAsText(data): |
| 288 |
target = io.BytesIO() |
| 289 |
renderAsText(data, target) |
| 290 |
return target.getvalue().decode("utf-8") |
| 291 |
|
| 292 |
|
| 293 |
def readTSV(inFile): |
| 294 |
"""returns a list of tuples for a tab-separated-values file. |
| 295 |
|
| 296 |
Lines starting with # and lines containing only whitespace are ignored. |
| 297 |
Whitespace at front and back is stripped. |
| 298 |
|
| 299 |
No checks are done at this point, i.e., the tuples could be of varying |
| 300 |
lengths. |
| 301 |
""" |
| 302 |
data = [] |
| 303 |
for ln in inFile: |
| 304 |
ln = ln.strip() |
| 305 |
if not ln or ln.startswith("#"): |
| 306 |
continue |
| 307 |
data.append(tuple(ln.split("\t"))) |
| 308 |
return data |
| 309 |
|
| 310 |
|
| 311 |
# NOTE: This will only serialize the primary table. |
| 312 |
common.registerDataWriter("tsv", renderAsText, "text/tab-separated-values", |
| 313 |
"Tab separated values", ".tsv") |
| 314 |
common.registerDataWriter("txt", renderAsColumns, "text/plain", |
| 315 |
"Fixed-column plain text", ".txt") |