nitrocsv-eda 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ include nitrocsv_eda/corr_engine.c
2
+ include nitrocsv_eda/corr_engine.cu
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: nitrocsv-eda
3
+ Version: 0.1.0
4
+ Summary: A hardware-accelerated CSV EDA and heatmap generator.
5
+ Author-email: CodingMaster24 <sivatech24@gmail.com>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: POSIX :: Linux
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pandas
13
+ Requires-Dist: numpy
14
+ Requires-Dist: seaborn
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: hwdetect
17
+ Dynamic: license-file
18
+
19
+ --
20
+
21
+ # NitroCSV-EDA 🚀
22
+
23
+ A high-performance, hardware-aware Exploratory Data Analysis (EDA) tool for CSV files. NitroCSV-EDA automates data classification, statistical descriptions, and correlation heatmap generation.
24
+
25
+ It leverages a hybrid architecture: using Python for data orchestration and visualization, while offloading heavy matrix math to a dynamically compiled **CUDA C++** backend if an NVIDIA GPU is detected, or a **C** backend for CPU only systems.
26
+
27
+ ## ✨ Key Features
28
+
29
+ * **Automated Dependency Management:** Automatically installs missing Python dependencies (`pandas`, `numpy`, `seaborn`, `matplotlib`, `hwdetect`) on the first run.
30
+ * **Smart Hardware Detection:** Uses `hwdetect` to scan the PCI bus for NVIDIA GPUs and seamlessly routes workloads.
31
+ * **Dynamic Backend Compilation:** Compiles high-performance C (`gcc`) or CUDA (`nvcc`) backend engines at runtime. No manual building required.
32
+ * **Automated EDA Pipeline:**
33
+ * Generates `head()` and `tail()` previews.
34
+ * Calculates descriptive statistics for all columns.
35
+ * Classifies data types (Numeric, Categorical, Temporal) and provides column-level explanations.
36
+
37
+
38
+ * **Headless & GUI Aware:** Automatically detects if you are running in a GUI/Jupyter environment or a headless Linux/WSL terminal. It displays an interactive heatmap window when possible, or gracefully falls back to a clean, DB-formatted ASCII matrix in the terminal.
39
+ * **Memory Optimized:** Employs aggressive garbage collection (`gc`) and binary `.dat` file streaming to keep RAM usage low during heavy matrix transpositions.
40
+ * **Secure Session Windup:** Visual outputs are cached in the system's `/tmp` directory and automatically purged the moment the session closes.
41
+
42
+ ---
43
+
44
+ ## 🛠️ Prerequisites
45
+
46
+ * **Python:** 3.7+
47
+ * **OS:** Linux or WSL (Windows Subsystem for Linux) recommended.
48
+ * **Compilers:**
49
+ * `gcc` (Required for the CPU backend compilation)
50
+ * `nvcc` / CUDA Toolkit (Optional, required only for GPU backend compilation)
51
+
52
+
53
+
54
+ ---
55
+
56
+ ## 📦 Installation
57
+
58
+ Since NitroCSV-EDA is packaged with a CLI entry point, you can install it directly via pip.
59
+
60
+ 1. **Install the package:**
61
+ ```bash
62
+ pip install nitrocsv-eda
63
+
64
+ ```
65
+
66
+
67
+
68
+ ---
69
+
70
+ ## 🚀 Usage
71
+
72
+ Once installed, the `nitrocsv` command becomes available globally in your terminal. Pass the target CSV file as an argument:
73
+
74
+ ```bash
75
+ nitrocsv path/to/your/dataset.csv
76
+
77
+ ```
78
+
79
+ ### Example Output Workflow
80
+
81
+ 1. **Dependency Check:** Verifies and installs missing Python libraries.
82
+ 2. **Analysis:** Prints data types, missing values, and column statistics.
83
+ 3. **Execution:**
84
+ * Detects hardware (e.g., *NVIDIA GPU detected. Will utilize CUDA backend.*)
85
+ * Flattens the dataframe into a temporary binary file.
86
+ * Executes the optimized C or CUDA engine to compute the Pearson correlation matrix.
87
+
88
+
89
+ 4. **Rendering:**
90
+ * **In Jupyter/Desktop:** Opens a high-res Seaborn heatmap window.
91
+ * **In WSL/Terminal:** Prints a structured, readable raw correlation matrix directly to the console.
92
+
93
+
94
+
95
+ ---
96
+
97
+ ## 🧠 Under the Hood (How it Works)
98
+
99
+ NitroCSV-EDA is built to bypass Python's Global Interpreter Lock (GIL) and memory bottlenecks during heavy EDA operations:
100
+
101
+ 1. **Python Orchestrator:** Pandas is used solely for initial CSV ingestion, type checking, and printing standard data shapes.
102
+ 2. **Binary Handoff:** Instead of using `.corr()` in Pandas, the numeric data is packed into raw bytes (`struct.pack`) and dumped to an `input_matrix.dat` file. The Pandas dataframe is immediately garbage-collected to free RAM.
103
+ 3. **External Compute:** The Python script calls the compiled `./corr_gpu` or `./corr_cpu` binary via `subprocess`. The C/CUDA script loads the `.dat` file, processes the $O(n^2)$ correlation math at hardware speeds, and writes an `output_corr.dat` file.
104
+ 4. **Visual Windup:** Python reads the output binary, generates a Seaborn heatmap, saves it to a temporary `.png`, and either displays it or prints the raw table. An `atexit` hook ensures no temporary files are left behind on your hard drive.
@@ -0,0 +1,86 @@
1
+ --
2
+
3
+ # NitroCSV-EDA 🚀
4
+
5
+ A high-performance, hardware-aware Exploratory Data Analysis (EDA) tool for CSV files. NitroCSV-EDA automates data classification, statistical descriptions, and correlation heatmap generation.
6
+
7
+ It leverages a hybrid architecture: using Python for data orchestration and visualization, while offloading heavy matrix math to a dynamically compiled **CUDA C++** backend if an NVIDIA GPU is detected, or a **C** backend for CPU only systems.
8
+
9
+ ## ✨ Key Features
10
+
11
+ * **Automated Dependency Management:** Automatically installs missing Python dependencies (`pandas`, `numpy`, `seaborn`, `matplotlib`, `hwdetect`) on the first run.
12
+ * **Smart Hardware Detection:** Uses `hwdetect` to scan the PCI bus for NVIDIA GPUs and seamlessly routes workloads.
13
+ * **Dynamic Backend Compilation:** Compiles high-performance C (`gcc`) or CUDA (`nvcc`) backend engines at runtime. No manual building required.
14
+ * **Automated EDA Pipeline:**
15
+ * Generates `head()` and `tail()` previews.
16
+ * Calculates descriptive statistics for all columns.
17
+ * Classifies data types (Numeric, Categorical, Temporal) and provides column-level explanations.
18
+
19
+
20
+ * **Headless & GUI Aware:** Automatically detects if you are running in a GUI/Jupyter environment or a headless Linux/WSL terminal. It displays an interactive heatmap window when possible, or gracefully falls back to a clean, DB-formatted ASCII matrix in the terminal.
21
+ * **Memory Optimized:** Employs aggressive garbage collection (`gc`) and binary `.dat` file streaming to keep RAM usage low during heavy matrix transpositions.
22
+ * **Secure Session Windup:** Visual outputs are cached in the system's `/tmp` directory and automatically purged the moment the session closes.
23
+
24
+ ---
25
+
26
+ ## 🛠️ Prerequisites
27
+
28
+ * **Python:** 3.7+
29
+ * **OS:** Linux or WSL (Windows Subsystem for Linux) recommended.
30
+ * **Compilers:**
31
+ * `gcc` (Required for the CPU backend compilation)
32
+ * `nvcc` / CUDA Toolkit (Optional, required only for GPU backend compilation)
33
+
34
+
35
+
36
+ ---
37
+
38
+ ## 📦 Installation
39
+
40
+ Since NitroCSV-EDA is packaged with a CLI entry point, you can install it directly via pip.
41
+
42
+ 1. **Install the package:**
43
+ ```bash
44
+ pip install nitrocsv-eda
45
+
46
+ ```
47
+
48
+
49
+
50
+ ---
51
+
52
+ ## 🚀 Usage
53
+
54
+ Once installed, the `nitrocsv` command becomes available globally in your terminal. Pass the target CSV file as an argument:
55
+
56
+ ```bash
57
+ nitrocsv path/to/your/dataset.csv
58
+
59
+ ```
60
+
61
+ ### Example Output Workflow
62
+
63
+ 1. **Dependency Check:** Verifies and installs missing Python libraries.
64
+ 2. **Analysis:** Prints data types, missing values, and column statistics.
65
+ 3. **Execution:**
66
+ * Detects hardware (e.g., *NVIDIA GPU detected. Will utilize CUDA backend.*)
67
+ * Flattens the dataframe into a temporary binary file.
68
+ * Executes the optimized C or CUDA engine to compute the Pearson correlation matrix.
69
+
70
+
71
+ 4. **Rendering:**
72
+ * **In Jupyter/Desktop:** Opens a high-res Seaborn heatmap window.
73
+ * **In WSL/Terminal:** Prints a structured, readable raw correlation matrix directly to the console.
74
+
75
+
76
+
77
+ ---
78
+
79
+ ## 🧠 Under the Hood (How it Works)
80
+
81
+ NitroCSV-EDA is built to bypass Python's Global Interpreter Lock (GIL) and memory bottlenecks during heavy EDA operations:
82
+
83
+ 1. **Python Orchestrator:** Pandas is used solely for initial CSV ingestion, type checking, and printing standard data shapes.
84
+ 2. **Binary Handoff:** Instead of using `.corr()` in Pandas, the numeric data is packed into raw bytes (`struct.pack`) and dumped to an `input_matrix.dat` file. The Pandas dataframe is immediately garbage-collected to free RAM.
85
+ 3. **External Compute:** The Python script calls the compiled `./corr_gpu` or `./corr_cpu` binary via `subprocess`. The C/CUDA script loads the `.dat` file, processes the $O(n^2)$ correlation math at hardware speeds, and writes an `output_corr.dat` file.
86
+ 4. **Visual Windup:** Python reads the output binary, generates a Seaborn heatmap, saves it to a temporary `.png`, and either displays it or prints the raw table. An `atexit` hook ensures no temporary files are left behind on your hard drive.
File without changes
@@ -0,0 +1,248 @@
1
+ import sys
2
+ import subprocess
3
+ import logging
4
+ import os
5
+ import struct
6
+ import tempfile
7
+ import atexit
8
+ import gc
9
+
10
+ # Configure robust logging
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format='%(asctime)s - %(levelname)s - %(message)s',
14
+ handlers=[logging.StreamHandler(sys.stdout)]
15
+ )
16
+
17
+ # ---------------------------------------------------------
18
+ # DEPENDENCY MANAGER
19
+ # ---------------------------------------------------------
20
+ REQUIRED_PACKAGES = {
21
+ "pandas": "pandas",
22
+ "numpy": "numpy",
23
+ "seaborn": "seaborn",
24
+ "matplotlib": "matplotlib",
25
+ "hwdetect": "hwdetect"
26
+ }
27
+
28
+ def install_and_import():
29
+ """Checks for required packages and installs them dynamically if missing."""
30
+ logging.info("Checking system dependencies...")
31
+ for module_name, pip_name in REQUIRED_PACKAGES.items():
32
+ try:
33
+ __import__(module_name)
34
+ except ImportError:
35
+ logging.warning(f"Missing package '{module_name}'. Installing '{pip_name}'...")
36
+ try:
37
+ subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])
38
+ logging.info(f"Successfully installed {pip_name}.")
39
+ except subprocess.CalledProcessError as e:
40
+ logging.critical(f"Failed to install {pip_name}. Error: {e}")
41
+ sys.exit(1)
42
+
43
+ # Run dependency check before importing heavy libraries
44
+ install_and_import()
45
+
46
+ # Now it is safe to import them
47
+ import pandas as pd
48
+ import numpy as np
49
+ import seaborn as sns
50
+ import matplotlib
51
+ import matplotlib.pyplot as plt
52
+
53
+ # ---------------------------------------------------------
54
+ # HARDWARE & BACKEND ORCHESTRATION
55
+ # ---------------------------------------------------------
56
+ def detect_gpu():
57
+ """Uses hwdetect to check for an NVIDIA GPU (Vendor ID 0x10de)."""
58
+ try:
59
+ logging.info("Running hwdetect to identify hardware...")
60
+ result = subprocess.run(['hwdetect'], capture_output=True, text=True, check=True)
61
+
62
+ if '0x10de' in result.stdout.lower():
63
+ logging.info("NVIDIA GPU detected. Will utilize CUDA backend.")
64
+ return True
65
+ else:
66
+ logging.info("No NVIDIA GPU detected. Falling back to CPU (C backend).")
67
+ return False
68
+ except Exception as e:
69
+ logging.warning(f"hwdetect failed or not found: {e}. Defaulting to C backend.")
70
+ return False
71
+
72
+ def compile_backends():
73
+ """Compiles the C and CUDA files if the executables don't exist."""
74
+ try:
75
+ if not os.path.exists('./corr_cpu'):
76
+ logging.info("Compiling C backend (corr_cpu)...")
77
+ subprocess.run(['gcc', '-O3', 'corr_engine.c', '-o', 'corr_cpu', '-lm'], check=True)
78
+
79
+ if not os.path.exists('./corr_gpu') and detect_gpu():
80
+ logging.info("Compiling CUDA backend (corr_gpu)...")
81
+ subprocess.run(['nvcc', '-O3', 'corr_engine.cu', '-o', 'corr_gpu'], check=True)
82
+ except subprocess.CalledProcessError as e:
83
+ logging.error(f"Compilation failed: {e}. Ensure gcc/nvcc are installed and in your PATH.")
84
+ raise
85
+
86
+ # ---------------------------------------------------------
87
+ # DATA ANALYSIS CORE
88
+ # ---------------------------------------------------------
89
+ def explain_features(df):
90
+ """Classifies and explains the data types of all fields."""
91
+ logging.info("Classifying and Explaining Fields...")
92
+ print("\n" + "="*50)
93
+ print("FIELD CLASSIFICATION & EXPLANATION")
94
+ print("="*50)
95
+ for col in df.columns:
96
+ dtype = df[col].dtype
97
+ unique_vals = df[col].nunique()
98
+ missing = df[col].isnull().sum()
99
+
100
+ explanation = f"- Column: '{col}'\n Type: {dtype}"
101
+ if pd.api.types.is_numeric_dtype(dtype):
102
+ explanation += f"\n Description: Numeric continuous or discrete data. Contains {missing} missing values."
103
+ elif pd.api.types.is_datetime64_any_dtype(dtype):
104
+ explanation += f"\n Description: Temporal/Date data. Range: {df[col].min()} to {df[col].max()}."
105
+ else:
106
+ explanation += f"\n Description: Categorical or Text data. Contains {unique_vals} unique categories."
107
+
108
+ print(explanation + "\n")
109
+
110
+ def compute_correlation_external(df, use_gpu):
111
+ """Exports numeric data, calls C/CUDA to compute correlation, and reads it back."""
112
+ numeric_df = df.select_dtypes(include=[np.number]).dropna()
113
+ if numeric_df.empty:
114
+ raise ValueError("No numeric data available to compute a heatmap.")
115
+
116
+ rows, cols = numeric_df.shape
117
+ input_bin = "input_matrix.dat"
118
+ output_bin = "output_corr.dat"
119
+
120
+ logging.info(f"Exporting numeric matrix ({rows}x{cols}) to binary for external processing...")
121
+ flat_data = numeric_df.values.flatten().astype(np.float32)
122
+
123
+ with open(input_bin, 'wb') as f:
124
+ f.write(struct.pack('ii', rows, cols))
125
+ f.write(flat_data.tobytes())
126
+
127
+ # Free up memory before external execution
128
+ del flat_data
129
+ gc.collect()
130
+
131
+ cmd = ['./corr_gpu'] if use_gpu and os.path.exists('./corr_gpu') else ['./corr_cpu']
132
+ cmd.extend([input_bin, output_bin])
133
+
134
+ try:
135
+ logging.info(f"Executing external binary: {' '.join(cmd)}")
136
+ subprocess.run(cmd, check=True)
137
+
138
+ with open(output_bin, 'rb') as f:
139
+ corr_bytes = f.read()
140
+ corr_array = np.frombuffer(corr_bytes, dtype=np.float32).reshape((cols, cols))
141
+
142
+ return pd.DataFrame(corr_array, index=numeric_df.columns, columns=numeric_df.columns)
143
+
144
+ finally:
145
+ if os.path.exists(input_bin): os.remove(input_bin)
146
+ if os.path.exists(output_bin): os.remove(output_bin)
147
+ gc.collect() # Cleanup after external run
148
+
149
+ def check_gui_environment():
150
+ """Detects if we are in Jupyter or a GUI-capable environment."""
151
+ try:
152
+ shell = get_ipython().__class__.__name__
153
+ if shell in ['ZMQInteractiveShell', 'TerminalInteractiveShell']:
154
+ return True # Jupyter Notebook/Console
155
+ except NameError:
156
+ pass
157
+
158
+ # Check for display variable in Linux/WSL
159
+ if os.environ.get('DISPLAY') and matplotlib.get_backend().lower() != 'agg':
160
+ return True
161
+
162
+ return False
163
+
164
+ def main(csv_path):
165
+ try:
166
+ logging.info(f"Loading CSV file: {csv_path}")
167
+ df = pd.read_csv(csv_path)
168
+ except Exception as e:
169
+ logging.critical(f"Failed to load CSV: {e}")
170
+ sys.exit(1)
171
+
172
+ explain_features(df)
173
+
174
+ print("\n" + "="*50 + "\nDATA HEAD (First 5 Rows)\n" + "="*50)
175
+ print(df.head())
176
+
177
+ print("\n" + "="*50 + "\nDATA TAIL (Last 5 Rows)\n" + "="*50)
178
+ print(df.tail())
179
+
180
+ print("\n" + "="*50 + "\nDATA DESCRIPTION (Statistics)\n" + "="*50)
181
+ print(df.describe(include='all'))
182
+
183
+ try:
184
+ use_gpu = detect_gpu()
185
+ compile_backends()
186
+
187
+ corr_matrix = compute_correlation_external(df, use_gpu)
188
+
189
+ # Optimize memory: drop large dataframe if no longer needed
190
+ del df
191
+ gc.collect()
192
+
193
+ logging.info("Rendering heatmap...")
194
+ plt.figure(figsize=(12, 10))
195
+ sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt=".2f", vmin=-1, vmax=1)
196
+ plt.title("Feature Correlation Heatmap")
197
+ plt.tight_layout()
198
+
199
+ # Temp file management - auto deletes on script exit
200
+ temp_img = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
201
+ temp_img.close()
202
+
203
+ def cleanup_temp_image():
204
+ if os.path.exists(temp_img.name):
205
+ os.remove(temp_img.name)
206
+ logging.info("Session ended: Temporary heatmap image cleaned up.")
207
+
208
+ atexit.register(cleanup_temp_image)
209
+
210
+ plt.savefig(temp_img.name, dpi=300)
211
+ logging.info(f"Image cached in tmp directory at '{temp_img.name}'.")
212
+
213
+ if check_gui_environment():
214
+ logging.info("GUI/Notebook detected. Displaying image...")
215
+ plt.show()
216
+ else:
217
+ logging.info("Headless terminal detected. Displaying raw data DB format heatmap:")
218
+ print("\n" + "="*70)
219
+ print(" RAW CORRELATION MATRIX (TERMINAL HEATMAP) ".center(70, "="))
220
+ print("="*70)
221
+ # Format as a clean grid for the terminal
222
+ pd.set_option('display.float_format', lambda x: f'{x:6.2f}')
223
+ print(corr_matrix)
224
+ pd.reset_option('display.float_format')
225
+ print("="*70 + "\n")
226
+
227
+ except Exception as e:
228
+ logging.error(f"Failed to process correlation/heatmap: {e}")
229
+ finally:
230
+ gc.collect()
231
+
232
+ def main_cli():
233
+ """CLI entry point for the pyproject.toml script."""
234
+ if len(sys.argv) < 2:
235
+ print("Usage: nitrocsv <path_to_csv>")
236
+ sys.exit(1)
237
+
238
+ # Resolve absolute path of the CSV file provided by the user
239
+ csv_path = os.path.abspath(sys.argv[1])
240
+
241
+ # Change working directory to the package directory so it finds corr_engine.c / .cu
242
+ package_dir = os.path.dirname(os.path.abspath(__file__))
243
+ os.chdir(package_dir)
244
+
245
+ main(csv_path)
246
+
247
+ if __name__ == "__main__":
248
+ main_cli()
@@ -0,0 +1,78 @@
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <math.h>
4
+
5
+ int main(int argc, char** argv) {
6
+ if (argc != 3) {
7
+ fprintf(stderr, "Usage: %s <input.dat> <output.dat>\n", argv[0]);
8
+ return 1;
9
+ }
10
+
11
+ FILE* infile = fopen(argv[1], "rb");
12
+ if (!infile) {
13
+ perror("Failed to open input file");
14
+ return 1;
15
+ }
16
+
17
+ int rows, cols;
18
+ // Fix: Check return values of fread
19
+ if (fread(&rows, sizeof(int), 1, infile) != 1 || fread(&cols, sizeof(int), 1, infile) != 1) {
20
+ fprintf(stderr, "Error: Failed to read matrix dimensions.\n");
21
+ fclose(infile);
22
+ return 1;
23
+ }
24
+
25
+ float* data = (float*)malloc(rows * cols * sizeof(float));
26
+ // Fix: Check return value of fread for the array payload
27
+ if (fread(data, sizeof(float), rows * cols, infile) != (size_t)(rows * cols)) {
28
+ fprintf(stderr, "Error: Failed to read matrix data.\n");
29
+ free(data);
30
+ fclose(infile);
31
+ return 1;
32
+ }
33
+ fclose(infile);
34
+
35
+ float* corr = (float*)malloc(cols * cols * sizeof(float));
36
+
37
+ for (int i = 0; i < cols; i++) {
38
+ for (int j = 0; j < cols; j++) {
39
+ double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0;
40
+
41
+ for (int r = 0; r < rows; r++) {
42
+ float x = data[r * cols + i];
43
+ float y = data[r * cols + j];
44
+
45
+ sum_x += x;
46
+ sum_y += y;
47
+ sum_xy += (x * y);
48
+ sum_x2 += (x * x);
49
+ sum_y2 += (y * y);
50
+ }
51
+
52
+ double numerator = (rows * sum_xy) - (sum_x * sum_y);
53
+ double denom_x = (rows * sum_x2) - (sum_x * sum_x);
54
+ double denom_y = (rows * sum_y2) - (sum_y * sum_y);
55
+
56
+ double denominator = sqrt(denom_x * denom_y);
57
+ corr[i * cols + j] = (denominator == 0) ? 0.0f : (float)(numerator / denominator);
58
+ }
59
+ }
60
+
61
+ FILE* outfile = fopen(argv[2], "wb");
62
+ if (!outfile) {
63
+ perror("Failed to open output file");
64
+ free(data);
65
+ free(corr);
66
+ return 1;
67
+ }
68
+
69
+ // Fix: Check return value of fwrite
70
+ if (fwrite(corr, sizeof(float), cols * cols, outfile) != (size_t)(cols * cols)) {
71
+ fprintf(stderr, "Error: Failed to write correlation data.\n");
72
+ }
73
+ fclose(outfile);
74
+
75
+ free(data);
76
+ free(corr);
77
+ return 0;
78
+ }
@@ -0,0 +1,81 @@
1
+ #include <iostream>
2
+ #include <fstream>
3
+ #include <vector>
4
+ #include <cmath>
5
+ #include <cuda_runtime.h>
6
+
7
+ // Error checking macro
8
+ #define CUDA_CHECK(call) { \
9
+ cudaError_t err = call; \
10
+ if (err != cudaSuccess) { \
11
+ fprintf(stderr, "CUDA Error: %s:%d: %s\n", __FILE__, __LINE__, cudaGetErrorString(err)); \
12
+ exit(1); \
13
+ } \
14
+ }
15
+
16
+ __global__ void computeCorrelationKernel(const float* data, float* corr, int rows, int cols) {
17
+ int i = blockIdx.x * blockDim.x + threadIdx.x;
18
+ int j = blockIdx.y * blockDim.y + threadIdx.y;
19
+
20
+ if (i < cols && j < cols) {
21
+ float sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0;
22
+
23
+ for (int r = 0; r < rows; ++r) {
24
+ float x = data[r * cols + i];
25
+ float y = data[r * cols + j];
26
+
27
+ sum_x += x;
28
+ sum_y += y;
29
+ sum_xy += (x * y);
30
+ sum_x2 += (x * x);
31
+ sum_y2 += (y * y);
32
+ }
33
+
34
+ float numerator = (rows * sum_xy) - (sum_x * sum_y);
35
+ float denom_x = (rows * sum_x2) - (sum_x * sum_x);
36
+ float denom_y = (rows * sum_y2) - (sum_y * sum_y);
37
+
38
+ float denominator = sqrtf(denom_x * denom_y);
39
+
40
+ corr[i * cols + j] = (denominator == 0) ? 0.0f : numerator / denominator;
41
+ }
42
+ }
43
+
44
+ int main(int argc, char** argv) {
45
+ if (argc != 3) return 1;
46
+
47
+ std::ifstream infile(argv[1], std::ios::binary);
48
+ if (!infile) return 1;
49
+
50
+ int rows, cols;
51
+ infile.read(reinterpret_cast<char*>(&rows), sizeof(int));
52
+ infile.read(reinterpret_cast<char*>(&cols), sizeof(int));
53
+
54
+ size_t data_size = rows * cols * sizeof(float);
55
+ std::vector<float> h_data(rows * cols);
56
+ infile.read(reinterpret_cast<char*>(h_data.data()), data_size);
57
+ infile.close();
58
+
59
+ float *d_data, *d_corr;
60
+ CUDA_CHECK(cudaMalloc(&d_data, data_size));
61
+ CUDA_CHECK(cudaMalloc(&d_corr, cols * cols * sizeof(float)));
62
+
63
+ CUDA_CHECK(cudaMemcpy(d_data, h_data.data(), data_size, cudaMemcpyHostToDevice));
64
+
65
+ dim3 blockSize(16, 16);
66
+ dim3 gridSize((cols + blockSize.x - 1) / blockSize.x, (cols + blockSize.y - 1) / blockSize.y);
67
+
68
+ computeCorrelationKernel<<<gridSize, blockSize>>>(d_data, d_corr, rows, cols);
69
+ CUDA_CHECK(cudaDeviceSynchronize());
70
+
71
+ std::vector<float> h_corr(cols * cols);
72
+ CUDA_CHECK(cudaMemcpy(h_corr.data(), d_corr, cols * cols * sizeof(float), cudaMemcpyDeviceToHost));
73
+
74
+ std::ofstream outfile(argv[2], std::ios::binary);
75
+ outfile.write(reinterpret_cast<char*>(h_corr.data()), cols * cols * sizeof(float));
76
+ outfile.close();
77
+
78
+ cudaFree(d_data);
79
+ cudaFree(d_corr);
80
+ return 0;
81
+ }
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: nitrocsv-eda
3
+ Version: 0.1.0
4
+ Summary: A hardware-accelerated CSV EDA and heatmap generator.
5
+ Author-email: CodingMaster24 <sivatech24@gmail.com>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: POSIX :: Linux
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pandas
13
+ Requires-Dist: numpy
14
+ Requires-Dist: seaborn
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: hwdetect
17
+ Dynamic: license-file
18
+
19
+ --
20
+
21
+ # NitroCSV-EDA 🚀
22
+
23
+ A high-performance, hardware-aware Exploratory Data Analysis (EDA) tool for CSV files. NitroCSV-EDA automates data classification, statistical descriptions, and correlation heatmap generation.
24
+
25
+ It leverages a hybrid architecture: using Python for data orchestration and visualization, while offloading heavy matrix math to a dynamically compiled **CUDA C++** backend if an NVIDIA GPU is detected, or a **C** backend for CPU only systems.
26
+
27
+ ## ✨ Key Features
28
+
29
+ * **Automated Dependency Management:** Automatically installs missing Python dependencies (`pandas`, `numpy`, `seaborn`, `matplotlib`, `hwdetect`) on the first run.
30
+ * **Smart Hardware Detection:** Uses `hwdetect` to scan the PCI bus for NVIDIA GPUs and seamlessly routes workloads.
31
+ * **Dynamic Backend Compilation:** Compiles high-performance C (`gcc`) or CUDA (`nvcc`) backend engines at runtime. No manual building required.
32
+ * **Automated EDA Pipeline:**
33
+ * Generates `head()` and `tail()` previews.
34
+ * Calculates descriptive statistics for all columns.
35
+ * Classifies data types (Numeric, Categorical, Temporal) and provides column-level explanations.
36
+
37
+
38
+ * **Headless & GUI Aware:** Automatically detects if you are running in a GUI/Jupyter environment or a headless Linux/WSL terminal. It displays an interactive heatmap window when possible, or gracefully falls back to a clean, DB-formatted ASCII matrix in the terminal.
39
+ * **Memory Optimized:** Employs aggressive garbage collection (`gc`) and binary `.dat` file streaming to keep RAM usage low during heavy matrix transpositions.
40
+ * **Secure Session Windup:** Visual outputs are cached in the system's `/tmp` directory and automatically purged the moment the session closes.
41
+
42
+ ---
43
+
44
+ ## 🛠️ Prerequisites
45
+
46
+ * **Python:** 3.7+
47
+ * **OS:** Linux or WSL (Windows Subsystem for Linux) recommended.
48
+ * **Compilers:**
49
+ * `gcc` (Required for the CPU backend compilation)
50
+ * `nvcc` / CUDA Toolkit (Optional, required only for GPU backend compilation)
51
+
52
+
53
+
54
+ ---
55
+
56
+ ## 📦 Installation
57
+
58
+ Since NitroCSV-EDA is packaged with a CLI entry point, you can install it directly via pip.
59
+
60
+ 1. **Install the package:**
61
+ ```bash
62
+ pip install nitrocsv-eda
63
+
64
+ ```
65
+
66
+
67
+
68
+ ---
69
+
70
+ ## 🚀 Usage
71
+
72
+ Once installed, the `nitrocsv` command becomes available globally in your terminal. Pass the target CSV file as an argument:
73
+
74
+ ```bash
75
+ nitrocsv path/to/your/dataset.csv
76
+
77
+ ```
78
+
79
+ ### Example Output Workflow
80
+
81
+ 1. **Dependency Check:** Verifies and installs missing Python libraries.
82
+ 2. **Analysis:** Prints data types, missing values, and column statistics.
83
+ 3. **Execution:**
84
+ * Detects hardware (e.g., *NVIDIA GPU detected. Will utilize CUDA backend.*)
85
+ * Flattens the dataframe into a temporary binary file.
86
+ * Executes the optimized C or CUDA engine to compute the Pearson correlation matrix.
87
+
88
+
89
+ 4. **Rendering:**
90
+ * **In Jupyter/Desktop:** Opens a high-res Seaborn heatmap window.
91
+ * **In WSL/Terminal:** Prints a structured, readable raw correlation matrix directly to the console.
92
+
93
+
94
+
95
+ ---
96
+
97
+ ## 🧠 Under the Hood (How it Works)
98
+
99
+ NitroCSV-EDA is built to bypass Python's Global Interpreter Lock (GIL) and memory bottlenecks during heavy EDA operations:
100
+
101
+ 1. **Python Orchestrator:** Pandas is used solely for initial CSV ingestion, type checking, and printing standard data shapes.
102
+ 2. **Binary Handoff:** Instead of using `.corr()` in Pandas, the numeric data is packed into raw bytes (`struct.pack`) and dumped to an `input_matrix.dat` file. The Pandas dataframe is immediately garbage-collected to free RAM.
103
+ 3. **External Compute:** The Python script calls the compiled `./corr_gpu` or `./corr_cpu` binary via `subprocess`. The C/CUDA script loads the `.dat` file, processes the $O(n^2)$ correlation math at hardware speeds, and writes an `output_corr.dat` file.
104
+ 4. **Visual Windup:** Python reads the output binary, generates a Seaborn heatmap, saves it to a temporary `.png`, and either displays it or prints the raw table. An `atexit` hook ensures no temporary files are left behind on your hard drive.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ nitrocsv_eda/__init__.py
6
+ nitrocsv_eda/analyzer.py
7
+ nitrocsv_eda/corr_engine.c
8
+ nitrocsv_eda/corr_engine.cu
9
+ nitrocsv_eda.egg-info/PKG-INFO
10
+ nitrocsv_eda.egg-info/SOURCES.txt
11
+ nitrocsv_eda.egg-info/dependency_links.txt
12
+ nitrocsv_eda.egg-info/entry_points.txt
13
+ nitrocsv_eda.egg-info/requires.txt
14
+ nitrocsv_eda.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nitrocsv = nitrocsv_eda.analyzer:main_cli
@@ -0,0 +1,5 @@
1
+ pandas
2
+ numpy
3
+ seaborn
4
+ matplotlib
5
+ hwdetect
@@ -0,0 +1 @@
1
+ nitrocsv_eda
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nitrocsv-eda"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="CodingMaster24", email="sivatech24@gmail.com" },
10
+ ]
11
+ description = "A hardware-accelerated CSV EDA and heatmap generator."
12
+ readme = "README.md"
13
+ requires-python = ">=3.7"
14
+ dependencies = [
15
+ "pandas",
16
+ "numpy",
17
+ "seaborn",
18
+ "matplotlib",
19
+ "hwdetect"
20
+ ]
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: POSIX :: Linux",
25
+ ]
26
+
27
+ [project.scripts]
28
+ nitrocsv = "nitrocsv_eda.analyzer:main_cli"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+