liuhangbiao SciCode commited on
Commit
aef2c56
·
0 Parent(s):

Duplicate from SciCode/SciCode-Domain-Code

Browse files

Co-authored-by: SciCodePile <SciCode@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +190 -0
  2. README.md +150 -0
  3. data/dataset_2D.csv +3 -0
  4. data/dataset_3D.csv +3 -0
  5. data/dataset_ADMET.csv +0 -0
  6. data/dataset_AMR.csv +3 -0
  7. data/dataset_Ab_initio.csv +3 -0
  8. data/dataset_Absorption.csv +3 -0
  9. data/dataset_Activation.csv +3 -0
  10. data/dataset_Agent_based_model.csv +3 -0
  11. data/dataset_Allele.csv +0 -0
  12. data/dataset_AlphaFold.csv +0 -0
  13. data/dataset_Anomaly_detection.csv +3 -0
  14. data/dataset_Antagonist.csv +3 -0
  15. data/dataset_Antibody.csv +3 -0
  16. data/dataset_Antigen.csv +3 -0
  17. data/dataset_Assay.csv +0 -0
  18. data/dataset_Autoregressive.csv +3 -0
  19. data/dataset_Bio.csv +3 -0
  20. data/dataset_Bio_foundation_model.csv +0 -0
  21. data/dataset_Biochemistry.csv +968 -0
  22. data/dataset_Bioengineering.csv +0 -0
  23. data/dataset_Bioinformatics.csv +3 -0
  24. data/dataset_Biologics.csv +3 -0
  25. data/dataset_Biology.csv +3 -0
  26. data/dataset_Biomarker.csv +3 -0
  27. data/dataset_Biomedical.csv +3 -0
  28. data/dataset_Biophysics.csv +0 -0
  29. data/dataset_Biosensors.csv +1614 -0
  30. data/dataset_Biotechnology.csv +3 -0
  31. data/dataset_CRISPR.csv +0 -0
  32. data/dataset_Cell_atlas.csv +3 -0
  33. data/dataset_Cell_biology.csv +0 -0
  34. data/dataset_Chemical_space.csv +3 -0
  35. data/dataset_Cheminformatics.csv +3 -0
  36. data/dataset_Chemistry.csv +3 -0
  37. data/dataset_Codon.csv +0 -0
  38. data/dataset_Compartmental_model.csv +3 -0
  39. data/dataset_Computational_Biochemistry.csv +0 -0
  40. data/dataset_Computational_Chemistry.csv +3 -0
  41. data/dataset_Computational_Materials.csv +3 -0
  42. data/dataset_Conformation.csv +0 -0
  43. data/dataset_Conjugate.csv +0 -0
  44. data/dataset_Coupled_cluster.csv +3 -0
  45. data/dataset_Crystal.csv +3 -0
  46. data/dataset_Cycle.csv +3 -0
  47. data/dataset_DFT.csv +3 -0
  48. data/dataset_DNA.csv +3 -0
  49. data/dataset_De_novo.csv +3 -0
  50. data/dataset_Design.csv +3 -0
.gitattributes ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/dataset_2D.csv filter=lfs diff=lfs merge=lfs -text
62
+ data/dataset_3D.csv filter=lfs diff=lfs merge=lfs -text
63
+ data/dataset_AMR.csv filter=lfs diff=lfs merge=lfs -text
64
+ data/dataset_Ab_initio.csv filter=lfs diff=lfs merge=lfs -text
65
+ data/dataset_Absorption.csv filter=lfs diff=lfs merge=lfs -text
66
+ data/dataset_Activation.csv filter=lfs diff=lfs merge=lfs -text
67
+ data/dataset_Agent_based_model.csv filter=lfs diff=lfs merge=lfs -text
68
+ data/dataset_Anomaly_detection.csv filter=lfs diff=lfs merge=lfs -text
69
+ data/dataset_Antagonist.csv filter=lfs diff=lfs merge=lfs -text
70
+ data/dataset_Antibody.csv filter=lfs diff=lfs merge=lfs -text
71
+ data/dataset_Antigen.csv filter=lfs diff=lfs merge=lfs -text
72
+ data/dataset_Autoregressive.csv filter=lfs diff=lfs merge=lfs -text
73
+ data/dataset_Bio.csv filter=lfs diff=lfs merge=lfs -text
74
+ data/dataset_Bioinformatics.csv filter=lfs diff=lfs merge=lfs -text
75
+ data/dataset_Biologics.csv filter=lfs diff=lfs merge=lfs -text
76
+ data/dataset_Biology.csv filter=lfs diff=lfs merge=lfs -text
77
+ data/dataset_Biomarker.csv filter=lfs diff=lfs merge=lfs -text
78
+ data/dataset_Biomedical.csv filter=lfs diff=lfs merge=lfs -text
79
+ data/dataset_Biotechnology.csv filter=lfs diff=lfs merge=lfs -text
80
+ data/dataset_Cell_atlas.csv filter=lfs diff=lfs merge=lfs -text
81
+ data/dataset_Chemical_space.csv filter=lfs diff=lfs merge=lfs -text
82
+ data/dataset_Cheminformatics.csv filter=lfs diff=lfs merge=lfs -text
83
+ data/dataset_Chemistry.csv filter=lfs diff=lfs merge=lfs -text
84
+ data/dataset_Compartmental_model.csv filter=lfs diff=lfs merge=lfs -text
85
+ data/dataset_Computational_Chemistry.csv filter=lfs diff=lfs merge=lfs -text
86
+ data/dataset_Computational_Materials.csv filter=lfs diff=lfs merge=lfs -text
87
+ data/dataset_Coupled_cluster.csv filter=lfs diff=lfs merge=lfs -text
88
+ data/dataset_Crystal.csv filter=lfs diff=lfs merge=lfs -text
89
+ data/dataset_Cycle.csv filter=lfs diff=lfs merge=lfs -text
90
+ data/dataset_DFT.csv filter=lfs diff=lfs merge=lfs -text
91
+ data/dataset_DNA.csv filter=lfs diff=lfs merge=lfs -text
92
+ data/dataset_De_novo.csv filter=lfs diff=lfs merge=lfs -text
93
+ data/dataset_Design.csv filter=lfs diff=lfs merge=lfs -text
94
+ data/dataset_Diagnostics.csv filter=lfs diff=lfs merge=lfs -text
95
+ data/dataset_Diffusion.csv filter=lfs diff=lfs merge=lfs -text
96
+ data/dataset_Discovery.csv filter=lfs diff=lfs merge=lfs -text
97
+ data/dataset_Disease.csv filter=lfs diff=lfs merge=lfs -text
98
+ data/dataset_Docking.csv filter=lfs diff=lfs merge=lfs -text
99
+ data/dataset_Drug.csv filter=lfs diff=lfs merge=lfs -text
100
+ data/dataset_Drug_repurpose.csv filter=lfs diff=lfs merge=lfs -text
101
+ data/dataset_Dynamics.csv filter=lfs diff=lfs merge=lfs -text
102
+ data/dataset_Electronic_structure.csv filter=lfs diff=lfs merge=lfs -text
103
+ data/dataset_Ensemble.csv filter=lfs diff=lfs merge=lfs -text
104
+ data/dataset_Enzyme.csv filter=lfs diff=lfs merge=lfs -text
105
+ data/dataset_Evolution.csv filter=lfs diff=lfs merge=lfs -text
106
+ data/dataset_Explainable_AI.csv filter=lfs diff=lfs merge=lfs -text
107
+ data/dataset_Finite_element_method.csv filter=lfs diff=lfs merge=lfs -text
108
+ data/dataset_First_principles_based_DFT.csv filter=lfs diff=lfs merge=lfs -text
109
+ data/dataset_Flow_matching.csv filter=lfs diff=lfs merge=lfs -text
110
+ data/dataset_Folding.csv filter=lfs diff=lfs merge=lfs -text
111
+ data/dataset_Free_energy_perturbation.csv filter=lfs diff=lfs merge=lfs -text
112
+ data/dataset_GAN.csv filter=lfs diff=lfs merge=lfs -text
113
+ data/dataset_Gene.csv filter=lfs diff=lfs merge=lfs -text
114
+ data/dataset_Gene_editing.csv filter=lfs diff=lfs merge=lfs -text
115
+ data/dataset_Generate.csv filter=lfs diff=lfs merge=lfs -text
116
+ data/dataset_Generative.csv filter=lfs diff=lfs merge=lfs -text
117
+ data/dataset_Genomics.csv filter=lfs diff=lfs merge=lfs -text
118
+ data/dataset_Genotype.csv filter=lfs diff=lfs merge=lfs -text
119
+ data/dataset_Hartree_Fock.csv filter=lfs diff=lfs merge=lfs -text
120
+ data/dataset_Heterogeneity.csv filter=lfs diff=lfs merge=lfs -text
121
+ data/dataset_High_throughput.csv filter=lfs diff=lfs merge=lfs -text
122
+ data/dataset_Human.csv filter=lfs diff=lfs merge=lfs -text
123
+ data/dataset_Hydrophobic.csv filter=lfs diff=lfs merge=lfs -text
124
+ data/dataset_Imaging.csv filter=lfs diff=lfs merge=lfs -text
125
+ data/dataset_Immunology.csv filter=lfs diff=lfs merge=lfs -text
126
+ data/dataset_Integration.csv filter=lfs diff=lfs merge=lfs -text
127
+ data/dataset_Ion.csv filter=lfs diff=lfs merge=lfs -text
128
+ data/dataset_Kinetics.csv filter=lfs diff=lfs merge=lfs -text
129
+ data/dataset_Lead_discovery.csv filter=lfs diff=lfs merge=lfs -text
130
+ data/dataset_Lead_optimization.csv filter=lfs diff=lfs merge=lfs -text
131
+ data/dataset_Ligand.csv filter=lfs diff=lfs merge=lfs -text
132
+ data/dataset_Lipid.csv filter=lfs diff=lfs merge=lfs -text
133
+ data/dataset_Marker.csv filter=lfs diff=lfs merge=lfs -text
134
+ data/dataset_Material.csv filter=lfs diff=lfs merge=lfs -text
135
+ data/dataset_Mechanism.csv filter=lfs diff=lfs merge=lfs -text
136
+ data/dataset_Medicine.csv filter=lfs diff=lfs merge=lfs -text
137
+ data/dataset_Metabolomics.csv filter=lfs diff=lfs merge=lfs -text
138
+ data/dataset_Metagenomics.csv filter=lfs diff=lfs merge=lfs -text
139
+ data/dataset_Microbial.csv filter=lfs diff=lfs merge=lfs -text
140
+ data/dataset_Modeling.csv filter=lfs diff=lfs merge=lfs -text
141
+ data/dataset_Molecular_biology.csv filter=lfs diff=lfs merge=lfs -text
142
+ data/dataset_Monte_Carlo.csv filter=lfs diff=lfs merge=lfs -text
143
+ data/dataset_Multi_omics.csv filter=lfs diff=lfs merge=lfs -text
144
+ data/dataset_Networks.csv filter=lfs diff=lfs merge=lfs -text
145
+ data/dataset_Next_generation_sequencing.csv filter=lfs diff=lfs merge=lfs -text
146
+ data/dataset_Omics.csv filter=lfs diff=lfs merge=lfs -text
147
+ data/dataset_Pandemic.csv filter=lfs diff=lfs merge=lfs -text
148
+ data/dataset_Pathology.csv filter=lfs diff=lfs merge=lfs -text
149
+ data/dataset_Pathway.csv filter=lfs diff=lfs merge=lfs -text
150
+ data/dataset_Personalized.csv filter=lfs diff=lfs merge=lfs -text
151
+ data/dataset_Pharmaceutics.csv filter=lfs diff=lfs merge=lfs -text
152
+ data/dataset_Pharmacokinetics.csv filter=lfs diff=lfs merge=lfs -text
153
+ data/dataset_Pharmacology.csv filter=lfs diff=lfs merge=lfs -text
154
+ data/dataset_Pharmacometrics.csv filter=lfs diff=lfs merge=lfs -text
155
+ data/dataset_Phase_field_technique.csv filter=lfs diff=lfs merge=lfs -text
156
+ data/dataset_Phenotype.csv filter=lfs diff=lfs merge=lfs -text
157
+ data/dataset_Physiology.csv filter=lfs diff=lfs merge=lfs -text
158
+ data/dataset_Porous.csv filter=lfs diff=lfs merge=lfs -text
159
+ data/dataset_Potential.csv filter=lfs diff=lfs merge=lfs -text
160
+ data/dataset_Prediction.csv filter=lfs diff=lfs merge=lfs -text
161
+ data/dataset_Profiling.csv filter=lfs diff=lfs merge=lfs -text
162
+ data/dataset_Protein.csv filter=lfs diff=lfs merge=lfs -text
163
+ data/dataset_Protein_Protein_Interactions.csv filter=lfs diff=lfs merge=lfs -text
164
+ data/dataset_Protein_protein.csv filter=lfs diff=lfs merge=lfs -text
165
+ data/dataset_Proteomics.csv filter=lfs diff=lfs merge=lfs -text
166
+ data/dataset_QM_MM.csv filter=lfs diff=lfs merge=lfs -text
167
+ data/dataset_Quantum_biology.csv filter=lfs diff=lfs merge=lfs -text
168
+ data/dataset_Quantum_mechanics.csv filter=lfs diff=lfs merge=lfs -text
169
+ data/dataset_RNA.csv filter=lfs diff=lfs merge=lfs -text
170
+ data/dataset_Reaction.csv filter=lfs diff=lfs merge=lfs -text
171
+ data/dataset_Redox.csv filter=lfs diff=lfs merge=lfs -text
172
+ data/dataset_Reinforcement_learning.csv filter=lfs diff=lfs merge=lfs -text
173
+ data/dataset_Reproduction_number.csv filter=lfs diff=lfs merge=lfs -text
174
+ data/dataset_Rosettafold.csv filter=lfs diff=lfs merge=lfs -text
175
+ data/dataset_Score.csv filter=lfs diff=lfs merge=lfs -text
176
+ data/dataset_Screening.csv filter=lfs diff=lfs merge=lfs -text
177
+ data/dataset_Sensors.csv filter=lfs diff=lfs merge=lfs -text
178
+ data/dataset_Sequencing.csv filter=lfs diff=lfs merge=lfs -text
179
+ data/dataset_Signaling.csv filter=lfs diff=lfs merge=lfs -text
180
+ data/dataset_Single_cell.csv filter=lfs diff=lfs merge=lfs -text
181
+ data/dataset_Spatial_Transcriptomics.csv filter=lfs diff=lfs merge=lfs -text
182
+ data/dataset_Spatial_biology.csv filter=lfs diff=lfs merge=lfs -text
183
+ data/dataset_Spectrometry.csv filter=lfs diff=lfs merge=lfs -text
184
+ data/dataset_Stochastic_modeling.csv filter=lfs diff=lfs merge=lfs -text
185
+ data/dataset_System_biology.csv filter=lfs diff=lfs merge=lfs -text
186
+ data/dataset_Transcription.csv filter=lfs diff=lfs merge=lfs -text
187
+ data/dataset_Transcriptomics.csv filter=lfs diff=lfs merge=lfs -text
188
+ data/dataset_Transformer.csv filter=lfs diff=lfs merge=lfs -text
189
+ data/dataset_Translation.csv filter=lfs diff=lfs merge=lfs -text
190
+ data/dataset_Variational_autoencoders.csv filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ task_categories:
4
+ - text-generation
5
+ language:
6
+ - code
7
+ tags:
8
+ - code
9
+ - scientific-computing
10
+ - domain-specific
11
+ - chemistry
12
+ - biology
13
+ - physics
14
+ size_categories:
15
+ - 1M<n<10M
16
+ ---
17
+
18
+ # DATA1: Domain-Specific Code Dataset
19
+
20
+ ## Dataset Overview
21
+
22
+ DATA1 is a large-scale domain-specific code dataset focusing on code samples from interdisciplinary fields such as biology, chemistry, materials science, and related areas. The dataset is collected and organized from GitHub repositories, covering 178 different domain topics with over 1.1 billion lines of code.
23
+
24
+ ## Dataset Statistics
25
+
26
+ - **Total Datasets**: 178 CSV files
27
+ - **Total Data Size**: ~115 GB
28
+ - **Total Lines of Code**: Over 1.1 billion lines
29
+ - **Data Format**: CSV (Comma-Separated Values)
30
+ - **Encoding**: UTF-8
31
+
32
+ ## Dataset Structure
33
+
34
+ Each CSV file corresponds to a specific domain topic, with the naming format `dataset_{Topic}.csv`, where `{Topic}` is the domain keyword (e.g., Protein, Drug, Genomics).
35
+
36
+ ### Data Field Description
37
+
38
+ Each CSV file contains the following fields:
39
+
40
+ | Field Name | Type | Description |
41
+ |------------|------|-------------|
42
+ | `keyword` | String | Domain keyword used to identify the domain of the code sample |
43
+ | `repo_name` | String | GitHub repository name (format: owner/repo) |
44
+ | `file_path` | String | Relative path of the file in the repository |
45
+ | `file_extension` | String | File extension (e.g., .py, .java, .cpp) |
46
+ | `file_size` | Integer | File size in bytes |
47
+ | `line_count` | Integer | Number of lines of code in the file |
48
+ | `content` | String | Complete file content |
49
+ | `language` | String | Programming language (e.g., Python, Java, C++) |
50
+
51
+ ## Domain Categories
52
+
53
+ The dataset covers the following major domain categories:
54
+
55
+ ### Biology-Related
56
+ - **Molecular Biology**: Protein, DNA, RNA, Gene, Enzyme, Receptor, Ligand
57
+ - **Cell Biology**: Cell_biology, Single_cell, Cell_atlas, Organoid
58
+ - **Genomics**: Genomics, Genotype, Phenotype, Epigenetics, Metagenomics
59
+ - **Transcriptomics**: Transcriptomics, Spatial_Transcriptomics, Transcription, Translation
60
+ - **Proteomics**: Proteomics, Protein_Protein_Interactions, Folding
61
+ - **Metabolomics**: Metabolomics, Metabolic, Lipidomics, Glycomics
62
+ - **Systems Biology**: System_biology, Signaling, Pathway, Networks
63
+
64
+ ### Chemistry-Related
65
+ - **Computational Chemistry**: Computational_Chemistry, Quantum_Chemistry, DFT, QM_MM
66
+ - **Medicinal Chemistry**: Drug, ADMET, QSAR, Docking, Lead_discovery, Lead_optimization
67
+ - **Materials Chemistry**: Material, Crystal, Conformation, Chemical_space
68
+ - **Reaction Chemistry**: Reaction, Kinetics, Mechanism, Redox
69
+
70
+ ### Medicine and Pharmacology
71
+ - **Pharmacology**: Pharmacology, Pharmacokinetics, Pharmacogenomics, Pharmacogenetics
72
+ - **Medicine**: Medicine, Disease, Diagnostics, Pathology, Vaccine
73
+ - **Toxicology**: Toxicology, Biomarker, Marker
74
+
75
+ ### Computational Methods
76
+ - **Machine Learning**: Transformer, GAN, VAE, Diffusion, Flow_matching, Reinforcement_learning
77
+ - **Quantum Computing**: Quantum_mechanics, Quantum_biology, Electronic_structure
78
+ - **Modeling Methods**: Modeling, Multi_scale_modeling, Agent_based_model, Stochastic_modeling
79
+ - **Numerical Methods**: Monte_Carlo, Finite_element_method, Phase_field_technique
80
+
81
+ ### Other Specialized Fields
82
+ - **Bioinformatics**: Bioinformatics, Cheminformatics, Next_generation_sequencing
83
+ - **Bioengineering**: Bioengineering, Biotechnology, Biosensors
84
+ - **Immunology**: Immunology, Antibody, Antigen, Antagonist
85
+ - **Virology**: Viral, Pandemic, Pathogens, AMR (Antimicrobial Resistance)
86
+
87
+ ## Data Source
88
+
89
+ The data is collected from open-source repositories on GitHub through the following process:
90
+
91
+ 1. **Keyword Search**: Search for relevant repositories on GitHub using domain-specific keywords
92
+ 2. **Repository Filtering**: Filter repositories based on relevance scores and code quality
93
+ 3. **File Extraction**: Extract code files from filtered repositories
94
+ 4. **Categorization**: Classify files into corresponding topic datasets based on keywords and domain characteristics
95
+
96
+ ## Dataset Characteristics
97
+
98
+ 1. **Wide Domain Coverage**: Covers multiple interdisciplinary fields including biology, chemistry, materials science, and medicine
99
+ 2. **Diverse Code Types**: Includes multiple programming languages such as Python, Java, C++, R, and MATLAB
100
+ 3. **Large Scale**: Over 1.1 billion lines of code with a total data size of 115 GB
101
+ 4. **Structured Storage**: Each domain topic is stored independently as a CSV file for convenient on-demand usage
102
+ 5. **Rich Metadata**: Contains comprehensive metadata including repository information, file paths, and language types
103
+
104
+ ## Usage Guidelines
105
+
106
+ ### Data Loading
107
+
108
+ ```python
109
+ import pandas as pd
110
+
111
+ # Load dataset for a specific domain
112
+ df = pd.read_csv('dataset_Protein.csv')
113
+
114
+ # View basic dataset information
115
+ print(f"Dataset size: {len(df)} files")
116
+ print(f"Programming language distribution: {df['language'].value_counts()}")
117
+ print(f"File type distribution: {df['file_extension'].value_counts()}")
118
+ ```
119
+
120
+ ### Data Filtering
121
+
122
+ ```python
123
+ # Filter by programming language
124
+ python_files = df[df['language'] == 'Python']
125
+
126
+ # Filter by file size (e.g., files smaller than 100KB)
127
+ small_files = df[df['file_size'] < 100000]
128
+
129
+ # Filter by line count
130
+ medium_files = df[(df['line_count'] > 50) & (df['line_count'] < 1000)]
131
+ ```
132
+
133
+ ### Domain-Specific Analysis
134
+
135
+ ```python
136
+ # Analyze code characteristics for a specific domain
137
+ protein_df = pd.read_csv('dataset_Protein.csv')
138
+ print(f"Number of code files in Protein domain: {len(protein_df)}")
139
+ print(f"Average file size: {protein_df['file_size'].mean():.2f} bytes")
140
+ print(f"Average line count: {protein_df['line_count'].mean():.2f} lines")
141
+ ```
142
+
143
+ ## Important Notes
144
+
145
+ 1. **File Size**: Some dataset files are large (up to several GB), please be mindful of memory usage when loading
146
+ 2. **Encoding**: All files use UTF-8 encoding; ensure proper handling of special characters if encountered
147
+ 3. **Data Quality**: Data is sourced from public repositories and may vary in code quality; preprocessing is recommended before use
148
+ 4. **License Compliance**: Please comply with the license requirements of the original repositories when using the data
149
+
150
+
data/dataset_2D.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0620bded2a39990458f05c32a8b48c1cde5b128c7d1e5cd60cca23f03526c5b
3
+ size 114408225
data/dataset_3D.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9465cfacec422939059b5315ff0a200f254f8f9cc78ea4c78707186b2d751aba
3
+ size 4534234376
data/dataset_ADMET.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_AMR.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac9cdc76976729284244511d29efa15cd5714a2801788f6e5735d658157beb64
3
+ size 115785642
data/dataset_Ab_initio.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c265a75ded3a89baddc37405f88278118ae5ea69bfcbcb501111b40b8fda2a5
3
+ size 126307508
data/dataset_Absorption.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79b0d1163d9016986276dc615f6968d0abdd25351e506b362613c0a3e93fa1c5
3
+ size 161543122
data/dataset_Activation.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b20717efa055c630d0fb3fbf5173381212b3267dde1200e803e42b9ebe0b732b
3
+ size 5981782032
data/dataset_Agent_based_model.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21295c6bbbc80ce1713f0ef17e047a6073b2bb602830eb7ef50fcff281a0991d
3
+ size 182081411
data/dataset_Allele.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_AlphaFold.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Anomaly_detection.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5e8830c4f43fc668123a5a8fa6bc8d19578b454613a4a1c285b11db8f1f0773
3
+ size 98558570
data/dataset_Antagonist.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b22ddc4a72da52bb1f48987e22bfd78c298bcc083ca6cc831eca9acf93b1714
3
+ size 18356896
data/dataset_Antibody.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f345d73b836ed1336ebfa3e4926fa13b66cbfd93ee2633dc8d30d47b8844881
3
+ size 848909782
data/dataset_Antigen.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dcaeb7286f3fc7da58de322b271239a583ccbce6c9884df4893afac05595384
3
+ size 142704238
data/dataset_Assay.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Autoregressive.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:509947ff6d9c605f84d427b1c68f088b01ff87793f7ba8bff51a9c9ad1545a9c
3
+ size 149122966
data/dataset_Bio.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97605fb27851febe0dd70d540a23b625c8c21022526950df00afd227d0e12f17
3
+ size 52464173
data/dataset_Bio_foundation_model.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Biochemistry.csv ADDED
@@ -0,0 +1,968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "keyword","repo_name","file_path","file_extension","file_size","line_count","content","language"
2
+ "Biochemistry","Bin-Cao/TCLRmodel","Template/Execution template/template.py",".py","5138","104","#coding=utf-8
3
+ from TCLR import TCLRalgorithm as model
4
+
5
+
6
+ """"""
7
+ :param correlation : {'PearsonR(+)','PearsonR(-)',''MIC','R2'},default PearsonR(+).
8
+ Methods:
9
+ * PearsonR: (+)(-). for linear relationship.
10
+ * MIC for no-linear relationship.
11
+ * R2 for no-linear relationship.
12
+
13
+ :param tolerance_list: constraints imposed on features, default is null
14
+ list shape in two dimensions, viz., [[constraint_1,tol_1],[constraint_2,tol_2]...]
15
+ constraint_1, constraint_2 (string) are the feature name ;
16
+ tol_1, tol_2 (float)are feature's tolerance ratios;
17
+ relative variation range of features must be within the tolerance;
18
+ example: tolerance_list = [['feature_name1',0.2],['feature_name2',0.1]].
19
+
20
+ :param gpl_dummyfea: dummy features in gpleran regression, default is null
21
+ list shape in one dimension, viz., ['feature_name1','feature_name2',...]
22
+ dummy features : 'feature_name1','feature_name2',... are not used anymore in gpleran regression
23
+
24
+ :param minsize : a int number (default=3), minimum unique values for linear features of data on each leaf.
25
+
26
+ :param threshold : a float (default=0.9), less than or equal to 1, default 0.95 for PearsonR.
27
+ In the process of dividing the dataset, the smallest relevant index allowed in the you research.
28
+ To avoid overfitting, threshold = 0.5 is suggested for MIC 0.5.
29
+
30
+ :param mininc : Minimum expected gain of objective function (default=0.01)
31
+
32
+ :param split_tol : a float (default=0.8), constrained features value shound be narrowed in a minmimu ratio of split_tol on split path
33
+
34
+ :param gplearn : Whether to call the embedded gplearn package of TCLR to regress formula (default=False).
35
+
36
+ :param population_size : integer, optional (default=500), the number of programs in each generation.
37
+
38
+ :param generations : integer, optional (default=100),the number of generations to evolve.
39
+
40
+ :param verbose : int, optional (default=0). Controls the verbosity of the evolution building process.
41
+
42
+ :param metric : str, optional (default='mean absolute error')
43
+ The name of the raw fitness metric. Available options include:
44
+ - 'mean absolute error'.
45
+ - 'mse' for mean squared error.
46
+ - 'rmse' for root mean squared error.
47
+ - 'pearson', for Pearson's product-moment correlation coefficient.
48
+ - 'spearman' for Spearman's rank-order correlation coefficient.
49
+
50
+ :param function_set : iterable, optional (default=['add', 'sub', 'mul', 'div', 'log', 'sqrt',
51
+ 'abs', 'neg','inv','sin','cos','tan', 'max', 'min'])
52
+ The functions to use when building and evolving programs. This iterable can include strings
53
+ to indicate either individual functions as outlined below.
54
+ Available individual functions are:
55
+ - 'add' : addition, arity=2.
56
+ - 'sub' : subtraction, arity=2.
57
+ - 'mul' : multiplication, arity=2.
58
+ - 'div' : protected division where a denominator near-zero returns 1.,
59
+ arity=2.
60
+ - 'sqrt' : protected square root where the absolute value of the
61
+ argument is used, arity=1.
62
+ - 'log' : protected log where the absolute value of the argument is
63
+ used and a near-zero argument returns 0., arity=1.
64
+ - 'abs' : absolute value, arity=1.
65
+ - 'neg' : negative, arity=1.
66
+ - 'inv' : protected inverse where a near-zero argument returns 0.,
67
+ arity=1.
68
+ - 'max' : maximum, arity=2.
69
+ - 'min' : minimum, arity=2.
70
+ - 'sin' : sine (radians), arity=1.
71
+ - 'cos' : cosine (radians), arity=1.
72
+ - 'tan' : tangent (radians), arity=1.
73
+
74
+ Algorithm Patent No. : 2021SR1951267, China
75
+ Reference : Domain knowledge guided interpretive machine learning —— Formula discovery for the oxidation behavior of Ferritic-Martensitic steels in supercritical water. Bin Cao et al., 2022, JMI, journal paper.
76
+ DOI : 10.20517/jmi.2022.04
77
+ """"""
78
+
79
+
80
+ dataSet = ""testdata.csv""
81
+ correlation = 'PearsonR(+)'
82
+ tolerance_list = [
83
+ ['E_Cr_split_feature_1',0.001],
84
+ ]
85
+
86
+ gpl_dummyfea = ['ln(t)_split_feature_4',]
87
+ minsize = 3
88
+ threshold = 0.9
89
+ mininc = 0.01
90
+ split_tol = 0.8
91
+ gplearn = True
92
+ population_size = 500
93
+ generations = 100
94
+ verbose = 1
95
+ metric = 'mean absolute error'
96
+ function_set = ['add', 'sub', 'mul', 'div', 'log', 'sqrt', 'abs', 'neg','inv','sin','cos','tan', 'max', 'min']
97
+
98
+
99
+ model.start(filePath = dataSet, correlation = correlation, tolerance_list = tolerance_list, gpl_dummyfea = gpl_dummyfea, minsize = minsize, threshold = threshold,
100
+ mininc = mininc ,split_tol = split_tol, gplearn = gplearn, population_size = population_size,
101
+ generations = generations,verbose = verbose, metric =metric, function_set =function_set)
102
+
103
+
104
+
105
+ ","Python"
106
+ "Biochemistry","Bin-Cao/TCLRmodel","TCLR/TCLRalgorithm.py",".py","38792","861","""""""
107
+ Tree Classifier for Linear Regression (TCLR)
108
+ Author : Bin CAO (binjacobcao@gmail.com)
109
+
110
+ TCLR is a new tree model proposed by Professor T-Y Zhang and Mr. Bin Cao et al. for capturing the functional relationships
111
+ between features and target variables. The model partitions the feature space into a set of rectangles, with each partition
112
+ embodying a specific function. This approach is conceptually simple, yet powerful for distinguishing mechanisms. The entire
113
+ feature space is divided into disjointed unit intervals by hyperplanes parallel to the coordinate axes. Within each partition,
114
+ the target variable y is modeled as a linear function of a feature xj (j = 1,⋯,m), which is the linear function used in our studied problem.
115
+
116
+ Patent No. : 2021SR1951267, China
117
+ Reference : Domain knowledge guided interpretive machine learning —— Formula discovery for the oxidation behavior of Ferritic-Martensitic steels in supercritical water. Bin Cao et al., 2022, JMI, journal paper.
118
+ DOI : 10.20517/jmi.2022.04
119
+ """"""
120
+
121
+ import math
122
+ import re
123
+ from tabnanny import check
124
+ from textwrap import indent
125
+ import time
126
+ import copy
127
+ import os
128
+ import warnings
129
+ import random
130
+ from typing import List
131
+ import numpy as np
132
+ import pandas as pd
133
+ from graphviz import Digraph
134
+ from scipy import stats
135
+ from gplearn import genetic
136
+ from minepy import MINE
137
+
138
+
139
+ # Define the basic structure of a Tree Model - Node
140
+ class Node:
141
+ def __init__(self, data):
142
+ self.data = data
143
+ self.lc = None
144
+ self.rc = None
145
+ self.slope = None
146
+ self.intercept = None
147
+ self.size = data.shape[0]
148
+ self.R = 0
149
+ self.bestFeature = 0
150
+ self.bestValue = 0
151
+ self.leaf_no = -1
152
+
153
+
154
+ def start(filePath, correlation='PearsonR(+)', minsize=3, threshold=0.95, mininc=0.01, split_tol = 0.8, epochs = 5,random_seed=42, Generate_Features = True, tolerance_list = None , weight=True,
155
+ gplearn = False, gpl_dummyfea = None, population_size = 500, generations = 100, verbose = 1,
156
+ metric = 'mean absolute error',
157
+ function_set = ['add', 'sub', 'mul', 'div', 'log', 'sqrt', 'abs', 'neg','inv','sin','cos','tan',]):
158
+
159
+ """"""
160
+ Tree Classifier for Linear Regression (TCLR)
161
+
162
+ TCLR is a new tree model proposed by Professor T-Y Zhang and Mr. Bin Cao et al. for capturing the functional relationships
163
+ between features and target variables. The model partitions the feature space into a set of rectangles, with each partition
164
+ embodying a specific function. This approach is conceptually simple, yet powerful for distinguishing mechanisms. The entire
165
+ feature space is divided into disjointed unit intervals by hyperplanes parallel to the coordinate axes. Within each partition,
166
+ the target variable y is modeled as a linear function of a feature xj (j = 1,⋯,m), which is the linear function used in our studied problem.
167
+
168
+ Patent No. : 2021SR1951267, China
169
+ Reference : Domain knowledge guided interpretive machine learning —— Formula discovery for the oxidation behavior of Ferritic-Martensitic steels in supercritical water. Bin Cao et al., 2022, JMI, journal paper.
170
+ DOI : 10.20517/jmi.2022.04
171
+
172
+ :param correlation : {'PearsonR(+)','PearsonR(-)',''MIC','R2'}, default PearsonR(+).
173
+ Methods:
174
+ * PearsonR: (+)(-). for linear relationship.
175
+ * MIC for no-linear relationship.
176
+ * R2 for no-linear relationship.
177
+
178
+ The evaluation factor for capture the functional relationship between feature and response
179
+ 1>
180
+ PearsonR:
181
+ Pearson correlation coefficient, also known as Pearson's r, the Pearson product-moment correlation coefficient.
182
+ PearsonR is a measure of linear correlation between two sets of data.
183
+ PearsonR = Cov(X,Y) / (sigmaX * sigmaY)
184
+
185
+ 2>
186
+ MIC:
187
+ The maximal information coefficient (MIC). MIC captures a wide range of associations both functional and not,
188
+ and for functional relationships provides a score that roughly equals the coefficient of determination (R2) of
189
+ the data relative to the regression function. MIC belongs to a larger class of maximal information-based
190
+ nonparametric exploration (MINE) statistics for identifying and classifying relationship.
191
+ Reference : Reshef, D. N., Reshef, Y. A., Finucane, H. K., Grossman, S. R., McVean, G., Turnbaugh, P. J., ...
192
+ and Sabeti, P. C. (2011). Detecting novel associations in large data sets. science, 334(6062), 1518-1524.
193
+
194
+ 3>
195
+ R2:
196
+ In statistics, the coefficient of determination, denoted R2 or r2 and pronounced ""R squared"",
197
+ is the proportion of the variation in the dependent variable that is predictable from the independent variable(s).
198
+ t is a statistic used in the context of statistical models whose main purpose is either the prediction of future
199
+ outcomes or the testing of hypotheses, on the basis of other related information. It provides a measure of how well
200
+ observed outcomes are replicated by the model, based on the proportion of total variation of outcomes explained by the model.
201
+ Definition from Wikipedia : https://en.wikipedia.org/wiki/Coefficient_of_determination
202
+ R2 = 1 - SSres / SStot. Its value may be a negative one for poor correlation.
203
+
204
+
205
+ :param minsize :
206
+ a int number (default=3), minimum unique values for linear features of data on each leaf.
207
+
208
+ :param threshold :
209
+ a float (default=0.9), less than or equal to 1, default 0.95 for PearsonR.
210
+ In the process of dividing the dataset, the smallest relevant index allowed in the you research.
211
+ To avoid overfitting, threshold = 0.5 is suggested for MIC 0.5.
212
+
213
+ :param mininc : Minimum expected gain of objective function (default=0.01)
214
+
215
+ :param split_tol : a float (default=0.8), constrained features value shound be narrowed in a minmimu ratio of split_tol on split path
216
+
217
+ :param epochs : an integer (default=5), see parameter Generate_Features (below)
218
+
219
+ :param random_seed : an integer (default=42), see parameter Generate_Features (below)
220
+
221
+ :param Generate_Features : boole (default=True). When Generate_Features = True, TCLR will generate new features by operating
222
+ the ['+','-','*'] on original features. Iterating [param : epoachs] times, and each time generating 3 new features. [param : random_seed]
223
+ is used to control the randomness.
224
+ When Generate_Features = False, TCLR will apply the original features
225
+
226
+ :param tolerance_list:
227
+ constraints imposed on features, default is null
228
+ list shape in two dimensions, viz., [['feature_name1',tol_1],['feature_name2',tol_2]...]
229
+ 'feature_name1', 'feature_name2' (string) are names of input features;
230
+ tol_1, tol_2 (float, between 0 to 1) are feature's tolerance ratios;
231
+ the variations of feature values on each leaf must be in the tolerance;
232
+ if tol_1 = 0, the value of feature 'feature_name1' must be a constant on each leaf,
233
+ if tol_1 = 1, there is no constraints on value of feature 'feature_name1';
234
+ example: tolerance_list = [['feature_name1',0.2],['feature_name2',0.1]].
235
+
236
+ :param weight:
237
+ The weight of the gain function, default is True.
238
+ When weight is True: linear_gain = R(father node) - ( W_l * R(left child node) + W_r * R(right child node)) / 2
239
+ Where W_l is the ratio of the number of samples in the left child node to the total number of samples ;
240
+ W_r is the ratio of the number of samples in the right child node to the total number of samples.
241
+ When weight is False: linear_gain = R(father node) - ( R(left child node) + R(right child node)) / 2
242
+
243
+ :param gplearn : Whether to call the embedded gplearn package of TCLR to regress formula (default=False).
244
+
245
+ :param gpl_dummyfea:
246
+ dummy features in gpleran regression, default is null
247
+ list shape in one dimension, viz., ['feature_name1','feature_name2',...]
248
+ dummy features : 'feature_name1','feature_name2',... are not used anymore in gpleran regression
249
+
250
+ :param population_size : integer, optional (default=500), the number of programs in each generation.
251
+
252
+ :param generations : integer, optional (default=100),the number of generations to evolve.
253
+
254
+ :param verbose : int, optional (default=0). Controls the verbosity of the evolution building process.
255
+
256
+ :param metric :
257
+ str, optional (default='mean absolute error')
258
+ The name of the raw fitness metric. Available options include:
259
+ - 'mean absolute error'.
260
+ - 'mse' for mean squared error.
261
+ - 'rmse' for root mean squared error.
262
+ - 'pearson', for Pearson's product-moment correlation coefficient.
263
+ - 'spearman' for Spearman's rank-order correlation coefficient.
264
+
265
+ :param function_set :
266
+ iterable, optional (default=['add', 'sub', 'mul', 'div', 'log', 'sqrt',
267
+ 'abs', 'neg','inv','sin','cos','tan', 'max', 'min'])
268
+ The functions to use when building and evolving programs. This iterable can include strings
269
+ to indicate either individual functions as outlined below.
270
+ Available individual functions are:
271
+ - 'add' : addition, arity=2.
272
+ - 'sub' : subtraction, arity=2.
273
+ - 'mul' : multiplication, arity=2.
274
+ - 'div' : protected division where a denominator near-zero returns 1.,
275
+ arity=2.
276
+ - 'sqrt' : protected square root where the absolute value of the
277
+ argument is used, arity=1.
278
+ - 'log' : protected log where the absolute value of the argument is
279
+ used and a near-zero argument returns 0., arity=1.
280
+ - 'abs' : absolute value, arity=1.
281
+ - 'neg' : negative, arity=1.
282
+ - 'inv' : protected inverse where a near-zero argument returns 0.,
283
+ arity=1.
284
+ - 'max' : maximum, arity=2.
285
+ - 'min' : minimum, arity=2.
286
+ - 'sin' : sine (radians), arity=1.
287
+ - 'cos' : cosine (radians), arity=1.
288
+ - 'tan' : tangent (radians), arity=1.
289
+
290
+ Exampel :
291
+ #coding=utf-8
292
+ from TCLR import TCLRalgorithm as model
293
+
294
+ dataSet = ""testdata.csv""
295
+ correlation = 'PearsonR(+)'
296
+ minsize = 3
297
+ threshold = 0.9
298
+ mininc = 0.01
299
+ split_tol = 0.8
300
+
301
+ model.start(filePath = dataSet, correlation = correlation, minsize = minsize, threshold = threshold,
302
+ mininc = mininc ,split_tol = split_tol,)
303
+ """"""
304
+
305
+ os.makedirs('Segmented', exist_ok=True)
306
+ # global var. for statisticaling results
307
+ global record
308
+ record = 0
309
+ timename = time.localtime(time.time())
310
+ namey, nameM, named, nameh, namem = timename.tm_year, timename.tm_mon, timename.tm_mday, timename.tm_hour, timename.tm_min
311
+
312
+ read_csvData = pd.read_csv(filePath)
313
+
314
+ input_csvData = read_csvData.iloc[:,:-2]
315
+ if Generate_Features == True:
316
+ # cal an appropriate value of batch
317
+ if len(input_csvData) - 1 <= 3:
318
+ batch = 1
319
+ else:
320
+ batch = 3
321
+ # generate new dataset
322
+ for epoch in range(epochs):
323
+ # for increasing the randomness
324
+ random_seed += 1
325
+ input_csvData = generate_random_features(input_csvData,[column for column in input_csvData],batch,random_seed)
326
+
327
+ input_csvData = input_csvData.assign(linear_X=read_csvData.iloc[:,-2])
328
+ csvData = input_csvData.assign(linear_Y=read_csvData.iloc[:,-1])
329
+
330
+ else:
331
+ csvData = read_csvData
332
+
333
+
334
+ copy_csvData = copy.deepcopy(csvData)
335
+ copy_csvData['slope'] = None
336
+ copy_csvData['intercept'] = None
337
+ copy_csvData[correlation] = None
338
+ copy_csvData.to_csv('Segmented/all_dataset.csv', index=False)
339
+
340
+ feats = [column for column in csvData]
341
+ csvData = np.array(csvData)
342
+ root, _ = createTree(csvData, csvData, feats, 0, correlation,tolerance_list, minsize, threshold, mininc, split_tol,weight)
343
+
344
+ print('All non-image results have been successfully saved!')
345
+ print('#'*80,'\n')
346
+
347
+ # excute gplearn
348
+ if gplearn == True :
349
+ if correlation == 'MIC' or correlation == 'R2':
350
+ print('{name} is a non-linear correlation metrics'.format(name = correlation ))
351
+ print('This is illegal, linear slopes are only allowed to generate when PearsonR is chosen')
352
+ elif correlation == 'PearsonR(+)' or correlation == 'PearsonR(-)':
353
+ sr_data = pd.read_csv('Segmented/all_dataset.csv')
354
+ sr_featurname = sr_data.columns
355
+ sr_data = np.array(sr_data)
356
+
357
+ if gpl_dummyfea == None:
358
+
359
+ gpmodel = genetic.SymbolicRegressor(
360
+ population_size = population_size, generations = generations,
361
+ verbose = verbose,feature_names = sr_featurname[:-4],function_set = function_set,
362
+ metric = metric
363
+ )
364
+ formula = gpmodel.fit(sr_data[:,:-4], sr_data[:,-3])
365
+ score = gpmodel.score(sr_data[:,:-4], sr_data[:,-3])
366
+ print( 'slope = ' + str(formula))
367
+
368
+ else:
369
+ # fea_num --> fea_loc
370
+ dummyfea = []
371
+ for i in range(len(gpl_dummyfea)):
372
+ index = feats.index(gpl_dummyfea[i])
373
+ dummyfea.append(index)
374
+ # remove fea_loc
375
+ index_array = [i for i in range(len(sr_featurname)-4)]
376
+ for i in range(len(gpl_dummyfea)):
377
+ index_array.remove(dummyfea[i])
378
+
379
+ gpmodel = genetic.SymbolicRegressor(
380
+ population_size = population_size, generations = generations,
381
+ verbose = verbose,feature_names = sr_featurname[index_array],function_set = function_set,
382
+ metric = metric
383
+ )
384
+ formula = gpmodel.fit(sr_data[:,index_array], sr_data[:,-3])
385
+ score = gpmodel.score(sr_data[:,index_array], sr_data[:,-3])
386
+ print( 'slope = ' + str(formula))
387
+
388
+
389
+ with open(os.path.join('Segmented', 'A_formula derived by gplearn.txt'), 'w') as wfid:
390
+ print('Formula : ', file=wfid)
391
+ print(str(formula), file=wfid)
392
+ print('Fitness : ', file=wfid)
393
+ print(str(metric) + ' = ' + str(score), file=wfid)
394
+ print('\n', file=wfid)
395
+ print('#'*80, file=wfid)
396
+ print('Symbols annotation:', file=wfid)
397
+ print('- add : addition, arity=2.', file=wfid)
398
+ print('- sub : subtraction, arity=2.', file=wfid)
399
+ print('- mul : multiplication, arity=2.', file=wfid)
400
+ print('- div : protected division where a denominator near-zero returns 1.', file=wfid)
401
+ print('- sqrt : protected square root where the absolute value of the argument is used.', file=wfid)
402
+ print('- log : protected log where the absolute value of the argument is used.', file=wfid)
403
+ print('- abs : absolute value, arity=1.', file=wfid)
404
+ print('- neg : negative, arity=1.', file=wfid)
405
+ print('- inv : protected inverse where a near-zero argument returns 0.', file=wfid)
406
+ print('- max : maximum, arity=2.', file=wfid)
407
+ print('- sin : sine (radians), arity=1.', file=wfid)
408
+ print('- cos : cosine (radians), arity=1.', file=wfid)
409
+ print('- tan : tangent (radians), arity=1.', file=wfid)
410
+
411
+
412
+
413
+ elif gplearn == False:
414
+ pass
415
+
416
+
417
+ try:
418
+ # generate figure in pdf
419
+ warnings.filterwarnings('ignore')
420
+ dot = Digraph(comment='Result of TCLR')
421
+ render('A', root, dot, feats)
422
+ dot.render(
423
+ 'Result of TCLR {year}.{month}.{day}-{hour}.{minute}'.format(year=namey, month=nameM, day=named, hour=nameh,
424
+ minute=namem))
425
+ return True
426
+ except :
427
+ print('Can not generate the Tree plot !')
428
+ print('Please ensure that the executable files of Graphviz are present on your system.')
429
+ print('See : https://github.com/Bin-Cao/TCLRmodel/tree/main/User%20Guide')
430
+ return True
431
+
432
+
433
+
434
+ # Capture the functional relationships between features and target
435
+ # Partitions the feature space into a set of rectangles,
436
+ def createTree(dataSet, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight):
437
+ # It is a positive linear relationship
438
+ if correlation == 'PearsonR(+)':
439
+ node = Node(dataSet)
440
+ # Initial R0
441
+ bestR = PearsonR(dataSet[:, -2], dataSet[:, -1])
442
+ node.R = bestR
443
+ __slope = stats.linregress(dataSet[:, -2], dataSet[:, -1])[0]
444
+ node.slope = __slope
445
+ node.intercept = stats.linregress(dataSet[:, -2], dataSet[:, -1])[1]
446
+ if bestR >= threshold and fea_tol(dataSet,ori_dataset,feats,tolerance_list) == True:
447
+ node.leaf_no = leaf_no
448
+ leaf_no += 1
449
+ write_csv(node, feats, True, correlation)
450
+ return node, leaf_no
451
+ # Leave the last two columns of DataSet, a feature of interest and a response
452
+ numFeatures = len(dataSet[0]) - 2
453
+ splitSuccess = False
454
+ bestFeature = -1
455
+ bestValue = 0
456
+
457
+ check_valve = False
458
+ for i in range(numFeatures):
459
+ featList = [example[i] for example in dataSet]
460
+ uniqueVals = sorted(list(set(featList)))
461
+ for value in range(len(uniqueVals) - 1):
462
+ # constraints imposed on features (greater tolerance in split process)
463
+ if not fea_tol_split(dataSet,ori_dataset,feats,tolerance_list,split_tol):
464
+ continue
465
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
466
+
467
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
468
+ subDataSetB[:, -2]).size <= minsize - 1:
469
+ continue
470
+
471
+ R = weight_gain(subDataSetA,subDataSetB,weight,0)
472
+
473
+ if R - bestR >= mininc:
474
+ check_valve = True
475
+ splitSuccess = True
476
+ bestR = R
477
+ lc = subDataSetA
478
+ rc = subDataSetB
479
+ bestFeature = i
480
+ bestValue = uniqueVals[value]
481
+
482
+ if check_valve == False:
483
+ for i in range(numFeatures):
484
+ featList = [example[i] for example in dataSet]
485
+ uniqueVals = sorted(list(set(featList)))
486
+ for value in range(len(uniqueVals) - 1):
487
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
488
+
489
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
490
+ subDataSetB[:, -2]).size <= minsize - 1:
491
+ continue
492
+
493
+ R = weight_gain(subDataSetA,subDataSetB,weight,0)
494
+
495
+ if R - bestR >= mininc:
496
+ splitSuccess = True
497
+ bestR = R
498
+ lc = subDataSetA
499
+ rc = subDataSetB
500
+ bestFeature = i
501
+ bestValue = uniqueVals[value]
502
+ else:
503
+ pass
504
+
505
+
506
+ # The recursive boundary is unable to find a division node that can increase factor(R, MIC, R2) by mininc or more.
507
+ if splitSuccess:
508
+ node.lc, leaf_no = createTree(lc, ori_dataset,feats, leaf_no, correlation, tolerance_list,minsize, threshold, mininc,split_tol,weight)
509
+ node.rc, leaf_no = createTree(rc, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight)
510
+ node.bestFeature, node.bestValue = bestFeature, bestValue
511
+
512
+ # This node is leaf
513
+ if node.lc is None:
514
+ node.leaf_no = leaf_no
515
+ leaf_no += 1
516
+ # determine if this node is to save in all_dataset.csv
517
+ save_in_all = False
518
+ if node.R >= threshold and fea_tol(node.data,ori_dataset,feats,tolerance_list) == True:
519
+ save_in_all = True
520
+ write_csv(node, feats, save_in_all, correlation)
521
+
522
+ return node, leaf_no
523
+
524
+ # It is a negative linear relationship
525
+ elif correlation == 'PearsonR(-)':
526
+ node = Node(dataSet)
527
+ bestR = PearsonR(dataSet[:, -2], dataSet[:, -1])
528
+ node.R = bestR
529
+ __slope = stats.linregress(dataSet[:, -2], dataSet[:, -1])[0]
530
+ node.slope = __slope
531
+ node.intercept = stats.linregress(dataSet[:, -2], dataSet[:, -1])[1]
532
+ if bestR <= -threshold and fea_tol(dataSet,ori_dataset,feats,tolerance_list) == True:
533
+ node.leaf_no = leaf_no
534
+ leaf_no += 1
535
+ write_csv(node, feats, True, correlation)
536
+ return node, leaf_no
537
+
538
+ numFeatures = len(dataSet[0]) - 2
539
+ splitSuccess = False
540
+ bestFeature = -1
541
+ bestValue = 0
542
+
543
+ check_valve = False
544
+ for i in range(numFeatures):
545
+ featList = [example[i] for example in dataSet]
546
+ uniqueVals = sorted(list(set(featList)))
547
+ for value in range(len(uniqueVals) - 1):
548
+ # constraints imposed on features (greater tolerance in split process)
549
+ if not fea_tol_split(dataSet,ori_dataset,feats,tolerance_list,split_tol):
550
+ continue
551
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
552
+
553
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
554
+ subDataSetB[:, -2]).size <= minsize - 1:
555
+ continue
556
+
557
+
558
+ R = weight_gain(subDataSetA,subDataSetB,weight,0)
559
+
560
+ if R - bestR <= - mininc:
561
+ check_valve = True
562
+ splitSuccess = True
563
+ bestR = R
564
+ lc = subDataSetA
565
+ rc = subDataSetB
566
+ bestFeature = i
567
+ bestValue = uniqueVals[value]
568
+
569
+ if check_valve == False:
570
+ for i in range(numFeatures):
571
+ featList = [example[i] for example in dataSet]
572
+ uniqueVals = sorted(list(set(featList)))
573
+ for value in range(len(uniqueVals) - 1):
574
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
575
+
576
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
577
+ subDataSetB[:, -2]).size <= minsize - 1:
578
+ continue
579
+
580
+ R = weight_gain(subDataSetA,subDataSetB,weight,0)
581
+
582
+ if R - bestR <= - mininc:
583
+ splitSuccess = True
584
+ bestR = R
585
+ lc = subDataSetA
586
+ rc = subDataSetB
587
+ bestFeature = i
588
+ bestValue = uniqueVals[value]
589
+ else: pass
590
+
591
+ if splitSuccess:
592
+ node.lc, leaf_no = createTree(lc, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight)
593
+ node.rc, leaf_no = createTree(rc, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight)
594
+ node.bestFeature, node.bestValue = bestFeature, bestValue
595
+
596
+ if node.lc is None:
597
+ node.leaf_no = leaf_no
598
+ leaf_no += 1
599
+ # determine if this node is to save in all_dataset.csv
600
+ save_in_all = False
601
+ if node.R >= threshold and fea_tol(node.data,ori_dataset,feats,tolerance_list) == True:
602
+ save_in_all = True
603
+ write_csv(node, feats, save_in_all, correlation)
604
+
605
+ return node, leaf_no
606
+
607
+ elif correlation == 'MIC':
608
+ node = Node(dataSet)
609
+ bestR = MIC(dataSet[:, -2], dataSet[:, -1])
610
+ node.R = bestR
611
+ node.slope == None
612
+ if bestR >= threshold and fea_tol(dataSet,ori_dataset,feats,tolerance_list) == True:
613
+ node.leaf_no = leaf_no
614
+ leaf_no += 1
615
+ write_csv(node, feats, True, correlation)
616
+ return node, leaf_no
617
+
618
+ numFeatures = len(dataSet[0]) - 2
619
+ splitSuccess = False
620
+ bestFeature = -1
621
+ bestValue = 0
622
+
623
+ check_valve = False
624
+ for i in range(numFeatures):
625
+ featList = [example[i] for example in dataSet]
626
+ uniqueVals = sorted(list(set(featList)))
627
+ for value in range(len(uniqueVals) - 1):
628
+ # constraints imposed on features (greater tolerance in split process)
629
+ if not fea_tol_split(dataSet,ori_dataset,feats,tolerance_list,split_tol):
630
+ continue
631
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
632
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
633
+ subDataSetB[:, -2]).size <= minsize - 1:
634
+ continue
635
+
636
+ R = weight_gain(subDataSetA,subDataSetB,weight,1)
637
+
638
+ if R - bestR >= mininc:
639
+ check_valve = True
640
+ splitSuccess = True
641
+ bestR = R
642
+ lc = subDataSetA
643
+ rc = subDataSetB
644
+ bestFeature = i
645
+ bestValue = uniqueVals[value]
646
+
647
+ if check_valve == False:
648
+ for i in range(numFeatures):
649
+ featList = [example[i] for example in dataSet]
650
+ uniqueVals = sorted(list(set(featList)))
651
+ for value in range(len(uniqueVals) - 1):
652
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
653
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
654
+ subDataSetB[:, -2]).size <= minsize - 1:
655
+ continue
656
+
657
+ R = weight_gain(subDataSetA,subDataSetB,weight,1)
658
+
659
+ if R - bestR >= mininc:
660
+ splitSuccess = True
661
+ bestR = R
662
+ lc = subDataSetA
663
+ rc = subDataSetB
664
+ bestFeature = i
665
+ bestValue = uniqueVals[value]
666
+ else: pass
667
+
668
+ if splitSuccess:
669
+ node.lc, leaf_no = createTree(lc, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight)
670
+ node.rc, leaf_no = createTree(rc,ori_dataset, feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol,weight)
671
+ node.bestFeature, node.bestValue = bestFeature, bestValue
672
+
673
+ if node.lc is None:
674
+ node.leaf_no = leaf_no
675
+ leaf_no += 1
676
+ # determine if this node is to save in all_dataset.csv
677
+ save_in_all = False
678
+ if node.R >= threshold and fea_tol(node.data,ori_dataset,feats,tolerance_list) == True:
679
+ save_in_all = True
680
+ write_csv(node, feats, save_in_all, correlation)
681
+
682
+ return node, leaf_no
683
+
684
+ elif correlation == 'R2':
685
+ node = Node(dataSet)
686
+ bestR = R2(dataSet[:, -2], dataSet[:, -1])
687
+ node.R = bestR
688
+ node.slope == None
689
+ if bestR >= threshold and fea_tol(dataSet,ori_dataset,feats,tolerance_list) == True:
690
+ node.leaf_no = leaf_no
691
+ leaf_no += 1
692
+ write_csv(node, feats, True, correlation)
693
+ return node, leaf_no
694
+
695
+ numFeatures = len(dataSet[0]) - 2
696
+ splitSuccess = False
697
+ bestFeature = -1
698
+ bestValue = 0
699
+
700
+ check_valve = False
701
+ for i in range(numFeatures):
702
+ featList = [example[i] for example in dataSet]
703
+ uniqueVals = sorted(list(set(featList)))
704
+ for value in range(len(uniqueVals) - 1):
705
+ # constraints imposed on features (greater tolerance in split process)
706
+ if not fea_tol_split(dataSet,ori_dataset,feats,tolerance_list,split_tol):
707
+ continue
708
+
709
+ subDataSetA, subDataSetB = splitDataSet(dataSet, i, uniqueVals[value])
710
+
711
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
712
+ subDataSetB[:, -2]).size <= minsize - 1:
713
+ continue
714
+
715
+ R = weight_gain(subDataSetA,subDataSetB,weight,2)
716
+
717
+ if R - bestR >= mininc:
718
+ check_valve = True
719
+ splitSuccess = True
720
+ bestR = R
721
+ lc = subDataSetA
722
+ rc = subDataSetB
723
+ bestFeature = i
724
+ bestValue = uniqueVals[value]
725
+
726
+ if check_valve == False:
727
+ for i in range(numFeatures):
728
+ featList = [example[i] for example in dataSet]
729
+ uniqueVals = sorted(list(set(featList)))
730
+
731
+ for value in range(len(uniqueVals) - 1):
732
+ if np.unique(subDataSetA[:, -2]).size <= minsize - 1 or np.unique(
733
+ subDataSetB[:, -2]).size <= minsize - 1:
734
+ continue
735
+
736
+ R = weight_gain(subDataSetA,subDataSetB,weight,2)
737
+
738
+ if R - bestR >= mininc:
739
+ splitSuccess = True
740
+ bestR = R
741
+ lc = subDataSetA
742
+ rc = subDataSetB
743
+ bestFeature = i
744
+ bestValue = uniqueVals[value]
745
+ else: pass
746
+
747
+ if splitSuccess:
748
+ node.lc, leaf_no = createTree(lc, ori_dataset,feats, leaf_no, correlation, tolerance_list,minsize, threshold, mininc,split_tol)
749
+ node.rc, leaf_no = createTree(rc, ori_dataset,feats, leaf_no, correlation,tolerance_list, minsize, threshold, mininc,split_tol)
750
+ node.bestFeature, node.bestValue = bestFeature, bestValue
751
+
752
+ if node.lc is None:
753
+ node.leaf_no = leaf_no
754
+ leaf_no += 1
755
+ # determine if this node is to save in all_dataset.csv
756
+ save_in_all = False
757
+ if node.R >= threshold and fea_tol(node.data,feats,tolerance_list) == True:
758
+ save_in_all = True
759
+ write_csv(node, feats, save_in_all, correlation)
760
+
761
+ return node, leaf_no
762
+
763
+
764
+ def PearsonR(X, Y):
765
+ xBar = np.mean(X)
766
+ yBar = np.mean(Y)
767
+ SSR = 0
768
+ varX = 0
769
+ varY = 0
770
+ if len(X) > 1:
771
+ for i in range(0, len(X)):
772
+ diffXXBar = X[i] - xBar
773
+ diffYYBar = Y[i] - yBar
774
+ SSR += (diffXXBar * diffYYBar)
775
+ varX += diffXXBar ** 2
776
+ varY += diffYYBar ** 2
777
+ SST = math.sqrt(varX * varY)
778
+ else:
779
+ SST = 1
780
+ SSR = 0
781
+ if SST == 0:
782
+ return 0
783
+ return SSR / SST
784
+
785
+
786
+ def MIC(X, Y):
787
+ if len(X) > 0:
788
+ mine = MINE(alpha=0.6, c=15)
789
+ mine.compute_score(X, Y)
790
+ return mine.mic()
791
+ else:
792
+ MICs = 0
793
+ return MICs
794
+
795
+
796
+ def R2(X, Y):
797
+ X = np.array(X)
798
+ Y = np.array(Y)
799
+ if len(X) > 0:
800
+ a = (X - np.mean(Y)) ** 2
801
+ SStot = np.sum(a)
802
+ b = (X - Y) ** 2
803
+ SSres = np.sum(b)
804
+ r2 = 1 - SSres / SStot
805
+ return r2
806
+ else:
807
+ r2 = -10
808
+ return r2
809
+
810
+
811
+ # Split the DataSet in a specific node
812
+ def splitDataSet(dataSet, axis, value):
813
+ retDataSetA = []
814
+ retDataSetB = []
815
+ for featVec in dataSet:
816
+ if featVec[axis] <= value:
817
+ retDataSetA.append(featVec)
818
+ else:
819
+ retDataSetB.append(featVec)
820
+ return np.array(retDataSetA), np.array(retDataSetB)
821
+
822
+ def fea_tol(dataSet,ori_dataSet,feats,tolerance_list):
823
+ if tolerance_list == None: return True
824
+ else:
825
+ record = 0
826
+ for i in range(len(tolerance_list)):
827
+ __feaname = tolerance_list[i][0]
828
+ __tolratio = float(tolerance_list[i][1])
829
+ index = feats.index(__feaname)
830
+ if (dataSet[:,index].max() - dataSet[:,index].min()) / (ori_dataSet[:,index].max()- ori_dataSet[:,index].min()) <= __tolratio:
831
+ record += 1
832
+ if record == len(tolerance_list):
833
+ return True
834
+
835
+ def fea_tol_split(dataSet,ori_dataSet,feats,tolerance_list,split_tol):
836
+ if tolerance_list == None: return True
837
+ else:
838
+ record = 0
839
+ for i in range(len(tolerance_list)):
840
+ __feaname = tolerance_list[i][0]
841
+ __tolratio = float(tolerance_list[i][1])
842
+ criter = max(split_tol,__tolratio)
843
+ index = feats.index(__feaname)
844
+ if (dataSet[:,index].max() - dataSet[:,index].min()) / (ori_dataSet[:,index].max()- ori_dataSet[:,index].min()) <= criter:
845
+ record += 1
846
+ if record > int(0.5*len(tolerance_list)):
847
+ return True
848
+
849
+
850
+ # Use graphviz to visualize the TCLR
851
+ def render(label, node, dot, feats):
852
+ mark = ''
853
+ if node.slope == None:
854
+ mark = ""#="" + str(node.size) + "" , ρ="" + str(round(node.R, 3))
855
+ else:
856
+ mark = ""#="" + str(node.size) + "" , ρ="" + str(round(node.R, 3)) + ' , slope=' + str(
857
+ round(node.slope, 3)) + ' , intercept=' + str(round(node.intercept, 3))
858
+
859
+ if node.lc is None:
860
+ mark = 'No_{}, '.format(node.leaf_no) + mark
861
+ dot.node(label, mark)
862
+
863
+ if node.lc is not None:
864
+ render(label + 'A', node.lc, dot, feats)
865
+ render(label + 'B', node.rc, dot, feats)
866
+ dot.edge(label, label + 'A', feats[node.bestFeature] + ""≤"" + str(node.bestValue))
867
+ dot.edge(label, label + 'B', feats[node.bestFeature] + "">"" + str(node.bestValue))
868
+
869
+
870
+ def write_csv(node, feats, save_in_all, correlation):
871
+ global record
872
+
873
+ frame = {}
874
+ for i in range(len(feats)):
875
+ frame[feats[i]] = node.data[:, i]
876
+ frame = pd.DataFrame(frame)
877
+
878
+ if node.slope == None:
879
+ frame['slope'] = None
880
+ frame['intercept'] = None
881
+ frame[correlation] = np.repeat(node.R, node.size)
882
+ frame.to_csv('Segmented/subdataset_{}.csv'.format(str(node.leaf_no)))
883
+ else:
884
+ frame['slope'] = node.slope
885
+ frame['intercept'] = node.intercept
886
+ frame[correlation] = np.repeat(node.R, node.size)
887
+ frame.to_csv('Segmented/subdataset_{}.csv'.format(str(node.leaf_no)))
888
+
889
+ frame.to_csv('Segmented/subdataset_{}.csv'.format(str(node.leaf_no)))
890
+
891
+ if not save_in_all: # do not save in the all_dataset.csv
892
+ _all_dataset = pd.read_csv('./Segmented/all_dataset.csv')
893
+ _all_dataset.drop(index=range(record, record+node.size), axis=0, inplace=True)
894
+ _all_dataset.to_csv('Segmented/all_dataset.csv', index=False)
895
+ return
896
+
897
+ _all_dataset = pd.read_csv('./Segmented/all_dataset.csv')
898
+ for item in range(len(frame.iloc[:, 0])):
899
+ _all_dataset.iloc[item + record, :] = frame.iloc[item, :]
900
+ record += len(frame.iloc[:, 0])
901
+ _all_dataset.to_csv('Segmented/all_dataset.csv', index=False)
902
+
903
+ def weight_gain(subDataSetA,subDataSetB,weight,matrix):
904
+ if matrix == 0:
905
+ newRa = PearsonR(subDataSetA[:, -2], subDataSetA[:, -1])
906
+ newRb = PearsonR(subDataSetB[:, -2], subDataSetB[:, -1])
907
+ elif matrix == 1:
908
+ newRa = MIC(subDataSetA[:, -2], subDataSetA[:, -1])
909
+ newRb = MIC(subDataSetB[:, -2], subDataSetB[:, -1])
910
+ elif matrix == 2:
911
+ newRa = R2(subDataSetA[:, -2], subDataSetA[:, -1])
912
+ newRb = R2(subDataSetB[:, -2], subDataSetB[:, -1])
913
+
914
+
915
+ if weight == False:
916
+ R = (newRa + newRb) / 2
917
+ return R
918
+ elif weight == True:
919
+ weightRa = len(subDataSetA[:, -1]) / (len(subDataSetA[:, -1]) + len(subDataSetB[:, -1]))
920
+ weightRb = len(subDataSetB[:, -1]) / (len(subDataSetA[:, -1]) + len(subDataSetB[:, -1]))
921
+ R = weightRa * newRa + weightRb * newRb
922
+ return R
923
+ else:
924
+ print('Parameter error | weight')
925
+
926
+
927
+ # code on 2023 May 9, Bin Cao
928
+ def generate_random_features(df: pd.DataFrame,
929
+ feature_list: List[str],
930
+ num_combinations: int,
931
+ random_seed:int) -> pd.DataFrame:
932
+ """"""
933
+ randomly generates new feature combinations.
934
+
935
+ :param df: DataFrame containing the original features.
936
+ :param feature_list: List of original features.
937
+ :param num_combinations: Number of combination features to generate.
938
+ :return: DataFrame containing the new features.
939
+ """"""
940
+ new_features = []
941
+ random.seed(random_seed)
942
+ # randomly generates combination features
943
+ for i in range(num_combinations):
944
+ # randomly chooses two features
945
+ f1 = random.choice(feature_list)
946
+ f2 = random.choice(feature_list)
947
+
948
+ # choose a operator
949
+ op = random.choice(['+', '-', '*',])
950
+
951
+ self_op1 = random.choice(['*1', '*2', '*3','*4','**2','**3'])
952
+ self_op2 = random.choice(['*1', '*2', '*3','*4','**2','**3'])
953
+
954
+ new_f1 = f'{f1} {self_op1}'
955
+ new_f2 = f'{f2} {self_op2}'
956
+
957
+ # new feature name
958
+ new_feature = f'({new_f1} {op} {new_f2})'
959
+
960
+ new_features.append(new_feature)
961
+
962
+ # cal new features
963
+ df[new_feature] = eval(f'(df[""{f1}""] {self_op1}) {op} (df[""{f2}""] {self_op2})')
964
+
965
+ # reture DataFrame
966
+ return df","Python"
967
+ "Biochemistry","Bin-Cao/TCLRmodel","Researches/Note.md",".md","38","2","# Relevant researches applied of TCLR
968
+ ","Markdown"
data/dataset_Bioengineering.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Bioinformatics.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7568d53619cdad685ef5d0593de391aaeaf60de36448791f2a4cd4e80619ab94
3
+ size 1053278348
data/dataset_Biologics.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:651d86e23d790a0818a076c5461d4e5b2caaffc8313ab31ab57a573ed41e3782
3
+ size 719907555
data/dataset_Biology.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:464d2634df001ff502b538b52c3826fbcd674e1b755312aade441887871ea037
3
+ size 345150375
data/dataset_Biomarker.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e43c7f13f678ba395e1ea202a41a0535c7869cc64226d9006bb91591b64abddb
3
+ size 26337596
data/dataset_Biomedical.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e2336d0e2542c72e76f98648c0b008b24554b6d3c4e703fbf1563d3dbe4521de
3
+ size 1104666414
data/dataset_Biophysics.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Biosensors.csv ADDED
@@ -0,0 +1,1614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "keyword","repo_name","file_path","file_extension","file_size","line_count","content","language"
2
+ "Biosensors","Cassey2016/PPG_Peak_Detection","main.m",".m","3040","58","% =========================================================================
3
+ % Below functions are the implementation for the comparison methods in
4
+ % paper:
5
+ % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian,
6
+ % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson,
7
+ % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons,
8
+ % David D. McManus, and Ki H. Chon. 2022.
9
+ % ""A Real-Time PPG Peak Detection Method for Accurate Determination of
10
+ % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia""
11
+ % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082
12
+ %
13
+ % Please cite our paper if you used our implementation code. Thank you.
14
+ % Author: Dong Han (dong.han@uconn.edu), 01/31/2022.
15
+ % =========================================================================
16
+
17
+ % -------------------------------------------------------------------------
18
+ % Input:
19
+ % PPG_raw_buffer: should be 30-sec segment.
20
+ % fs_PPG_raw: the sampling frequency of the PPG_raw_buffer.
21
+ % -------------------------------------------------------------------------
22
+ %% Preparation of PPG signal:
23
+ addpath('.\func')
24
+ [PPG_buffer,fs_PPG] = my_func_prep_PPG_buffer(PPG_raw_buffer,fs_PPG_raw);
25
+
26
+ %% Method 1: implemented method 1-a
27
+ V_max_flag = true; % true == upper peak detection.
28
+ addpath('.\method_01_and_02');
29
+ output_upper_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper.
30
+
31
+ %% Method 2: implemented method 1-b
32
+ V_max_flag = false; % false == lower peak detection.
33
+ output_lower_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper.
34
+
35
+ %% Method 3 & 4: implemented method 2, it has two output peaks in ""output_Elgendi_1_2013""
36
+ delta = 0.5; % it was 0.1 as mentioned in the paper. But I think 0.5 works better (0.5 is in the billauer's website).
37
+ addpath('.\method_03_and_04');
38
+ [output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(PPG_buffer, delta, fs_PPG);
39
+
40
+ %% Method 5: first derivative and adaptive thresholding method in Li et al. [4] and Elgendi's paper [3]
41
+ abpsig = resample(PPG_buffer,fs_abpsig,fs_PPG_buffer); % upsampling it to 125 Hz.
42
+ addpath('.\method_05');
43
+ [output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(abpsig,fs_abpsig);
44
+
45
+ %% Method 6: implemented method 4
46
+ fs_abp = 250; % Hz.
47
+ abp = resample(PPG_buffer,fs_abp,fs_PPG); % upsampling it to 125 Hz.
48
+ addpath('.\method_06');
49
+ [output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(abp,fs_abp);
50
+
51
+ %% Method 7: event-related moving averages with dynamic threshold method in Elgendi et al.'s paper [3]
52
+ addpath('.\method_07');
53
+ [output_Elgendi_4_2013] = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(-PPG_raw_buffer,fs_PPG_raw);
54
+
55
+ %% Method 8 & 9: peak detection on Stationary Wavelet Transform of PPG signal
56
+ fs_swt = 125; % Hz.
57
+ PPG_swt = resample(PPG_buffer,fs_swt,fs_PPG); % upsampling it to 125 Hz.
58
+ addpath('.\method_08_and_09');
59
+ [output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_swt,fs_swt);","MATLAB"
60
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_07/my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV.m",".m","6505","156","function output_Elgendi_4_2013 = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(raw_PPG,fs_PPG)
61
+ % =========================================================================
62
+ % This is my implementation of the method IV in this paper:
63
+ % Elgendi, Mohamed, et al.
64
+ % ""Systolic peak detection in acceleration photoplethysmograms measured from
65
+ % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
66
+ %
67
+ % Implemented by Dong Han on 03/02/2020.
68
+ %
69
+ % Please cite our paper if you used this code:
70
+ % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian,
71
+ % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson,
72
+ % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons,
73
+ % David D. McManus, and Ki H. Chon. 2022.
74
+ % ""A Real-Time PPG Peak Detection Method for Accurate Determination of
75
+ % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia""
76
+ % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082
77
+ %
78
+ % Please cite our paper if you used our code. Thank you.
79
+ % =========================================================================
80
+ %% pre-processing - bandpass filtering
81
+ [b, a] = butter(2,[0.5 8]/(fs_PPG/2)); % 2nd order bandpass filter 0.5-8Hz;
82
+ filtered_PPG = filtfilt(b, a, raw_PPG); % zero-phase filter.
83
+ filtered_PPG = filtered_PPG ./ std(filtered_PPG); % normalizing data is very important for my peak detection.
84
+ filtered_PPG = filtered_PPG - mean(filtered_PPG);
85
+
86
+ debugging_plot_flag = false; % only for plotting debugging figures.
87
+
88
+ % clip the signal by keeping the signal above zero.
89
+ % I do not want to do this, so i will move all signal above zero.
90
+ S_n = filtered_PPG;
91
+ % ---- Not following the paper to clip signal but move all signal above zero:
92
+ % if min(S_n) < 0
93
+ % Z_n = S_n - min(S_n); % elevate signal above zero.
94
+ % else
95
+ % % the minimum of S_n is still above zero, so do nothing.
96
+ % Z_n = S_n;
97
+ % end
98
+ % ---- Following the paper: only keep the positive value:
99
+ Z_n = S_n;
100
+ Z_n(Z_n < 0) = 0;
101
+ %% pre-processing - squaring
102
+ y_n = (Z_n).^2; % element-wise power.
103
+ %% feature extraction - generating potential blocks using two moving averages
104
+ W_1 = round(0.111 * fs_PPG); % mentioned as the paper by brute-force search.
105
+ % first moving average:
106
+ % MA_peak = y_n; % for the beginning and ending signal, use the original signal.
107
+ % for nn = 1+round(W_1/2):length(raw_PPG)-round(W_1/2)
108
+ % temp_range = (nn-round(W_1/2)):(nn+round(W_1/2));
109
+ % MA_peak(nn) = sum(y_n(temp_range))/W_1;
110
+ % end
111
+ MA_peak = movmean(y_n,W_1);
112
+
113
+ % second moving average:
114
+ W_2 = round(0.667 * fs_PPG);
115
+ % MA_beat = y_n;
116
+ % for nn = 1+round(W_2/2):length(raw_PPG)-round(W_2/2)
117
+ % temp_range = (nn-round(W_2/2)):(nn+round(W_2/2));
118
+ % MA_beat(nn) = sum(y_n(temp_range))/W_2;
119
+ % end
120
+ MA_beat = movmean(y_n,W_2);
121
+ %% classification - thresholding
122
+ beta = 0.02; % from the paper, by brute force search.
123
+ z_bar = mean(y_n);
124
+ alpha = beta * z_bar; % offset level.
125
+ THR_1 = MA_beat + alpha;
126
+
127
+ Blocks_Of_Interest = zeros(size(MA_peak)); % I initial it as zero.
128
+ for nn = 1:length(MA_peak)
129
+ if MA_peak(nn) > THR_1(nn) % I think it is THR_1(nn).
130
+ Blocks_Of_Interest(nn) = 0.1;
131
+ else
132
+ % since I inital block of interest as zero, so I do not need to
133
+ % assign zero again.
134
+ end
135
+ end
136
+
137
+ % searh for onset and offset of each block.
138
+ count_blocks = 0;
139
+ block_onset = NaN(size(MA_peak));
140
+ block_offset = NaN(size(MA_peak));
141
+ if any(Blocks_Of_Interest > 0) % there is a block exist.
142
+ for nn = 1:length(MA_peak)
143
+ if nn == 1 && Blocks_Of_Interest(nn) > 0
144
+ % the first point is a block;
145
+ count_blocks = count_blocks + 1; % since the block start from zero, I have to add the counter first.
146
+ block_onset(count_blocks,1) = nn;
147
+ elseif nn == length(MA_peak) && Blocks_Of_Interest(nn) > 0
148
+ % end with a block:
149
+ % no need to add count_blocks;
150
+ block_offset(count_blocks,1) = nn;
151
+ else
152
+ if nn > 1
153
+ if Blocks_Of_Interest(nn-1) == 0 && Blocks_Of_Interest(nn) > 0 % a jump means a new block.
154
+ count_blocks = count_blocks + 1;
155
+ block_onset(count_blocks,1) = nn;
156
+ elseif Blocks_Of_Interest(nn-1) > 0 && Blocks_Of_Interest(nn) == 0 % a drop means the end of previous block.
157
+ block_offset(count_blocks,1) = nn;
158
+ end
159
+ end
160
+ end
161
+ end
162
+ else
163
+ % there is no block existed. Check why.
164
+ % keyboard;
165
+ HR_Elgendi_4_2013 = 0; % there is no peak location.
166
+ S_peaks = 1;
167
+ output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,...
168
+ 'PPG_peak_loc_Elgendi_4_2013',S_peaks,...
169
+ 'HR_Elgendi_4_2013',HR_Elgendi_4_2013);
170
+ return
171
+ end
172
+
173
+ block_onset(isnan(block_onset)) = []; % remove extra elements.
174
+ block_offset(isnan(block_offset)) = []; % remove extra elements.
175
+ if size(block_onset,1) ~= size(block_offset,1)
176
+ % not same number of onset and offset, check here.
177
+ keyboard;
178
+ end
179
+
180
+ if size(block_onset,1) ~= count_blocks
181
+ keyboard;
182
+ end
183
+ S_peaks = NaN(count_blocks,1);
184
+ THR_2 = W_1;
185
+
186
+ for jj = 1:count_blocks
187
+ block_idx = [block_onset(jj,1):block_offset(jj,1)];
188
+ [~,I] = max(y_n(block_idx));
189
+ S_peaks(jj,1) = block_onset(jj,1) + I - 1;
190
+ end
191
+
192
+ if debugging_plot_flag
193
+ figure;
194
+ plot(filtered_PPG);hold on;
195
+ plot(S_peaks,y_n(S_peaks),'r.','markersize',10);
196
+ plot(y_n);
197
+ plot(MA_peak,'k:');
198
+ plot(MA_beat,'r--');
199
+ plot(THR_1,'g.-');
200
+ plot(Blocks_Of_Interest*max(y_n)*10,'color',[0.5,0.5,0.5]); % grey color. I want to make block more obvious.
201
+
202
+ legend('filtered PPG','peaks', 'squared PPG with clip to zero', 'MA peak', 'MA beat','THR 1', 'Blocks of Interest');
203
+ end
204
+
205
+ if isempty(S_peaks)
206
+ HR_Elgendi_4_2013 = 0; % there is no peak location.
207
+ S_peaks = 1;
208
+ else
209
+ HR_Elgendi_4_2013 = 60 * fs_PPG ./ diff(S_peaks); % calculate the HR.
210
+ end
211
+
212
+ output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,...
213
+ 'PPG_peak_loc_Elgendi_4_2013',S_peaks,...
214
+ 'HR_Elgendi_4_2013',HR_Elgendi_4_2013);
215
+ end","MATLAB"
216
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_01_and_02/my_peak_compare_Shin_2009.m",".m","21523","388","function [output_Shin_2009] = my_peak_compare_Shin_2009(raw_PPG,fs_PPG,V_max_flag)
217
+ % =========================================================================
218
+ % This function is the implementation of this paper:
219
+ % Shin, Hang Sik, Chungkeun Lee, and Myoungho Lee.
220
+ % ""Adaptive threshold method for the peak detection of
221
+ % photoplethysmographic waveform.""
222
+ % Computers in biology and medicine
223
+ % 39.12 (2009): 1145-1152.
224
+ %
225
+ % Implemented by: Dong Han, on 02/10/2020.
226
+ %
227
+ % Please cite our paper if you used this code:
228
+ % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian,
229
+ % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson,
230
+ % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons,
231
+ % David D. McManus, and Ki H. Chon. 2022.
232
+ % ""A Real-Time PPG Peak Detection Method for Accurate Determination of
233
+ % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia""
234
+ % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082
235
+ %
236
+ % Please cite our paper if you used our code. Thank you.
237
+ % =========================================================================
238
+ debugging_plot_flag = false; % debugging plot. Can be false if don't want to plot anything.
239
+ %% Section 2.4 PPG frequency analysis and filtering.
240
+
241
+ % (1): high pass >= 0.5 Hz.
242
+ [b, a] = butter(6,[0.5 20]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018
243
+ raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component
244
+ raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection.
245
+ raw_PPG = raw_PPG - mean(raw_PPG);
246
+ %% Section 2.5 & 2.6 Peak detection algorithm & Adaptive threshold detection
247
+
248
+ % (1): bandpass filtering, no moving average filter or wavelet
249
+ % decomposition.
250
+ filtered_PPG = raw_PPG;
251
+ Fs = fs_PPG;
252
+
253
+ % % ===== interpolation to 1kHz of PPG: =====
254
+ % x = 1:length(filtered_PPG);
255
+ % v = filtered_PPG;
256
+ %
257
+ % upsample_Fs = 250;
258
+ % xq = 1:Fs/upsample_Fs:length(filtered_PPG);
259
+ % vq1 = interp1(x,v,xq);
260
+ %
261
+ % filtered_PPG = vq1;
262
+ % Fs = upsample_Fs; % upsampled to 1000 Hz.
263
+
264
+ % figure
265
+ % plot(x,v,'o',xq,vq1,':.');
266
+ % xlim([0 max(xq)]);
267
+ % title('(Default) Linear Interpolation');
268
+
269
+ % (2): V_max
270
+ % slope_k: k-th slope amplitude;
271
+ % s_r: slope changing rate (empirically: V_max = -0.6);
272
+ % V_n_1: previous peak amplitude;
273
+ % std_PPG: standard deviation of entire PPG signal;
274
+ % Fs: sampling frequency.
275
+
276
+ filtered_PPG = filtered_PPG(:);
277
+ slope_k = NaN(size(filtered_PPG)); % should be a column vector.
278
+ peak_loc = NaN(size(filtered_PPG)); % the array to store PPG peak index.
279
+ pk_idx = 1; % the counter of peaks.
280
+ %% Section 2.7: Peak Correction
281
+ refractory_period = 0.6 * Fs; % sec * sampling frequency, initial refractory period is 0.6 sec.
282
+
283
+ temp_win_left = round(0.15 * Fs); % sec * sampling frequency. This is the search region for local minima or maxima detection. chose 0.15 sec because 0.3 sec == 200 BPM.
284
+ temp_win_right = round(0.15 * Fs);
285
+
286
+
287
+ if V_max_flag % doing upper peak detection.
288
+ s_r = -0.6;
289
+ else
290
+ s_r = 0.6;%0.6; % not positive because my signal is zero mean.
291
+ % I need to make all bottom signal positive, so I am moving them up.
292
+ % move_filter_amp = min(filtered_PPG) * (-1);
293
+ % filtered_PPG = filtered_PPG + move_filter_amp + std(raw_PPG); % move the lowest value more than zero.
294
+ end
295
+
296
+
297
+ slope_meet_PPG_flag = false; % mark if the slope meet PPG.
298
+ slope_lower_PPG_flag = false; % mark if slope is lower than PPG, once PPG amp is lower than slope, mark it back.
299
+ prev_slope = NaN; % First, I want to test not decreasing with PPG amplitude.
300
+ if debugging_plot_flag % debugging plot
301
+ figure;
302
+ plot(filtered_PPG);
303
+ hold on;
304
+ end
305
+ for kk = 1:length(filtered_PPG)
306
+ % this is for debugging:
307
+ if kk == 2
308
+ my_stop = 1;
309
+ end
310
+ if kk == 1 % initial the slope value
311
+ if V_max_flag
312
+ slope_k(1,1) = 0.2 * max(filtered_PPG);
313
+ std_PPG = std(filtered_PPG);
314
+ else
315
+ slope_k(1,1) = 0.2 * min(filtered_PPG); % since my signal is zero mean, I start from the negative amp. % I added what I moved.
316
+ std_PPG = -std(filtered_PPG);
317
+ end
318
+ % std_PPG = std(filtered_PPG);
319
+ V_n_1 = slope_k(1,1);
320
+ else
321
+ if slope_meet_PPG_flag % slope has met PPG before.
322
+ slope_k(kk,1) = filtered_PPG(kk,1);
323
+ if V_max_flag % upper peak detection.
324
+ if kk < 2 % in the second point of signal
325
+ turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)); % we met local maximum.
326
+ else
327
+ turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)) & (slope_k(kk - 1,1) > slope_k(kk-2,1)); % we met local maximum.
328
+ end
329
+ else
330
+ if kk < 2 % in the second point of signal
331
+ turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)); % we met local minimum.
332
+ else
333
+ turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)) & (slope_k(kk - 1,1) < slope_k(kk-2,1)); % we met local minimum.
334
+ end
335
+ end
336
+
337
+ if turn_point_flag % there is a turning point.
338
+ if pk_idx > 1 % not the first peak
339
+ % check local maxima or minima:
340
+ if (kk - temp_win_left) < 1
341
+ temp_left = 1;
342
+ else
343
+ temp_left = kk - temp_win_left;
344
+ end
345
+
346
+ if (kk + temp_win_right) > length(filtered_PPG)
347
+ temp_right = length(filtered_PPG);
348
+ else
349
+ temp_right = kk + temp_win_right;
350
+ end
351
+ temp_win = temp_left:temp_right;
352
+ local_m_check = filtered_PPG(temp_win);
353
+ if V_max_flag
354
+ temp_m_idx = find(local_m_check > slope_k(kk - 1,1)); % check if there is another maximum than detected, remember use k-1.
355
+ else
356
+ temp_m_idx = find(local_m_check < slope_k(kk - 1,1)); % check if there is another minimum than detected
357
+ end
358
+
359
+ if isempty(temp_m_idx) % there is no more max or min than this peak
360
+ if (kk - peak_loc(pk_idx-1,1) > refractory_period) % it is not the first peak, and the second peak is outside refractory period. It should be kk, because I have not assign the peak to the array.
361
+ peak_loc(pk_idx,1) = kk-1;
362
+ V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1);% previous peak amplitude %slope_k(kk-1,1);
363
+ % update refractory period:
364
+ refractory_period = 0.6 * (kk - peak_loc(pk_idx-1,1)); % current index minus peak location. update the refractory peroid before updating the peak counting.
365
+ pk_idx = pk_idx + 1;
366
+
367
+ % reset slope meet flag:
368
+ slope_meet_PPG_flag = false;
369
+ slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs);
370
+
371
+ % ---- for checking lower slope -------
372
+ temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
373
+ if V_max_flag
374
+ if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
375
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
376
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
377
+ end
378
+ else
379
+ if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
380
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
381
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
382
+ end
383
+ end
384
+ % -------------------------------------------
385
+ if V_max_flag
386
+ temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal.
387
+ else
388
+ temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal.
389
+ end
390
+ if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude.
391
+ slope_lower_PPG_flag = true; % slope is lower than PPG signal.
392
+ prev_slope = slope_k(kk,1); % store the slope value now.
393
+ slope_k(kk,1) = filtered_PPG(kk,1);
394
+ end
395
+ if debugging_plot_flag % debugging plot
396
+ plot(kk,slope_k(kk,1),'r.');
397
+ end
398
+
399
+ else
400
+ if (kk - peak_loc(pk_idx-1,1) <= refractory_period) % it is because of the refractory period that cause the no peak. It should be kk, because I have not assign the peak to the array.
401
+ slope_k(kk,1) = filtered_PPG(kk,1);% from the fig.3(c) in the paper, I see they are using the signal amplitude, not slope.
402
+ % no need to reset slope meet flag, waiting for
403
+ % next turning point.
404
+ if debugging_plot_flag % debugging plot
405
+ plot(kk,slope_k(kk,1),'r.');
406
+ end
407
+ end
408
+ end
409
+ else % there are more peaks higher then current kk peak.
410
+ if debugging_plot_flag % debugging plot
411
+ plot(kk,slope_k(kk,1),'r.');
412
+ end
413
+ end
414
+ else % the first peak, no need to check refractory period.
415
+ % check local maxima or minima:
416
+ if (kk - temp_win_left) < 1
417
+ temp_left = 1;
418
+ else
419
+ temp_left = kk - temp_win_left;
420
+ end
421
+
422
+ if (kk + temp_win_right) > length(filtered_PPG)
423
+ temp_right = length(filtered_PPG);
424
+ else
425
+ temp_right = kk + temp_win_right;
426
+ end
427
+ temp_win = temp_left:temp_right;
428
+ local_m_check = filtered_PPG(temp_win);
429
+ if V_max_flag
430
+ temp_m_idx = find(local_m_check > slope_k(kk-1,1)); % check if there is another maximum than detected, always detect previous peak.
431
+ else
432
+ temp_m_idx = find(local_m_check < slope_k(kk-1,1)); % check if there is another minimum than detected
433
+ end
434
+
435
+ if isempty(temp_m_idx)
436
+ peak_loc(pk_idx,1) = kk-1;
437
+ if pk_idx > 1
438
+ V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1);
439
+ else
440
+ V_n_1 = slope_k(kk-1,1);% previous peak amplitude %slope_k(kk-1,1);
441
+ end
442
+ pk_idx = pk_idx + 1;
443
+
444
+ % reset slope meet flag:
445
+ slope_meet_PPG_flag = false;
446
+ slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs);
447
+ % ---- for checking lower slope -------
448
+ temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
449
+ if V_max_flag
450
+ if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
451
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
452
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
453
+ end
454
+ else
455
+ if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
456
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
457
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
458
+ end
459
+ end
460
+ % -------------------------------------------
461
+ if V_max_flag
462
+ temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal.
463
+ else
464
+ temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal.
465
+ end
466
+
467
+ if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude.
468
+ slope_k(kk,1) = filtered_PPG(kk,1);
469
+ end
470
+ if debugging_plot_flag % debugging plot
471
+ plot(kk,slope_k(kk,1),'r.');
472
+ end
473
+ else % there are more peaks higher then current kk peak.
474
+ if debugging_plot_flag % debugging plot
475
+ plot(kk,slope_k(kk,1),'r.');
476
+ end
477
+ end
478
+ % no need to calculate refractory period, because there is only one peak, at least two peaks can give this correctly:
479
+ end
480
+ else
481
+ % turning point did not meet, so keep decreasing or
482
+ % increasing the slope.
483
+ % slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs);
484
+ if debugging_plot_flag % debugging plot
485
+ plot(kk,slope_k(kk,1),'r.');
486
+ end
487
+ end
488
+ else % slope has not met PPG before. Keep decresing or increasing according to 'V_max_flag'.
489
+ % if slope_lower_PPG_flag % if there is a slope lower than PPG before:
490
+ % slope_k(kk,1) = prev_slope;
491
+ % else
492
+ slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs);
493
+ % ---- for checking lower slope -------
494
+ temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
495
+ if V_max_flag
496
+ if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
497
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
498
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
499
+ end
500
+ else
501
+ if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
502
+ temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
503
+ slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
504
+ end
505
+ end
506
+ % -------------------------------------------
507
+
508
+ % end
509
+ % if slope_k(kk,1) < filtered_PPG(kk,1) % if slope is below PPG signal, we will reset slope value to PPG amplitude.
510
+ % slope_lower_PPG_flag = true; % slope is lower than PPG signal.
511
+ % prev_slope = slope_k(kk,1); % store the slope value now.
512
+ % slope_k(kk,1) = filtered_PPG(kk,1);
513
+ % elseif slope_k(kk,1) > filtered_PPG(kk,1) % slope is higher.
514
+ % slope_lower_PPG_flag = false;
515
+ % prev_slope = NaN; % reset the prev value.
516
+
517
+ % end
518
+
519
+ % if slope_lower_PPG_flag ~= 1 % if slope was not lower than PPG.
520
+ % % -------------- Check if two lines will meet -----------------
521
+ % PPG_x1 = kk - 1;
522
+ % PPG_x2 = kk;
523
+ % PPG_y1 = filtered_PPG(kk-1,1);
524
+ % PPG_y2 = filtered_PPG(kk,1);
525
+ % slope = s_r;
526
+ % slope_y2 = slope_k(kk,1);
527
+ % slope_y1 = slope_k(kk-1,1);
528
+ % [meet_x] = my_slope_meet_PPG(PPG_x1,PPG_x2,PPG_y1,PPG_y2,slope,slope_y2,slope_y1);
529
+ %
530
+ % slope_meet_PPG_flag = (ceil(meet_x) == kk);%(slope_k(kk,1) - filtered_PPG(kk,1)) < 0.1; % 0.3 is a testing value. %slope_k(kk,1) == filtered_PPG(kk,1) % slope meets the PPG signal.
531
+ % end
532
+ if V_max_flag
533
+ slope_meet_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) > filtered_PPG(kk - 1,1));
534
+ else
535
+ slope_meet_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) < filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude.
536
+ end
537
+ % -------------------------------------------------------------
538
+ % I found I cannot use equal, because the PPG sampling
539
+ % frequency is not so high.
540
+ if slope_meet_PPG_flag
541
+ slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude.
542
+ else
543
+ % don't need to do anything.
544
+ if slope_lower_PPG_flag ~= 1 % there was no slope lower than PPG before.
545
+ if V_max_flag
546
+ slope_lower_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % beginning part has same amplitude, but the ending part slope is lower.
547
+ else
548
+ slope_lower_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude.
549
+ end
550
+ if slope_lower_PPG_flag
551
+ prev_slope = slope_k(kk,1); % store the slope value now.
552
+ slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude.
553
+ end
554
+ else % there was slope lower than PPG before.
555
+
556
+ if V_max_flag
557
+ temp_PPG_below_slope_flag = filtered_PPG(kk,1) < prev_slope; % upper peak detection, so PPG below slope.
558
+ else
559
+ temp_PPG_below_slope_flag = filtered_PPG(kk,1) > prev_slope; % lower peak detection, so PPG above slope.
560
+ end
561
+
562
+ if temp_PPG_below_slope_flag % PPG is lower than prev slope.
563
+ slope_k(kk,1) = prev_slope; % stop tracking PPG amp.
564
+ slope_lower_PPG_flag = false; % reset the lower PPG flag.
565
+ prev_slope = NaN;
566
+ else
567
+ slope_k(kk,1) = filtered_PPG(kk,1); % keep tracking PPG amp.
568
+ end
569
+ end
570
+ end
571
+ if debugging_plot_flag % debugging plot
572
+ plot(kk,slope_k(kk,1),'r.');
573
+ end
574
+ end
575
+ end
576
+
577
+ end
578
+ % ================== IMPORTANT: clean up NaN value ========================
579
+ peak_loc(isnan(peak_loc)) = []; % remove empty peak loc.
580
+ if V_max_flag % doing upper peak detection.
581
+
582
+ else
583
+ % moving signal back.
584
+ % filtered_PPG = filtered_PPG - move_filter_amp - std(raw_PPG); % move the lowest value more than zero.
585
+ % slope_k = slope_k - move_filter_amp - std(raw_PPG); % move the slope as well.
586
+ end
587
+
588
+ if debugging_plot_flag % debugging plot
589
+ plot(peak_loc,filtered_PPG(peak_loc),'ko');
590
+ end
591
+
592
+ if isempty(peak_loc)
593
+ HR_Shin_2009 = 0; % there is no peak location.
594
+ peak_loc = 1;
595
+ else
596
+ HR_Shin_2009 = 60 * Fs ./ diff(peak_loc); % calculate the HR.
597
+ end
598
+
599
+ output_Shin_2009 = struct('PPG_peak_loc_Shin_2009',peak_loc,...
600
+ 'slope_Shin_2009',slope_k,...
601
+ 'filtered_PPG_Shin_2009',filtered_PPG,...
602
+ 'HR_Shin_2009',HR_Shin_2009);
603
+ end","MATLAB"
604
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_05/my_func_ppg_peakdet_method_05_Elgendi_2013_method_II.m",".m","11993","412","function [output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(raw_PPG,fs_PPG)
605
+ % -------------------------------------------------------------------------
606
+ % This peak detection function was mentioned in this paper:
607
+ % Elgendi, Mohamed, et al.
608
+ % ""Systolic peak detection in acceleration photoplethysmograms measured from
609
+ % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
610
+ %
611
+ [onsetp,peakp,dicron,abpsig] = delineator(raw_PPG,fs_PPG);
612
+ % -------------------------------------------------------------------------
613
+
614
+ if isempty(peakp) % there is no peak detected:
615
+ HR_Elgendi_2_2013 = 0; % there is no peak location.
616
+ peakp = 1;
617
+ else
618
+ HR_Elgendi_2_2013 = 60 * fs_PPG ./ diff(peakp); % calculate the HR.
619
+ end
620
+
621
+
622
+ output_Elgendi_2_2013 = struct('PPG_peak_loc_Elgendi_2_2013',peakp,...
623
+ 'HR_Elgendi_2_2013',HR_Elgendi_2_2013,...
624
+ 'filtered_PPG_Elgendi_2_2013',abpsig);
625
+ end
626
+
627
+ function [onsetp,peakp,dicron,abpsig] = delineator(abpsig,abpfreq)
628
+ % Below was copied from Mathwords File Exchange ""Pulse Waveform Delineator"":
629
+ % https://www.mathworks.com/matlabcentral/fileexchange/29484-pulse-waveform-delineator
630
+
631
+ % This program is intended to delineate the fiducial points of pulse waveforms
632
+ % Inputs:
633
+ % abpsig: input as original pulse wave signals;
634
+ % abpfreq: input as the sampling frequency;
635
+ % Outputs:
636
+ % onsetp: output fiducial points as the beginning of each beat;
637
+ % peakp: output fiducial points as systolic peaks;
638
+ % dicron: output fiducial points as dicrotic notches;
639
+
640
+ % Its delineation is based on the self-adaptation in pulse waveforms, but
641
+ % not in the differentials.
642
+
643
+ % Reference:
644
+ % BN Li, MC Dong & MI Vai (2010)
645
+ % On an automatic delineator for arterial blood pressure waveforms
646
+ % Biomedical Signal Processing and Control 5(1) 76-81.
647
+
648
+ % LI Bing Nan @ University of Macau, Feb 2007
649
+ % Revision 2.0.5, Apr 2009
650
+
651
+ %Initialization
652
+ peakIndex=0;
653
+ onsetIndex=0;
654
+ dicroIndex=0;
655
+ stepWin=2*abpfreq;
656
+ closeWin=floor(0.1*abpfreq); %invalide for pulse beat > 200BPM
657
+
658
+ sigLen=length(abpsig);
659
+
660
+ peakp=[];
661
+ onsetp=[];
662
+ dicron=[];
663
+
664
+ %lowpass filter at first
665
+ coh=25; %cutoff frequency is 25Hz
666
+ coh=coh*2/abpfreq;
667
+ od=3; %3rd order bessel filter
668
+ [B,A]=besself(od,coh);
669
+ abpsig=filter(B,A,abpsig);
670
+ abpsig=10*abpsig;
671
+
672
+ abpsig=smooth(abpsig);
673
+
674
+ %Compute differentials
675
+ ttp=diff(abpsig);
676
+ diff1(2:sigLen)=ttp;
677
+ diff1(1)=diff1(2);
678
+ diff1=100*diff1;
679
+ clear ttp;
680
+ diff1=smooth(diff1);
681
+
682
+ if sigLen>12*abpfreq
683
+ tk=10;
684
+ elseif sigLen>7*abpfreq
685
+ tk=5;
686
+ elseif sigLen>4*abpfreq
687
+ tk=2;
688
+ else
689
+ tk=1;
690
+ end
691
+
692
+ %Seek avaerage threshold in original signal
693
+ if tk>1 %self-learning threshold with interval sampling
694
+ tatom=floor(sigLen/(tk+2));
695
+ for ji=1:tk %search the slopes of abp waveforms
696
+ sigIndex=ji*tatom;
697
+ tempIndex=sigIndex+abpfreq;
698
+ [tempMin,jk,tempMax,jl]=seeklocales(abpsig,sigIndex,tempIndex);
699
+ tempTH(ji)=tempMax-tempMin;
700
+ end
701
+ abpMaxTH=mean(tempTH);
702
+ else
703
+ [tempMin,jk,tempMax,jl]=seeklocales(abpsig,closeWin,sigLen);
704
+ abpMaxTH=tempMax-tempMin;
705
+ end
706
+ clear j*;
707
+ clear t*;
708
+
709
+ abpMaxLT=0.4*abpMaxTH;
710
+
711
+ %Seek pulse beats by MinMax method
712
+ % diffIndex=1;
713
+ diffIndex=closeWin; %Avoid filter distortion
714
+
715
+ while diffIndex<sigLen
716
+ tempMin=abpsig(diffIndex); %Initialization
717
+ tempMax=abpsig(diffIndex);
718
+ tempIndex=diffIndex;
719
+ tpeakp=diffIndex; %Avoid initial error
720
+ tonsetp=diffIndex; %Avoid initial error
721
+
722
+ while tempIndex<sigLen
723
+ %If no pulses within 2s, then adjust threshold and retry
724
+ if (tempIndex-diffIndex)>stepWin
725
+ % tempIndex=diffIndex-closeWin;
726
+ tempIndex=diffIndex;
727
+ abpMaxTH=0.6*abpMaxTH;
728
+ if abpMaxTH<=abpMaxLT
729
+ abpMaxTH=2.5*abpMaxLT;
730
+ end
731
+ break;
732
+ end
733
+
734
+ if (diff1(tempIndex-1)*diff1(tempIndex+1))<=0 %Candidate fiducial points
735
+ if (tempIndex+5)<=sigLen
736
+ jk=tempIndex+5;
737
+ else
738
+ jk=sigLen;
739
+ end
740
+ if (tempIndex-5)>=1
741
+ jj=tempIndex-5;
742
+ else
743
+ jj=1;
744
+ end
745
+
746
+ %Artifacts of oversaturated or signal loss?
747
+ if (jk-tempIndex)>=5
748
+ for ttk=tempIndex:jk
749
+ if diff1(ttk)~=0
750
+ break;
751
+ end
752
+ end
753
+ if ttk==jk
754
+ break; %Confirm artifacts
755
+ end
756
+ end
757
+
758
+ if diff1(jj)<0 %Candidate onset
759
+ if diff1(jk)>0
760
+ [tempMini,tmin,ta,tb]=seeklocales(abpsig,jj,jk);
761
+ if abs(tmin-tempIndex)<=2
762
+ tempMin=tempMini;
763
+ tonsetp=tmin;
764
+ end
765
+ end
766
+ elseif diff1(jj)>0 %Candidate peak
767
+ if diff1(jk)<0
768
+ [tc,td,tempMaxi,tmax]=seeklocales(abpsig,jj,jk);
769
+ if abs(tmax-tempIndex)<=2
770
+ tempMax=tempMaxi;
771
+ tpeakp=tmax;
772
+ end
773
+ end
774
+ end
775
+
776
+ if ((tempMax-tempMin)>0.4*abpMaxTH) %evaluation
777
+ if ((tempMax-tempMin)<2*abpMaxTH)
778
+ if tpeakp>tonsetp
779
+ %If more zero-crossing points, further refine!
780
+ ttempMin=abpsig(tonsetp);
781
+ ttonsetp=tonsetp;
782
+ for ttk=tpeakp:-1:(tonsetp+1)
783
+ if abpsig(ttk)<ttempMin
784
+ ttempMin=abpsig(ttk);
785
+ ttonsetp=ttk;
786
+ end
787
+ end
788
+ tempMin=ttempMin;
789
+ tonsetp=ttonsetp;
790
+
791
+ if peakIndex>0
792
+ %If pulse period less than eyeclose, then artifact
793
+ if (tonsetp-peakp(peakIndex))<(3*closeWin)
794
+ %too many fiducial points, then reset
795
+ tempIndex=diffIndex;
796
+ abpMaxTH=2.5*abpMaxLT;
797
+ break;
798
+ end
799
+
800
+ %If pulse period bigger than 2s, then artifact
801
+ if (tpeakp-peakp(peakIndex))>stepWin
802
+ peakIndex=peakIndex-1;
803
+ onsetIndex=onsetIndex-1;
804
+ if dicroIndex>0
805
+ dicroIndex=dicroIndex-1;
806
+ end
807
+ end
808
+
809
+ if peakIndex>0
810
+ %new pulse beat
811
+ peakIndex=peakIndex+1;
812
+ peakp(peakIndex)=tpeakp;
813
+ onsetIndex=onsetIndex+1;
814
+ onsetp(onsetIndex)=tonsetp;
815
+
816
+ tf=onsetp(peakIndex)-onsetp(peakIndex-1);
817
+
818
+ to=floor(abpfreq./20); %50ms
819
+ tff=floor(0.1*tf);
820
+ if tff<to
821
+ to=tff;
822
+ end
823
+ to=peakp(peakIndex-1)+to;
824
+
825
+ te=floor(abpfreq./2); %500ms
826
+ tff=floor(0.5*tf);
827
+ if tff<te
828
+ te=tff;
829
+ end
830
+ te=peakp(peakIndex-1)+te;
831
+ % Dong added on 05/07/2020:
832
+ % For MIMIC III PACPVC 3_2, ii = 25.
833
+ if te > length(diff1)
834
+ te = length(diff1);
835
+ end
836
+ tff=seekdicrotic(diff1(to:te));
837
+ if tff==0
838
+ tff=te-peakp(peakIndex-1);
839
+ tff=floor(tff/3);
840
+ end
841
+ dicroIndex=dicroIndex+1;
842
+ dicron(dicroIndex)=to+tff;
843
+
844
+ tempIndex=tempIndex+closeWin;
845
+ break;
846
+ end
847
+ end
848
+
849
+ if peakIndex==0 %new pulse beat
850
+ peakIndex=peakIndex+1;
851
+ peakp(peakIndex)=tpeakp;
852
+ onsetIndex=onsetIndex+1;
853
+ onsetp(onsetIndex)=tonsetp;
854
+
855
+ tempIndex=tempIndex+closeWin;
856
+ break;
857
+ end
858
+ end
859
+ end
860
+ end
861
+ end
862
+
863
+ tempIndex=tempIndex+1; %step forward
864
+ end
865
+
866
+ % diffIndex=tempIndex+closeWin; %for a new beat
867
+ diffIndex=tempIndex+1;
868
+ end
869
+
870
+ if isempty(peakp),return;end
871
+ %Compensate the offsets of lowpass filter
872
+ sigLen=length(peakp);
873
+ for diffIndex=1:sigLen %avoid edge effect
874
+ tempp(diffIndex)=peakp(diffIndex)-od;
875
+ end
876
+ ttk=tempp(1);
877
+ if ttk<=0
878
+ tempp(1)=1;
879
+ end
880
+ clear peakp;
881
+ peakp=tempp;
882
+ clear tempp;
883
+
884
+ sigLen=length(onsetp);
885
+ for diffIndex=1:sigLen
886
+ tempp(diffIndex)=onsetp(diffIndex)-od;
887
+ end
888
+ ttk=tempp(1);
889
+ if ttk<=0
890
+ tempp(1)=1;
891
+ end
892
+ clear onsetp;
893
+ onsetp=tempp;
894
+ clear tempp;
895
+
896
+ if isempty(dicron),return;end
897
+ sigLen=length(dicron);
898
+ for diffIndex=1:sigLen
899
+ if dicron(diffIndex)~=0
900
+ tempp(diffIndex)=dicron(diffIndex)-od;
901
+ else
902
+ tempp(diffIndex)=0;
903
+ end
904
+ end
905
+ clear dicron;
906
+ dicron=tempp;
907
+ clear tempp;
908
+ end
909
+
910
+ function [mini,minip,maxi,maxip]=seeklocales(tempsig,tempbegin,tempend)
911
+ tempMin=tempsig(tempbegin);
912
+ tempMax=tempsig(tempbegin);
913
+ minip=tempbegin;
914
+ maxip=tempbegin;
915
+ for j=tempbegin:tempend
916
+ if tempsig(j)>tempMax
917
+ tempMax=tempsig(j);
918
+ maxip=j;
919
+ elseif tempsig(j)<tempMin
920
+ tempMin=tempsig(j);
921
+ minip=j;
922
+ end
923
+ end
924
+
925
+ mini=tempMin;
926
+ maxi=tempMax;
927
+ end
928
+
929
+ function [dicron]=seekdicrotic(tempdiff)
930
+ izcMin=0;
931
+ izcMax=0;
932
+ itemp=3;
933
+ tempLen=length(tempdiff)-3;
934
+
935
+ dicron=0;
936
+
937
+ tempdiff=smooth(tempdiff);
938
+
939
+ while itemp<=tempLen
940
+ if (tempdiff(itemp)*tempdiff(itemp+1))<=0
941
+ if tempdiff(itemp-2)<0
942
+ if tempdiff(itemp+2)>=0
943
+ izcMin=izcMin+1;
944
+ tzcMin(izcMin)=itemp;
945
+ end
946
+ end
947
+
948
+ % if tempdiff(itemp-2)>0
949
+ % if tempdiff(itemp+2)<=0
950
+ % izcMax=izcMax+1;
951
+ % tzcMax(izcMax)=itemp;
952
+ % end
953
+ % end
954
+ end
955
+
956
+ itemp=itemp+1;
957
+ end
958
+
959
+ if izcMin==0 %big inflection
960
+ itemp=3;
961
+ tempMin=tempdiff(itemp);
962
+ itempMin=itemp;
963
+
964
+ while itemp<tempLen
965
+ if tempdiff(itemp)<tempMin
966
+ tempMin=tempdiff(itemp);
967
+ itempMin=itemp;
968
+ end
969
+ itemp=itemp+1;
970
+ end
971
+
972
+ itemp=itempMin+1;
973
+ while itemp<tempLen
974
+ if tempdiff(itemp+1)<=tempdiff(itemp-1)
975
+ dicron=itemp;
976
+ return;
977
+ end
978
+ itemp=itemp+1;
979
+ end
980
+ elseif izcMin==1
981
+ dicron=tzcMin(izcMin);
982
+ return;
983
+ else
984
+ itemp=tzcMin(1);
985
+ tempMax=tempdiff(itemp);
986
+ itempMax=itemp;
987
+
988
+ while itemp<tempLen
989
+ if tempdiff(itemp)>tempMax
990
+ tempMax=tempdiff(itemp);
991
+ itempMax=itemp;
992
+ end
993
+ itemp=itemp+1;
994
+ end
995
+
996
+ for itemp=izcMin:-1:1
997
+ if tzcMin(itemp)<itempMax
998
+ dicron=tzcMin(itemp);
999
+ return;
1000
+ end
1001
+ end
1002
+ end
1003
+ end
1004
+
1005
+ function [diap]=seekdiap(tempabp)
1006
+ diap=0;
1007
+
1008
+ [tt,ti]=max(tempabp);
1009
+ if ti==0
1010
+ diap=floor(length(tempabp)./2);
1011
+ else
1012
+ diap=ti;
1013
+ end
1014
+ end
1015
+ ","MATLAB"
1016
+ "Biosensors","Cassey2016/PPG_Peak_Detection","func/my_func_standardizing_PPG.m",".m","422","11","function PPG_buffer = my_func_standardizing_PPG(PPG_buffer)
1017
+ % Standardizing PPG into zero-mean and uni-variance.
1018
+ var_sig_PPG = var(PPG_buffer);
1019
+ if var_sig_PPG == 0
1020
+ univar_sig_PPG = PPG_buffer;
1021
+ else
1022
+ univar_sig_PPG = sqrt(1/var_sig_PPG) * PPG_buffer;
1023
+ end
1024
+ zeromean_sig_PPG = univar_sig_PPG - mean(univar_sig_PPG);
1025
+ PPG_buffer = zeromean_sig_PPG; % univariance for PPG 30 sec segment
1026
+ end","MATLAB"
1027
+ "Biosensors","Cassey2016/PPG_Peak_Detection","func/my_func_prep_PPG_buffer.m",".m","554","17","function [PPG_buffer,fs_PPG] = my_func_prep_PPG_buffer(PPG_raw_buffer,fs_PPG)
1028
+ % Resample PPG to 50 Hz.
1029
+ if fs_PPG ~= 50 % Hz
1030
+ PPG_down = resample(PPG_raw_buffer,50,fs_PPG);
1031
+ fs_PPG = 50;
1032
+ else
1033
+ PPG_down = PPG_raw_buffer;
1034
+ end
1035
+
1036
+ PPG_buffer = PPG_down(:); % Make sure PPG is column vector
1037
+ % Standardizing PPG in sub-function.
1038
+ PPG_buffer = my_func_standardizing_PPG(PPG_buffer);
1039
+
1040
+ % Filter signal.
1041
+ [b, a] = butter(6,[0.5 20]/(fs_PPG/2)); % Bandpass filter.
1042
+ PPG_buffer = filtfilt(b, a, PPG_buffer);
1043
+ end","MATLAB"
1044
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_06/my_revise_run_wabp.m",".m","4330","109","function [r,ssf,my_avg0,A] = my_revise_run_wabp(abp,fs_abp)
1045
+ % Below was copied from Erick Andres Perez Alday's Github repository
1046
+ % "" physionetchallenges / matlab-classifier-2020 "":
1047
+ % https://github.com/physionetchallenges/matlab-classifier-2020/blob/master/Tools/PhysioNet-Cardiovascular-Signal-Toolbox-master/Tools/BP_Tools/run_wabp.m
1048
+ % WABP ABP waveform onset detector.
1049
+ % r = run_wabp(abp) obtains the onset time (in samples)
1050
+ % of each beat in the ABP waveform.
1051
+ %
1052
+ % In: ABP (125Hz sampled)
1053
+ % Out: Onset sample time
1054
+ %
1055
+ % Usage:
1056
+ % - ABP waveform must have units of mmHg
1057
+ %
1058
+ % Written by James Sun (xinsun@mit.edu) on Nov 19, 2005. This ABP onset
1059
+ % detector is adapted from Dr. Wei Zong's wabp.c.
1060
+ %
1061
+ % LICENSE:
1062
+ % This software is offered freely and without warranty under
1063
+ % the GNU (v3 or later) public license. See license file for
1064
+ % more information
1065
+
1066
+ % Dong changed: input should be 250 Hz for filtering.
1067
+ %% Input checks
1068
+ % if nargin ~=1
1069
+ % error('exactly 1 argment needed');
1070
+ % end
1071
+
1072
+ if size(abp,2)~=1
1073
+ error('Input must be a <nx1> vector');
1074
+ end
1075
+
1076
+ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1077
+
1078
+ % scale physiologic ABP
1079
+ offset = 1600;
1080
+ scale = 20;
1081
+ Araw = abp*scale-offset;
1082
+
1083
+ % LPF
1084
+ A = filter([1 0 0 0 0 -2 0 0 0 0 1],[1 -2 1],Araw)/24+30;
1085
+ A = (A(4:end)+offset)/scale; % Takes care of 4 sample group delay
1086
+
1087
+ % ------- Dong changed this: -------
1088
+ A = A ./ std(A); % normalizing data is very important for my peak detection.
1089
+ A = A - mean(A);
1090
+
1091
+ % Slope-sum function
1092
+ dypos = diff(A);
1093
+ dypos(dypos<0) = 0;
1094
+ % ssf = [0; 0; conv(ones(16,1),dypos)];
1095
+ w = 16/125*fs_abp; % 125 Hz to 250 Hz.
1096
+ ssf = [0; 0; conv(ones(w,1),dypos)];
1097
+
1098
+ % Decision rule
1099
+ first_8sec = 8*fs_abp;
1100
+ % avg0 = sum(ssf(1:1000))/1000; % average of 1st 8 seconds (1000 samples) of SSF
1101
+ avg0 = sum(ssf(1:first_8sec))/first_8sec;
1102
+ Threshold0 = 3*avg0; % initial decision threshold
1103
+
1104
+ % ignoring ""learning period"" for now
1105
+ lockout = 0; % lockout >0 means we are in refractory
1106
+ timer = 0;
1107
+ % z = zeros(100000,1);
1108
+ z = zeros(fs_abp*800,1);
1109
+ counter = 0;
1110
+
1111
+ % Dong: copied from wabp.c, 02/27/2020. % Dong change here. 02/27/2020.
1112
+ TmDEF = 0.25; %5;% Dong change here. 02/27/2020.
1113
+ max_min_thres = 0.1; %10;% Dong change here. 02/27/2020.
1114
+ my_avg0 = zeros(size(abp));% Dong change here. 02/27/2020.
1115
+ step_adjust_thres = 0.025; % it was 0.1 % Dong change here. 02/27/2020.
1116
+ % for t = 50:length(ssf)-17
1117
+ for t = round(0.4*fs_abp):length(ssf)-w-1
1118
+ lockout = lockout - 1;
1119
+ timer = timer + 1; % Timer used for counting time after previous ABP pulse
1120
+
1121
+ if (lockout<1) & (ssf(t)>avg0+TmDEF) %(ssf(t)>avg0+5) % Not in refractory and SSF has exceeded threshold here % Dong change here. 02/27/2020.
1122
+ timer = 0;
1123
+ maxSSF = max(ssf(t:t+w)); % Find local max of SSF
1124
+ minSSF = min(ssf(t-w:t)); % Find local min of SSF
1125
+ if maxSSF > (minSSF + max_min_thres) %(minSSF + 10)% Dong change here. 02/27/2020.
1126
+ onset = 0.01*maxSSF ; % Onset is at the time in which local SSF just exceeds 0.01*maxSSF
1127
+
1128
+ tt = t-w:t;
1129
+ dssf = ssf(tt) - ssf(tt-1);
1130
+ BeatTime = find(dssf<onset,1,'last')+t-w-1;
1131
+ counter = counter+1;
1132
+
1133
+ if isempty(BeatTime)
1134
+ counter = counter-1;
1135
+ else
1136
+ z(counter) = BeatTime;
1137
+ end
1138
+ Threshold0 = Threshold0 + step_adjust_thres*(maxSSF - Threshold0); % adjust threshold
1139
+ avg0 = Threshold0 / 3; % adjust avg
1140
+
1141
+ lockout = round(32/125*fs_abp); % lock so prevent sensing right after detection (refractory period)
1142
+ end
1143
+ end
1144
+
1145
+ if timer > round(312/125*fs_abp) % Lower threshold if no pulse detection for a while
1146
+ Threshold0 = Threshold0 - 0.1; %Threshold0 - 1; % Dong change here. 02/27/2020.
1147
+ avg0 = Threshold0/3;
1148
+ end
1149
+ my_avg0(t,1) = avg0+TmDEF; % % Dong change here. 02/27/2020.
1150
+ end
1151
+ r = z(find(z))-2;
1152
+ end","MATLAB"
1153
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_06/my_Elgendi_2013_method_III_peakdet.m",".m","1028","22","function [output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(raw_PPG,fs_PPG)
1154
+ % -------------------------------------------------------------------------
1155
+ % This peak detection function was mentioned in this paper:
1156
+ % Elgendi, Mohamed, et al.
1157
+ % ""Systolic peak detection in acceleration photoplethysmograms measured from
1158
+ % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
1159
+ %
1160
+ [r,ssf,my_avg0,A] = my_revise_run_wabp(raw_PPG,fs_PPG);
1161
+ % -------------------------------------------------------------------------
1162
+ if isempty(r)
1163
+ HR_Elgendi_3_2013 = 0; % there is no peak location.
1164
+ r = 1;
1165
+ else
1166
+ HR_Elgendi_3_2013 = 60 * fs_PPG ./ diff(r); % calculate the HR.
1167
+ end
1168
+ A = [A;0;0;0;]; % add zero
1169
+ A(1:6) = A(7); % first six plots are all high amplitude.
1170
+ output_Elgendi_3_2013 = struct('PPG_peak_loc_Elgendi_3_2013',r,...
1171
+ 'HR_Elgendi_3_2013',HR_Elgendi_3_2013,...
1172
+ 'filtered_PPG_Elgendi_3_2013',A,...
1173
+ 'thres_Elgendi_3_2013',my_avg0);
1174
+ end","MATLAB"
1175
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_03_and_04/my_Elgendi_2013_method_I_peakdet.m",".m","3762","111","function [output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(raw_PPG, delta, fs_PPG)
1176
+ % -------------------------------------------------------------------------
1177
+ % Dong add this on 02/25/2020, based on this paper:
1178
+ % Elgendi, Mohamed, et al.
1179
+ % ""Systolic peak detection in acceleration photoplethysmograms measured from
1180
+ % emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
1181
+ %
1182
+ % (1): bandpass filter (0.5-8Hz)
1183
+ [b, a] = butter(6,[0.5 8]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018
1184
+ raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component
1185
+ raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection.
1186
+ raw_PPG = raw_PPG - mean(raw_PPG);
1187
+
1188
+ debugging_plot_flag = false; % only for plotting debugging figures.
1189
+ % -------------------------------------------------------------------------
1190
+ % Below code is copied from: http://billauer.co.il/peakdet.html
1191
+ % PEAKDET Detect peaks in a vector
1192
+ % [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
1193
+ % maxima and minima (""peaks"") in the vector V.
1194
+ % MAXTAB and MINTAB consists of two columns. Column 1
1195
+ % contains indices in V, and column 2 the found values.
1196
+ %
1197
+ % With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
1198
+ % in MAXTAB and MINTAB are replaced with the corresponding
1199
+ % X-values.
1200
+ %
1201
+ % A point is considered a maximum peak if it has the maximal
1202
+ % value, and was preceded (to the left) by a value lower by
1203
+ % DELTA.
1204
+
1205
+ % Eli Billauer, 3.4.05 (Explicitly not copyrighted).
1206
+ % This function is released to the public domain; Any use is allowed.
1207
+ maxtab = [];
1208
+ mintab = [];
1209
+
1210
+ raw_PPG = raw_PPG(:); % Just in case this wasn't a proper vector
1211
+
1212
+ % if nargin < 3
1213
+ x = (1:length(raw_PPG))';
1214
+ % else
1215
+ % x = x(:);
1216
+ % if length(raw_PPG)~= length(x)
1217
+ % error('Input vectors v and x must have same length');
1218
+ % end
1219
+ % end
1220
+
1221
+ if (length(delta(:)))>1
1222
+ error('Input argument DELTA must be a scalar');
1223
+ end
1224
+
1225
+ if delta <= 0
1226
+ error('Input argument DELTA must be positive');
1227
+ end
1228
+
1229
+ mn = Inf; mx = -Inf;
1230
+ mnpos = NaN; mxpos = NaN;
1231
+
1232
+ lookformax = 1;
1233
+
1234
+ for i=1:length(raw_PPG)
1235
+ this = raw_PPG(i);
1236
+ if this > mx, mx = this; mxpos = x(i); end
1237
+ if this < mn, mn = this; mnpos = x(i); end
1238
+
1239
+ if lookformax
1240
+ if this < mx-delta
1241
+ maxtab = [maxtab ; mxpos mx];
1242
+ mn = this; mnpos = x(i);
1243
+ lookformax = 0;
1244
+ end
1245
+ else
1246
+ if this > mn+delta
1247
+ mintab = [mintab ; mnpos mn];
1248
+ mx = this; mxpos = x(i);
1249
+ lookformax = 1;
1250
+ end
1251
+ end
1252
+ end
1253
+
1254
+
1255
+
1256
+ if isempty(maxtab)
1257
+ HR_Elgendi_1_max_2009 = 0; % there is no peak location.
1258
+ peak_loc_max = 1;
1259
+ else
1260
+ peak_loc_max = maxtab(:,1);
1261
+ HR_Elgendi_1_max_2009 = 60 * fs_PPG ./ diff(peak_loc_max); % calculate the HR.
1262
+ end
1263
+
1264
+ if isempty(mintab)
1265
+ HR_Elgendi_1_min_2009 = 0; % there is no peak location.
1266
+ peak_loc_min = 1;
1267
+ else
1268
+ peak_loc_min = mintab(:,1);
1269
+ HR_Elgendi_1_min_2009 = 60 * fs_PPG ./ diff(peak_loc_min); % calculate the HR.
1270
+ end
1271
+
1272
+ output_Elgendi_1_2013 = struct('filtered_PPG_Elgendi_1_2013',raw_PPG,...
1273
+ 'PPG_peak_loc_Elgendi_1_max_2013',peak_loc_max,...
1274
+ 'PPG_peak_loc_Elgendi_1_min_2013',peak_loc_min,...
1275
+ 'HR_Elgendi_1_max_2013',HR_Elgendi_1_max_2009,...
1276
+ 'HR_Elgendi_1_min_2013',HR_Elgendi_1_min_2009);
1277
+
1278
+
1279
+ if debugging_plot_flag % debugging plot
1280
+ figure;
1281
+ plot(x,raw_PPG);hold on;
1282
+ plot(peak_loc_max,raw_PPG(peak_loc_max),'ro');
1283
+ plot(peak_loc_min,raw_PPG(peak_loc_min),'go');
1284
+ end
1285
+ end","MATLAB"
1286
+ "Biosensors","Cassey2016/PPG_Peak_Detection","method_08_and_09/my_Vadrevu_2019_peakdet.m",".m","10598","329","function [output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_buffer,fs_PPG)
1287
+ % =========================================================================
1288
+ % This is my implementation of this paper:
1289
+ %
1290
+ % Vadrevu, Simhadri, and M. Sabarimalai Manikandan.
1291
+ % ""A robust pulse onset and peak detection method for automated PPG signal
1292
+ % analysis system."" IEEE Transactions on Instrumentation and Measurement
1293
+ % 68.3 (2018): 807-817.
1294
+ %
1295
+ % Implemented by Dong Han on 05/03/2020.
1296
+ %
1297
+ % Please cite our paper if you used this code:
1298
+ % Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian,
1299
+ % Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson,
1300
+ % Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons,
1301
+ % David D. McManus, and Ki H. Chon. 2022.
1302
+ % ""A Real-Time PPG Peak Detection Method for Accurate Determination of
1303
+ % Heart Rate during Sinus Rhythm and Cardiac Arrhythmia""
1304
+ % Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082
1305
+ %
1306
+ % Please cite our paper if you used our code. Thank you.
1307
+ % =========================================================================
1308
+ debug_flag = false; % decide to plot the paper figure or not.
1309
+ %% A. Stationary Wavelet Transform of PPG signal.
1310
+
1311
+ % first, for the input length, you can know the maximum wavelet
1312
+ % decomposition level you can get:
1313
+ TYPE = '1D'; % extension method.
1314
+ MODE = 'zpd'; % zero extension.
1315
+ X = PPG_buffer;
1316
+
1317
+ % based on your input signal length, you have to extend your input signal
1318
+ % to MATLAB suggested length.
1319
+ LEN = 45;%18; % 18 for fs_PPG 50, 45 for fs_PPG 125; for 30 sec input.
1320
+ YEXT = wextend(TYPE,MODE,X,LEN); % required by swt.
1321
+ sig = YEXT;
1322
+ % s = PPG_buffer;
1323
+ sLen = length(sig);
1324
+ wname = 'bior1.5';
1325
+ L = wmaxlev(sLen,wname);
1326
+
1327
+ % [swa,swd] = swt(s,3,'bior1.5'); % the author mentioned wavelet biorthogonal 1.5 (bior1.5)
1328
+ [swa,swd] = swt(sig,L,wname); % the author mentioned wavelet biorthogonal 1.5 (bior1.5)
1329
+ s1 = swd(3,:) + swd(4,:);
1330
+ s1 = s1(:); % make sure it is column vector.
1331
+ s2 = swd(5,:) + swd(6,:) + swd(7,:);
1332
+ s2 = s2(:); % make sure it is column vector.
1333
+
1334
+ if debug_flag
1335
+ % if you want to debug the result.
1336
+ figure;
1337
+ t_plot = [1:length(sig)]'./fs_PPG; %
1338
+ subplot(5,1,1);
1339
+ plot(t_plot,sig);
1340
+ xlim([0 t_plot(end)])
1341
+ ylabel('Orig');
1342
+ title('Fig.3 in TIM 2019 paper');
1343
+
1344
+ subplot(5,1,2)
1345
+ plot(t_plot,(swd(1,:) + swd(2,:)))
1346
+ xlim([0 t_plot(end)])
1347
+ ylabel('s_0');
1348
+
1349
+ subplot(5,1,3);
1350
+ plot(t_plot,s1);
1351
+ xlim([0 t_plot(end)])
1352
+ ylabel('s_1');
1353
+
1354
+ subplot(5,1,4);
1355
+ plot(t_plot,s2);
1356
+ xlim([0 t_plot(end)])
1357
+ ylabel('s_2');
1358
+
1359
+ subplot(5,1,5);
1360
+ plot(t_plot,swa(7,:));
1361
+ xlim([0 t_plot(end)])
1362
+ ylabel('a_7');
1363
+ end
1364
+ %% B. Multiscale Sum and Products:
1365
+ p = s1 .* s2;
1366
+ p = p(:);
1367
+
1368
+ if debug_flag
1369
+ % if you want to debug the result.
1370
+ figure;
1371
+ ax(1) = subplot(4,1,1);
1372
+ plot(t_plot,sig);
1373
+ xlim([0 t_plot(end)])
1374
+ ylabel('Orig');
1375
+ title('Fig.4 in TIM 2019 paper');
1376
+
1377
+ ax(2) = subplot(4,1,2);
1378
+ p1 = swd(1,:) .* swd(2,:) .* swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:);
1379
+ plot(t_plot,p1);
1380
+ xlim([0 t_plot(end)])
1381
+ ylabel('p_1');
1382
+
1383
+ ax(3) = subplot(4,1,3);
1384
+ p1 = swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:);
1385
+ plot(t_plot,p1);
1386
+ xlim([0 t_plot(end)])
1387
+ ylabel('p_2');
1388
+
1389
+ ax(4) = subplot(4,1,4);
1390
+ plot(t_plot,p);
1391
+ xlim([0 t_plot(end)])
1392
+ ylabel('p');
1393
+
1394
+ linkaxes(ax,'x');
1395
+ end
1396
+ %% C. Shannon Entropy Envelope Extraction
1397
+ eta = 0.01 + std(p);
1398
+ p_tilda = abs(p);
1399
+ p_tilda(p_tilda < eta) = 0;
1400
+ p_tilda = p_tilda(:);
1401
+
1402
+ % normalize p_tilda:
1403
+ norm_p_tilda = (p_tilda - min(p_tilda)) ./ (max(p_tilda) - min(p_tilda));
1404
+ norm_p_tilda = norm_p_tilda(:);
1405
+
1406
+ se = NaN(size(norm_p_tilda));
1407
+
1408
+ for tttt = 1:size(norm_p_tilda,1)
1409
+ if norm_p_tilda(tttt) == 0
1410
+ % from MATLAB page: https://www.mathworks.com/help/wavelet/ref/wentropy.html
1411
+ % log(0) = 0
1412
+ % 0log(0) = 0.
1413
+ se(tttt) = 0;
1414
+ else
1415
+ se(tttt) = -1 * norm_p_tilda(tttt) .* log(norm_p_tilda(tttt));
1416
+ end
1417
+ end
1418
+
1419
+ % % method 1: CONV twice:
1420
+ filt_Len = floor(0.2 * fs_PPG); % 0.4 is better. 05/04/2020.
1421
+ % h = ones(filt_Len,1)/filt_Len; % A third-order filter has length 4
1422
+ % s = conv(se,h,'same'); % return the same size as se
1423
+ % s = conv(s,h,'same'); % conv twice
1424
+
1425
+ % method 2: FILTFILT.
1426
+ % for 4020, ii = 2, PPG is zero.
1427
+ if any(isnan(se))
1428
+ % any sample is NaN.
1429
+ new_se = se;
1430
+ new_se(isnan(new_se)) = [];
1431
+ if isempty(new_se)
1432
+ % nothing left after removing NaN.
1433
+
1434
+ HR_Vadrevu_1_2019 = 0; % there is no peak location.
1435
+ onset_zx = 1;
1436
+
1437
+ HR_Vadrevu_2_2019 = 0; % there is no peak location.
1438
+ peak_zx = 1;
1439
+
1440
+ filter_PPG = PPG_buffer;
1441
+ output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
1442
+ 'PPG_peak_loc_Vadrevu_1_2019',onset_zx,...
1443
+ 'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019);
1444
+
1445
+ output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
1446
+ 'PPG_peak_loc_Vadrevu_2_2019',peak_zx,...
1447
+ 'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019);
1448
+ return
1449
+ else
1450
+ % part of data is NaN, maybe I should fill zeros in it?
1451
+ keyboard;
1452
+ end
1453
+ end
1454
+ b = ones(filt_Len,1);
1455
+ a = -1;
1456
+ s = filtfilt(b, a, se); % -> AC component
1457
+
1458
+
1459
+ %% D. Pulse Peak and Onset Determination.
1460
+ % 1. Gaussian derivative kernel:
1461
+ sigma_1 = floor(0.05 * fs_PPG); % 0.05 mentioned in the paper.
1462
+ M = floor(2 * fs_PPG); % 2 mentioned in the paper.
1463
+ g = gausswin(M,sigma_1); % size should be 250 if Fs = 125.
1464
+ h_d = diff(g); % g(m+1) - g(m).
1465
+ z = conv(s,h_d,'same');
1466
+
1467
+ % % My conv function did not work.
1468
+ % temp_z = zeros(size(s,1),1);
1469
+ % for nnnn = 1:size(s,1)
1470
+ % for mmmm = 1:size(g,1)-1
1471
+ % if (nnnn-mmmm+1 > 0)
1472
+ % % h_d(mmmm) = g(mmmm+1) - g(mmmm);
1473
+ % temp_z(nnnn) = temp_z(nnnn) + s(mmmm) * h_d(nnnn-mmmm+1);
1474
+ % end
1475
+ % end
1476
+ % end
1477
+
1478
+ DownZCi = @(v) find(v(1:end-1) >= 0 & v(2:end) < 0); % Returns Down Zero-Crossing Indices. https://www.mathworks.com/matlabcentral/answers/267222-easy-way-of-finding-zero-crossing-of-a-function
1479
+ zx = DownZCi(z); % negative zero crossing point.
1480
+
1481
+ % peak correction algorithm for onset:
1482
+ search_intv = floor(0.1 * fs_PPG / 2); % w/2
1483
+ onset_zx = NaN(size(zx));
1484
+ for zz = 1:size(zx,1)
1485
+ temp_zx = zx(zz);
1486
+ if temp_zx - search_intv > 0 % not exceed signal limit.
1487
+ if temp_zx + search_intv <= size(sig,1)
1488
+ temp_PPG = sig(temp_zx - search_intv : temp_zx + search_intv);
1489
+ [~,I] = min(temp_PPG);
1490
+ if isempty(I) ~= 1
1491
+ adj_loc = temp_zx - search_intv + I - 1;
1492
+ else
1493
+ % no local minimum.
1494
+ adj_loc = temp_zx;
1495
+ end
1496
+ onset_zx(zz) = adj_loc;
1497
+ else
1498
+ % right interval exceed signal length.
1499
+ onset_zx(zz) = zx(zz);
1500
+ end
1501
+ else
1502
+ % left interval exceed index 1.
1503
+ onset_zx(zz) = zx(zz);
1504
+ end
1505
+ end
1506
+
1507
+ % find peak:
1508
+ peak_zx = NaN(size(onset_zx,1)-1,1); % one sample smaller.
1509
+ for zz = 2:size(onset_zx,1)
1510
+ temp_onset_1 = onset_zx(zz-1);
1511
+ temp_onset_2 = onset_zx(zz);
1512
+ temp_PPG = sig(temp_onset_1:temp_onset_2);
1513
+ [~,I] = max(temp_PPG);
1514
+ if isempty(I) ~= 1
1515
+ peak_zx(zz-1) = temp_onset_1 + I - 1; % peak is one sample size smaller.
1516
+ else
1517
+ peak_zx(zz-1) = onset_zx(zz);
1518
+ end
1519
+ end
1520
+
1521
+ % prepare to output signal:
1522
+ filter_PPG = z(LEN+1:end-LEN);
1523
+ remove_left = find(onset_zx < LEN+1);
1524
+ if isempty(remove_left) ~= 1
1525
+ onset_zx(remove_left) = [];
1526
+ end
1527
+ remove_right = find(onset_zx > size(z,1) - LEN);
1528
+ if isempty(remove_right) ~= 1
1529
+ onset_zx(remove_right) = [];
1530
+ end
1531
+ onset_zx = onset_zx - LEN; % shifted.
1532
+
1533
+ remove_left = find(peak_zx < LEN+1);
1534
+ if isempty(remove_left) ~= 1
1535
+ peak_zx(remove_left) = [];
1536
+ end
1537
+ remove_right = find(peak_zx > size(z,1) - LEN);
1538
+ if isempty(remove_right) ~= 1
1539
+ peak_zx(remove_right) = [];
1540
+ end
1541
+ peak_zx = peak_zx - LEN;
1542
+
1543
+ if debug_flag
1544
+ % if you want to debug the result.
1545
+ figure;
1546
+ ax(1) = subplot(7,1,1);
1547
+ plot(t_plot,sig);
1548
+ xlim([0 t_plot(end)])
1549
+ ylabel('Orig');
1550
+ title('Fig.5 in TIM 2019 paper');
1551
+
1552
+ ax(2) = subplot(7,1,2);
1553
+ plot(t_plot,p);
1554
+ xlim([0 t_plot(end)])
1555
+ ylabel('p');
1556
+
1557
+ ax(3) = subplot(7,1,3);
1558
+ plot(t_plot,norm_p_tilda);
1559
+ xlim([0 t_plot(end)])
1560
+ ylabel('p_th');
1561
+
1562
+ ax(4) = subplot(7,1,4);
1563
+ plot(t_plot,se);
1564
+ xlim([0 t_plot(end)])
1565
+ ylabel('se');
1566
+
1567
+ ax(5) = subplot(7,1,5);
1568
+ plot(t_plot,s);
1569
+ xlim([0 t_plot(end)])
1570
+ ylabel('s');
1571
+
1572
+ ax(6) = subplot(7,1,6);
1573
+ plot(t_plot,z);
1574
+ hold on;
1575
+ plot(t_plot(zx),z(zx),'ro');
1576
+ xlim([0 t_plot(end)]);
1577
+ ylabel('z');
1578
+
1579
+
1580
+ ax(7) = subplot(7,1,7);
1581
+ plot(t_plot,sig);
1582
+ hold on;
1583
+ plot(t_plot(onset_zx),sig(onset_zx),'go');
1584
+ plot(t_plot(peak_zx),sig(peak_zx),'ro');
1585
+ xlim([0 t_plot(end)])
1586
+ ylabel('orig with peak');
1587
+
1588
+ linkaxes(ax,'x');
1589
+ end
1590
+
1591
+ if isempty(onset_zx)
1592
+ HR_Vadrevu_1_2019 = 0; % there is no peak location.
1593
+ onset_zx = 1;
1594
+ else
1595
+ HR_Vadrevu_1_2019 = 60 * fs_PPG ./ diff(onset_zx); % calculate the HR.
1596
+ end
1597
+
1598
+ if isempty(peak_zx)
1599
+ HR_Vadrevu_2_2019 = 0; % there is no peak location.
1600
+ peak_zx = 1;
1601
+ else
1602
+ HR_Vadrevu_2_2019 = 60 * fs_PPG ./ diff(peak_zx); % calculate the HR.
1603
+ end
1604
+
1605
+ output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
1606
+ 'PPG_peak_loc_Vadrevu_1_2019',onset_zx,...
1607
+ 'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019);
1608
+
1609
+ output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
1610
+ 'PPG_peak_loc_Vadrevu_2_2019',peak_zx,...
1611
+ 'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019);
1612
+
1613
+ end
1614
+ ","MATLAB"
data/dataset_Biotechnology.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae5f6ff49b57e523d83cffa0adfba6beba919e74e8a9773a4c00f3285db0a67a
3
+ size 246280813
data/dataset_CRISPR.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Cell_atlas.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e46bc111a26a198e9990aeec58c4326df3fdaa844367bd99de4799e3b55f940
3
+ size 72197401
data/dataset_Cell_biology.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Chemical_space.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8e88459d479bed92bb767b49e33308e1ba7b7f647833fe1bd148c1b2d696261
3
+ size 235865458
data/dataset_Cheminformatics.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1af279c2ad8a474f8b20ba802133582721a9632ae9a44b94ccee9eb13bcbf47d
3
+ size 141839346
data/dataset_Chemistry.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ecb76934a5e29f73eacfccf98c9c30d757aee7dcee171c87801213ff40c98e4
3
+ size 360112090
data/dataset_Codon.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Compartmental_model.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38a3208e3bd4e15690469264821eb34aee6fb9dfdb5d8341f90a72feea70296f
3
+ size 196516716
data/dataset_Computational_Biochemistry.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Computational_Chemistry.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b247737bff18ee9764de11fb60af1ec36463fdc675e3d8fb96cab61c9f16203a
3
+ size 514818775
data/dataset_Computational_Materials.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:692f98166f96bb3c6fdcb960ac112919ad5cc68cfa47b731e274706e9cdc4e05
3
+ size 1470023569
data/dataset_Conformation.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Conjugate.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/dataset_Coupled_cluster.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fef50d2653d98af56b95e40ad57999f3677a31f4af0bf09e736b0ad65a00fab
3
+ size 418368710
data/dataset_Crystal.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7489bbaa15fb8c604382a0ec85c53dd59d8917ea4d78cd6c3cc2de97f3336bb7
3
+ size 64264594
data/dataset_Cycle.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6bbe1d5327b4c320764174215507daacdc0ea79a202c8d184a32fc78c0041d81
3
+ size 1497335713
data/dataset_DFT.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ecae0254d24c6869b154f623f907c398190152aba00fccf71a7ce9cec112617
3
+ size 610647978
data/dataset_DNA.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ffe1dafda9ee5f9f22a5dbe85a4d71803740adf98b4bcbcea220b6e2db16df9
3
+ size 90689920
data/dataset_De_novo.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba29166e48d838ec4fabda954a33d8d7e5979ac95f07c8c7ce9c6525c08ced98
3
+ size 63275132
data/dataset_Design.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe2185aac337a9af160e74bf77ab2dc88342aff8bd672dd00c011c70bc935f1b
3
+ size 325191237