0
# Environment & Diagnostics
1
2
Tools for environment configuration, troubleshooting, and system health checks to ensure proper PyImageJ operation. The diagnostics system helps identify and resolve common configuration issues.
3
4
## Capabilities
5
6
### System Health Checks
7
8
Comprehensive environment analysis to identify potential PyImageJ compatibility issues.
9
10
```python { .api }
11
def checkup(output=print):
12
"""
13
Check environment for health problems that could prevent PyImageJ from functioning.
14
15
Args:
16
output: Function to use for displaying results (default: print)
17
18
Analyzes:
19
- Python executable and version
20
- Java installation and version
21
- Required dependencies and versions
22
- Environment variables and paths
23
- Known compatibility issues
24
"""
25
```
26
27
**Usage Examples:**
28
29
```python
30
import imagej.doctor
31
32
# Run comprehensive checkup with default output
33
imagej.doctor.checkup()
34
35
# Capture checkup results to custom function
36
results = []
37
def capture_output(message):
38
results.append(message)
39
40
imagej.doctor.checkup(output=capture_output)
41
42
# Review captured results
43
for result in results:
44
print(f"CHECKUP: {result}")
45
46
# Run checkup before ImageJ initialization
47
imagej.doctor.checkup()
48
ij = imagej.init()
49
```
50
51
### Debug Logging Configuration
52
53
Enable detailed logging for troubleshooting PyImageJ initialization and operation issues.
54
55
```python { .api }
56
def debug_to_stderr(logger=None, debug_maven=False):
57
"""
58
Enable debug logging to standard error stream.
59
60
Args:
61
logger: Specific logger name, or None for all PyImageJ loggers
62
debug_maven: Enable verbose Maven debug logging (default: False)
63
"""
64
```
65
66
**Usage Examples:**
67
68
```python
69
import imagej.doctor
70
71
# Enable debug logging for all PyImageJ components
72
imagej.doctor.debug_to_stderr()
73
74
# Enable debug logging with Maven details
75
imagej.doctor.debug_to_stderr(debug_maven=True)
76
77
# Enable for specific logger only
78
imagej.doctor.debug_to_stderr(logger="scyjava._logger")
79
80
# Now initialize with verbose logging
81
import imagej
82
ij = imagej.init()
83
```
84
85
### Dependency Verification
86
87
Check for required and optional dependencies with version compatibility.
88
89
**Manual Dependency Checking:**
90
91
```python
92
import imagej.doctor
93
94
# Check specific dependencies
95
def check_dependencies():
96
"""Custom dependency verification example."""
97
required_packages = [
98
'numpy', 'scyjava', 'jpype1', 'xarray',
99
'imglyb', 'labeling', 'jgo'
100
]
101
102
optional_packages = [
103
'matplotlib', 'scikit-image', 'pandas'
104
]
105
106
for package in required_packages:
107
try:
108
__import__(package)
109
print(f"✓ {package} - Available")
110
except ImportError:
111
print(f"✗ {package} - Missing (Required)")
112
113
for package in optional_packages:
114
try:
115
__import__(package)
116
print(f"✓ {package} - Available (Optional)")
117
except ImportError:
118
print(f"- {package} - Missing (Optional)")
119
120
# Run dependency check
121
check_dependencies()
122
```
123
124
### Java Environment Analysis
125
126
Detailed analysis of Java installation and configuration for ImageJ2 compatibility.
127
128
**Java Configuration Checking:**
129
130
```python
131
import imagej.doctor
132
import scyjava as sj
133
134
# Analyze Java environment
135
def analyze_java_environment():
136
"""Analyze Java setup for PyImageJ compatibility."""
137
138
print("=== Java Environment Analysis ===")
139
140
# Check Java version before JVM start
141
try:
142
java_version = sj.jvm_version()
143
print(f"Java version: {java_version}")
144
except RuntimeError as e:
145
print(f"Java detection issue: {e}")
146
147
# Check Java memory configuration
148
heap_size = sj.config.get_max_heap_size()
149
print(f"Max heap size: {heap_size}")
150
151
# Check for Java fetch configuration
152
fetch_java = sj.config.get_fetch_java()
153
print(f"Auto-fetch Java: {fetch_java}")
154
155
# Start JVM and get runtime info
156
if not sj.jvm_started():
157
sj.start_jvm()
158
159
Runtime = sj.jimport('java.lang.Runtime')
160
runtime = Runtime.getRuntime()
161
162
total_memory = runtime.totalMemory() // (1024 * 1024) # MB
163
free_memory = runtime.freeMemory() // (1024 * 1024) # MB
164
max_memory = runtime.maxMemory() // (1024 * 1024) # MB
165
166
print(f"JVM Memory - Total: {total_memory}MB, Free: {free_memory}MB, Max: {max_memory}MB")
167
168
# Run Java analysis
169
analyze_java_environment()
170
```
171
172
### Common Issue Resolution
173
174
Automated detection and suggested fixes for common PyImageJ problems.
175
176
**Environment Issue Detection:**
177
178
```python
179
import imagej.doctor
180
181
def diagnose_common_issues():
182
"""Diagnose and suggest fixes for common PyImageJ issues."""
183
184
issues_found = []
185
suggestions = []
186
187
# Check for common environment problems
188
try:
189
import jpype
190
if jpype.isJVMStarted():
191
issues_found.append("JVM already started")
192
suggestions.append("Restart Python interpreter to reinitialize PyImageJ")
193
except ImportError:
194
issues_found.append("JPype not available")
195
suggestions.append("Install JPype: pip install jpype1")
196
197
try:
198
import imagej
199
# Try basic initialization
200
ij = imagej.init()
201
print("✓ Basic PyImageJ initialization successful")
202
except Exception as e:
203
issues_found.append(f"Initialization failed: {e}")
204
suggestions.append("Run imagej.doctor.checkup() for detailed analysis")
205
206
# Report findings
207
if issues_found:
208
print("\n=== Issues Found ===")
209
for issue in issues_found:
210
print(f"- {issue}")
211
212
print("\n=== Suggested Solutions ===")
213
for suggestion in suggestions:
214
print(f"- {suggestion}")
215
else:
216
print("✓ No common issues detected")
217
218
# Run diagnostic
219
diagnose_common_issues()
220
```
221
222
### Performance Monitoring
223
224
Monitor PyImageJ performance and resource usage for optimization.
225
226
```python
227
import time
228
import psutil
229
import imagej
230
231
def monitor_performance():
232
"""Monitor PyImageJ initialization and operation performance."""
233
234
print("=== Performance Monitoring ===")
235
236
# Monitor initialization time
237
start_time = time.time()
238
process = psutil.Process()
239
initial_memory = process.memory_info().rss // (1024 * 1024) # MB
240
241
print(f"Initial memory usage: {initial_memory}MB")
242
print("Initializing PyImageJ...")
243
244
ij = imagej.init()
245
246
init_time = time.time() - start_time
247
post_init_memory = process.memory_info().rss // (1024 * 1024) # MB
248
memory_increase = post_init_memory - initial_memory
249
250
print(f"Initialization time: {init_time:.2f} seconds")
251
print(f"Memory after init: {post_init_memory}MB (+{memory_increase}MB)")
252
253
# Test basic operations
254
start_time = time.time()
255
test_array = ij.py.to_dataset(np.random.rand(512, 512))
256
conversion_time = time.time() - start_time
257
258
print(f"Array conversion time: {conversion_time:.4f} seconds")
259
260
return {
261
'init_time': init_time,
262
'memory_increase': memory_increase,
263
'conversion_time': conversion_time
264
}
265
266
# Run performance monitoring
267
performance = monitor_performance()
268
```
269
270
## Environment Variables
271
272
PyImageJ respects several environment variables for configuration:
273
274
- **`DEBUG`**: Enable debug logging when set to any non-empty value
275
- **`JAVA_HOME`**: Specify Java installation directory
276
- **`PYJAVA_CLASSPATH`**: Additional JAR files for classpath
277
- **`SCYJAVA_CACHE_DIR`**: Directory for caching downloaded JAR files
278
279
## Troubleshooting Checklist
280
281
Common resolution steps for PyImageJ issues:
282
283
1. **Installation Issues**: Run `imagej.doctor.checkup()`
284
2. **Java Problems**: Verify Java 8+ installation with `java -version`
285
3. **Memory Issues**: Increase JVM heap size with `scyjava.config.add_option("-Xmx8g")`
286
4. **Dependency Conflicts**: Use fresh virtual environment
287
5. **JVM Restart**: Restart Python interpreter if JVM settings change
288
6. **Legacy Issues**: Try `add_legacy=False` for pure ImageJ2 mode
289
7. **Platform Issues**: Check platform-specific installation requirements
290
291
## Error Logging
292
293
PyImageJ provides structured error logging for debugging:
294
295
```python
296
import logging
297
import imagej
298
299
# Configure logging to see PyImageJ internals
300
logging.basicConfig(level=logging.DEBUG)
301
logger = logging.getLogger('imagej')
302
logger.setLevel(logging.DEBUG)
303
304
# Now PyImageJ operations will show detailed logs
305
ij = imagej.init()
306
```