pax_global_header00006660000000000000000000000064145264250360014521gustar00rootroot0000000000000052 comment=eb4f37aa67033844db6b5b093301c2578334abb8 pyomop-4.2.0/000077500000000000000000000000001452642503600130475ustar00rootroot00000000000000pyomop-4.2.0/.coveragerc000066400000000000000000000011151452642503600151660ustar00rootroot00000000000000# .coveragerc to control coverage.py [run] branch = True source = pyomop # omit = bad_file.py [paths] source = src/ */site-packages/ [report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about missing debug-only code: def __repr__ if self\.debug # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: pyomop-4.2.0/.devcontainer/000077500000000000000000000000001452642503600156065ustar00rootroot00000000000000pyomop-4.2.0/.devcontainer/Dockerfile000066400000000000000000000017401452642503600176020ustar00rootroot00000000000000# [Choice] Python version: 3, 3.9, 3.8, 3.7, 3.6 ARG VARIANT=3.10 FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT} # [Option] Install Node.js ARG INSTALL_NODE="true" ARG NODE_VERSION="lts/*" RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. # COPY requirements.txt /tmp/pip-tmp/ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ # && rm -rf /tmp/pip-tmp # [Optional] Uncomment this section to install additional OS packages. # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ # && apt-get -y install --no-install-recommends # [Optional] Uncomment this line to install global node packages. # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1pyomop-4.2.0/.devcontainer/devcontainer.json000066400000000000000000000041431452642503600211640ustar00rootroot00000000000000{ "name": "Python 3", "build": { "dockerfile": "Dockerfile", "context": "..", "args": { // Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8, 3.9 "VARIANT": "3.10", // Options "INSTALL_NODE": "false", "NODE_VERSION": "lts/*" } }, "containerEnv": { "GITHUB_TOKEN": "${localEnv:GITHUB_TOKEN}", "GITHUB_USER": "${localEnv:GITHUB_USER}" }, "workspaceFolder": "/nlp-qrmine", "workspaceMount": "src=nlp-qrmine,dst=/nlp-qrmine,type=volume,volume-driver=local", // Set *default* container specific settings.json values on container create. "settings": { "python.pythonPath": "/usr/local/bin/python", "python.languageServer": "Pylance", "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", "python.formatting.blackPath": "/usr/local/py-utils/bin/black", "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint" }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ], // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip3 install --user -r requirements.txt -r dev-requirements.txt", // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. // "remoteUser": "vscode" }pyomop-4.2.0/.github/000077500000000000000000000000001452642503600144075ustar00rootroot00000000000000pyomop-4.2.0/.github/config.yml000066400000000000000000000014171452642503600164020ustar00rootroot00000000000000# Configurations for todo: https://probot.github.io/apps/todo/ # Automatically add issues from @todo with @body # /** # * @todo What needs to be done # * @body How to do it. # */ # https://github.com/behaviorbot/welcome newIssueWelcomeComment: > Thank you for raising this issue. We will try and get back to you as soon as possible. Be sure to star ✨ the repository for a priority response! Please make sure you have given us as much context as possible. newPRWelcomeComment: > Thank you for submitting a pull request. Please make sure you have followed our contributing guidelines in CONTRIBUTING.md. We will review it as soon as possible. Be sure to star ✨ the repository. firstPRMergeComment: > Congrats on merging your first pull request! 🎉🎉🎉pyomop-4.2.0/.github/dependabot.yml000066400000000000000000000003571452642503600172440ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: "weekly" # open-pull-requests-limit: 10 - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" pyomop-4.2.0/.github/workflows/000077500000000000000000000000001452642503600164445ustar00rootroot00000000000000pyomop-4.2.0/.github/workflows/bump.yml000066400000000000000000000007501452642503600201340ustar00rootroot00000000000000name: Generate changelog on: push: branches: - "release/**" jobs: build: runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Checkout Latest Commit uses: actions/checkout@v3 - name: Generate changelog uses: charmixer/auto-changelog-action@v1 with: token: ${{ secrets.github_token }} - name: Commit changes uses: EndBug/add-and-commit@v7 with: default_author: github_actions add: '*.md'pyomop-4.2.0/.github/workflows/docs.yml000066400000000000000000000017401452642503600201210ustar00rootroot00000000000000name: Generate and publish gh-pages # https://docs.github.com/en/actions/guides/building-and-testing-python # https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/ on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest timeout-minutes: 15 steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v2.3.1 with: python-version: '3.10.13' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt -r dev-requirements.txt - name: Create docs run: | make -C docs/ html cp docs/_config.yml docs/_build/html/_config.yml - name: Deploy Docs 🚀 uses: JamesIves/github-pages-deploy-action@v4 with: branch: gh-pages # The branch the action should deploy to. folder: docs/_build/html # The folder the action should deploy.pyomop-4.2.0/.github/workflows/publish.yml000066400000000000000000000016311452642503600206360ustar00rootroot00000000000000name: Upload Python Package to PyPi # https://docs.github.com/en/actions/guides/building-and-testing-python # https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/ on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest timeout-minutes: 20 steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v2.3.1 with: python-version: '3.10.13' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r dev-requirements.txt - name: Build and publish run: | python setup.py bdist_wheel - name: Publish distribution 📦 to PyPI if: startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@master with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }}pyomop-4.2.0/.github/workflows/pytest.yml000066400000000000000000000012601452642503600205160ustar00rootroot00000000000000name: Python Test on: push: branches: - develop pull_request: branches: - master - develop jobs: build: runs-on: ubuntu-latest timeout-minutes: 15 strategy: max-parallel: 4 matrix: python-version: [3.10.13] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2.3.1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r dev-requirements.txt -r requirements.txt - name: Test with pytest run: | pytestpyomop-4.2.0/.github/workflows/tox.yml000066400000000000000000000011541452642503600200020ustar00rootroot00000000000000name: Python Test on: push: branches: - master jobs: build: runs-on: ubuntu-latest timeout-minutes: 15 strategy: max-parallel: 4 matrix: python-version: [3.10.13] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2.3.1 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r dev-requirements.txt -r requirements.txt - name: Test with tox run: | toxpyomop-4.2.0/.gitignore000066400000000000000000000010241452642503600150340ustar00rootroot00000000000000# Temporary and binary files *~ *.py[cod] *.so *.cfg !.isort.cfg !setup.cfg *.orig *.log *.pot __pycache__/* .cache/* .*.swp */.ipynb_checkpoints/* .DS_Store # Project files .ropeproject .project .pydevproject .settings .idea tags # Package files *.egg *.eggs/ .installed.cfg *.egg-info # Unittest and coverage htmlcov/* .coverage .tox junit.xml coverage.xml .pytest_cache/ # Build and docs folder/files build/* dist/* sdist/* docs/api/* docs/_rst/* docs/_build/* cover/* MANIFEST # Per-project virtualenvs .venv*/ cdm6.sqlite pyomop-4.2.0/.readthedocs.yml000066400000000000000000000007161452642503600161410ustar00rootroot00000000000000# Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Build documentation in the docs/ directory with Sphinx sphinx: configuration: docs/conf.py # Build documentation with MkDocs #mkdocs: # configuration: mkdocs.yml # Optionally build your docs in additional formats such as PDF formats: - pdf python: version: 3.10 install: - requirements: docs/requirements.txt pyomop-4.2.0/.travis.yml000066400000000000000000000022101452642503600151530ustar00rootroot00000000000000# Travis configuration file using the build matrix feature # Read more under http://docs.travis-ci.com/user/build-configuration/ # THIS SCRIPT IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! sudo: false language: python virtualenv: system_site_packages: false matrix: fast_finish: true include: - python: 3.6 env: DISTRIB="ubuntu" TOX_PYTHON_VERSION="py36" COVERAGE="true" - env: DISTRIB="conda" PYTHON_VERSION="3.6" COVERAGE="false" install: - source tests/travis_install.sh - pip install -r requirements.txt # ^ DEPRECATION WARNING: # The automatic creation of a `requirements.txt` file is deprecated. # See `Dependency Management` in the docs for other options. before_script: - git config --global user.email "you@example.com" - git config --global user.name "Your Name" script: - python setup.py develop - tox - | if [[ "$COVERAGE" == "true" ]]; then pre-commit install pre-commit run --all-files fi after_success: - if [[ "$COVERAGE" == "true" ]]; then coveralls || echo "failed"; fi after_script: - travis-cleanup cache: pip: true directories: - $HOME/miniconda pyomop-4.2.0/.vscode/000077500000000000000000000000001452642503600144105ustar00rootroot00000000000000pyomop-4.2.0/.vscode/launch.json000066400000000000000000000003211452642503600165510ustar00rootroot00000000000000{ "version": "0.2.0", "configurations": [ { "name": "Python: Pytest", "type": "python", "request": "launch", "module": "pytest" } ] }pyomop-4.2.0/.vscode/settings.json000066400000000000000000000003261452642503600171440ustar00rootroot00000000000000{ "licenser.author": "Bell Eapen", "licenser.projectName": "PyOMOP", "licenser.license": "GPLv3", "licenser.useSingleLineStyle": false, "cSpell.words": [ "OMOP", "pyomop" ] }pyomop-4.2.0/AUTHORS.md000066400000000000000000000000651452642503600145170ustar00rootroot00000000000000# Contributors * Bell Eapen pyomop-4.2.0/CHANGELOG.md000066400000000000000000000043351452642503600146650ustar00rootroot00000000000000# Changelog ## [4.1.0](https://github.com/dermatologist/pyomop/tree/4.1.0) (2023-11-19) [Full Changelog](https://github.com/dermatologist/pyomop/compare/4.0.0...4.1.0) ## [4.0.0](https://github.com/dermatologist/pyomop/tree/4.0.0) (2023-11-19) [Full Changelog](https://github.com/dermatologist/pyomop/compare/3.2.0...4.0.0) **Closed issues:** - SQLAlchemy 1.4 raises error [\#6](https://github.com/dermatologist/pyomop/issues/6) ## [3.2.0](https://github.com/dermatologist/pyomop/tree/3.2.0) (2023-01-20) [Full Changelog](https://github.com/dermatologist/pyomop/compare/3.1.0...3.2.0) ## [3.1.0](https://github.com/dermatologist/pyomop/tree/3.1.0) (2021-09-17) [Full Changelog](https://github.com/dermatologist/pyomop/compare/3.0.0...3.1.0) **Closed issues:** - Import directly \(no need for conditional\) when `python_requires = >= 3.8` [\#12](https://github.com/dermatologist/pyomop/issues/12) - ", [\#11](https://github.com/dermatologist/pyomop/issues/11) ## [3.0.0](https://github.com/dermatologist/pyomop/tree/3.0.0) (2020-10-23) [Full Changelog](https://github.com/dermatologist/pyomop/compare/2.0.0...3.0.0) ## [2.0.0](https://github.com/dermatologist/pyomop/tree/2.0.0) (2020-06-27) [Full Changelog](https://github.com/dermatologist/pyomop/compare/1.2.0...2.0.0) ## [1.2.0](https://github.com/dermatologist/pyomop/tree/1.2.0) (2020-05-23) [Full Changelog](https://github.com/dermatologist/pyomop/compare/1.1.1...1.2.0) ## [1.1.1](https://github.com/dermatologist/pyomop/tree/1.1.1) (2020-05-03) [Full Changelog](https://github.com/dermatologist/pyomop/compare/1.1.0...1.1.1) ## [1.1.0](https://github.com/dermatologist/pyomop/tree/1.1.0) (2020-05-03) [Full Changelog](https://github.com/dermatologist/pyomop/compare/1.0.0...1.1.0) ## [1.0.0](https://github.com/dermatologist/pyomop/tree/1.0.0) (2020-05-03) [Full Changelog](https://github.com/dermatologist/pyomop/compare/0.1.0...1.0.0) ## [0.1.0](https://github.com/dermatologist/pyomop/tree/0.1.0) (2020-05-03) [Full Changelog](https://github.com/dermatologist/pyomop/compare/c647331d8bcb13f0353f85a49ed552294631fee3...0.1.0) \* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* pyomop-4.2.0/CONTRIBUTING.md000066400000000000000000000050661452642503600153070ustar00rootroot00000000000000# How to contribute ## Please note: * (Optional) We adopt [Git Flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow). Most feature branches are pushed to the repository and deleted when merged to *develop* branch. * (**Important**): Submit pull requests to the *develop* branch or *feature/* branches * Use *GitHub Issues* for feature requests and bug reports. Include as much information as possible while reporting bugs. ## Contributing (Step-by-step) 1. [Fork the repo](http://help.github.com/fork-a-repo) and clone it to your local computer, and set up the upstream remote: git clone https://github.com/YourGithubUsername/pyomop.git cd pyomop git remote add upstream https://github.com/dermatologist/pyomop.git 2. Checkout out a new local branch based on your master and update it to the latest (TRUNK-123 is the branch name, You can name it whatever you want. Try to give it a meaningful name. If you are fixing an issue, please include the issue #). git checkout -b BRANCH-123 develop git clean -df git pull --rebase upstream develop > Please keep your code clean. If you find another bug, you want to fix while being in a new branch, please fix it in a separated branch instead. 3. Push the branch to your fork. Treat it as a backup. git push origin BRANCH-123 4. Code * Adhere to common conventions you see in the existing code. * Include tests as much as possible, and ensure they pass. 5. Commit to your branch git commit -m "BRANCH-123: Put change summary here (can be a ticket title)" **NEVER leave the commit message blank!** Provide a detailed, clear, and complete description of your commit! 6. Update your branch to the latest code. git pull --rebase upstream develop 7. **Important** If you have made many commits, please squash them into atomic units of work. (Most Git GUIs such as sourcetree and smartgit offer a squash option) git checkout develop git pull --rebase upstream develop git merge --squash BRANCH-123 git commit -m "fix: 123" Push changes to your fork: git push 8. Issue a Pull Request In order to make a pull request: * Click "Pull Request". * Choose the develop branch * Click 'Create pull request' * Fill in some details about your potential patch including a meaningful title. * Click "Create pull request". Thanks for that -- we'll get to your pull request ASAP. We love pull requests! ## Feedback If you need to contact me, see my contact details on my profile page. pyomop-4.2.0/LICENSE.txt000066400000000000000000001045001452642503600146720ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 2020 Bell Eapen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) 2020 Bell Eapen This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . pyomop-4.2.0/README.md000066400000000000000000000116661452642503600143400ustar00rootroot00000000000000# pyomop ![Libraries.io SourceRank](https://img.shields.io/librariesio/sourcerank/pypi/pyomop) [![forthebadge made-with-python](http://ForTheBadge.com/images/badges/made-with-python.svg)](https://www.python.org/) [![PyPI download total](https://img.shields.io/pypi/dm/pyomop.svg)](https://pypi.python.org/pypi/pyomop/) [![Build](https://github.com/dermatologist/pyomop/workflows/Python%20Test/badge.svg)](https://nuchange.ca) * *Inspired by [@jbadger3's](https://github.com/jbadger3) [inspectomop](https://github.com/jbadger3/inspectomop)* ### [Documentation](https://dermatologist.github.io/pyomop/) ## Description The [OHSDI](https://www.ohdsi.org/) OMOP Common Data Model allows for the systematic analysis of healthcare observational databases. This is a python library to use the CDM v6 compliant databases using SQLAlchemy as the ORM. **pyomop** also supports converting query results to a pandas dataframe (see below) for use in machine learning pipelines. See some useful [SQL Queries here.](https://github.com/OHDSI/QueryLibrary) ## Installation (stable) ``` pip install pyomop ``` ## Installation (current) * git clone this repository and: ``` pip install -e . ``` ## Usage >= 4.0.0 (Async) Example ``` from pyomop import CdmEngineFactory, CdmVocabulary, CdmVector, Cohort, Vocabulary, metadata from sqlalchemy.future import select import datetime import asyncio async def main(): cdm = CdmEngineFactory() # Creates SQLite database by default # Postgres example (db='mysql' also supported) # cdm = CdmEngineFactory(db='pgsql', host='', port=5432, # user='', pw='', # name='', schema='cdm6') engine = cdm.engine # Create Tables if required await cdm.init_models(metadata) # Create vocabulary if required vocab = CdmVocabulary(cdm) # vocab.create_vocab('/path/to/csv/files') # Uncomment to load vocabulary csv files # Add a cohort async with cdm.session() as session: async with session.begin(): session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) await session.commit() # Query the cohort stmt = select(Cohort).where(Cohort.subject_id == 100) result = await session.execute(stmt) for row in result.scalars(): print(row) assert row.subject_id == 100 # Query the cohort pattern 2 cohort = await session.get(Cohort, 1) print(cohort) assert cohort.subject_id == 100 # Convert result to a pandas dataframe vec = CdmVector() vec.result = result print(vec.df.dtypes) result = await vec.sql_df(cdm, 'TEST') # TEST is defined in sqldict.py for row in result: print(row) result = await vec.sql_df(cdm, query='SELECT * from cohort') for row in result: print(row) # Close session await session.close() await engine.dispose() # Run the main function asyncio.run(main()) ``` ## Usage <=3.2.0 ``` from pyomop import CdmEngineFactory, CdmVocabulary, CdmVector, Cohort, Vocabulary, metadata from sqlalchemy.sql import select import datetime cdm = CdmEngineFactory() # Creates SQLite database by default # Postgres example (db='mysql' also supported) # cdm = CdmEngineFactory(db='pgsql', host='', port=5432, # user='', pw='', # name='', schema='cdm6') engine = cdm.engine # Create Tables if required metadata.create_all(engine) # Create vocabulary if required vocab = CdmVocabulary(cdm) # vocab.create_vocab('/path/to/csv/files') # Uncomment to load vocabulary csv files # Create a Cohort (SQLAlchemy as ORM) session = cdm.session session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) session.commit() result = session.query(Cohort).all() for row in result: print(row) # Convert result to a pandas dataframe vec = CdmVector() vec.result = result print(vec.df.dtypes) # Execute a query and convert it to dataframe vec.sql_df(cdm, 'TEST') # TEST is defined in sqldict.py print(vec.df.dtypes) # vec.df is a pandas dataframe # OR vec.sql_df(cdm, query='SELECT * from cohort') print(vec.df.dtypes) # vec.df is a pandas dataframe ``` ## command-line usage ``` pyomop -help ``` ## Other utils **Want to convert FHIR to pandas data frame? Try [fhiry](https://github.com/dermatologist/fhiry)** **Use the same functions in [.NET](https://github.com/dermatologist/omopcdm-dot-net) and [Golang](https://github.com/E-Health/gocdm)!** ### Support * Postgres * MySQL * SqLite * More to follow.. ## Give us a star ⭐️ If you find this project useful, give us a star. It helps others discover the project. ## Contributors * [Bell Eapen](https://nuchange.ca) | [![Twitter Follow](https://img.shields.io/twitter/follow/beapen?style=social)](https://twitter.com/beapen) * PRs welcome. See CONTRIBUTING.md pyomop-4.2.0/dev-requirements.in000066400000000000000000000001721452642503600166760ustar00rootroot00000000000000# dev-requirements.in -c requirements.txt pytest-cov pytest recommonmark sphinx>=3.2.1 setuptools setuptools_scm wheel toxpyomop-4.2.0/dev-requirements.txt000066400000000000000000000043461452642503600171160ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile dev-requirements.in # alabaster==0.7.12 # via sphinx attrs==21.2.0 # via pytest babel==2.9.1 # via sphinx backports-entry-points-selectable==1.1.0 # via virtualenv certifi==2022.12.7 # via requests charset-normalizer==2.0.6 # via requests commonmark==0.9.1 # via recommonmark coverage[toml]==5.5 # via # coverage # pytest-cov distlib==0.3.2 # via virtualenv docutils==0.17.1 # via # recommonmark # sphinx filelock==3.0.12 # via # tox # virtualenv idna==3.2 # via requests imagesize==1.2.0 # via sphinx iniconfig==1.1.1 # via pytest jinja2==3.0.1 # via sphinx markupsafe==2.0.1 # via jinja2 packaging==21.0 # via # pytest # setuptools-scm # sphinx # tox platformdirs==2.3.0 # via virtualenv pluggy==1.0.0 # via # pytest # tox py==1.10.0 # via # pytest # tox pygments==2.10.0 # via sphinx pyparsing==2.4.7 # via packaging pytest==6.2.5 # via # -r dev-requirements.in # pytest-cov pytest-cov==3.0.0 # via -r dev-requirements.in pytz==2023.3.post1 # via # -c requirements.txt # babel recommonmark==0.7.1 # via -r dev-requirements.in requests==2.26.0 # via sphinx setuptools-scm==6.3.2 # via -r dev-requirements.in six==1.16.0 # via # -c requirements.txt # tox # virtualenv snowballstemmer==2.1.0 # via sphinx sphinx==4.2.0 # via # -r dev-requirements.in # recommonmark sphinxcontrib-applehelp==1.0.2 # via sphinx sphinxcontrib-devhelp==1.0.2 # via sphinx sphinxcontrib-htmlhelp==2.0.0 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-qthelp==1.0.3 # via sphinx sphinxcontrib-serializinghtml==1.1.5 # via sphinx toml==0.10.2 # via # coverage # pytest # tox tomli==1.2.1 # via setuptools-scm tox==3.24.5 # via -r dev-requirements.in urllib3==1.26.6 # via requests virtualenv==20.8.0 # via tox wheel==0.37.1 # via -r dev-requirements.in # The following packages are considered to be unsafe in a requirements file: # setuptools pyomop-4.2.0/docs/000077500000000000000000000000001452642503600137775ustar00rootroot00000000000000pyomop-4.2.0/docs/Makefile000066400000000000000000000022011452642503600154320ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build AUTODOCDIR = api # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $?), 1) $(error "The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/") endif .PHONY: help clean Makefile # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) clean: rm -rf $(BUILDDIR)/* $(AUTODOCDIR) # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) pyomop-4.2.0/docs/_config.yml000066400000000000000000000001031452642503600161200ustar00rootroot00000000000000theme: jekyll-theme-leap-day include: [_sources, _modules, _static]pyomop-4.2.0/docs/_static/000077500000000000000000000000001452642503600154255ustar00rootroot00000000000000pyomop-4.2.0/docs/_static/.gitignore000066400000000000000000000000221452642503600174070ustar00rootroot00000000000000# Empty directory pyomop-4.2.0/docs/authors.md000077700000000000000000000000001452642503600176632../AUTHORS.mdustar00rootroot00000000000000pyomop-4.2.0/docs/changelog.md000077700000000000000000000000001452642503600202672../CHANGELOG.mdustar00rootroot00000000000000pyomop-4.2.0/docs/conf.py000066400000000000000000000234461452642503600153070ustar00rootroot00000000000000# This file is execfile()d with the current directory set to its containing dir. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import inspect import shutil # -- Path setup -------------------------------------------------------------- __location__ = os.path.join( os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())) ) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.join(__location__, "../src")) # -- Run sphinx-apidoc ------------------------------------------------------- # This hack is necessary since RTD does not issue `sphinx-apidoc` before running # `sphinx-build -b html . _build/html`. See Issue: # https://github.com/rtfd/readthedocs.org/issues/1139 # DON'T FORGET: Check the box "Install your project inside a virtualenv using # setup.py install" in the RTD Advanced Settings. # Additionally it helps us to avoid running apidoc manually try: # for Sphinx >= 1.7 from sphinx.ext import apidoc except ImportError: from sphinx import apidoc output_dir = os.path.join(__location__, "api") module_dir = os.path.join(__location__, "../src/pyomop") try: shutil.rmtree(output_dir) except FileNotFoundError: pass try: import sphinx cmd_line_template = ( "sphinx-apidoc --implicit-namespaces -f -o {outputdir} {moduledir}" ) cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir) args = cmd_line.split(" ") if tuple(sphinx.__version__.split(".")) >= ("1", "7"): # This is a rudimentary parse_version to avoid external dependencies args = args[1:] apidoc.main(args) except Exception as e: print("Running `sphinx-apidoc` failed!\n{}".format(e)) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.autosummary", "sphinx.ext.viewcode", "sphinx.ext.coverage", "sphinx.ext.doctest", "sphinx.ext.ifconfig", "sphinx.ext.mathjax", "sphinx.ext.napoleon", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # Configure AutoStructify # https://recommonmark.readthedocs.io/en/latest/auto_structify.html def setup(app): from recommonmark.transform import AutoStructify params = { "enable_auto_toc_tree": True, "auto_toc_tree_section": "Contents", "auto_toc_maxdepth": 2, "enable_eval_rst": True, "enable_math": True, "enable_inline_math": True, } app.add_config_value("recommonmark_config", params, True) app.add_transform(AutoStructify) # Enable markdown extensions.append("recommonmark") # The suffix of source filenames. source_suffix = [".rst", ".md"] # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "pyomop" copyright = "2021, Bell Eapen" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "" # Is set by calling `setup.py docs` # The full version, including alpha/beta/rc tags. release = "" # Is set by calling `setup.py docs` # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".venv"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { "sidebar_width": "300px", "page_width": "1200px" } # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". try: from pyomop import __version__ as version except ImportError: pass else: release = version # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = "" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "pyomop-doc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ("letterpaper" or "a4paper"). # "papersize": "letterpaper", # The font size ("10pt", "11pt" or "12pt"). # "pointsize": "10pt", # Additional stuff for the LaTeX preamble. # "preamble": "", } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "user_guide.tex", "pyomop Documentation", "Bell Eapen", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = "" # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- External mapping -------------------------------------------------------- python_version = ".".join(map(str, sys.version_info[0:2])) intersphinx_mapping = { "sphinx": ("http://www.sphinx-doc.org/en/stable", None), "python": ("https://docs.python.org/" + python_version, None), "matplotlib": ("https://matplotlib.org", None), "numpy": ("https://docs.scipy.org/doc/numpy", None), "sklearn": ("https://scikit-learn.org/stable", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), "pyscaffold": ("https://pyscaffold.org/en/stable", None), }pyomop-4.2.0/docs/index.md000066400000000000000000000011731452642503600154320ustar00rootroot00000000000000# pyomop OMOP CDM utils in Python *[by Bell Eapen](https://nuchange.ca)* ## Contents * [Overview](readme) * [License](license) * [Authors](authors) * [Changelog](changelog) * [Module Reference](api/modules) ## Indices and tables ```eval_rst * :ref:`genindex` * :ref:`modindex` * :ref:`search` ``` [Sphinx]: http://www.sphinx-doc.org/ [Markdown]: https://daringfireball.net/projects/markdown/ [reStructuredText]: http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html [recommonmark]: https://recommonmark.readthedocs.io/en/latest [autostructify]: https://recommonmark.readthedocs.io/en/latest/auto_structify.html pyomop-4.2.0/docs/license.rst000066400000000000000000000001031452642503600161450ustar00rootroot00000000000000.. _license: ======= License ======= .. include:: ../LICENSE.txt pyomop-4.2.0/docs/readme.md000077700000000000000000000000001452642503600172432../README.mdustar00rootroot00000000000000pyomop-4.2.0/docs/requirements.txt000066400000000000000000000003661452642503600172700ustar00rootroot00000000000000# Requirements file for ReadTheDocs, check .readthedocs.yml. # To build the module reference correctly, make sure every external package # under `install_requires` in `setup.cfg` is also listed here! # sphinx_rtd_theme recommonmark sphinx>=3.2.1 pyomop-4.2.0/main.py000066400000000000000000000002001452642503600143350ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from src.pyomop import main if __name__ == '__main__': main.main_routine()pyomop-4.2.0/notes/000077500000000000000000000000001452642503600141775ustar00rootroot00000000000000pyomop-4.2.0/notes/create_table.py000066400000000000000000000011511452642503600171610ustar00rootroot00000000000000from engine_factory import CdmEngineFactory from cdm6_tables import metadata from sqlalchemy.sql import select import datetime cdm = CdmEngineFactory() engine = cdm.engine metadata.create_all(engine) metadata.reflect(bind=engine) for table in reversed(metadata.sorted_tables): print(table) Cohort = cdm.base.cohort session = cdm.session session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) session.commit() s = select([Cohort]) result = session.execute(s) for row in result: print(row)pyomop-4.2.0/notes/libraries.md000066400000000000000000000004301452642503600164720ustar00rootroot00000000000000## Other useful libraries * [cui-cdm](https://github.com/E-Health/cui-cdm) - CUI to Concept mapping * [cui-embed](https://github.com/dermatologist/cui-embed) - CUI embeddings (Word2Vec) for similarity search. * [Hephaestus](https://github.com/dermatologist/hephaestus) - For ETL pyomop-4.2.0/notes/notes.md000066400000000000000000000003641452642503600156540ustar00rootroot00000000000000## Use sqlacodegen pip install sqlacodegen sqlacodegen sqlite:///database.db ## Create an _id primary key field in the autogenerated script Replace metadata, with ``` metadata, Column('_id', Integer, nullable=False, primary_key=True), ```pyomop-4.2.0/notes/pip-tools.md000066400000000000000000000003241452642503600164460ustar00rootroot00000000000000* pip install pip-tools * pip-compile --upgrade * pip-compile dev-requirements.in * pip-sync OR * pip-sync requirements.txt dev-requirements.txt ## pre-commit * pip install pre-commit * pre-commit installpyomop-4.2.0/pyproject.toml000066400000000000000000000004671452642503600157720ustar00rootroot00000000000000[build-system] # AVOID CHANGING REQUIRES: IT WILL BE UPDATED BY PYSCAFFOLD! requires = ["setuptools>=46.1.0", "setuptools_scm[toml]>=5", "wheel"] build-backend = "setuptools.build_meta" [tool.setuptools_scm] # See configuration details in https://github.com/pypa/setuptools_scm version_scheme = "no-guess-dev" pyomop-4.2.0/requirements.txt000066400000000000000000000010441452642503600163320ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile # aiosqlite==0.19.0 # via pyomop (setup.py) click==8.1.7 # via pyomop (setup.py) greenlet==3.0.1 # via sqlalchemy numpy==1.26.2 # via pandas pandas==2.1.3 # via pyomop (setup.py) python-dateutil==2.8.2 # via pandas pytz==2023.3.post1 # via pandas six==1.16.0 # via python-dateutil sqlalchemy==2.0.23 # via pyomop (setup.py) typing-extensions==4.8.0 # via sqlalchemy tzdata==2023.3 # via pandas pyomop-4.2.0/setup.cfg000066400000000000000000000066041452642503600146760ustar00rootroot00000000000000# This file is used to configure your project. # Read more about the various options under: # http://setuptools.readthedocs.io/en/latest/setuptools.html#configuring-setup-using-setup-cfg-files [metadata] name = pyomop description = OMOP CDM utils in Python author = Bell Eapen author-email = github@gulfdoctor.net license = gpl3 url = https://github.com/dermatologist/pyomop long-description = file: README.md long-description-content-type = text/markdown; charset=UTF-8 project-urls = Documentation = https://dermatologist.github.io/pyomop/ # Change if running only on Windows, Mac or Linux (comma-separated) platforms = any # Add here all kinds of additional classifiers as defined under # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers = Intended Audience :: Science/Research Development Status :: 4 - Beta Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 3.10 Topic :: Scientific/Engineering :: Information Analysis [options] zip_safe = False packages = find_namespace: include_package_data = True package_dir = =src # DON'T CHANGE THE FOLLOWING LINE! IT WILL BE UPDATED BY PYSCAFFOLD! # Add here dependencies of your project (semicolon/line-separated), e.g. install_requires = importlib-metadata; python_version<"3.8" sqlalchemy>=1.4 click pandas aiosqlite # The usage of test_requires is discouraged, see `Dependency Management` docs # tests_require = pytest; pytest-cov # Require a specific Python version, e.g. Python 2.7 or >= 3.4 # python_requires = >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* [options.packages.find] where = src exclude = tests [options.extras_require] # Add here additional requirements for extra features, to install with: # `pip install pyomop[PDF]` like: # PDF = ReportLab; RXP # Add here test requirements (semicolon/line-separated) testing = pytest pytest-cov [options.entry_points] # Add here console scripts like: # console_scripts = # script_name = pyomop.module:function # For example: # console_scripts = # fibonacci = pyomop.skeleton:run # And any other entry points, for example: # pyscaffold.cli = # awesome = pyscaffoldext.awesome.extension:AwesomeExtension console_scripts = pyomop = pyomop.main:main_routine [test] # py.test options when running `python setup.py test` # addopts = --verbose extras = True [tool:pytest] # Options for py.test: # Specify command line options as you would do when invoking py.test directly. # e.g. --cov-report html (or xml) for html/xml output or --junitxml junit.xml # in order to write a coverage file that can be read by Jenkins. addopts = #--cov pyomop --cov-report term-missing --verbose norecursedirs = dist build .tox testpaths = tests [aliases] dists = bdist_wheel [bdist_wheel] # Use this option if your package is pure-python universal = 1 [build_sphinx] source_dir = docs build_dir = build/sphinx [devpi:upload] # Options for the devpi: PyPI server and packaging tool # VCS export must be deactivated since we are using setuptools-scm no-vcs = 1 formats = bdist_wheel [flake8] # Some sane defaults for the code style checker flake8 exclude = .tox build dist .eggs docs/conf.py [pyscaffold] # PyScaffold's parameters when the project was created. # This will be used when updating. Do not change! version = 4.0.2 package = pyomop extensions = travis tox markdown pyomop-4.2.0/setup.py000066400000000000000000000012771452642503600145700ustar00rootroot00000000000000""" Setup file for pyomop. Use setup.cfg to configure your project. This file was generated with PyScaffold 4.0.2. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: https://pyscaffold.org/ """ from setuptools import setup if __name__ == "__main__": try: setup(use_scm_version={"version_scheme": "no-guess-dev"}) except: # noqa print( "\n\nAn error occurred while building the project, " "please ensure you have the most updated version of setuptools, " "setuptools_scm and wheel with:\n" " pip install -U setuptools setuptools_scm wheel\n\n" ) raise pyomop-4.2.0/src/000077500000000000000000000000001452642503600136365ustar00rootroot00000000000000pyomop-4.2.0/src/__init__.py000066400000000000000000000001171452642503600157460ustar00rootroot00000000000000import warnings warnings.filterwarnings("ignore", category=DeprecationWarning)pyomop-4.2.0/src/pyomop/000077500000000000000000000000001452642503600151615ustar00rootroot00000000000000pyomop-4.2.0/src/pyomop/__init__.py000066400000000000000000000042251452642503600172750ustar00rootroot00000000000000import sys from .engine_factory import CdmEngineFactory from .cdm6_tables import metadata from .vocabulary import CdmVocabulary from .vector import CdmVector from .cdm6_tables import AttributeDefinition from .cdm6_tables import CareSite from .cdm6_tables import CdmSource from .cdm6_tables import Cohort from .cdm6_tables import CohortAttribute from .cdm6_tables import CohortDefinition from .cdm6_tables import Concept from .cdm6_tables import ConceptAncestor from .cdm6_tables import ConceptClass from .cdm6_tables import ConceptRelationship from .cdm6_tables import ConceptSynonym from .cdm6_tables import ConditionEra from .cdm6_tables import ConditionOccurrence from .cdm6_tables import Death from .cdm6_tables import DeviceCost from .cdm6_tables import DeviceExposure from .cdm6_tables import Domain from .cdm6_tables import DoseEra from .cdm6_tables import DrugCost from .cdm6_tables import DrugEra from .cdm6_tables import DrugExposure from .cdm6_tables import DrugStrength from .cdm6_tables import FactRelationship from .cdm6_tables import Location from .cdm6_tables import Measurement from .cdm6_tables import Note from .cdm6_tables import Observation from .cdm6_tables import ObservationPeriod from .cdm6_tables import PayerPlanPeriod from .cdm6_tables import Person from .cdm6_tables import ProcedureCost from .cdm6_tables import ProcedureOccurrence from .cdm6_tables import Provider from .cdm6_tables import Relationship from .cdm6_tables import SourceToConceptMap from .cdm6_tables import Speciman from .cdm6_tables import VisitCost from .cdm6_tables import VisitOccurrence from .cdm6_tables import Vocabulary if sys.version_info[:2] >= (3, 8): # TODO: Import directly (no need for conditional) when `python_requires = >= 3.8` from importlib.metadata import PackageNotFoundError, version # pragma: no cover else: from importlib_metadata import PackageNotFoundError, version # pragma: no cover try: # Change here if project is renamed and does not equal the package name dist_name = __name__ __version__ = version(dist_name) except PackageNotFoundError: # pragma: no cover __version__ = "unknown" finally: del version, PackageNotFoundError pyomop-4.2.0/src/pyomop/__main__.py000066400000000000000000000000401452642503600172450ustar00rootroot00000000000000import main main.main_routine()pyomop-4.2.0/src/pyomop/cdm6_tables.py000066400000000000000000000541421452642503600177240ustar00rootroot00000000000000""" Copyright (C) 2020 Bell Eapen This file is part of PyOMOP. PyOMOP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PyOMOP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PyOMOP. If not, see . """ # coding: utf-8 from sqlalchemy import BigInteger, Column, Integer, Numeric, String, Text from sqlalchemy.orm import declarative_base Base = declarative_base() metadata = Base.metadata class AttributeDefinition(Base): __tablename__ = 'attribute_definition' # _id = Column(Integer, primary_key=True) attribute_definition_id = Column(Integer, primary_key=True) attribute_name = Column(String(255), nullable=False) attribute_description = Column(Text) attribute_type_concept_id = Column(Integer, nullable=False) attribute_syntax = Column(Text) class CareSite(Base): __tablename__ = 'care_site' # _id = Column(Integer, primary_key=True) care_site_id = Column(Integer, primary_key=True) care_site_name = Column(String(255)) place_of_service_concept_id = Column(Integer) location_id = Column(Integer) care_site_source_value = Column(String(50)) place_of_service_source_value = Column(String(50)) class CdmSource(Base): __tablename__ = 'cdm_source' # _id = Column(Integer, primary_key=True) cdm_source_name = Column(String(255), primary_key=True) cdm_source_abbreviation = Column(String(25)) cdm_holder = Column(String(255)) source_description = Column(Text) source_documentation_reference = Column(String(255)) cdm_etl_reference = Column(String(255)) source_release_date = Column(String(30)) cdm_release_date = Column(String(30)) cdm_version = Column(String(10)) vocabulary_version = Column(String(20)) class Cohort(Base): __tablename__ = 'cohort' _id = Column(Integer, primary_key=True) cohort_definition_id = Column(Integer, nullable=False) subject_id = Column(Integer, nullable=False) cohort_start_date = Column(String(30), nullable=False) cohort_end_date = Column(String(30), nullable=False) class CohortAttribute(Base): __tablename__ = 'cohort_attribute' _id = Column(Integer, primary_key=True) cohort_definition_id = Column(Integer, nullable=False) cohort_start_date = Column(String(30), nullable=False) cohort_end_date = Column(String(30), nullable=False) subject_id = Column(Integer, nullable=False) attribute_definition_id = Column(Integer, nullable=False) value_as_number = Column(Numeric) value_as_concept_id = Column(Integer) class CohortDefinition(Base): __tablename__ = 'cohort_definition' # _id = Column(Integer, primary_key=True) cohort_definition_id = Column(Integer, primary_key=True) cohort_definition_name = Column(String(255), nullable=False) cohort_definition_description = Column(Text) definition_type_concept_id = Column(Integer, nullable=False) cohort_definition_syntax = Column(Text) subject_concept_id = Column(Integer, nullable=False) cohort_initiation_date = Column(String(30)) class Concept(Base): __tablename__ = 'concept' # _id = Column(Integer, primary_key=True) concept_id = Column(Integer, primary_key=True) concept_name = Column(String(255), nullable=False) domain_id = Column(String(20), nullable=False) vocabulary_id = Column(String(20), nullable=False) concept_class_id = Column(String(20), nullable=False) standard_concept = Column(String(1)) concept_code = Column(String(50), nullable=False) valid_start_date = Column(String(30), nullable=False) valid_end_date = Column(String(30), nullable=False) invalid_reason = Column(String(1)) class ConceptAncestor(Base): __tablename__ = 'concept_ancestor' _id = Column(Integer, primary_key=True) ancestor_concept_id = Column(Integer, nullable=False) descendant_concept_id = Column(Integer, nullable=False) min_levels_of_separation = Column(Integer, nullable=False) max_levels_of_separation = Column(Integer, nullable=False) class ConceptClass(Base): __tablename__ = 'concept_class' # _id = Column(Integer, primary_key=True) concept_class_id = Column(String(20), primary_key=True) concept_class_name = Column(String(255), nullable=False) concept_class_concept_id = Column(Integer, nullable=False) class ConceptRelationship(Base): __tablename__ = 'concept_relationship' _id = Column(Integer, primary_key=True) concept_id_1 = Column(Integer, nullable=False) concept_id_2 = Column(Integer, nullable=False) relationship_id = Column(String(20), nullable=False) valid_start_date = Column(String(30), nullable=False) valid_end_date = Column(String(30), nullable=False) invalid_reason = Column(String(1)) class ConceptSynonym(Base): __tablename__ = 'concept_synonym' _id = Column(Integer, primary_key=True) concept_id = Column(Integer, nullable=False) concept_synonym_name = Column(String(1000), nullable=False) language_concept_id = Column(Integer, nullable=False) class ConditionEra(Base): __tablename__ = 'condition_era' # _id = Column(Integer, primary_key=True) condition_era_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) condition_concept_id = Column(Integer, nullable=False) condition_era_start_date = Column(String(30), nullable=False) condition_era_end_date = Column(String(30), nullable=False) condition_occurrence_count = Column(Integer) class ConditionOccurrence(Base): __tablename__ = 'condition_occurrence' # _id = Column(Integer, primary_key=True) condition_occurrence_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) condition_concept_id = Column(Integer, nullable=False) condition_start_date = Column(String(30), nullable=False) condition_end_date = Column(String(30)) condition_type_concept_id = Column(Integer, nullable=False) stop_reason = Column(String(20)) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) condition_source_value = Column(String(50)) condition_source_concept_id = Column(Integer) class Death(Base): __tablename__ = 'death' _id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) death_date = Column(String(30), nullable=False) death_type_concept_id = Column(Integer, nullable=False) cause_concept_id = Column(Integer) cause_source_value = Column(String(50)) cause_source_concept_id = Column(Integer) class DeviceCost(Base): __tablename__ = 'device_cost' # _id = Column(Integer, primary_key=True) device_cost_id = Column(Integer, primary_key=True) device_exposure_id = Column(Integer, nullable=False) currency_concept_id = Column(Integer) paid_copay = Column(Numeric) paid_coinsurance = Column(Numeric) paid_toward_deductible = Column(Numeric) paid_by_payer = Column(Numeric) paid_by_coordination_benefits = Column(Numeric) total_out_of_pocket = Column(Numeric) total_paid = Column(Numeric) payer_plan_period_id = Column(Integer) class DeviceExposure(Base): __tablename__ = 'device_exposure' # _id = Column(Integer, primary_key=True) device_exposure_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) device_concept_id = Column(Integer, nullable=False) device_exposure_start_date = Column(String(30), nullable=False) device_exposure_end_date = Column(String(30)) device_type_concept_id = Column(Integer, nullable=False) unique_device_id = Column(String(50)) quantity = Column(Integer) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) device_source_value = Column(String(100)) device_source_concept_id = Column(Integer) class Domain(Base): __tablename__ = 'domain' # _id = Column(Integer, primary_key=True, nullable=False) domain_id = Column(String(20), primary_key=True) domain_name = Column(String(255), nullable=False) domain_concept_id = Column(Integer, nullable=False) class DoseEra(Base): __tablename__ = 'dose_era' # _id = Column(Integer, primary_key=True) dose_era_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) drug_concept_id = Column(Integer, nullable=False) unit_concept_id = Column(Integer, nullable=False) dose_value = Column(Numeric, nullable=False) dose_era_start_date = Column(String(30), nullable=False) dose_era_end_date = Column(String(30), nullable=False) class DrugCost(Base): __tablename__ = 'drug_cost' # _id = Column(Integer, primary_key=True) drug_cost_id = Column(Integer, primary_key=True) drug_exposure_id = Column(Integer, nullable=False) currency_concept_id = Column(Integer) paid_copay = Column(Numeric) paid_coinsurance = Column(Numeric) paid_toward_deductible = Column(Numeric) paid_by_payer = Column(Numeric) paid_by_coordination_benefits = Column(Numeric) total_out_of_pocket = Column(Numeric) total_paid = Column(Numeric) ingredient_cost = Column(Numeric) dispensing_fee = Column(Numeric) average_wholesale_price = Column(Numeric) payer_plan_period_id = Column(Integer) class DrugEra(Base): __tablename__ = 'drug_era' # _id = Column(Integer, primary_key=True) drug_era_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) drug_concept_id = Column(Integer, nullable=False) drug_era_start_date = Column(String(30), nullable=False) drug_era_end_date = Column(String(30), nullable=False) drug_exposure_count = Column(Integer) gap_days = Column(Integer) class DrugExposure(Base): __tablename__ = 'drug_exposure' # _id = Column(Integer, primary_key=True) drug_exposure_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) drug_concept_id = Column(Integer, nullable=False) drug_exposure_start_date = Column(String(30), nullable=False) drug_exposure_end_date = Column(String(30)) drug_type_concept_id = Column(Integer, nullable=False) stop_reason = Column(String(20)) refills = Column(Integer) quantity = Column(Numeric) days_supply = Column(Integer) sig = Column(Text) route_concept_id = Column(Integer) effective_drug_dose = Column(Numeric) dose_unit_concept_id = Column(Integer) lot_number = Column(String(50)) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) drug_source_value = Column(String(50)) drug_source_concept_id = Column(Integer) route_source_value = Column(String(50)) dose_unit_source_value = Column(String(50)) class DrugStrength(Base): __tablename__ = 'drug_strength' # TODO Check this # _id = Column(Integer, primary_key=True) # drug_concept_id = Column(Integer, nullable=False) drug_concept_id = Column(Integer, primary_key=True) ingredient_concept_id = Column(Integer, nullable=False) amount_value = Column(Numeric) amount_unit_concept_id = Column(Integer) numerator_value = Column(Numeric) numerator_unit_concept_id = Column(Integer) denominator_value = Column(Numeric) denominator_unit_concept_id = Column(Integer) box_size = Column(Integer) valid_start_date = Column(String(30), nullable=False) valid_end_date = Column(String(30), nullable=False) invalid_reason = Column(String(1)) class FactRelationship(Base): __tablename__ = 'fact_relationship' _id = Column(Integer, primary_key=True) domain_concept_id_1 = Column(Integer, nullable=False) fact_id_1 = Column(Integer, nullable=False) domain_concept_id_2 = Column(Integer, nullable=False) fact_id_2 = Column(Integer, nullable=False) relationship_concept_id = Column(Integer, nullable=False) class Location(Base): __tablename__ = 'location' # _id = Column(Integer, primary_key=True) location_id = Column(Integer, primary_key=True) address_1 = Column(String(50)) address_2 = Column(String(50)) city = Column(String(50)) state = Column(String(2)) zip = Column(String(9)) county = Column(String(20)) location_source_value = Column(String(50)) class Measurement(Base): __tablename__ = 'measurement' # _id = Column(Integer, primary_key=True) measurement_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) measurement_concept_id = Column(Integer, nullable=False) measurement_date = Column(String(30), nullable=False) measurement_time = Column(String(10)) measurement_type_concept_id = Column(Integer, nullable=False) operator_concept_id = Column(Integer) value_as_number = Column(Numeric) value_as_concept_id = Column(Integer) unit_concept_id = Column(Integer) range_low = Column(Numeric) range_high = Column(Numeric) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) measurement_source_value = Column(String(50)) measurement_source_concept_id = Column(Integer) unit_source_value = Column(String(50)) value_source_value = Column(String(50)) class Note(Base): __tablename__ = 'note' # _id = Column(Integer, primary_key=True) note_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) note_date = Column(String(30), nullable=False) note_time = Column(String(10)) note_type_concept_id = Column(Integer, nullable=False) note_text = Column(Text, nullable=False) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) note_source_value = Column(String(50)) class Observation(Base): __tablename__ = 'observation' # _id = Column(Integer, primary_key=True) observation_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) observation_concept_id = Column(Integer, nullable=False) observation_date = Column(String(30), nullable=False) observation_time = Column(String(10)) observation_type_concept_id = Column(Integer, nullable=False) value_as_number = Column(Numeric) value_as_string = Column(String(60)) value_as_concept_id = Column(Integer) qualifier_concept_id = Column(Integer) unit_concept_id = Column(Integer) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) observation_source_value = Column(String(50)) observation_source_concept_id = Column(Integer) unit_source_value = Column(String(50)) qualifier_source_value = Column(String(50)) class ObservationPeriod(Base): __tablename__ = 'observation_period' # _id = Column(Integer, primary_key=True) observation_period_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) observation_period_start_date = Column(String(30), nullable=False) observation_period_end_date = Column(String(30), nullable=False) period_type_concept_id = Column(Integer, nullable=False) class PayerPlanPeriod(Base): __tablename__ = 'payer_plan_period' # _id = Column(Integer, primary_key=True) payer_plan_period_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) payer_plan_period_start_date = Column(String(30), nullable=False) payer_plan_period_end_date = Column(String(30), nullable=False) payer_source_value = Column(String(50)) plan_source_value = Column(String(50)) family_source_value = Column(String(50)) class Person(Base): __tablename__ = 'person' #_id = Column(Integer, primary_key=True) person_id = Column(Integer, primary_key=True) gender_concept_id = Column(Integer, nullable=False) year_of_birth = Column(Integer, nullable=False) month_of_birth = Column(Integer) day_of_birth = Column(Integer) #time_of_birth = Column(String(10)) birth_datetime = Column(String(10)) death_datetime = Column(String(10)) race_concept_id = Column(Integer, nullable=False) ethnicity_concept_id = Column(Integer, nullable=False) location_id = Column(Integer) provider_id = Column(Integer) care_site_id = Column(Integer) person_source_value = Column(String(50)) gender_source_value = Column(String(50)) gender_source_concept_id = Column(Integer) race_source_value = Column(String(50)) race_source_concept_id = Column(Integer) ethnicity_source_value = Column(String(50)) ethnicity_source_concept_id = Column(Integer) class ProcedureCost(Base): __tablename__ = 'procedure_cost' # _id = Column(Integer, primary_key=True) procedure_cost_id = Column(Integer, primary_key=True) procedure_occurrence_id = Column(Integer, nullable=False) currency_concept_id = Column(Integer) paid_copay = Column(Numeric) paid_coinsurance = Column(Numeric) paid_toward_deductible = Column(Numeric) paid_by_payer = Column(Numeric) paid_by_coordination_benefits = Column(Numeric) total_out_of_pocket = Column(Numeric) total_paid = Column(Numeric) revenue_code_concept_id = Column(Integer) payer_plan_period_id = Column(Integer) revenue_code_source_value = Column(String(50)) class ProcedureOccurrence(Base): __tablename__ = 'procedure_occurrence' # _id = Column(Integer, primary_key=True) procedure_occurrence_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) procedure_concept_id = Column(Integer, nullable=False) procedure_date = Column(String(30), nullable=False) procedure_type_concept_id = Column(Integer, nullable=False) modifier_concept_id = Column(Integer) quantity = Column(Integer) provider_id = Column(Integer) visit_occurrence_id = Column(BigInteger) procedure_source_value = Column(String(50)) procedure_source_concept_id = Column(Integer) qualifier_source_value = Column(String(50)) class Provider(Base): __tablename__ = 'provider' # _id = Column(Integer, primary_key=True) provider_id = Column(Integer, primary_key=True) provider_name = Column(String(255)) npi = Column(String(20)) dea = Column(String(20)) specialty_concept_id = Column(Integer) care_site_id = Column(Integer) year_of_birth = Column(Integer) gender_concept_id = Column(Integer) provider_source_value = Column(String(50)) specialty_source_value = Column(String(50)) specialty_source_concept_id = Column(Integer) gender_source_value = Column(String(50)) gender_source_concept_id = Column(Integer) class Relationship(Base): __tablename__ = 'relationship' # _id = Column(Integer, primary_key=True) relationship_id = Column(String(20), primary_key=True) relationship_name = Column(String(255), nullable=False) is_hierarchical = Column(String(1), nullable=False) defines_ancestry = Column(String(1), nullable=False) reverse_relationship_id = Column(String(20), nullable=False) relationship_concept_id = Column(Integer, nullable=False) class SourceToConceptMap(Base): __tablename__ = 'source_to_concept_map' _id = Column(Integer, primary_key=True) source_code = Column(String(50), nullable=False) source_concept_id = Column(Integer, nullable=False) source_vocabulary_id = Column(String(20), nullable=False) source_code_description = Column(String(255)) target_concept_id = Column(Integer, nullable=False) target_vocabulary_id = Column(String(20), nullable=False) valid_start_date = Column(String(30), nullable=False) valid_end_date = Column(String(30), nullable=False) invalid_reason = Column(String(1)) class Speciman(Base): __tablename__ = 'specimen' # _id = Column(Integer, primary_key=True) specimen_id = Column(Integer, primary_key=True) person_id = Column(Integer, nullable=False) specimen_concept_id = Column(Integer, nullable=False) specimen_type_concept_id = Column(Integer, nullable=False) specimen_date = Column(String(30), nullable=False) specimen_time = Column(String(10)) quantity = Column(Numeric) unit_concept_id = Column(Integer) anatomic_site_concept_id = Column(Integer) disease_status_concept_id = Column(Integer) specimen_source_id = Column(String(50)) specimen_source_value = Column(String(50)) unit_source_value = Column(String(50)) anatomic_site_source_value = Column(String(50)) disease_status_source_value = Column(String(50)) class VisitCost(Base): __tablename__ = 'visit_cost' # _id = Column(Integer, primary_key=True) visit_cost_id = Column(Integer, primary_key=True) visit_occurrence_id = Column(BigInteger, nullable=False) currency_concept_id = Column(Integer) paid_copay = Column(Numeric) paid_coinsurance = Column(Numeric) paid_toward_deductible = Column(Numeric) paid_by_payer = Column(Numeric) paid_by_coordination_benefits = Column(Numeric) total_out_of_pocket = Column(Numeric) total_paid = Column(Numeric) payer_plan_period_id = Column(Integer) class VisitOccurrence(Base): __tablename__ = 'visit_occurrence' # _id = Column(Integer, primary_key=True) visit_occurrence_id = Column(BigInteger, primary_key=True) person_id = Column(Integer, nullable=False) visit_concept_id = Column(Integer, nullable=False) visit_start_date = Column(String(30), nullable=False) visit_start_time = Column(String(10)) visit_end_date = Column(String(30), nullable=False) visit_end_time = Column(String(10)) visit_type_concept_id = Column(Integer, nullable=False) provider_id = Column(Integer) care_site_id = Column(Integer) visit_source_value = Column(String(50)) visit_source_concept_id = Column(Integer) class Vocabulary(Base): __tablename__ = 'vocabulary' # _id = Column(Integer, primary_key=True) vocabulary_id = Column(String(20), primary_key=True) vocabulary_name = Column(String(255), nullable=False) vocabulary_reference = Column(String(255), nullable=False) vocabulary_version = Column(String(255)) vocabulary_concept_id = Column(Integer, nullable=False) pyomop-4.2.0/src/pyomop/engine_factory.py000066400000000000000000000072041452642503600205320ustar00rootroot00000000000000# from sqlalchemy import create_engine # from sqlalchemy.orm import Session # from sqlalchemy.ext.automap import automap_base import asyncio from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.automap import automap_base class CdmEngineFactory(object): def __init__(self, db = 'sqlite', host = 'localhost', port = 5432, user = 'root', pw='pass', name = 'cdm6.sqlite', schema = 'public'): self._db = db self._name = name self._host = host self._port = port self._user = user self._pw = pw self._schema = schema self._engine = None self._base = None async def init_models(self, metadata): async with self._engine.begin() as conn: await conn.run_sync(metadata.drop_all) await conn.run_sync(metadata.create_all) @property def db(self): return self._db @property def host(self): return self._host @property def port(self): return self._port @property def name(self): return self._name @property def user(self): return self._user @property def pw(self): return self._pw @property def schema(self): return self._schema @property def engine(self): return self.engine @property def base(self): if self.engine is not None: # Not self_engine Base = automap_base() Base.prepare(self.engine, reflect=True) return Base.classes return None @property def engine(self): if self._db == 'sqlite': self._engine = create_async_engine("sqlite+aiosqlite:///"+self._name) if self._db == 'mysql': mysql_url = 'mysql://{}:{}@{}:{}/{}' mysql_url = mysql_url.format(self._user, self._pw, self._host, self._port, self._name) self._engine = create_async_engine(mysql_url, isolation_level="READ UNCOMMITTED") if self._db == 'pgsql': # https://stackoverflow.com/questions/9298296/sqlalchemy-support-of-postgres-schemas dbschema = '{},public' # Searches left-to-right dbschema = dbschema.format(self._schema) pgsql_url = 'postgresql+psycopg2://{}:{}@{}:{}/{}' pgsql_url = pgsql_url.format(self._user, self._pw, self._host, self._port, self._name) self._engine = create_async_engine( pgsql_url, connect_args={'options': '-csearch_path={}'.format(dbschema)}) return self._engine @property def session(self): if self._engine is not None: async_session = sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession) return async_session return None @property def async_session(self): if self._engine is not None: async_session = sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession) return async_session return None @db.setter def db(self, value): self._db = value @name.setter def name(self, value): self._name = value @port.setter def port(self, value): self._port = value @host.setter def host(self, value): self._host = value @user.setter def user(self, value): self._user = value @pw.setter def pw(self, value): self._pw = value @schema.setter def schema(self, value): self._schema = value pyomop-4.2.0/src/pyomop/main.py000066400000000000000000000036771452642503600164740ustar00rootroot00000000000000import click import asyncio from . import CdmEngineFactory from . import CdmVocabulary from . import metadata from . import __version__ @click.command() @click.option('--verbose', '-v', is_flag=True, help="Will print verbose messages.") @click.option('--create', '-c', is_flag=True, help="Create CDM6 schema on the database.") @click.option('--dbtype', '-t', multiple=False, default='sqlite', help='Database Type for creating CDM (sqlite, mysql or pgsql') @click.option('--host', '-h', multiple=False, default='localhost', help='Database host') @click.option('--port', '-p', multiple=False, default='5432', help='Database port') @click.option('--user', '-u', multiple=False, default='root', help='Database user') @click.option('--pw', '-w', multiple=False, default='pass', help='Database password') @click.option('--name', '-n', multiple=False, default='cdm6.sqlite', help='Database name') @click.option('--schema', '-s', multiple=False, default='public', help='Database schema (for pgsql)') @click.option('--vocab', '-i', multiple=False, default='', help='Folder with vocabulary files (csv) to import') def cli(verbose, create, dbtype, host, port, user, pw, name, schema, vocab): if verbose: print("verbose") if create: cdm = CdmEngineFactory(dbtype, host, port, user, pw, name, schema) # initialize default engine engine = cdm.engine asyncio.run(cdm.init_models(metadata)) if vocab is not '': cdm = CdmEngineFactory(dbtype, host, port, user, pw, name, schema) _vocab = CdmVocabulary(cdm) _vocab.create_vocab(vocab) print("Done") def main_routine(): click.echo("_________________________________________") click.echo("Pyomop v" + __version__ + " working:.....") cli() # run the main function click.echo("Pyomop done.") if __name__ == '__main__': main_routine()pyomop-4.2.0/src/pyomop/sqldict.py000066400000000000000000000007471452642503600172060ustar00rootroot00000000000000# https://github.com/OHDSI/QueryLibrary/tree/master/inst/shinyApps/QueryLibrary/queries # Test TEST = "SELECT * from cohort;" # PE03: Number of patients grouped by gender PE03 = """ SELECT person.gender_concept_id, concept.concept_name AS gender_name, COUNT(person.person_id) AS num_persons FROM person JOIN concept ON person.gender_concept_id = concept.concept_id GROUP BY person.gender_concept_id, concept.concept_name; """ CDMSQL = { "TEST": TEST, "PE03": PE03 }pyomop-4.2.0/src/pyomop/vector.py000066400000000000000000000031421452642503600170350ustar00rootroot00000000000000import asyncio import pandas as pd from sqlalchemy.inspection import inspect from sqlalchemy import text from .sqldict import CDMSQL # https://gist.github.com/dermatologist/f436cb461a3290732a27c4dc040229f9 # Thank you! https://gist.github.com/garaud class CdmVector(object): def __init__(self, result=None): self._result = result self._df = None @property def df(self): if self._df is None: self.create_df() return self._df @property def result(self): return self._result @result.setter def result(self, value): self._result = value def query_to_list(self): """List of result Return: columns name, list of result """ result_list = [] instance = None if self._result is None: return None, [] for obj in self._result: instance = inspect(obj) items = instance.attrs.items() result_list.append([x.value for _,x in items]) if instance is None: return None, [] return instance.attrs.keys(), result_list def create_df(self, _names=None): names, data = self.query_to_list() if(_names): names = _names self._df = pd.DataFrame.from_records(data, columns=names) async def sql_df(self, cdm, sqldict=None, query=None, chunksize=1000): if sqldict: query=CDMSQL[sqldict] async with cdm.session() as session: result = await session.execute(text(query)) self._result = result await session.close() return result pyomop-4.2.0/src/pyomop/vocabulary.py000066400000000000000000000144031452642503600177040ustar00rootroot00000000000000import pandas as pd from .cdm6_tables import Concept import asyncio from contextlib import asynccontextmanager from typing import AsyncGenerator from sqlalchemy.ext.asyncio import ( AsyncSession, async_scoped_session, ) from sqlalchemy.orm import sessionmaker from sqlalchemy import insert import numpy as np from sqlalchemy.ext.automap import automap_base, AutomapBase from sqlalchemy import select class CdmVocabulary(object): def __init__(self, cdm): self._concept_id = 0 self._concept_name = '' self._domain_id = '' self._vocabulary_id = '' self._concept_class_id = '' self._concept_code = '' self._cdm = cdm self._engine = cdm.engine self._maker = sessionmaker(self._engine, class_=AsyncSession) self._scope = async_scoped_session(self._maker, scopefunc=asyncio.current_task) @property def concept_id(self): return self._concept_id @property def concept_code(self): return self._concept_code @property def concept_name(self): return self._concept_name @property def vocabulary_id(self): return self._vocabulary_id @property def domain_id(self): return self._domain_id @concept_id.setter def concept_id(self, concept_id): self._concept_id = concept_id _concept = asyncio.run(self.get_concept(concept_id)) self._concept_name = _concept.concept_name self._domain_id = _concept.domain_id self._vocabulary_id = _concept.vocabulary_id self._concept_class_id = _concept.concept_class_id self._concept_code = _concept.concept_code async def get_concept(self, concept_id): stmt = select(Concept).where(Concept.concept_id == concept_id) async with self._cdm.session() as session: _concept = await session.execute(stmt) return _concept.scalar_one() async def get_concept_by_code(self, concept_code, vocabulary_id): stmt = select(Concept).where(Concept.concept_code == concept_code) \ .where(Concept.vocabulary_id == vocabulary_id) async with self._cdm.session() as session: _concept = await session.execute(stmt) return _concept.scalar_one() def set_concept(self, concept_code, vocabulary_id=None): self._concept_code = concept_code try: if vocabulary_id is not None: self._vocabulary_id = vocabulary_id _concept = asyncio.run(self.get_concept_by_code(concept_code, vocabulary_id)) else: _concept = asyncio.run(self.get_concept_by_code(concept_code)) self._vocabulary_id = _concept.vocabulary_id self._concept_name = _concept.concept_name self._domain_id = _concept.domain_id self._concept_id = _concept.concept_id self._concept_class_id = _concept.concept_class_id self._concept_code = _concept.concept_code except: self._vocabulary_id = 0 self._concept_id = 0 def create_vocab(self, folder, sample=None): try: df = pd.read_csv(folder + '/DRUG_STRENGTH.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'drug_strength', 'replace')) # df.to_sql('drug_strength', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/CONCEPT.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'concept', 'replace')) # df.to_sql('concept', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/CONCEPT_RELATIONSHIP.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'concept_relationship', 'replace')) # df.to_sql('concept_relationship', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/CONCEPT_ANCESTOR.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'concept_ancestor', 'replace')) # df.to_sql('concept_ancester', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/CONCEPT_SYNONYM.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'concept_synonym', 'replace')) # df.to_sql('concept_synonym', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/VOCABULARY.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'vocabulary', 'replace')) # df.to_sql('vocabulary', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/RELATIONSHIP.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'relationship', 'replace')) # df.to_sql('relationship', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/CONCEPT_CLASS.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'concept_class', 'replace')) # df.to_sql('concept_class', con=self._engine, if_exists = 'replace') df = pd.read_csv(folder + '/DOMAIN.csv', sep='\t', nrows=sample, on_bad_lines='skip') asyncio.run(self.write_vocab(df, 'domain', 'replace')) # df.to_sql('domain', con=self._engine, if_exists = 'replace') except Exception as e: print(f"An error occurred while creating the vocabulary: {e}") @asynccontextmanager async def get_session(self) -> AsyncGenerator[AsyncSession, None]: async with self._scope() as session: yield session async def write_vocab(self, df, table, if_exists='replace', chunk_size=1000): async with self.get_session() as session: conn = await session.connection() automap: AutomapBase = automap_base() await conn.run_sync(lambda sync_conn: automap.prepare(autoload_with=sync_conn)) mapper = getattr(automap.classes, table) stmt = insert(mapper) for _, group in df.groupby(np.arange(df.shape[0], dtype=int) // chunk_size): await session.execute(stmt, group.to_dict("records")) await session.commit() await session.close()pyomop-4.2.0/t_install.py000066400000000000000000000034351452642503600154170ustar00rootroot00000000000000from pyomop import CdmEngineFactory, CdmVocabulary, CdmVector, Cohort, Vocabulary, metadata from sqlalchemy.future import select import datetime import asyncio async def main(): cdm = CdmEngineFactory() # Creates SQLite database by default # Postgres example (db='mysql' also supported) # cdm = CdmEngineFactory(db='pgsql', host='', port=5432, # user='', pw='', # name='', schema='cdm6') engine = cdm.engine # Create Tables if required await cdm.init_models(metadata) # Create vocabulary if required vocab = CdmVocabulary(cdm) # vocab.create_vocab('/path/to/csv/files') # Uncomment to load vocabulary csv files # Add a cohort async with cdm.session() as session: async with session.begin(): session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) await session.commit() # Query the cohort stmt = select(Cohort).where(Cohort.subject_id == 100) result = await session.execute(stmt) for row in result.scalars(): print(row) assert row.subject_id == 100 # Query the cohort pattern 2 cohort = await session.get(Cohort, 1) print(cohort) assert cohort.subject_id == 100 # Convert result to a pandas dataframe vec = CdmVector() vec.result = result print(vec.df.dtypes) result = await vec.sql_df(cdm, 'TEST') # TEST is defined in sqldict.py for row in result: print(row) result = await vec.sql_df(cdm, query='SELECT * from cohort') for row in result: print(row) # Close session await session.close() await engine.dispose() # Run the main function asyncio.run(main())pyomop-4.2.0/tests/000077500000000000000000000000001452642503600142115ustar00rootroot00000000000000pyomop-4.2.0/tests/CONCEPT.csv000066400000000000000000000007321452642503600160230ustar00rootroot00000000000000concept_id concept_name domain_id vocabulary_id concept_class_id standard_concept concept_code valid_start_date valid_end_date invalid_reason 45956931 xxxxx xxxxxxxxxxx xxxxxx xxxxxxxxx x 3578611000001105 19700101 20991231 45956935 xxxx xxxxxxx xxxxxxxxxxx xxxxxx xxxxxxxxx x 3579011000001108 19700101 20991231 45956943 xxxxx xxxxxxxxxxx xxxxxx xxxxxxxxx x 3330611000001108 19700101 20991231 45956945 xxxxx xxxxxxxxxxx xxxxxx xxxxxxxxx x 3565611000001107 19700101 20991231 pyomop-4.2.0/tests/CONCEPT_ANCESTOR.csv000066400000000000000000000006201452642503600173150ustar00rootroot00000000000000ancestor_concept_id descendant_concept_id min_levels_of_separation max_levels_of_separation 36217216 41278033 3 4 36217214 40037983 2 2 36217214 43822796 3 3 36206173 46236751 2 2 36214405 41377546 1 2 36156761 41153847 1 1 36217214 40916412 3 5 36217214 40737295 3 5 36153416 43818534 1 1 36217214 42873437 2 3 36217216 41134585 3 5 36217214 21087154 3 3 36206173 37067288 3 3 36217216 21062809 3 4 pyomop-4.2.0/tests/CONCEPT_CLASS.csv000066400000000000000000000012501452642503600167440ustar00rootroot00000000000000concept_class_id concept_class_name concept_class_concept_id xxxxxxxxx xxxxx xxxxxxxxx xxxxx 44819021 xxxxxxx xxxxxx xxxxxxx xxxxxx 44819092 xxxx1 xxxx 44819030 xxxx xxxx 44819273 xxxxxx xxxxxxxx xxxxxx xxxxxxxx 44818999 xxxxxxxxxxxx xxxx xxxxxxxxxxxx 44819274 xxxxxxxxxxx xxxxxxx xxxxxxxx xx xxx xxxxxxxxxxx xxxxxx 44819176 xxxxxxx xxxx xxxxxxx xxxx 44819075 xxxx2 xxxxxxx xxxxxxxx xx xxx xxxx xxx xxxxxxxxxxxx xxxxxx 44819178 xxx3 xxxxxxxxxxxx xxxxxx xxxxx 44819060 xxx xxxxxx xxxxx xxxxx 44819037 xxxxxx4 xxxxxxx xxxxxx xxxxxxx 44819022 xxxx5 xxxxxx xxxxxxx xxxxxxxx xx xxx xxxxxxxxxxxxxxx xxxxxx xxx xxxxxxxxxx xxxxxx 44819179 xxxxxxx xxxx xxxxx xxx xxxxxxx xxxxxxxx 44819236 pyomop-4.2.0/tests/CONCEPT_RELATIONSHIP.csv000066400000000000000000000015401452642503600200020ustar00rootroot00000000000000concept_id_1 concept_id_2 relationship_id valid_start_date valid_end_date invalid_reason 21157062 19082229 xxxxxx xxx xxxx xxxx 20150817 20991231 19126920 21166241 xxxxxx xxxx xxxx xx 20150817 20991231 21079498 19129634 xxxxxx xxx xxxx xxxx 20150817 20991231 21150652 19082077 xxxxxx xxx xxxx xxxx 20150817 20991231 19082170 21079242 xxxxxx xxxx xxxx xx 20150817 20991231 21019960 21086967 xxxxxxxx xx 20150817 20991231 19082573 21081309 xxxxxx xxxx xxxx xx 20150817 20991231 19082170 21061663 xxxxxx xxxx xxxx xx 20150817 20991231 19082573 21165151 xxxxxx xxxx xxxx xx 20150817 20991231 938296 21024404 xxx xxxxxxxx xxxx 20150817 20991231 40221904 42838706 xxxxxx xxxx 20180420 20991231 19126920 21126749 xxxxxx xxxx xxxx xx 20150817 20991231 21132583 19082227 xxxxxx xxx xxxx xxxx 20150817 20991231 21048063 21019960 xxx xxxxxxxx 20150817 20991231 pyomop-4.2.0/tests/CONCEPT_SYNONYM.csv000066400000000000000000000005661452642503600172640ustar00rootroot00000000000000concept_id concept_synonym_name language_concept_id 45567944 Blank 4180186 45567944 Blank 4180186 45567949 Blank 4180186 45567951 Blank 4180186 45567957 Blank 4180186 45567966 Blank 4180186 45567969 Blank 4180186 45567969 Blank 4180186 45567975 Blank 4180186 45567975 Blank 4180186 45567982 Blank 4180186 45567982 Blank 4180186 45567986 Blank 4180186 45567986 Blank 4180186 pyomop-4.2.0/tests/DOMAIN.csv000066400000000000000000000005021452642503600156720ustar00rootroot00000000000000domain_id domain_name domain_concept_id Cost Cost 581456 Condition/Device Condition/Device 235 Gender Gender 2 Race Race 3 Ethnicity Ethnicity 4 Metadata Metadata 7 Visit Visit 8 Procedure Procedure 10 Modifier Modifier 12 Drug Drug 13 Route Route Of Administration 15 Unit Unit 16 Device Device 17 Condition Condition 19 pyomop-4.2.0/tests/DRUG_STRENGTH.csv000066400000000000000000000015361452642503600170120ustar00rootroot00000000000000drug_concept_id ingredient_concept_id amount_value amount_unit_concept_id numerator_value numerator_unit_concept_id denominator_value denominator_unit_concept_id box_size valid_start_date valid_end_date invalid_reason 40864711 730729 8576 19700101 20991231 40926439 730729 8576 19700101 20991231 40987545 730729 8576 19700101 20991231 41049802 730729 8576 19700101 20991231 41267981 730729 8576 19700101 20991231 44108350 730729 8576 19700101 20991231 45776842 730729 8576 19700101 20991231 45892192 730729 8576 19700101 20991231 40055995 731533 8576 19700101 20991231 40127423 731533 8576 19700101 20991231 21169601 732309 8576 19700101 20991231 40068331 732309 8576 19700101 20991231 35749651 732893 8576 19700101 20991231 40015130 732893 8576 19700101 20991231 pyomop-4.2.0/tests/RELATIONSHIP.csv000066400000000000000000000014711452642503600166320ustar00rootroot00000000000000relationship_id relationship_name is_hierarchical defines_ancestry reverse_relationship_id relationship_concept_id xxx1 xxxxxxxx xxxx xxx xxxxxxxx xxxxxxxxx (xxxxxx) 0 0 xxxxxxxx xxxx xx 44818775 xxx2 xxxxxxxx xxxxxx xxx xxxxxxxx xxxxxx xxxxxxxx (xxxxxx) 0 0 xxxxxxxx xxxxxxxx xx 44818776 xxx3 xxxxxxxx xxxxx xxx xxxxxxxx xxxxxx xxxxxxxxxx (xxxxxx) 0 0 xxxxxxxx xxxxx xx 44818777 xxx4 xxxxxxxx xxxx xxx xxxxxxxx xxxxxx xxxxxxxxxx (xxxxxx) 0 0 xxxxxxxx xxxx xx 44818778 xxx5 xxxxxxxx xxxxx xxx xxxxxxxx xxxxxxxxx (xxxxxx) 0 0 xxxxxxxx xxxxx xx 44818779 xxx6 xxx xx xxx xxx xx (xxxxxx) 0 0 xxx xx xx 44818780 xxx7 xxxxx xxxxxxx xxx xxxxxxx xxxxxxxxxxxx xxxxxxx (xxxxxx) 0 0 xxxxx xxxxxxx xx 44818781 xxx8 xxxx xxxx xxx xxxx xxxx (xxxxxx) 0 0 xxxx xxxx xx 44818782 xxxxxx xxxxx xxxxxx xxxxx (xxxxxx) 0 0 xxxxxx xxxxxx 44818783 pyomop-4.2.0/tests/VOCABULARY.csv000066400000000000000000000030701452642503600163750ustar00rootroot00000000000000vocabulary_id vocabulary_name vocabulary_reference vocabulary_version vocabulary_concept_id xxx xxx xxxxxxxx xxxxxxxxxxx xxxxxxxx xxxxxxxxxxxxxx xxx xx xxxxxxxxxxxx xxxxxxx xxxxxx 2018-08-12 44819117 xxx4xxx xxxxxxx - xxxxxxxxxxx xx xxxxxxxxxx xxxxxxxxx xxxxxxxxxx xxxxxxxxxxxx xxxx xxxxxxxxx 32472 xxx2xxxxx xxxx xxxx xxxxxxxxx xxxxxxxxxx xxxx xxxx xxxxxxxxx 44819127 xxx8x xxxx xxxx xxxxx xxxx xxxx xxxxxxxxx 44819150 xxx0xxxx xxxxxxxxx xxxxxxxx xxxxxxxx/xxxxxxxx xxxxxxxxx xxxxx (xxx) xxxx://xxx.xxx.xxx/xxxxxxxx/xxxxxxxx-xxxxxxxxxx-xxx-xxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxx.xxxx 2018-06-26 xxxxxxxxx 44819138 xx00xxxxx xxxx xxxx xxxxxxxxx xxxxxxxxxx xxxx xxxx xxxxxxxxx 44819128 xx00xx xxxx xxxx xxxxxx xxxx xxxx xxxxxxxxx 44819234 xxx0x xxxxxx xx xxxxxxx xxxxxxxx (xxxxx) xxxx://xxx.xxxxx.xxx/xxxxxxxxx/xxxxx-xxxxxxxx-xxxxxx.xxx xxxxxxx 3.0 32473 xx66xx xxxx xxxxxx xxxx xxxxxxxxx 44819108 xx04 xxx xxxx xx04 xxxx xx xxxx - xxxxxxxxxxxxx (xxxxx) xxxxx://xxxxx.xxxx.xxx/xxxxxxxxxxxxxxx?&xxxxxx=xxxx&xxxxxxx=196987000 32044 xxx9xx xxxxxxxxxxxxx xxxxxxxxxxxxxx xx xxxxxxxx, xxxxx xxxxxxxx, xxxxxxxx xxxxxxxxxxxx, xxxxxx 1 xxx 2 (xxxx) xxxx://xxx.xxx.xxx/xxxxxxxx/xxxxxx/xxx9xxxxxxxxxxxxxxxxxxxxxxx/xxxxx.xxxx xxx9xx x32 xxxxxx xxxxxxxxxxxx 5046 xxx5x xxxx xxxx xxxx xxxxxxxxx 581457 xxx5 xxxxxxxxxxxxx xxxxx://xxx.xxxxxxxxxxxxx.xxx/xxxxxxxxx/xx, xxxxx://xxxxxxxxxx-xxx.xxxxxxx/xxxxxxxxxx/ xxx xxxxxxx 2019-02-21 32541 xxx4 xxxxxxx xxxxxxxxxx xxxxxxxxxxx xxxxxxx 4 (xxx) xxxx://xxx.xxx.xxx.xxx/xxxxxxxx/xxxx/xxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx.xxxx 2020 xxxxxxx 44819100 pyomop-4.2.0/tests/__init__.py000066400000000000000000000000001452642503600163100ustar00rootroot00000000000000pyomop-4.2.0/tests/conftest.py000066400000000000000000000010631452642503600164100ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Dummy conftest.py for pyomop. If you don't know what this is for, just leave it empty. Read more about conftest.py under: https://pytest.org/latest/plugins.html """ import asyncio import pytest @pytest.fixture def pyomop_fixture(): from src.pyomop import CdmEngineFactory cdm = CdmEngineFactory() return cdm @pytest.fixture def metadata_fixture(): from src.pyomop import metadata return metadata @pytest.fixture def vector_fixture(): from src.pyomop import CdmVector return CdmVector()pyomop-4.2.0/tests/test_a_pyomop.py000066400000000000000000000021771452642503600174540ustar00rootroot00000000000000import asyncio import pytest @staticmethod def test_create_cohort(pyomop_fixture, metadata_fixture, capsys): engine = pyomop_fixture.engine # create tables asyncio.run(pyomop_fixture.init_models(metadata_fixture)) asyncio.run(create_cohort(pyomop_fixture, engine)) async def create_cohort(pyomop_fixture,engine): from src.pyomop import Cohort import datetime from sqlalchemy.future import select # Add a cohort async with pyomop_fixture.session() as session: async with session.begin(): session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) await session.commit() # Query the cohort stmt = select(Cohort).where(Cohort.subject_id == 100) result = await session.execute(stmt) for row in result.scalars(): print(row) assert row.subject_id == 100 # Query the cohort pattern 2 cohort = await session.get(Cohort, 1) print(cohort) assert cohort.subject_id == 100 await session.close() await engine.dispose() pyomop-4.2.0/tests/test_ab_vector.py000066400000000000000000000030371452642503600175710ustar00rootroot00000000000000import asyncio import pytest @staticmethod def test_create_patient(pyomop_fixture, metadata_fixture, capsys): engine = pyomop_fixture.engine # create tables asyncio.run(pyomop_fixture.init_models(metadata_fixture)) asyncio.run(create_patient(pyomop_fixture, engine)) async def create_patient(pyomop_fixture,engine): from src.pyomop import Person from src.pyomop import Cohort import datetime from sqlalchemy.future import select # Add a patient async with pyomop_fixture.session() as session: async with session.begin(): session.add(Person( gender_concept_id=100, year_of_birth=2000, race_concept_id=200, ethnicity_concept_id=300 )) await session.commit() # Add couple of cohorts async with pyomop_fixture.session() as session: async with session.begin(): session.add(Cohort(cohort_definition_id=2, subject_id=1, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) session.add(Cohort(cohort_definition_id=3, subject_id=1, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) await session.commit() # Query the cohort for patient 1 stmt = select(Cohort).where(Cohort.subject_id == 1).order_by(Cohort._id) result = await session.execute(stmt) for row in result.scalars(): print(row) assert row.subject_id == 1 pyomop-4.2.0/tests/test_b_create_vocab.py000066400000000000000000000020161452642503600205370ustar00rootroot00000000000000import asyncio import pytest @staticmethod def test_create_tables(pyomop_fixture, metadata_fixture, capsys): engine = pyomop_fixture.engine # create tables asyncio.run(pyomop_fixture.init_models(metadata_fixture)) def test_create_vocab(pyomop_fixture, metadata_fixture, capsys): engine = pyomop_fixture.engine create_vocab(pyomop_fixture, engine) def create_vocab(pyomop_fixture,engine): from src.pyomop import CdmVocabulary vocab = CdmVocabulary(pyomop_fixture) vocab.create_vocab('tests', 10) print("Done") # import pytest # import os # @pytest.fixture # def pyomop_fixture(): # from src.pyomop import CdmEngineFactory # cdm = CdmEngineFactory() # return cdm # @pytest.fixture # def metadata_fixture(): # from src.pyomop import metadata # return metadata # def test_create_vocab(pyomop_fixture, metadata_fixture, capsys): # from src.pyomop import CdmVocabulary # vocab = CdmVocabulary(pyomop_fixture) # vocab.create_vocab('tests', 10) # print("Done") pyomop-4.2.0/tests/test_c_vocab.py000066400000000000000000000005041452642503600172150ustar00rootroot00000000000000 def test_vocab(pyomop_fixture, capsys): from src.pyomop import CdmVocabulary vocab = CdmVocabulary(pyomop_fixture) # for x in pyomop_fixture.base: # print(x) # setters are called like this vocab.concept_id = 45956935 # 'C0020538' Hypertension assert(vocab.concept_name == 'xxxx xxxxxxx') pyomop-4.2.0/tests/test_d_vector.py000066400000000000000000000023441452642503600174320ustar00rootroot00000000000000import asyncio import pytest @staticmethod def test_create_vector(pyomop_fixture, metadata_fixture, vector_fixture, capsys): engine = pyomop_fixture.engine # create tables asyncio.run(pyomop_fixture.init_models(metadata_fixture)) asyncio.run(create_vector(pyomop_fixture, vector_fixture, engine)) async def create_vector(pyomop_fixture, vector_fixture, engine): from src.pyomop import Cohort import datetime from sqlalchemy.future import select # Add a cohort async with pyomop_fixture.session() as session: async with session.begin(): session.add(Cohort(cohort_definition_id=2, subject_id=100, cohort_end_date=datetime.datetime.now(), cohort_start_date=datetime.datetime.now())) await session.commit() # Query the cohort stmt = select(Cohort).where(Cohort.subject_id == 100) result = await session.execute(stmt) vector_fixture.result = result.scalars() print(vector_fixture.df.dtypes) assert vector_fixture.df.empty is False result2 = await vector_fixture.sql_df(pyomop_fixture, 'TEST') for row in result2: print(row) assert row.subject_id == 100 await session.close() await engine.dispose() pyomop-4.2.0/tests/travis_install.sh000066400000000000000000000041031452642503600176010ustar00rootroot00000000000000#!/bin/bash # This script is meant to be called by the "install" step defined in # .travis.yml. See http://docs.travis-ci.com/ for more details. # The behavior of the script is controlled by environment variabled defined # in the .travis.yml in the top level folder of the project. # # This script is inspired by Scikit-Learn (http://scikit-learn.org/) # # THIS SCRIPT IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! set -e if [[ "$DISTRIB" == "conda" ]]; then # Deactivate the travis-provided virtual environment and setup a # conda-based environment instead deactivate if [[ -f "$HOME/miniconda/bin/conda" ]]; then echo "Skip install conda [cached]" else # By default, travis caching mechanism creates an empty dir in the # beginning of the build, but conda installer aborts if it finds an # existing folder, so let's just remove it: rm -rf "$HOME/miniconda" # Use the miniconda installer for faster download / install of conda # itself wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \ -O miniconda.sh chmod +x miniconda.sh && ./miniconda.sh -b -p $HOME/miniconda fi export PATH=$HOME/miniconda/bin:$PATH # Make sure to use the most updated version conda update --yes conda # Configure the conda environment and put it in the path using the # provided versions # (prefer local venv, since the miniconda folder is cached) conda create -p ./.venv --yes python=${PYTHON_VERSION} pip virtualenv source activate ./.venv fi # for all pip install -U pip setuptools pip install tox if [[ "$COVERAGE" == "true" ]]; then pip install -U pytest-cov pytest-virtualenv coverage coveralls flake8 pre-commit fi travis-cleanup() { printf "Cleaning up environments ... " # printf avoids new lines if [[ "$DISTRIB" == "conda" ]]; then # Force the env to be recreated next time, for build consistency source deactivate conda remove -p ./.venv --all --yes rm -rf ./.venv fi echo "DONE" } pyomop-4.2.0/tox.ini000066400000000000000000000010031452642503600143540ustar00rootroot00000000000000# Tox configuration file # Read more under https://tox.readthedocs.org/ # THIS SCRIPT IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! [tox] minversion = 2.4 envlist = py310, integration [testenv] setenv = TOXINIDIR = {toxinidir} deps = -rrequirements.txt -rdev-requirements.txt commands = py.test {posargs} extras = all testing [testenv:integration] setenv = TOXINIDIR = {toxinidir} deps = -rrequirements.txt -rdev-requirements.txt commands = python t_install.py