chowclassifier 1.0.10__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,117 @@
1
+ Creative Commons Attribution-NonCommercial 4.0 International Public License
2
+
3
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
4
+
5
+ Section 1 – Definitions.
6
+
7
+ a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
8
+
9
+ b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
10
+
11
+ c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
12
+
13
+ d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
14
+
15
+ e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
16
+
17
+ f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
18
+
19
+ g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
20
+
21
+ h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
22
+
23
+ i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
24
+
25
+ j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
26
+
27
+ k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
28
+
29
+ l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
30
+
31
+ Section 2 – Scope.
32
+
33
+ a. License grant.
34
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
35
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
36
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
37
+ 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
38
+ 3. Term. The term of this Public License is specified in Section 6(a).
39
+ 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
40
+ 5. Downstream recipients.
41
+ A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
42
+ B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
43
+ 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
44
+
45
+ b. Other rights.
46
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
47
+ 2. Patent and trademark rights are not licensed under this Public License.
48
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
49
+
50
+ Section 3 – License Conditions.
51
+
52
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
53
+
54
+ a. Attribution.
55
+ 1. If You Share the Licensed Material (including in modified form), You must:
56
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
57
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
58
+ ii. a copyright notice;
59
+ iii. a notice that refers to this Public License;
60
+ iv. a notice that refers to the disclaimer of warranties;
61
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
62
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
63
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
64
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
65
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
66
+ 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
67
+
68
+ Section 4 – Sui Generis Database Rights.
69
+
70
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
71
+
72
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
73
+ b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
74
+ c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
75
+
76
+ For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
77
+
78
+ Section 5 – Disclaimer of Warranties and Limitation of Liability.
79
+
80
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
81
+
82
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
83
+
84
+ c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
85
+
86
+ Section 6 – Term and Termination.
87
+
88
+ a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
89
+
90
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
91
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
92
+ 2. upon express reinstatement by the Licensor.
93
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
94
+
95
+ c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
96
+
97
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
98
+
99
+ Section 7 – Other Terms and Conditions.
100
+
101
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
102
+
103
+ b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
104
+
105
+ Section 8 – Interpretation.
106
+
107
+ a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
108
+
109
+ b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
110
+
111
+ c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
112
+
113
+ d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
114
+
115
+ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
116
+
117
+ Creative Commons may be contacted at creativecommons.org.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: chowclassifier
3
+ Version: 1.0.10
4
+ Summary: Classification of time trends using Chow test
5
+ Author-email: Luc Miaz <luc@miaz.ch>
6
+ License-Expression: CC-BY-NC-4.0
7
+ Project-URL: Homepage, https://chowclassifier.readthedocs.io/en/latest/
8
+ Keywords: chow,time-trends
9
+ Classifier: Programming Language :: Python
10
+ Classifier: Natural Language :: English
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.6
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: matplotlib>=3.5.0
17
+ Requires-Dist: numpy>=1.19.4
18
+ Requires-Dist: pandas>=1.1.5
19
+ Requires-Dist: openpyxl
20
+ Requires-Dist: scipy>=1.1.5
21
+ Requires-Dist: seaborn>=0.11.2
22
+ Requires-Dist: statsmodels>=0.13.1
23
+ Requires-Dist: tqdm>=4.65.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # ChowClassifier
29
+
30
+ ## Description
31
+ There are many application where it is useful to analyse rapidly a large number of time-series for overall trends and possible breakpoint at which the trend changes. For example, spotting increasing trends in potential contaminants concentration from the outputs of non-target screening from high resolution mass spectrometry.
32
+
33
+ ChowClassifier aims to solve this. It is a script that performs a series of Chow tests on a time-indexed dataset to determine if a breakpoint in the time trends is probable. Two classes `Chow` and `ChewData` enable to perform the tests, generate plots and export the results in `csv` and `excel`. Dataset with groups can be ran simultaneously with `ChewData` indicating with `namecol` the name of the grouping column. Calling `run` on a `ChewData` instance will create an instance of `Chow` for each group and classify them into the following categories.
34
+
35
+ | Breakpoint ? | Category | Description |
36
+ |--------------|----------|-------------|
37
+ | No |N | non-significant overall trend |
38
+ | No | I | significant increasing overall trend |
39
+ | No | D | significant decreasing overall trend |
40
+ | Yes | NN | non-significant trend on set1 and non-significant trend on set2 |
41
+ | Yes | NI | non-significant trend on set1 and significant increasing trend on set2 |
42
+ | Yes | ND | non-significant trend on set1 ans significant decreasing trend on set2 |
43
+ | Yes | IN | significant increasing trend on set1 and non-significant trend on set2 |
44
+ | Yes | ID | significant increasing trend on set1 and significant decreasing trend on set2 |
45
+ | Yes | iI | significant increasing trend on both set1 and set2 with greater increase in set2 |
46
+ | Yes | Ii | significant increasing trend on both set1 and set2 with greater increase in set1 |
47
+ | Yes | DN | significant decreasing trend on set1 and non-significant trend on set2 |
48
+ | Yes | DI | significant decreasing trend on set1 and significant increasing trend on set2 |
49
+ | Yes | dD | significant decreasing trend on both set1 and set2 with greater decrease in set2 |
50
+ | Yes | Dd | significant decreasing trend on both set1 and set2 with greater decrease in set1 |
51
+
52
+ where set1 and set2 indicate respectively the data before the breakpoint and after. The decision process for this classification is shown in the following schema:
53
+
54
+
55
+ ![Image unavailable, see schema on readthedocs.](img/Categorisation_TT.png)
56
+
57
+
58
+ ## Chow test
59
+ Chow test was first derived by Gregory Chow[^1] in 1960 and later by Franklin Fisher[^2]. We test the significance of the breakpoint under the null hypothesis $Z=\frac{S_c-(S_1+S_2)}{S_1+S_2}\cdot\frac{N_1+N_2-2\cdot k}{k}$ where $k=3$ is the total number of parameters. This follows a F-distribution with $3$ and $N_1+N_2-6$ degrees of freedom, where $S_C$ is the sum of squared residuals of the regression on the full time series, $S_1$, $S_2$ are the sums of squared residuals of the regression on the first, and respectively, the second half of the time series and $N_1$, $N_2$ are the number of observation for each half. See also [^3].
60
+
61
+ ## Installation
62
+ ```
63
+ pip install chowclassifier
64
+ ```
65
+
66
+ ## Citation
67
+
68
+ If you use this package in your research, please cite:
69
+
70
+ Influence of Season on Biodegradation Rates in Rivers
71
+ Run Tian, Malte Posselt, Luc T. Miaz, Kathrin Fenner, and Michael S. McLachlan
72
+ Environmental Science & Technology 2024 58 (16), 7144-7153
73
+ DOI: [10.1021/acs.est.3c10541](https://doi.org/10.1021/acs.est.3c10541)
74
+
75
+ [Download citation](https://pubs.acs.org/action/downloadCitation?doi=10.1021%2Facs.est.3c10541&include=cit&format=ris&direct=true&downloadFileName=acs.est.3c10541)
76
+
77
+ ## Use
78
+ The script can be ran on any file with `python -m chowclassifier -f path/to/file/filename.csv -X xcol -y ycol -n grouping_name` or it can be imported:
79
+
80
+ ```python
81
+ from chowclassifier import ChewData
82
+ # define the path to data
83
+ filepath = "example/data"
84
+ # define the name of the file containing the data (with extension)
85
+ filename = "stocks.csv"
86
+ # define the path where figures will be saved
87
+ savingpath_figures = 'example/fig'
88
+ # what name has the X/time column?
89
+ timecol = 'Date'
90
+ # what name has the y/value column?
91
+ ycol = 'Close'
92
+ # what level of confidence? Note, when
93
+ # testing multiple breakpoint, a Bonferroni correction will be applied
94
+ alpha = 0.01
95
+ # what level of confidence? Note, when
96
+ # testing multiple breakpoint, a Bonferroni correction will be applied
97
+ alpha = 0.01
98
+ # initial breakpoint ?
99
+ initial_breakpoint = None
100
+
101
+ C = ChewData(filename = f"{'/'.join([x for x in [filepath,filename] if x not in [None,'']])}",
102
+ timecol = timecol,# name of time column (used as x-axis)
103
+ ycol = ycol,# name for value column (used as y-axis) Leave blank if multiple
104
+ alpha = alpha# level of confidence to use
105
+ )
106
+ timecol = timecol,# name of time column (used as x-axis)
107
+ ycol = ycol,# name for value column (used as y-axis) Leave blank if multiple
108
+ alpha = alpha# level of confidence to use
109
+ )
110
+
111
+ ########## use the code line below if your X/time column is not a number, e.g. a date
112
+ ########## comment it otherwise
113
+ # C.parse_timecol(date_format = '%Y-%m-%d') #
114
+ # C.parse_timecol(date_format = '%Y-%m-%d') #
115
+
116
+ C.run(initial_breakpoint = initial_breakpoint)
117
+ C.plot(xlabel = 'time',# label for x axis
118
+ ylabel='value',# label for y axis
119
+ title = "Chow Classification",# title of the main plot
120
+ filename = f"{'/'.join([x for x in [savingpath_figures,filename] if x not in [None,'']])}.png",# filename for the figure
121
+ figsize=(16,8),# figure size
122
+ sharey=True # whether the individual plots are forced to share y axis
123
+ )
124
+ C.plot_individually(savingpath = savingpath_figures,# Saving path for the figures
125
+ format = 'png',# figure format
126
+ xlabel = 'time',# label for x axis
127
+ ylabel='value',# label for y axis
128
+ )
129
+
130
+ C.plot_by_group('g',
131
+ savingpath = savingpath_figures,# Saving path for the figures
132
+ format = 'png',# figure format
133
+ xlabel = 'time',# label for x axis
134
+ ylabel='value',# label for y axis
135
+ plot_overall = True,# Whether to plot an overall trend across groups (including confidence inverval fill)
136
+ plot_individual_fill = True# Whether to plot individual confidence inverval fills
137
+ )
138
+ C.run(initial_breakpoint = initial_breakpoint)
139
+ C.plot(xlabel = 'time',# label for x axis
140
+ ylabel='value',# label for y axis
141
+ title = "Chow Classification",# title of the main plot
142
+ filename = f"{'/'.join([x for x in [savingpath_figures,filename] if x not in [None,'']])}.png",# filename for the figure
143
+ figsize=(16,8),# figure size
144
+ sharey=True # whether the individual plots are forced to share y axis
145
+ )
146
+ C.plot_individually(savingpath = savingpath_figures,# Saving path for the figures
147
+ format = 'png',# figure format
148
+ xlabel = 'time',# label for x axis
149
+ ylabel='value',# label for y axis
150
+ )
151
+
152
+ C.plot_by_group('g',
153
+ savingpath = savingpath_figures,# Saving path for the figures
154
+ format = 'png',# figure format
155
+ xlabel = 'time',# label for x axis
156
+ ylabel='value',# label for y axis
157
+ plot_overall = True,# Whether to plot an overall trend across groups (including confidence inverval fill)
158
+ plot_individual_fill = True# Whether to plot individual confidence inverval fills
159
+ )
160
+ ```
161
+
162
+ ## References
163
+
164
+ [^1]: Chow, Gregory C. ‘Test of Equality Between Sets of Coefficients in Two Linear Regressions’. Econometrica 28, no. 3 (1960): 591–605. [jstor.org/stable/1910133](https://www.jstor.org/stable/1910133).
165
+
166
+ [^2]: Fisher, Franklin M. ‘Tests of Equality Between Sets of Coefficients in Two Linear Regressions: An Expository Note’. Econometrica2 38, no. 2 (1970): 361–66. [jstor.org/stable/1913018](https://www.jstor.org/stable/1913018).
167
+
168
+ [^3]: *Chow test* entry on Wikipedia: https://en.wikipedia.org/wiki/Chow_test
169
+
170
+ ## Version changes
171
+
172
+ 1.0.10 Minor addition, with show_legend option
173
+ 1.0.9 Correction of bugs, added jupyter notebook example.
174
+ 1.0.8 Correction of bugs.
175
+ 1.0.7 Split main classes and utilities in multiple files, added option to ChewData.plot to have grouped trends, corrected input parsing, corrected inconsistancy with intial_breakpoint/margin
176
+ Added option to change linestyle by trend individually
177
+ 1.0.5 Added option to plot confidence interval fill for individual group trends
178
+ 1.0.4 Added support for plotting individual trends by group
179
+ 1.0.3 Bug correction
180
+ 1.0.2 Added support to parse full csv/excel automatically
181
+ 1.0.1 First implementation of algorithm
@@ -0,0 +1,154 @@
1
+ # ChowClassifier
2
+
3
+ ## Description
4
+ There are many application where it is useful to analyse rapidly a large number of time-series for overall trends and possible breakpoint at which the trend changes. For example, spotting increasing trends in potential contaminants concentration from the outputs of non-target screening from high resolution mass spectrometry.
5
+
6
+ ChowClassifier aims to solve this. It is a script that performs a series of Chow tests on a time-indexed dataset to determine if a breakpoint in the time trends is probable. Two classes `Chow` and `ChewData` enable to perform the tests, generate plots and export the results in `csv` and `excel`. Dataset with groups can be ran simultaneously with `ChewData` indicating with `namecol` the name of the grouping column. Calling `run` on a `ChewData` instance will create an instance of `Chow` for each group and classify them into the following categories.
7
+
8
+ | Breakpoint ? | Category | Description |
9
+ |--------------|----------|-------------|
10
+ | No |N | non-significant overall trend |
11
+ | No | I | significant increasing overall trend |
12
+ | No | D | significant decreasing overall trend |
13
+ | Yes | NN | non-significant trend on set1 and non-significant trend on set2 |
14
+ | Yes | NI | non-significant trend on set1 and significant increasing trend on set2 |
15
+ | Yes | ND | non-significant trend on set1 ans significant decreasing trend on set2 |
16
+ | Yes | IN | significant increasing trend on set1 and non-significant trend on set2 |
17
+ | Yes | ID | significant increasing trend on set1 and significant decreasing trend on set2 |
18
+ | Yes | iI | significant increasing trend on both set1 and set2 with greater increase in set2 |
19
+ | Yes | Ii | significant increasing trend on both set1 and set2 with greater increase in set1 |
20
+ | Yes | DN | significant decreasing trend on set1 and non-significant trend on set2 |
21
+ | Yes | DI | significant decreasing trend on set1 and significant increasing trend on set2 |
22
+ | Yes | dD | significant decreasing trend on both set1 and set2 with greater decrease in set2 |
23
+ | Yes | Dd | significant decreasing trend on both set1 and set2 with greater decrease in set1 |
24
+
25
+ where set1 and set2 indicate respectively the data before the breakpoint and after. The decision process for this classification is shown in the following schema:
26
+
27
+
28
+ ![Image unavailable, see schema on readthedocs.](img/Categorisation_TT.png)
29
+
30
+
31
+ ## Chow test
32
+ Chow test was first derived by Gregory Chow[^1] in 1960 and later by Franklin Fisher[^2]. We test the significance of the breakpoint under the null hypothesis $Z=\frac{S_c-(S_1+S_2)}{S_1+S_2}\cdot\frac{N_1+N_2-2\cdot k}{k}$ where $k=3$ is the total number of parameters. This follows a F-distribution with $3$ and $N_1+N_2-6$ degrees of freedom, where $S_C$ is the sum of squared residuals of the regression on the full time series, $S_1$, $S_2$ are the sums of squared residuals of the regression on the first, and respectively, the second half of the time series and $N_1$, $N_2$ are the number of observation for each half. See also [^3].
33
+
34
+ ## Installation
35
+ ```
36
+ pip install chowclassifier
37
+ ```
38
+
39
+ ## Citation
40
+
41
+ If you use this package in your research, please cite:
42
+
43
+ Influence of Season on Biodegradation Rates in Rivers
44
+ Run Tian, Malte Posselt, Luc T. Miaz, Kathrin Fenner, and Michael S. McLachlan
45
+ Environmental Science & Technology 2024 58 (16), 7144-7153
46
+ DOI: [10.1021/acs.est.3c10541](https://doi.org/10.1021/acs.est.3c10541)
47
+
48
+ [Download citation](https://pubs.acs.org/action/downloadCitation?doi=10.1021%2Facs.est.3c10541&include=cit&format=ris&direct=true&downloadFileName=acs.est.3c10541)
49
+
50
+ ## Use
51
+ The script can be ran on any file with `python -m chowclassifier -f path/to/file/filename.csv -X xcol -y ycol -n grouping_name` or it can be imported:
52
+
53
+ ```python
54
+ from chowclassifier import ChewData
55
+ # define the path to data
56
+ filepath = "example/data"
57
+ # define the name of the file containing the data (with extension)
58
+ filename = "stocks.csv"
59
+ # define the path where figures will be saved
60
+ savingpath_figures = 'example/fig'
61
+ # what name has the X/time column?
62
+ timecol = 'Date'
63
+ # what name has the y/value column?
64
+ ycol = 'Close'
65
+ # what level of confidence? Note, when
66
+ # testing multiple breakpoint, a Bonferroni correction will be applied
67
+ alpha = 0.01
68
+ # what level of confidence? Note, when
69
+ # testing multiple breakpoint, a Bonferroni correction will be applied
70
+ alpha = 0.01
71
+ # initial breakpoint ?
72
+ initial_breakpoint = None
73
+
74
+ C = ChewData(filename = f"{'/'.join([x for x in [filepath,filename] if x not in [None,'']])}",
75
+ timecol = timecol,# name of time column (used as x-axis)
76
+ ycol = ycol,# name for value column (used as y-axis) Leave blank if multiple
77
+ alpha = alpha# level of confidence to use
78
+ )
79
+ timecol = timecol,# name of time column (used as x-axis)
80
+ ycol = ycol,# name for value column (used as y-axis) Leave blank if multiple
81
+ alpha = alpha# level of confidence to use
82
+ )
83
+
84
+ ########## use the code line below if your X/time column is not a number, e.g. a date
85
+ ########## comment it otherwise
86
+ # C.parse_timecol(date_format = '%Y-%m-%d') #
87
+ # C.parse_timecol(date_format = '%Y-%m-%d') #
88
+
89
+ C.run(initial_breakpoint = initial_breakpoint)
90
+ C.plot(xlabel = 'time',# label for x axis
91
+ ylabel='value',# label for y axis
92
+ title = "Chow Classification",# title of the main plot
93
+ filename = f"{'/'.join([x for x in [savingpath_figures,filename] if x not in [None,'']])}.png",# filename for the figure
94
+ figsize=(16,8),# figure size
95
+ sharey=True # whether the individual plots are forced to share y axis
96
+ )
97
+ C.plot_individually(savingpath = savingpath_figures,# Saving path for the figures
98
+ format = 'png',# figure format
99
+ xlabel = 'time',# label for x axis
100
+ ylabel='value',# label for y axis
101
+ )
102
+
103
+ C.plot_by_group('g',
104
+ savingpath = savingpath_figures,# Saving path for the figures
105
+ format = 'png',# figure format
106
+ xlabel = 'time',# label for x axis
107
+ ylabel='value',# label for y axis
108
+ plot_overall = True,# Whether to plot an overall trend across groups (including confidence inverval fill)
109
+ plot_individual_fill = True# Whether to plot individual confidence inverval fills
110
+ )
111
+ C.run(initial_breakpoint = initial_breakpoint)
112
+ C.plot(xlabel = 'time',# label for x axis
113
+ ylabel='value',# label for y axis
114
+ title = "Chow Classification",# title of the main plot
115
+ filename = f"{'/'.join([x for x in [savingpath_figures,filename] if x not in [None,'']])}.png",# filename for the figure
116
+ figsize=(16,8),# figure size
117
+ sharey=True # whether the individual plots are forced to share y axis
118
+ )
119
+ C.plot_individually(savingpath = savingpath_figures,# Saving path for the figures
120
+ format = 'png',# figure format
121
+ xlabel = 'time',# label for x axis
122
+ ylabel='value',# label for y axis
123
+ )
124
+
125
+ C.plot_by_group('g',
126
+ savingpath = savingpath_figures,# Saving path for the figures
127
+ format = 'png',# figure format
128
+ xlabel = 'time',# label for x axis
129
+ ylabel='value',# label for y axis
130
+ plot_overall = True,# Whether to plot an overall trend across groups (including confidence inverval fill)
131
+ plot_individual_fill = True# Whether to plot individual confidence inverval fills
132
+ )
133
+ ```
134
+
135
+ ## References
136
+
137
+ [^1]: Chow, Gregory C. ‘Test of Equality Between Sets of Coefficients in Two Linear Regressions’. Econometrica 28, no. 3 (1960): 591–605. [jstor.org/stable/1910133](https://www.jstor.org/stable/1910133).
138
+
139
+ [^2]: Fisher, Franklin M. ‘Tests of Equality Between Sets of Coefficients in Two Linear Regressions: An Expository Note’. Econometrica2 38, no. 2 (1970): 361–66. [jstor.org/stable/1913018](https://www.jstor.org/stable/1913018).
140
+
141
+ [^3]: *Chow test* entry on Wikipedia: https://en.wikipedia.org/wiki/Chow_test
142
+
143
+ ## Version changes
144
+
145
+ 1.0.10 Minor addition, with show_legend option
146
+ 1.0.9 Correction of bugs, added jupyter notebook example.
147
+ 1.0.8 Correction of bugs.
148
+ 1.0.7 Split main classes and utilities in multiple files, added option to ChewData.plot to have grouped trends, corrected input parsing, corrected inconsistancy with intial_breakpoint/margin
149
+ Added option to change linestyle by trend individually
150
+ 1.0.5 Added option to plot confidence interval fill for individual group trends
151
+ 1.0.4 Added support for plotting individual trends by group
152
+ 1.0.3 Bug correction
153
+ 1.0.2 Added support to parse full csv/excel automatically
154
+ 1.0.1 First implementation of algorithm
@@ -0,0 +1,6 @@
1
+ # __init__.py
2
+
3
+ # Version of the chowclassifier package
4
+ __version__ = "1.0.9"
5
+ from chowclassifier.chow import Chow
6
+ from chowclassifier.chewdata import ChewData
@@ -0,0 +1,81 @@
1
+ # __main__.py
2
+ import argparse
3
+ from chowclassifier.chewdata import ChewData
4
+
5
+
6
+ def main():
7
+ """
8
+ run analysis on given data
9
+
10
+ :params -f, --filename: filename
11
+ :params -s, --sep: separator for parsing the filename (if type csv)
12
+ :params -X, --timecol: timecol
13
+ :params -y, --ycol: ycol
14
+ :params -n, --namecol: name of column for groupby
15
+ :params -b, --breakpoint: initial breakpoint (if None, midpoint will be taken)
16
+ :params -k, --breakpoints: candidates for breakpoints (list)
17
+ :params -m, --margin: margin around initial breakpoint
18
+ :params -o, --output: filename for the excel or csv file output
19
+ :params -p, --path: path where the figures will be saved
20
+ :params -a, --alpha: significance level in (0,1)
21
+ :params --no-figures: Do not export figures
22
+ :params --no-table: Do not export results table
23
+ :params --nrows: Numbers of rows in the grouped figure (leave ncols blank)
24
+ :params --ncols: Number of columns in the groupe figure (leave nrows blank)
25
+ :params --fig-title: title of the figure
26
+ :params --xlabel: label of the x axis
27
+ :params --ylabel: label of the y axis
28
+ :params --sharey: share y axis across subplots
29
+ :params --figsize: size of figures
30
+ """
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument('-f','--filename', type=str)
33
+ parser.add_argument('-X','--timecol', type=str, default = 'date')
34
+ parser.add_argument('-y','--ycol', type=str, default = 'value')
35
+ parser.add_argument('-n','--namecol', type=str, default = 'name')
36
+ parser.add_argument('-b','--breakpoint', type=float, default = None)
37
+ parser.add_argument('-k','--breakpoints', type=list, default = None)
38
+ parser.add_argument('-m','--margin', type=int, default = 5)
39
+ parser.add_argument('-o','--output', type=str, default = 'output.xlsx')
40
+ parser.add_argument('-p','--path', type=str, default = 'figs')
41
+ parser.add_argument('-s','--sep', type=str, default = ',')
42
+ parser.add_argument('-a','--alpha', type=float, default = 0.01)
43
+ parser.add_argument('--no-figures', type=bool, default = False)
44
+ parser.add_argument('--no-table', type=bool, default = False)
45
+ parser.add_argument('--nrows', type=int, default = None)
46
+ parser.add_argument('--ncols', type=int, default = 3)
47
+ parser.add_argument('--fig-title', type=str, default = '')
48
+ parser.add_argument('--fig-format', type=str, default = 'pdf')
49
+ parser.add_argument('--xlabel', type=str, default = 'X')
50
+ parser.add_argument('--ylabel', type=str, default = 'y')
51
+ parser.add_argument('--sharey', type=bool, default = True)
52
+ parser.add_argument('--figsize',type = list, default = (16,8))
53
+ args = parser.parse_args()
54
+ if args.filename is None:
55
+ print("No data given. Please pass filename as argument --filename 'data.csv'")
56
+ return None
57
+ C = ChewData(filename = args.filename,
58
+ namecol = args.namecol,
59
+ ycol = args.ycol,
60
+ timecol = args.timecol,
61
+ sep = args.sep,
62
+ margin = args.margin,
63
+ alpha = args.alpha,
64
+ initial_breakpoint = args.breakpoint,
65
+ breakpoints = args.breakpoints)
66
+ C.run()
67
+ if args.no_table is False:
68
+ C.save_to_file(filename = args.output, sep = args.sep)
69
+ if args.no_figures is False:
70
+ C.plot(f'output.{args.fig_format}',
71
+ nrows = args.nrows,
72
+ ncols = args.ncols,
73
+ sharey = args.sharey,
74
+ figsize = args.figsize
75
+ )
76
+ C.plot_individually(savingpath = args.path, format = args.fig_format)
77
+
78
+
79
+ if __name__ == "__main__":
80
+
81
+ main()