-
Notifications
You must be signed in to change notification settings - Fork 0
WIP: Uncertainties usdf #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
wilsonbb
wants to merge
15
commits into
main
Choose a base branch
from
uncertainties_USDF
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
2d32287
First draft of simple workflow to produce uncertainties on USDF
wilsonbb 6da225d
Update instructions
wilsonbb fbe9555
Fix uncertainty workflow import
wilsonbb fae703b
Switch WorkUnit.heliocentric_distance to WorkUnit.barycentric_distanc…
wilsonbb f7bd5bd
updated usdf config (#56)
ColinOrionChandler 72cc308
Increased max block size for the various partitions. (#58)
ColinOrionChandler 5bf19e9
Make Parsl Robust to Workflow Exceptions (#59)
wilsonbb 940d90f
Add option to cleanup sharded WorkUnit after search
wilsonbb a7fb13e
Updated files
wilsonbb 4be91a0
Remove date from Parsl workflow run directory (#61)
wilsonbb af4f8ad
Added parsl config scripts for USDF (#63)
ColinOrionChandler dc4a8ed
automatic detection of usdf; new Parsl fixes (#64)
ColinOrionChandler 353b91b
One node to rule them all (#65)
ColinOrionChandler 6d08418
Add flag to disorder/fuzz the obstimes of a WorkUnit (#66)
wilsonbb 903178f
Merge branch 'main' into uncertainties_USDF
wilsonbb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,255 @@ | ||
import argparse | ||
import os | ||
|
||
import toml | ||
import parsl | ||
from parsl import python_app, File | ||
import parsl.executors | ||
|
||
from kbmod_wf.utilities import ( | ||
apply_runtime_updates, | ||
get_resource_config, | ||
get_executors, | ||
get_configured_logger, | ||
) | ||
|
||
@python_app( | ||
cache=True, | ||
executors=get_executors(["local_dev_testing", "gpu"]), # TODO verify if gpu is needed | ||
ignore_for_cache=["logging_file"], | ||
) | ||
def get_uncertainties(inputs=(), outputs=(), runtime_config={}, logging_file=None): | ||
"""Loads a WorkUnit and KBMOD results and calculates the uncertaintties for those results | ||
|
||
Parameters | ||
---------- | ||
inputs : `tuple` or `list` | ||
Order sensitive input to the Python App. | ||
outputs : `tuple` or `list` | ||
Order sensitive output of the Python App. | ||
runtime_config : `dict`, optional | ||
Runtime configuration values. Keys ``butler_config_filepath``, | ||
``search_config_filepath`` and ``n_workers`` will be consumed | ||
if they exist. | ||
logging_file : `File` or `None`, optional | ||
Parsl File object poiting to the output logging file. | ||
|
||
Returns | ||
------- | ||
outputs : `tuple` or `list` | ||
Order sensitive output of the Python App. | ||
|
||
Inputs | ||
---------- | ||
wu_file : `File` | ||
Parsl File object pointing to the WorkUnit. | ||
res_file : `File` | ||
KBMOD results file corresponding to this WorkUnit. | ||
uuids : `list` | ||
List of UUID hex representations corresponding to results we want to | ||
measure uncertainties for. If empty, all results will be used. | ||
|
||
Outputs | ||
------- | ||
workunit_path : `File` | ||
Parsl File object poiting to the resampled WorkUnit. | ||
""" | ||
import json | ||
|
||
import numpy as np | ||
from astropy.table import Table | ||
|
||
from kbmod.work_unit import WorkUnit | ||
from kbmod.trajectory_explorer import TrajectoryExplorer | ||
|
||
from kbmod_wf.task_impls import calc_skypos_uncerts | ||
from kbmod_wf.utilities.logger_utilities import get_configured_logger, ErrorLogger | ||
logger = get_configured_logger("workflow.get_uncertainties", logging_file.filepath) | ||
|
||
with ErrorLogger(logger): | ||
logger.info("Starting getting uncertainties.") | ||
|
||
if os.path.exists(outputs[0].filepath): | ||
logger.info("Finished step 2. Uncertainties exist.") | ||
return outputs | ||
|
||
wu_path = inputs[0].filepath | ||
res_path = inputs[1].filepath | ||
uuids = inputs[2] | ||
|
||
# Load the WorkUnit | ||
wu = None | ||
try: | ||
wu = WorkUnit.from_fits(wu_path) | ||
logger.info(f"Loaded WorkUnit from fits") | ||
except Exception as e: | ||
wu_filename = os.path.basename(wu_path) | ||
wu_dir = os.path.dirname(wu_path) | ||
wu = WorkUnit.from_sharded_fits(wu_filename, wu_dir, lazy=False) | ||
logger.info(f"Loaded WorkUnit from sharded fits") | ||
|
||
# Load results from this WorkUnit | ||
results = Table.read(res_path) | ||
explorer = TrajectoryExplorer(wu.im_stack) | ||
|
||
wcs = wu.wcs | ||
|
||
uuids2, pgs, startt, endt = [], [], [], [] | ||
p1ra, p1dec, sigma_p1ra, sigma_p1dec = [], [], [], [] | ||
p2ra, p2dec, sigma_p2ra, sigma_p2dec = [], [], [], [] | ||
likelihoods, uncerts = [], [] | ||
|
||
if len(uuids) > 0: | ||
# If the user specified a list of UUIDs, filter the results to just those UUIDs | ||
results.table = results.table[results["uuid"].isin(uuids)] | ||
|
||
for r in results: | ||
# TODO Make UUIDs required | ||
uuid = r["uuid"] if "uuid" in r.table.colnames else -1 | ||
samples = explorer.evaluate_around_linear_trajectory( | ||
r["x"][0], | ||
r["y"][0], | ||
r["vx"][0], | ||
r["vy"][0], | ||
pixel_radius=10, | ||
max_ang_offset=0.785397999997775, # np.pi/4 | ||
ang_step=1.5*0.0174533, # deg2rad | ||
max_vel_offset=45, | ||
vel_step=0.55, | ||
) | ||
|
||
maxl = samples["likelihood"].max() | ||
bestfit = samples[samples["likelihood"] == maxl] | ||
# happens when oversampling | ||
if len(bestfit) > 1: | ||
bestfit = bestfit[:1] | ||
|
||
# Get the valid obstimes that were used this result | ||
valid_obstimes = [] | ||
for i in range(len(r["obs_valid"])): | ||
if r["obs_valid"][i]: | ||
valid_obstimes.append(wu.im_stack.get_obstime(i)) | ||
|
||
mjd_start = min(valid_obstimes) | ||
mjd_end = max(valid_obstimes) | ||
|
||
start_coord, end_coord, uncert = calc_skypos_uncerts( | ||
samples, | ||
mjd_start, | ||
mjd_end, | ||
wcs | ||
) | ||
|
||
uuids2.append(uuid) | ||
startt.append(mjd_start) | ||
endt.append(mjd_end) | ||
likelihoods.append(maxl) | ||
p1ra.append(start_coord.ra.deg) | ||
p1dec.append(start_coord.dec.deg) | ||
p2ra.append(end_coord.ra.deg) | ||
p2dec.append(end_coord.dec.deg) | ||
sigma_p1ra.append(uncert[0,0]) | ||
sigma_p1dec.append(uncert[1,1]) | ||
sigma_p2ra.append(uncert[2,2]) | ||
sigma_p2dec.append(uncert[3,3]) | ||
uncerts.append(uncert) | ||
|
||
t = Table({ | ||
"likelihood": likelihoods, | ||
"p1ra": p1ra, | ||
"p1dec": p1dec, | ||
"p2ra": p2ra, | ||
Comment on lines
+158
to
+161
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add the generated x's and y's to the table for debugging purposes |
||
"p2dec": p2dec, | ||
"sigma_p1ra": np.sqrt(sigma_p1ra), | ||
"sigma_p1dec": np.sqrt(sigma_p1dec), | ||
"sigma_p2ra": np.sqrt(sigma_p2ra), | ||
"sigma_p2dec": np.sqrt(sigma_p2dec), | ||
"uncertainty": uncerts, | ||
"uuid": uuids2, | ||
"t0": startt, | ||
"t1": endt | ||
}) | ||
t.write(outputs[0].filepath, format="ascii.ecsv", overwrite=True) | ||
logger.info("Finished step 2.") | ||
|
||
return outputs | ||
|
||
|
||
|
||
def workflow_runner(env=None, runtime_config={}): | ||
"""This function will load and configure Parsl, and run the workflow. | ||
|
||
Parameters | ||
---------- | ||
env : str, optional | ||
Environment string used to define which resource configuration to use, | ||
by default None | ||
runtime_config : dict, optional | ||
Dictionary of assorted runtime configuration parameters, by default {} | ||
""" | ||
resource_config = get_resource_config(env=env) | ||
resource_config = apply_runtime_updates(resource_config, runtime_config) | ||
|
||
app_configs = runtime_config.get("apps", {}) | ||
|
||
dfk = parsl.load(resource_config) | ||
if dfk: | ||
logging_file = File(os.path.join(dfk.run_dir, "kbmod.log")) | ||
logger = get_configured_logger("workflow.workflow_runner", logging_file.filepath) | ||
|
||
if runtime_config is not None: | ||
logger.info(f"Using runtime configuration definition:\n{toml.dumps(runtime_config)}") | ||
|
||
logger.info("Starting workflow") | ||
|
||
runtime_config=app_configs.get("get_uncertainties", {}) | ||
|
||
# Get filenames from runtime config | ||
wu_path = runtime_config.get("wu_path", None) | ||
wu_name = os.path.basename(wu_path) | ||
res_path = runtime_config.get("res_path", None) | ||
uuids = runtime_config.get("uuids", []) | ||
output_dir = runtime_config.get("output_dir", os.getcwd()) | ||
|
||
# create output directory if it doesn't exist | ||
os.makedirs(output_dir, exist_ok=True) | ||
|
||
# run kbmod search on each reprojected WorkUnit | ||
uncertainty_future = get_uncertainties( | ||
inputs=[File(wu_path), File(res_path), uuids], | ||
outputs=[File(os.path.join(output_dir, f"{wu_name}.meas"))], | ||
runtime_config=app_configs.get("kbmod_search", {}), | ||
logging_file=logging_file, | ||
) | ||
uncertainty_future.result() | ||
dfk.wait_for_current_tasks() | ||
|
||
logger.info("Workflow complete") | ||
|
||
parsl.clear() | ||
|
||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument( | ||
"--env", | ||
type=str, | ||
choices=["dev", "klone", "usdf"], | ||
help="The environment to run the workflow in.", | ||
) | ||
|
||
parser.add_argument( | ||
"--runtime-config", | ||
type=str, | ||
help="The complete runtime configuration filepath to use for the workflow.", | ||
) | ||
|
||
args = parser.parse_args() | ||
|
||
# if a runtime_config file was provided and exists, load the toml as a dict. | ||
runtime_config = {} | ||
if args.runtime_config is not None and os.path.exists(args.runtime_config): | ||
with open(args.runtime_config, "r") as toml_runtime_config: | ||
runtime_config = toml.load(toml_runtime_config) | ||
|
||
workflow_runner(env=args.env, runtime_config=runtime_config) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
# Example parsl config associated with wu_to_uncertainties_workflow.python_app | ||
# To run on USDF, run: | ||
# python /[YOUR_BASE_PATH]/kbmod-wf/src/kbmod_wf/wu_to_uncertainties_workflow.py --runtime-config=[PATH OF THIS RUNTIME CONFIG] --env=usdf | ||
|
||
# All values set here will be applied to the resource configuration prior to | ||
# calling parsl.load(config). Even if the key does't exist in the resource | ||
# config, it will be added with the value defined here. | ||
[resource_config_modifiers] | ||
checkpoint_mode = 'task_exit' | ||
|
||
# Values in the apps.XXX section will be passed as a dictionary to the corresponding | ||
# app. e.g. apps.create_uri_manifest will be passed to the create_uri_manifest app. | ||
[apps.get_uncertainties] | ||
|
||
# The path of a resampled workunit to process | ||
wu_path = "" # TODO update | ||
|
||
# Path of a KBMOD results file produced from a run on the resampled workunit | ||
res_path = "" # TODO Update | ||
|
||
# If the KBMOD results has a uuid column only, get uncertainties for these uuids. Otherwise, get_uncertainties for all provided results. | ||
# uuids = [] # Add if needed | ||
|
||
# The output directory to write the file with uncertainties to | ||
output_dir = "" # TODO Update |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add in check for velocity 0