diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..41d49b6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..6532412 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE/release.md b/.github/PULL_REQUEST_TEMPLATE/release.md new file mode 100644 index 0000000..ddab131 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/release.md @@ -0,0 +1,37 @@ +## Description of this release + + + + + +### Developer checklist + +- [ ] Assigned a reviewer + +- [ ] Indicated the level of changes to this package by affixing one of these labels: + * major -- Major changes to the API that may break current workflows + * minor -- Minor changes to the API that do not break current workflows + * patch -- Patches and bugfixes for the current version that do not break current workflows + * bumpless -- Changes to documentation, CI/CD pipelines, etc. that don't affect the software's version + +- [ ] (If applicable) Updated the dependencies and indicated any downstream changes that are required + +- [ ] Updated `CHANGELOG.md` +- [ ] Added/updated documentation for these changes +- [ ] Added/updated tests for these changes + +### Reviewer checklist + +- [ ] Have all dependencies been updated? +- [ ] Is the level of changes labeled appropriately? +- [ ] Are all the changes described appropriately in `CHANGELOG.md`? +- [ ] Has the documentation been adequately updated? +- [ ] Are the tests adequate? \ No newline at end of file diff --git a/.github/queries/associated-pr.query.yml b/.github/queries/associated-pr.query.yml new file mode 100644 index 0000000..e3b0adb --- /dev/null +++ b/.github/queries/associated-pr.query.yml @@ -0,0 +1,28 @@ +query: ' + query($owner:String!, $name:String!, $sha:String!) { + repository(owner:$owner, name:$name) { + commit: object(expression:$sha) { + ... on Commit { + associatedPullRequests(first:1, orderBy:{field: UPDATED_AT, direction: DESC}){ + edges{ + node{ + title + number + body + } + } + } + } + } + } + }' +variables: + owner: + type: arg + name: owner + name: + type: arg + name: name + sha: + type: arg + name: sha \ No newline at end of file diff --git a/.github/queries/pr-labels.query.yml b/.github/queries/pr-labels.query.yml new file mode 100644 index 0000000..a105712 --- /dev/null +++ b/.github/queries/pr-labels.query.yml @@ -0,0 +1,24 @@ +query: ' + query($owner:String!, $name:String!, $pr:Int!) { + repository(owner:$owner, name:$name) { + pullRequest(number:$pr) { + labels(first:100) { + nodes { + name + } + } + } + } + }' +variables: + owner: + type: arg + name: owner + name: + type: arg + name: name + pr: + type: jq + file: pr.json + query: '.data.repository.commit.associatedPullRequests.edges[0].node.number' + cast: Int \ No newline at end of file diff --git a/.trufflehog.txt b/.trufflehog.txt new file mode 100644 index 0000000..a91912f --- /dev/null +++ b/.trufflehog.txt @@ -0,0 +1 @@ +.*gitleaks.toml$ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100755 index 0000000..0fd0321 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/) +and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased](https://github.com/andrewplayer3/back_projection/compare/v0.0.0...develop) -- likely 0.0.1 + +### Added +-- Added validation for gpu existance (defaults to cpu if none exists) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100755 index 0000000..c71814b --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,130 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement by emailing the +ASF APD/Tools team at [UAF-asf-apd@alaska.edu](mailto:UAF-asf-apd@alaska.edu). +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. + diff --git a/Dockerfile b/Dockerfile new file mode 100755 index 0000000..4b25525 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,44 @@ +FROM ubuntu:latest + +# For opencontainers label definitions, see: +# https://github.com/opencontainers/image-spec/blob/master/annotations.md +LABEL org.opencontainers.image.title="Back_projection" +LABEL org.opencontainers.image.description="This is a process to process L0 Raw Products using a back projection algorithm" +LABEL org.opencontainers.image.vendor="Alaska Satellite Facility" +LABEL org.opencontainers.image.authors="ASF APD/Tools Team " +LABEL org.opencontainers.image.licenses="BSD-3-Clause" +LABEL org.opencontainers.image.url="https://github.com/ASFHyP3/hyp3-back-projection" +LABEL org.opencontainers.image.source="https://github.com/ASFHyP3/hyp3-back-projection" +# LABEL org.opencontainers.image.documentation="" + +# Dynamic lables to define at build time via `docker build --label` +# LABEL org.opencontainers.image.created="" +# LABEL org.opencontainers.image.version="" +# LABEL org.opencontainers.image.revision="" + +ENV TZ=America/Anchorage +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update && apt-get install -y --no-install-recommends build-essential wget gcc gfortran libgfortran-8-dev make unzip vim gdal-bin python3-pip libsqlite3-dev libfftw3-dev libfftw3-doc nvidia-cuda-toolkit && \ + apt-get clean && rm -rf /var/lib/apt/lists/* + +RUN useradd -ms /bin/bash user + +USER user +SHELL ["/bin/bash", "-l", "-c"] +ENV PYTHONDONTWRITEBYTECODE=true +WORKDIR /home/user + +COPY dist/* /home/user/ + +RUN python3 -m pip install /home/user/back_projection-0.0.0.tar.gz && \ + tar -xvf back_projection-0.0.0.tar.gz && \ + cd back_projection-0.0.0/back_projection/src && \ + source build_proc && \ + mkdir /home/user/back_projection-0.0.0/back_projection/src/output 2>/dev/null && \ + ls /home/user/back_projection-0.0.0/back_projection/src + +ENV PROC_HOME="/home/user/back_projection-0.0.0/back_projection/src" + +ENTRYPOINT ["python3", "/home/user/back_projection-0.0.0/back_projection/__main__.py"] +CMD ["-h"] diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 index bf1a8aa..c8c9868 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ BSD 3-Clause License -Copyright (c) 2021, HyP3 +Copyright (c) 0000, Alaska Satellite Facility All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100755 index 0000000..e1f9070 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include LICENSE +include README.md + +graft back_projection + +global-exclude *.py[cod] __pycache__ *.so diff --git a/README.md b/README.md new file mode 100755 index 0000000..81a017d --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Back_projection + +This is a process to process L0 Raw Products using a back projection algorithm diff --git a/back_projection/__init__.py b/back_projection/__init__.py new file mode 100755 index 0000000..76e1445 --- /dev/null +++ b/back_projection/__init__.py @@ -0,0 +1,19 @@ +"""Process L0 Raw Products using a back projection algorithm""" + +from importlib.metadata import PackageNotFoundError, version + +from back_projection.process import back_projection + +try: + __version__ = version(__name__) +except PackageNotFoundError: + print(f'{__name__} package is not installed!\n' + f'To install in editable/develop mode (from the repo\'s root):\n' + f' python -m pip install -e .[develop]\n' + f'Or, to just get the version number use:\n' + f' python setup.py --version') + +__all__ = [ + '__version__', + 'back_projection', +] diff --git a/back_projection/__main__.py b/back_projection/__main__.py new file mode 100755 index 0000000..0fbff8d --- /dev/null +++ b/back_projection/__main__.py @@ -0,0 +1,55 @@ +""" +projector processing for HyP3 +""" +import logging +import os +from argparse import ArgumentParser +from pathlib import Path + +import back_projection +from hyp3lib.aws import upload_file_to_s3 + +__version__ = 1.0 + + +def main(): + """ + HyP3 entrypoint for back_projection + """ + parser = ArgumentParser() + parser.add_argument("granule", metavar='granule', type=str, + help="name of granule to be processed.") + parser.add_argument('--bucket', + help='S3 bucket HyP3 for upload the final product(s)') + parser.add_argument('--bucket-prefix', default='', + help='Add a bucket prefix to product(s)') + parser.add_argument("--username", type=str, + help="hyp3 username") + parser.add_argument('--password', type=str, + help="hyp3 password") + parser.add_argument('--use_gpu', action='store_true', + help="use gpu rather than cpu for processing") + + args = parser.parse_args() + + logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', + datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) + + product_path_string = back_projection.back_projection( + granule=args.granule, + username=args.username, + password=args.password, + use_gpu=args.use_gpu + ) + + HOME = os.environ['PROC_HOME'] + print(os.listdir(HOME + "/output")) + + if args.bucket: + upload_file_to_s3(Path(product_path_string), + args.bucket, + args.bucket_prefix) + + +if __name__ == '__main__': + main() diff --git a/back_projection/process.py b/back_projection/process.py new file mode 100755 index 0000000..f0c6068 --- /dev/null +++ b/back_projection/process.py @@ -0,0 +1,126 @@ +""" +projector processing +""" +import argparse +import logging +import os +import subprocess +from pathlib import Path +from zipfile import ZipFile + +__version__ = 1.0 + +log = logging.getLogger(__name__) + + +def back_projection(granule: str, username: str, password: str, use_gpu: bool) -> Path: + """Create GSLCS and Convert them to tiffs for viewing + + Args: + granule: granule name to be processed. + username: hyp3 username + password: hyp3 password + """ + + HOME = os.environ['PROC_HOME'] + + # Make granules.list file to be read by sentinel_cpu.py + # to download necessary granules + file = open("granule.list", "w") + output_string = granule + ".zip\n" + file.write(output_string) + file.close() + + gpu_exists = False + if use_gpu: + # grab gpu number, -1 if there isn't one + proc = subprocess.Popen(HOME+"/sentinel/bestgpu.sh", stdout=subprocess.PIPE, shell=True) + (bestGPU, err) = proc.communicate() + bestGPU = str(int(bestGPU.strip())) + print("GPU: ", bestGPU) + if bestGPU != "-1": + gpu_exists = True + + # Run the back_projection through sentinel_cpu.py or sentinel_gpu.py VV + run_backprojection = "" + if use_gpu and gpu_exists: + print("RUNNING WITH GPU") + print("----------------") + run_backprojection = HOME + "/sentinel/sentinel_gpu.py" + else: + print("RUNNING WITH CPU") + print("----------------") + run_backprojection = HOME + "/sentinel/sentinel_cpu.py" + run_backprojection += " --username \"" + username + "\" --password \"" + password + "\"" + print("GRANULES TO DOWNLOAD: ", granule) + print("Command: ", run_backprojection) + ret = os.system(run_backprojection) + + # create a amplitude tiff + # band 1: amplitude + make_tiff = "python3 " + HOME + "/make_tiff.py " + granule + ".geo " + make_tiff += "elevation.dem.rsc " + granule + print(make_tiff + "_VV.tiff") + ret = os.system(make_tiff + "_VV.tiff") + + move_vv_file = "mv *.geo "+HOME+"/output/"+granule+"_VV.geo" + ret = os.system(move_vv_file) + + # Run the back_projection through sentinel_cpu.py VH + run_backprojection += " --polarization vh --use_existing_data True" + print("Command: ", run_backprojection) + ret = os.system(run_backprojection) + + # create amplitude tiff + # band 1: amplitude + print(make_tiff + "_VH.tiff") + ret = os.system(make_tiff + "_VH.tiff") + + move_vh_file = "mv *.geo "+HOME+"/output/"+granule+"_VH.geo" + ret = os.system(move_vh_file) + + # Remove all of the temporary files + remove_files = "rm *.list *.EOF *.dem *.orbtiming " + remove_files += "*.full latloncoords preciseorbitfiles " + remove_files += "precise_orbtiming params" + ret = os.system(remove_files) + remove_SAFE = "rm -rf *.SAFE" + ret = os.system(remove_SAFE) + move_rsc_files = "mv elevation.dem.rsc "+HOME+"/output/" + ret = os.system(move_rsc_files) + ret = os.system("rm *.rsc") + print(ret) + + with ZipFile(granule + ".zip", "w") as zipObj: + for folder_name, sub_folders, filenames in os.walk(HOME+"/output/"): + for filename in filenames: + file_path = os.path.join(folder_name, filename) + zipObj.write(file_path, os.path.basename(file_path)) + + return granule+".zip" + + +def main(): + """back_projection entrypoint""" + parser = argparse.ArgumentParser( + prog='back_projection', + description=__doc__, + ) + parser.add_argument("granule", type=str, + help="granule name to be processed") + parser.add_argument("--username", type=str, + help="hyp3 username") + parser.add_argument('--password', type=str, + help="hyp3 password") + parser.add_arguemnt('--use_gpu', action='store_true', + help="use gpu rather than cpu for processing") + parser.add_argument('--version', action='version', + version=f'%(prog)s {__version__}') + args = parser.parse_args() + + return back_projection(args.granule, args.username, args.password, args.use_gpu) + + +if __name__ == "__main__": + product = main() + print(product) diff --git a/pyproject.toml b/pyproject.toml new file mode 100755 index 0000000..51000e4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,2 @@ +[build-system] +requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4"] diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..039c98e --- /dev/null +++ b/setup.py @@ -0,0 +1,56 @@ +from pathlib import Path + +from setuptools import find_packages, setup + +readme = Path(__file__).parent / 'README.md' + +setup( + name='back_projection', + use_scm_version=False, + description='Process L0 Raw Products using a back projection algorithm', + long_description=readme.read_text(), + long_description_content_type='text/markdown', + + url='https://github.com/ASFHyP3/hyp3-back-projection', + + author='ASF APD/Tools Team', + author_email='uaf-asf-apd@alaska.edu', + + license='BSD', + include_package_data=True, + + classifiers=[ + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.8', + ], + + python_requires='~=3.8', + + install_requires=[ + 'hyp3lib', + ], + + extras_require={ + 'develop': [ + 'flake8', + 'flake8-import-order', + 'flake8-blind-except', + 'flake8-builtins', + 'pytest', + 'pytest-cov', + 'pytest-console-scripts', + ] + }, + + packages=find_packages(), + + entry_points={'console_scripts': [ + 'back_projection = back_projection.__main__:main', + ] + }, + + zip_safe=False, +) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100755 index 0000000..e69de29 diff --git a/tests/test_entrypoints.py b/tests/test_entrypoints.py new file mode 100755 index 0000000..7c980a9 --- /dev/null +++ b/tests/test_entrypoints.py @@ -0,0 +1,3 @@ +def test_back_projection(script_runner): + ret = script_runner.run('back_projection', '-h') + assert ret.success