quark-tre-sdk 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ !/main.py
2
+ !/local.py
@@ -0,0 +1,21 @@
1
+ # quark-tre-sdk configuration
2
+ # Copy this file to .env and fill in your values.
3
+ # The SDK will auto-load .env on startup if python-dotenv is installed.
4
+
5
+ # Required: Athena data catalog name registered for the Quark connector
6
+ TRE_CATALOG=your-catalog
7
+
8
+ # Required: Athena workgroup to submit queries under (managed workgroup, no S3 staging dir needed)
9
+ TRE_WORKGROUP=your-workgroup
10
+
11
+ # Optional: AWS region. Auto-detected from EC2 IMDSv2 when running on a TRE workstation.
12
+ # Set explicitly if running outside EC2 or IMDSv2 is not available.
13
+ # AWS_DEFAULT_REGION=us-east-1
14
+
15
+ # AWS credentials — resolved by boto3 in standard order:
16
+ # 1. Env vars below
17
+ # 2. ~/.aws/credentials
18
+ # 3. EC2 instance profile (recommended on TRE workstations)
19
+ # AWS_ACCESS_KEY_ID=
20
+ # AWS_SECRET_ACCESS_KEY=
21
+ # AWS_SESSION_TOKEN=
@@ -0,0 +1,36 @@
1
+ name: Publish Python SDK to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+
14
+ - uses: astral-sh/setup-uv@v5
15
+
16
+ - name: Build
17
+ run: uv build
18
+
19
+ - uses: actions/upload-artifact@v4
20
+ with:
21
+ name: dist
22
+ path: dist/
23
+
24
+ publish:
25
+ needs: build
26
+ runs-on: ubuntu-latest
27
+ environment: pypi
28
+ permissions:
29
+ id-token: write
30
+ steps:
31
+ - uses: actions/download-artifact@v4
32
+ with:
33
+ name: dist
34
+ path: dist/
35
+
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,53 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ *.so
7
+ *.egg
8
+ *.egg-info/
9
+ dist/
10
+ build/
11
+ .eggs/
12
+ .cache/
13
+
14
+ # Virtual environments
15
+ .venv/
16
+ venv/
17
+ env/
18
+
19
+ # uv
20
+ .uv/
21
+
22
+ # Testing
23
+ .pytest_cache/
24
+ .coverage
25
+ coverage.xml
26
+ htmlcov/
27
+
28
+ # Type checkers
29
+ .mypy_cache/
30
+ .ruff_cache/
31
+
32
+ # Jupyter
33
+ .ipynb_checkpoints/
34
+ *.ipynb
35
+
36
+ # Local dev / secrets
37
+ .env
38
+
39
+ # OS
40
+ .DS_Store
41
+ Thumbs.db
42
+
43
+ # IDE
44
+ .idea/
45
+ .vscode/
46
+ *.swp
47
+
48
+ # Build
49
+ *.whl
50
+ *.tar.gz
51
+ /main.py
52
+ /local.py
53
+ /tmp
@@ -0,0 +1,182 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source lists, discussion forums, and other communication systems managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claim embodied in the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, copy, modify, merge,
121
+ publish, distribute, sublicense, and/or sell copies of the Work
122
+ derivative works, provided Your use, reproduction, and distribution
123
+ of the Work otherwise complies with the conditions stated in this
124
+ License.
125
+
126
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
127
+ any Contribution intentionally submitted for inclusion in the Work
128
+ by You to the Licensor shall be under the terms and conditions of
129
+ this License, without any additional terms or conditions.
130
+ Notwithstanding the above, nothing herein shall supersede or modify
131
+ the terms of any separate license agreement you may have executed
132
+ with Licensor regarding such Contributions.
133
+
134
+ 6. Trademarks. This License does not grant permission to use the trade
135
+ names, trademarks, service marks, or product names of the Licensor,
136
+ except as required for reasonable and customary use in describing the
137
+ origin of the Work and reproducing the content of the NOTICE file.
138
+
139
+ 7. Disclaimer of Warranty. Unless required by applicable law or
140
+ agreed to in writing, Licensor provides the Work (and each
141
+ Contributor provides its Contributions) on an "AS IS" BASIS,
142
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
143
+ implied, including, without limitation, any warranties or conditions
144
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
145
+ PARTICULAR PURPOSE. You are solely responsible for determining the
146
+ appropriateness of using or reproducing the Work and assume any
147
+ risks associated with Your exercise of permissions under this License.
148
+
149
+ 8. Limitation of Liability. In no event and under no legal theory,
150
+ whether in tort (including negligence), contract, or otherwise,
151
+ unless required by applicable law (such as deliberate and grossly
152
+ negligent acts) or agreed to in writing, shall any Contributor be
153
+ liable to You for damages, including any direct, indirect, special,
154
+ incidental, or exemplary damages of any character arising as a
155
+ result of this License or out of the use or inability to use the
156
+ Work (including but not limited to damages for loss of goodwill,
157
+ work stoppage, computer failure or malfunction, or all other
158
+ commercial damages or losses), even if such Contributor has been
159
+ advised of the possibility of such damages.
160
+
161
+ 9. Accepting Warranty or Additional Liability. While redistributing
162
+ the Work or Derivative Works thereof, You may choose to offer, and
163
+ charge a fee for, acceptance of support, warranty, indemnity, or
164
+ other liability obligations and/or rights consistent with this
165
+ License. However, in accepting such obligations, You may offer only
166
+ conditions consistent with this License.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ Copyright 2024 Invisibl Cloud
171
+
172
+ Licensed under the Apache License, Version 2.0 (the "License");
173
+ you may not use this file except in compliance with the License.
174
+ You may obtain a copy of the License at
175
+
176
+ http://www.apache.org/licenses/LICENSE-2.0
177
+
178
+ Unless required by applicable law or agreed to in writing, software
179
+ distributed under the License is distributed on an "AS IS" BASIS,
180
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
181
+ See the License for the specific language governing permissions and
182
+ limitations under the License.
@@ -0,0 +1,25 @@
1
+ .PHONY: install test check lint fmt build clean
2
+
3
+ install:
4
+ uv sync --extra dev --extra dotenv
5
+
6
+ test:
7
+ uv run pytest tests/ -v
8
+
9
+ check:
10
+ uv run python -m py_compile quark_tre_sdk/tre.py quark_tre_sdk/__init__.py
11
+ @echo "syntax OK"
12
+
13
+ lint: check
14
+ uv run ruff check quark_tre_sdk/
15
+ uv run ruff format --check quark_tre_sdk/
16
+
17
+ fmt:
18
+ uv run ruff format quark_tre_sdk/
19
+ uv run ruff check --fix quark_tre_sdk/
20
+
21
+ build:
22
+ uv build
23
+
24
+ clean:
25
+ rm -rf dist/ .pytest_cache/ __pycache__ quark_tre_sdk/__pycache__
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: quark-tre-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Quark TRE Platform
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.9
7
+ Requires-Dist: pandas>=1.5
8
+ Requires-Dist: pyathena[pandas]>=3.0
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest-mock>=3.0; extra == 'dev'
11
+ Requires-Dist: pytest>=7.0; extra == 'dev'
12
+ Requires-Dist: python-dotenv>=1.0; extra == 'dev'
13
+ Requires-Dist: ruff>=0.4; extra == 'dev'
14
+ Provides-Extra: dotenv
15
+ Requires-Dist: python-dotenv>=1.0; extra == 'dotenv'
@@ -0,0 +1,174 @@
1
+ # quark-tre-sdk
2
+
3
+ Python SDK for the Quark TRE Platform.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install quark-tre-sdk
9
+
10
+ # With .env file support
11
+ pip install 'quark-tre-sdk[dotenv]'
12
+ ```
13
+
14
+ Requires Python 3.9+. Dependencies: `pyathena[pandas]`, `pandas`.
15
+
16
+ ```bash
17
+ # Optional: CloudWatch log streaming (for .logs())
18
+ pip install boto3
19
+
20
+ # Optional: Parquet export (for .export(..., format="parquet"))
21
+ pip install pyarrow
22
+ ```
23
+
24
+ The package ships a `py.typed` marker, so mypy and Pyright pick up type hints automatically with no extra configuration.
25
+
26
+ ## Quickstart
27
+
28
+ ```python
29
+ from quark_tre_sdk import TRE, parse_filter
30
+
31
+ # Config from TRE_CATALOG / TRE_WORKGROUP env vars; region auto-detected via EC2 IMDSv2
32
+ # Auto-loads .env if python-dotenv is installed
33
+ tre = TRE()
34
+
35
+ # -- Discover accessible cohorts --
36
+ df = tre.cohorts() # cohort_id, cohort_name, create_date, dataset_names
37
+
38
+ # -- Cohort analytics --
39
+ ctx = tre.cohort("my-cohort")
40
+
41
+ df = ctx.demographics() # gender / race / ethnicity / yearOfBirth / personsCount
42
+ df = ctx.conditions() # top conditions + unique condition list
43
+ df = ctx.drugs() # top drugs + unique drug list
44
+ df = ctx.age_plot() # age at first drug exposure
45
+ df = ctx.age_plot(plot="condition") # age at first condition occurrence
46
+ df = ctx.km_survival() # Kaplan-Meier survival (single-arm)
47
+ df = ctx.km_survival_multi_arm(1125315, 1127078) # KM two-arm with log-rank test
48
+ df = ctx.person_count() # total persons in cohort
49
+ df = ctx.persons(limit=1000) # cohort members — limit required, max 10000
50
+ df = ctx.persons(limit=1000, offset=1000) # paginate
51
+ df = ctx.datasets() # datasets the cohort spans
52
+
53
+ # -- Per-person --
54
+ p = ctx.person("P00123456")
55
+
56
+ df = p.drug_timeline() # one row per drug exposure
57
+ df = p.drug_table() # full drug table with dosing
58
+ df = p.condition_timeline() # one row per condition occurrence
59
+ df = p.condition_table() # full condition table
60
+ df = p.variant_frequency() # variant mutation frequency by specimen
61
+ df = p.person_profile() # demographic profile
62
+ df = p.person_sankey() # condition status for Sankey diagram
63
+ df = p.specimen_procedure_table() # specimens + linked procedures
64
+
65
+ # -- Per-specimen --
66
+ s = ctx.specimen("SP-2024-0042")
67
+
68
+ df = s.specimen_detail() # specimen metadata
69
+ df = s.specimen_variants() # full variant annotation table (28 columns)
70
+ df = s.specimen_variants(limit=100) # paginated
71
+ df = s.specimen_variants(limit=100, offset=100) # next page
72
+
73
+ # -- Specimen summary (cohort-level) --
74
+ df = ctx.specimen_summary() # aggregate specimen counts, types, days range
75
+
76
+ # -- Cache management --
77
+ info = ctx.cache_info() # L1/L2 cache status for this cohort's agg queries
78
+ ctx.invalidate_cache() # flush cached results (force re-run on next query)
79
+
80
+ # -- Preflight validation --
81
+ result = ctx.validate() # dict: ok, cohort, table_count, tables, missing, errors
82
+ if not result["ok"]:
83
+ print(result["errors"])
84
+
85
+ # -- Export to file (Parquet / CSV / JSON) --
86
+ n = ctx.export_parquet("demographics_all", "/tmp/demo.parquet") # Parquet (requires pyarrow)
87
+ n = ctx.export_csv("persons", "persons.csv") # CSV
88
+ n = ctx.export_json("conditions_all", "conditions.json") # JSON
89
+ # Or use the generic form with format= argument:
90
+ n = ctx.export("demographics_all", "/tmp/demo.parquet", format="parquet")
91
+
92
+ # -- Async queries (non-blocking, for slow 10-30s queries) --
93
+ future = ctx.age_plot_async(plot="condition") # starts immediately, returns QueryFuture
94
+ future2 = ctx.km_survival_async() # fire a second query in parallel
95
+ df1 = future.result() # block until done, raises on error
96
+ df2 = future2.result()
97
+ future.done() # True / False — non-blocking poll
98
+ future.cancel() # cancel if not yet started
99
+
100
+ # Generic async variant — works for any CohortContext method:
101
+ future = ctx.async_query("km_survival_multi_arm", concept_id_1=1125315, concept_id_2=1127078)
102
+ df = future.result()
103
+
104
+ # -- Debugging: CloudWatch Lambda logs --
105
+ # Requires boto3 and logs:FilterLogEvents IAM permission on /aws/lambda/{workgroup}
106
+ df = ctx.age_plot(plot="condition") # or any query that triggers the connector
107
+ ctx.logs() # stream Lambda logs for the last query
108
+ ctx.logs(minutes=10) # look back further (default 5 min)
109
+ ctx.logs(show_sql=True) # include full SQL in log output (truncated by default)
110
+ tre.logs() # same, at TRE level
111
+
112
+ # -- Global analytics (cross-cohort, no restriction) --
113
+ # tre.cohort() with no args is equivalent to tre.global_()
114
+ g = tre.cohort()
115
+
116
+ df = g.demographics()
117
+ df = g.conditions()
118
+ df = g.drugs()
119
+ df = g.age_plot(plot="condition")
120
+ df = g.km_survival()
121
+ df = g.person_count()
122
+
123
+ # -- Filtering global analytics --
124
+ # Pass a SQL-like expression string or a StructuredQuery dict
125
+ df = g.demographics(filter="drug = 1125315")
126
+ df = g.person_count(filter="drug = 1125315 AND gene IN ('EGFR', 'KRAS')")
127
+ df = g.demographics(filter="(drug = 1125315 OR drug = 1127078) AND gender = 8507")
128
+
129
+ # Field shortcuts: drug, condition, gender, race, ethnicity, dataset
130
+ # Operators: = != < > <= >= IN NOT IN
131
+ # Logical: AND OR ( )
132
+
133
+ # Inspect the produced StructuredQuery dict before sending
134
+ print(parse_filter("drug = 1125315 AND gene = 'EGFR'"))
135
+
136
+ # -- Schema / table / column discovery --
137
+ df = tre.schemas() # all connector schemas
138
+ df = tre.cohort("my-cohort").tables() # virtual tables in cohort's _agg schema
139
+ df = tre.cohort("my-cohort").columns("demographics_all") # columns for a table
140
+ df = tre.global_().tables() # virtual tables in global_agg
141
+ df = tre.global_().columns("conditions_all")
142
+
143
+ # -- Raw SQL via schema properties --
144
+ conn = tre._connect()
145
+ import pandas as pd
146
+ df = pd.read_sql(f'SELECT * FROM {ctx.agg_schema}."demographics_all"', conn)
147
+ df = pd.read_sql(f'SELECT * FROM {ctx.omop_schema}."drug_exposure" LIMIT 10', conn)
148
+ ```
149
+
150
+ ## Configuration
151
+
152
+ | Priority | Source | Variables |
153
+ |---|---|---|
154
+ | 1 | Constructor args | `catalog=`, `workgroup=`, `region=` |
155
+ | 2 | Environment vars | `TRE_CATALOG`, `TRE_WORKGROUP`, `AWS_DEFAULT_REGION` |
156
+ | 3 | EC2 IMDSv2 | region only |
157
+
158
+ Copy `.env.example` → `.env` and fill in your values. With `pip install 'quark-tre-sdk[dotenv]'` the SDK loads `.env` automatically.
159
+
160
+ The Athena connection is lazy — created on the first query call. Managed workgroups are supported (no S3 staging dir required).
161
+
162
+ ## Development
163
+
164
+ ```bash
165
+ make install # install dev dependencies
166
+ make check # syntax check (py_compile)
167
+ make test # run tests
168
+ make lint # ruff check + format check
169
+ make fmt # auto-format
170
+ ```
171
+
172
+ ## Documentation
173
+
174
+ Full API reference: [`docs/sdk-reference.md`](docs/sdk-reference.md)