diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..7da1f96 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 100 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..b21b4a5 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,64 @@ +name: Docs + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + build: + name: Docs + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9"] + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Autogenerate new documentation + continue-on-error: true + run: | + pip install -e . + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + pip install pyyaml + python automate_mkdocs.py + git add . + - name: Update and Build GH Pages + run: | + python -m pip install --upgrade pip + pip install mkdocs==1.2.3 + pip install mkgendocs==0.9.0 + pip install markupsafe==2.0.1 + pip install jinja2==2.11 + gendocs --config mkgendocs.yml + - name: deploy + run: | + mkdocs gh-deploy --force --clean --verbose + + - name: Commit any changes to docs + continue-on-error: true + run: | + git config --local user.name "github-actions[bot]" + git add ./docs + git commit -m "Auto-updating the docs" + + + - name: Push the changes to master + continue-on-error: true + uses: ad-m/github-push-action@master + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + branch: main + force: true + + + diff --git a/.github/workflows/lint_action.yml b/.github/workflows/lint_action.yml new file mode 100644 index 0000000..5169118 --- /dev/null +++ b/.github/workflows/lint_action.yml @@ -0,0 +1,37 @@ +name: Lint + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + run-linters: + name: Run linters + runs-on: ubuntu-latest + + steps: + - name: Check out Git repository + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: 3.9 + + - name: Install Python dependencies + run: pip install black flake8 + + - name: Run linters + uses: wearerequired/lint-action@v2 + with: + auto_fix: true + black: true + black_auto_fix: true + flake8: true + flake8_auto_fix: false diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml new file mode 100644 index 0000000..db8f299 --- /dev/null +++ b/.github/workflows/testing.yml @@ -0,0 +1,35 @@ +name: Tests + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + build: + name: Running Tests + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9"] + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pytest + pip install -e . + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Test with pytest + run: | + pytest + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 0933268..a15729d 100644 --- a/README.md +++ b/README.md @@ -42,3 +42,6 @@ Please look at all those materials before you start the exercise. 17. Check back in with Morgan or Florian if you have any questions (florian@allfed.info or morgan@allfed.info) If you get stuck at any point please reach out to one of the data scientists (either florian@allfed.info or morgan@allfed.info). + +# Documentation +Automated docs are available [here](https://mullach.github.io/Github-Training-Repository/) for the completed training. diff --git a/automate_mkdocs.py b/automate_mkdocs.py new file mode 100644 index 0000000..11e6bd9 --- /dev/null +++ b/automate_mkdocs.py @@ -0,0 +1,216 @@ +"""Automates Python scripts formatting, linting and Mkdocs documentation.""" + +import ast +import importlib +import json +import yaml +from collections import defaultdict +from pathlib import Path +from typing import Union + + +def add_val(indices, value, data): + if not len(indices): + return + element = data + for index in indices[:-1]: + element = element[index] + element[indices[-1]] = value + + +def automate_mkdocs_from_docstring( + mkdocs_dir: Union[str, Path], mkgendocs_f: str, repo_dir: Path, match_string: str +) -> dict: + """Automates the -pages for mkgendocs package by adding all Python functions in a + directory to the mkgendocs config. + Args: + mkdocs_dir (typing.Union[str, pathlib.Path]): textual directory for + the hierarchical directory & navigation in Mkdocs + mkgendocs_f (str): The configurations file for the mkgendocs package + repo_dir (pathlib.Path): textual directory to search for Python functions in + match_string (str): the text to be matches, after which the functions will be + added in mkgendocs format + Example: + >>> + >>> automate_mkdocs_from_docstring('scripts', repo_dir=Path.cwd(), match_string='pages:') + Returns: + list: list of created markdown files and their relative paths + + """ + p = repo_dir.glob("**/*.py") + scripts = [x for x in p if x.is_file()] + + if ( + Path.cwd() != repo_dir + ): # look for mkgendocs.yml in the parent file if a subdirectory is used + repo_dir = repo_dir.parent + + functions = defaultdict(dict) + structure = fix(defaultdict)() + full_repo_dir = str(repo_dir) + "/" + for script in scripts: + with open(script, "r") as source: + tree = ast.parse(source.read()) + funcs = {"classes": [], "functions": []} + for child in ast.iter_child_nodes(tree): + try: + if isinstance( + child, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef) + ): + if child.name not in ["main"]: + relative_path = ( + str(script) + .replace(full_repo_dir, "") + .replace("/", ".") + .replace(".py", "") + ) + module = importlib.import_module(relative_path) + f_ = getattr(module, child.name) + function = f_.__name__ + if isinstance(child, (ast.ClassDef)): + funcs["classes"].append(function) + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + funcs["functions"].append(function) + + except Exception as e: + print("trouble on importing " + script.stem) + print("did not document " + child.name) + print(str(e)) + if not funcs["classes"]: + funcs.pop("classes") + if not funcs["functions"]: + funcs.pop("functions") + if funcs: + functions[script] = funcs + with open(f"{repo_dir}/{mkgendocs_f}", "r+") as mkgen_config: + insert_string = "" + for path, function_names in functions.items(): + relative_path = str(path).replace(full_repo_dir, "").replace(".py", "") + insert_string += ( + f' - page: "{mkdocs_dir}/{relative_path}.md"\n ' + f'source: "{relative_path}.py"\n' # functions:\n' + ) + page = f"{mkdocs_dir}/{relative_path}" + split_page = page.split("/") + split_page = [" - " + s for s in split_page] + page += ".md" # removed f-string notation; possibly will result in future errors + + add_val(split_page, page, structure) + for class_name, class_list in function_names.items(): + insert_string += f" {class_name}:\n" + f_string = "" + for f in class_list: + insert_f_string = f" - {f}\n" + f_string += insert_f_string + + insert_string += f_string + insert_string += "\n" + + contents = mkgen_config.readlines() + if match_string in contents[-1]: + contents.append(insert_string) + else: + for index, line in enumerate(contents): + if match_string in line and insert_string not in contents[index + 1]: + contents = contents[: index + 1] + contents.append(insert_string) + break + + with open(f"{repo_dir}/{mkgendocs_f}", "w") as mkgen_config: + mkgen_config.writelines(contents) + + return structure + + +def automate_nav_structure( + mkdocs_dir: Union[str, Path], + mkdocs_f: str, + repo_dir: Path, + match_string: str, + structure: dict, +) -> str: + """Automates the -pages for mkgendocs package by adding all Python + functions in a directory to the mkgendocs config. + Args: + mkdocs_dir (typing.Union[str, pathlib.Path]): textual directory for + the hierarchical directory & navigation in Mkdocs + mkgendocs_f (str): The configurations file for the mkgendocs package + repo_dir (pathlib.Path): textual directory to search for Python functions in + match_string (str): the text to be matches, after which the functions + will be added in mkgendocs format + Example: + >>> + >>> automate_mkdocs_from_docstring('scripts', repo_dir=Path.cwd(), match_string='pages:') + Returns: + str: feedback message + + """ + insert_string = yaml.safe_dump(json.loads(json.dumps(structure, indent=4))).replace( + "'", "" + ) + # print(structure) + with open(f"{repo_dir}/{mkdocs_f}", "r+") as mkgen_config: + assert mkgen_config is not None + contents = mkgen_config.readlines() + if match_string in contents[-1]: + contents.append(insert_string) + else: + for index, line in enumerate(contents): + if match_string in line and insert_string not in contents[index + 1]: + contents = contents[: index + 1] + contents.append(insert_string) + break + + with open(f"{repo_dir}/{mkdocs_f}", "w") as mkgen_config: + mkgen_config.writelines(contents) + + +def fix(f): + """Allows creation of arbitrary length dict item + + Args: + f (type): Description of parameter `f`. + + Returns: + type: Description of returned object. + + """ + return lambda *args, **kwargs: f(fix(f), *args, **kwargs) + + +def indent(string: str) -> int: + """Count the indentation in whitespace characters. + Args: + string (str): text with indents + Returns: + int: Number of whitespace indentations + + """ + return sum(4 if char == "\t" else 1 for char in string[: -len(string.lstrip())]) + + +def main(): + """Execute when running this script.""" + # This is the path the script will look for code to document + python_tips_dir = Path.cwd().joinpath("src") + # This is the path the script will look for mkgendocs.yml + root_dir = Path.cwd() + + structure = automate_mkdocs_from_docstring( + mkdocs_dir="modules", + mkgendocs_f="mkgendocs.yml", + repo_dir=python_tips_dir, + match_string="pages:\n", + ) + + automate_nav_structure( + mkdocs_dir="modules", + mkdocs_f="mkdocs.yml", + repo_dir=root_dir, + match_string="- Home: index.md\n", + structure=structure, + ) + + +if __name__ == "__main__": + main() diff --git a/data/readme.txt b/data/readme.txt new file mode 100644 index 0000000..1b7b100 --- /dev/null +++ b/data/readme.txt @@ -0,0 +1 @@ +data: Where you put raw data for your project. You usually won’t sync this to source control, unless you use very small, text-based datasets (< 10 MBs). diff --git a/docs/readme.txt b/docs/readme.txt new file mode 100644 index 0000000..8128cbf --- /dev/null +++ b/docs/readme.txt @@ -0,0 +1 @@ +docs: Where you put documentation, including Markdown and reStructuredText (reST). Calling it docs makes it easy to publish documentation online through Github pages. diff --git a/docs/sources/index.md b/docs/sources/index.md new file mode 100644 index 0000000..a15729d --- /dev/null +++ b/docs/sources/index.md @@ -0,0 +1,47 @@ +# Github-Training-Repository +This repository is meant to be used to train new hires/volunteers on how to use Github. Reading the material and finishing the exercise should take around 6-8 hours. + +Before you get started, please check that your actual name is visible on your Github profile. This way we know which account belongs to whom and when we make repositories citable your real name will be used and not your nickname. + +Also, if you read this and you are not yet part of the ALLFED group on Github, please let Florian know your account name, so it can be added. + +# Preparation Material +Please look at all those materials before you start the exercise. + +* [Good enough practices in scientific computing](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1005510): This gives a good overview of why we need to adhere to good coding practices and what the general idea is +* [Good Research Code Handbook](https://goodresearch.dev/): Explanation of how to implement good coding practices in Python +* [Fundamentals of Git and Github](https://www.youtube.com/watch?v=8Dd7KRpKeaE) +* [How to use Github with Github Desktop](https://www.youtube.com/watch?v=8Dd7KRpKeaE) +* [Getting started with anaconda and conda](https://youtu.be/YJC6ldI3hWk) (if you feel like conda is too slow, check out [mamba](https://mamba.readthedocs.io/en/latest/) instead) +* [ALLFED Repository Template Readme](https://github.com/allfed/ALLFED-Repository-Template) +* [Overview of Python](https://www.youtube.com/watch?v=kqtD5dpn9C8) +* [Automated Testing](https://blog.deepjyoti30.dev/tests-github-python) +* [ChatGPT](https://chat.openai.com/chat) is pretty good at answering programming questions +* It is recommended to use [VS Code](https://www.youtube.com/watch?v=B-s71n0dHUk) as your code editor +* The [Seaweed Growth Model Repository](https://github.com/allfed/Seaweed-Growth-Model) can be seen as an example of how ALLFED repositories should look like. You can check how things are done there, if something here confuses you + +# Exercise +1. Fork this repository +2. Clone it to your local computer +3. Recreate the folder structure as described in the [ALLFED Guidelines](https://github.com/allfed/ALLFED-Repository-Template) +4. Create a local virtual environment for the repository + * When you try to install/change things make sure are [activating it first!](https://goodresearch.dev/setup.html?highlight=activate#conda). If something related to virtual environments isn't working, always make sure that it is really activated. +5. Create two files in the src folder: numerical.py and plotting.py +6. Write a function in numerical.py that takes at least one argument and returns a numerical value +7. Write a function in plotting.py that creates a scatter plot and uses the [ALLFED Style Sheet](https://github.com/allfed/ALLFED-matplotlib-style-sheet) +8. Make your repository an installable package as described in [Good Research Code Handbook](https://goodresearch.dev/setup.html) +9. Add a Jupyter Notebook in your scripts folder and import numerical.py and call it +11. Write two test for numerical.py +12. Make sure that the documenation of all code follows the [ALLFED Guidelines](https://github.com/allfed/ALLFED-Repository-Template#allfed-python-style-guide) + * If you set-up automated documentation, you can see the status in the [pages setting](https://github.com/allfed/Seaweed-Growth-Model/settings/pages) +14. Automate the tests, so they run on every commit (you can just copy the files needed for that from [the template](https://github.com/allfed/ALLFED-Repository-Template) + * The files used for testing in Github Actions are hidden files. You might need to change the settings of your operation system to show you the hidden files. + * you can play around with pytest in your terminal in VS Code +15. Create an environment.yml that specifies how your virtual environment can be recreated and save it in the repository +16. Send back a pull request, so we know you have finished this training +17. Check back in with Morgan or Florian if you have any questions (florian@allfed.info or morgan@allfed.info) + +If you get stuck at any point please reach out to one of the data scientists (either florian@allfed.info or morgan@allfed.info). + +# Documentation +Automated docs are available [here](https://mullach.github.io/Github-Training-Repository/) for the completed training. diff --git a/docs/sources/modules/src/numerical.md b/docs/sources/modules/src/numerical.md new file mode 100644 index 0000000..c695d1d --- /dev/null +++ b/docs/sources/modules/src/numerical.md @@ -0,0 +1,24 @@ +# + + +### multiply +[source](https://github.com/mullach/Github-Training-Repository/blob/master/src/numerical.py/#L6) +```python +.multiply( + x, y +) +``` + +--- +Calculates the product of x and y. + +**Arguments** + +* **x** (int or float) : first number to be multiplied +* **y** (int or float) : second number to be multiplied + + +**Returns** + +* **product** (int or float) : product of x and y + diff --git a/docs/sources/modules/src/plotting.md b/docs/sources/modules/src/plotting.md new file mode 100644 index 0000000..a44d5d4 --- /dev/null +++ b/docs/sources/modules/src/plotting.md @@ -0,0 +1,23 @@ +# + + +### scatterplot +[source](https://github.com/mullach/Github-Training-Repository/blob/master/src/plotting.py/#L13) +```python +.scatterplot( + N +) +``` + +--- +Plots a matplotlib scatterplot using random data. + + +**Arguments** + +* **N** (int) : number of random datapoints to plot + + +**Returns** + +None diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000..3e8973f --- /dev/null +++ b/environment.yml @@ -0,0 +1,7 @@ +name: slimenv +channels: + - defaults +dependencies: + - python=3.11 + - numpy + - matplotlib diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..4c2c914 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,28 @@ +site_name: Github Training Repository + + +# Repository +repo_name: Github Training Repository +repo_url: https://github.com/mullach/Github-Training-Repository +edit_uri: "" +# Copyright +copyright: ALLFED + +docs_dir: "docs/sources" + +plugins: + - search + +theme: + name: 'readthedocs' + custom_dir: 'docs' + palette: + primary: 'white' + logo: 'assets/images/logo_full.svg' + favicon: 'assets/images/favicon.svg' + features: + - navigation.tabs + - navigation.tabs.sticky + - instant +nav: + diff --git a/mkgendocs.yml b/mkgendocs.yml new file mode 100644 index 0000000..d0eabb5 --- /dev/null +++ b/mkgendocs.yml @@ -0,0 +1,21 @@ +site_name: Github-Training-Repository + + +# Repository +repo_name: Github-Training-Repository +repo: https://github.com/mullach/Github-Training-Repository +# Copyright +copyright: ALLFED + +#This specifies the autogeneration portion +pages: + - page: "modules/src/numerical.md" + source: "src/numerical.py" + functions: + - multiply + + - page: "modules/src/plotting.md" + source: "src/plotting.py" + functions: + - scatterplot + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4355f56 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +pandas>=1.4.3 +setuptools>=61.2.0 +pytest>=7.1.2 +numpy>=1.23.1 +matplotlib>=3.5.1 +mkdocs diff --git a/results/readme.txt b/results/readme.txt new file mode 100644 index 0000000..aede27e --- /dev/null +++ b/results/readme.txt @@ -0,0 +1 @@ +results: Where you put results, including checkpoints, hdf5 files, pickle files, as well as figures and tables. If these files are heavy, you won’t put these under source control. diff --git a/scripts/example_script.ipynb b/scripts/example_script.ipynb new file mode 100644 index 0000000..2440f59 --- /dev/null +++ b/scripts/example_script.ipynb @@ -0,0 +1,68 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example script which imports and calls numerical.py from src" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "from src.numerical import multiply" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Calling multiply(4,6) should return 4*6=24" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "24" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiply(4, 6)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "trainingenv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/scripts/readme.txt b/scripts/readme.txt new file mode 100644 index 0000000..e7c528c --- /dev/null +++ b/scripts/readme.txt @@ -0,0 +1 @@ +scripts: Where you put scripts - Python and bash alike - as well as .ipynb notebooks. diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..161f66e --- /dev/null +++ b/setup.py @@ -0,0 +1,6 @@ +from setuptools import find_packages, setup + +setup( + name="src", + packages=find_packages(), +) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/numerical.py b/src/numerical.py new file mode 100644 index 0000000..b2b9c06 --- /dev/null +++ b/src/numerical.py @@ -0,0 +1,16 @@ +""" +File contains a single function to return the product of two numbers. +""" + + +def multiply(x, y): + """ + Calculates the product of x and y. + Arguments: + x (int or float): first number to be multiplied + y (int or float): second number to be multiplied + Returns: + product (int or float): product of x and y + """ + product = x * y + return product diff --git a/src/plotting.py b/src/plotting.py new file mode 100644 index 0000000..bb71015 --- /dev/null +++ b/src/plotting.py @@ -0,0 +1,28 @@ +""" +File contains a single function to plot a scatter plot following ALLFED Guidelines. +""" +import matplotlib.pyplot as plt +import numpy as np + +# Set style +plt.style.use( + "https://raw.githubusercontent.com/allfed/ALLFED-matplotlib-style-sheet/main/ALLFED.mplstyle" +) + + +def scatterplot(N): + """ + Plots a matplotlib scatterplot using random data. + + Arguments: + N (int): number of random datapoints to plot + Returns: + None + """ + x = np.random.rand(N) + y = np.random.rand(N) + plt.scatter(x, y) + plt.ylabel("Y-Axis") + plt.xlabel("X-Axis") + plt.title("Example Data") + plt.show() diff --git a/src/readme.txt b/src/readme.txt new file mode 100644 index 0000000..503277b --- /dev/null +++ b/src/readme.txt @@ -0,0 +1 @@ +src: Where you put reusable Python modules for your project. This is the kind of python code that you import. diff --git a/tests/readme.txt b/tests/readme.txt new file mode 100644 index 0000000..2cbb868 --- /dev/null +++ b/tests/readme.txt @@ -0,0 +1 @@ +tests: Where you put tests for your code. diff --git a/tests/test_numerical.py b/tests/test_numerical.py new file mode 100644 index 0000000..52c189e --- /dev/null +++ b/tests/test_numerical.py @@ -0,0 +1,21 @@ +""" +Tests for src/numerical.py +""" + +from src.numerical import multiply + + +def test_multiply_int(): + """ + Tests multiply function using integer inputs. + """ + test_case = multiply(4, 6) + assert test_case == 24 + + +def test_multiply_float(): + """ + Tests multiply function using float inputs. + """ + test_case = multiply(2.5, 3.0) + assert test_case == 7.5