Skip to content

Commit

Permalink
add 'export' feature in the script
Browse files Browse the repository at this point in the history
  • Loading branch information
misho104 committed Apr 17, 2021
1 parent 2e98ff1 commit 6c054ce
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "susy_cross_section"
version = "0.2.0beta"
version = "0.2.0"
description = "A Python package for high-energy physics analysis to provide SUSY cross section data"
authors = ["Sho Iwamoto (Misho) <webmaster@misho-web.com>"]
license = "MIT"
Expand Down
10 changes: 10 additions & 0 deletions susy_cross_section/base/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ def __str__(self):
"""Dump the data-frame."""
return cast(str, self._df.__str__())

def header(self):
# type: ()->List[Any]
"""Return the header of DataFrame regarded as a table."""
return list(self._df.index.names) + list(self._df.columns)

def to_records(self):
# type: ()->numpy.record
"""Export the data-frame to a plain list."""
return self._df.to_records()


class BaseFile(Generic[TableT]):
"""File with table data-sets and annotations.
Expand Down
78 changes: 78 additions & 0 deletions susy_cross_section/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,84 @@ def show(**kw):
exit(0)


@main.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.argument("table", required=True, type=click.Path(exists=False))
@click.option("--name", default="xsec", help="name of a table")
@click.option("--unit/--no-unit", help="with unit", default=True, show_default=True)
@click.option("--unc/--no-unc", help="uncertainty", default=True, show_default=True)
@click.option(
"--format",
type=click.Choice(["TSV", "CSV", "Math"], case_sensitive=False),
default="TSV",
show_default=True,
)
@click.option(
"--info",
type=click.Path(exists=True, dir_okay=False),
help="path of table-info file if non-standard file name",
)
@click.pass_context
def export(context, **kw):
# type: (Any, Any)->None
"""Export cross-section table."""
_configure_logger()
# handle arguments
value_name = kw["name"] or _DEFAULT_VALUE_NAME
try:
table_path, info_path = Util.get_paths(kw["table"], kw["info"])
data_file = File(table_path, info_path)
except (FileNotFoundError, RuntimeError, ValueError, TypeError) as e:
click.echo(repr(e))
exit(1)

try:
table = data_file.tables[value_name]
except KeyError as e:
logger.critical("Data file does not contain specified table.")
click.echo(repr(e))
exit(1)

header = table.header()
records = table.to_records()
n_columns = len(header)

units = ["" for i in header]
if kw["unit"]:
try:
units = [" " + u for u in table.units()]
except RuntimeError:
logger.warning("Unit information not available for specified table.")

if kw["format"] == "TSV" or kw["format"] == "CSV":
sep = "\t" if kw["format"] == "TSV" else ","
click.echo(sep.join(header))
for record in records:
line = [] # type: List[str]
for i, v in enumerate(record):
if i < n_columns - 2:
line.append(str(v) + units[i]) # key & value
elif kw["unc"]:
line.append(f"{v:.5g}{units[-1]}") # unc
click.echo(sep.join(line))
elif kw["format"] == "Math": # Mathematica

def concat(c): # type: (List[str])->str
return " {" + ", ".join(c) + "}"

lines = [concat([f'"{s}"' for s in header[:-2]])] # header
for r in records:
if kw["unc"]:
value = f"Around[{r[-3]}, {{{r[-1]:.5g}, {r[-2]:.5g}}}]"
else:
value = str(r[-3])
value = value.replace("e", "*^") + units[-1] # Mathematica "E" notation
keys = [f"{v}{units[i]}" for i, v in enumerate(r) if i < n_columns - 3]
keys.append(value)
lines.append(concat(keys))
click.echo("{\n" + ",\n".join(lines) + "\n}")
exit(0)


@main.command(name="list", context_settings={"help_option_names": ["-h", "--help"]})
@click.argument("substr", nargs=-1)
@click.option("--all", "-a", is_flag=True, help="List all the tables in this package.")
Expand Down
13 changes: 13 additions & 0 deletions susy_cross_section/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ def attributes(self):
else:
raise RuntimeError("No information is given for this table.")

def units(self):
# type: ()->List[str]
"""Return the units of table keys and columns."""
if self.file and self.name:
units = [
self.file.info.get_column(p.column).unit
for p in self.file.info.parameters
] # keys' unit
units.append(self.unit) # value's unit
return units
else:
raise RuntimeError("No information is given for this table.")


class File(BaseFile[Table]):
"""Data of a cross section with parameters, read from a table file.
Expand Down

0 comments on commit 6c054ce

Please sign in to comment.