Sunday, February 15, 2026

Python: Detecting the Vehicle on the real-time footage

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
"""
Vehicle Detector with Timestamp Logging
Enhanced version: Logs timestamps for each vehicle and saves to daily log files
"""

import cv2
import numpy as np
from picamera2 import Picamera2
import time
import os
from datetime import datetime, timedelta
import json

class VehicleDetectorLogger:
    def __init__(self):
        # Create log directory
        self.log_dir = "vehicle_logs"
        os.makedirs(self.log_dir, exist_ok=True)
        
        # Current log file
        self.current_log_date = datetime.now().date()
        self.log_file = self.get_log_file_path()
        
        # Initialize statistics
        self.vehicle_count = 0
        self.vehicle_records = []  # Store all vehicle records
        self.daily_stats = self.load_daily_stats()
        
        # Detection parameters
        self.last_count_time = time.time()
        self.frame_count = 0
        self.start_time = time.time()
        
        # Initialize camera
        print("Initializing camera...")
        self.picam2 = Picamera2()
        config = self.picam2.create_video_configuration(
            main={"size": (640, 480), "format": "RGB888"}
        )
        self.picam2.configure(config)
        
        # Background subtractor
        self.fgbg = cv2.createBackgroundSubtractorMOG2(history=50, varThreshold=25)
        
        print("System ready!")
        print(f"Log file: {self.log_file}")
        print("-" * 50)
    
    def get_log_file_path(self):
        """Get log file path for current date"""
        date_str = datetime.now().strftime("%Y%m%d")
        return os.path.join(self.log_dir, f"vehicles_{date_str}.txt")
    
    def load_daily_stats(self):
        """Load daily statistics"""
        stats_file = os.path.join(self.log_dir, "daily_stats.json")
        if os.path.exists(stats_file):
            try:
                with open(stats_file, 'r') as f:
                    stats = json.load(f)
                    # Keep only last 7 days of data
                    seven_days_ago = (datetime.now() - timedelta(days=7)).strftime("%Y%m%d")
                    stats = {k: v for k, v in stats.items() if k >= seven_days_ago}
                    return stats
            except:
                return {}
        return {}
    
    def save_daily_stats(self):
        """Save daily statistics"""
        stats_file = os.path.join(self.log_dir, "daily_stats.json")
        date_str = datetime.now().strftime("%Y%m%d")
        self.daily_stats[date_str] = {
            "total_vehicles": self.vehicle_count,
            "records_count": len(self.vehicle_records),
            "date": datetime.now().strftime("%Y-%m-%d")
        }
        with open(stats_file, 'w') as f:
            json.dump(self.daily_stats, f, indent=2)
    
    def log_vehicle(self, vehicle_id, timestamp, position=None):
        """Log vehicle detection to file"""
        # Check if need to switch to new day's log file
        current_date = datetime.now().date()
        if current_date != self.current_log_date:
            self.current_log_date = current_date
            self.log_file = self.get_log_file_path()
            print(f"New day! Switching to log file: {self.log_file}")
        
        # Format timestamp
        time_str = timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        
        # Create record
        record = {
            "id": vehicle_id,
            "timestamp": time_str,
            "unix_time": timestamp.timestamp(),
            "date": timestamp.strftime("%Y-%m-%d"),
            "time": timestamp.strftime("%H:%M:%S"),
            "position": position
        }
        
        # Add to records list
        self.vehicle_records.append(record)
        
        # Save to text file
        with open(self.log_file, 'a') as f:
            log_line = f"[{time_str}] Vehicle #{vehicle_id:04d} detected"
            if position:
                log_line += f" at position {position}"
            log_line += "\n"
            f.write(log_line)
        
        # Also save to JSON file (for easy analysis)
        json_file = self.log_file.replace('.txt', '.json')
        with open(json_file, 'w') as f:
            json.dump(self.vehicle_records, f, indent=2)
        
        # Print to console
        print(f"[{timestamp.strftime('%H:%M:%S')}] πŸš— Vehicle #{vehicle_id:04d} detected")
        
        return record
    
    def detect_and_count(self, frame):
        """Detect and count vehicles"""
        # Convert to grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Apply background subtraction
        fgmask = self.fgbg.apply(gray)
        
        # Morphological operations
        kernel = np.ones((5,5), np.uint8)
        fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)
        fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
        
        # Find contours
        contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        detected_vehicles = []
        
        for contour in contours:
            area = cv2.contourArea(contour)
            if area > 1000:  # Only process large enough areas
                x, y, w, h = cv2.boundingRect(contour)
                
                # Only focus on bottom half of screen
                if y > 240 and w > 50 and h > 50:
                    # Calculate center point
                    center_x = x + w // 2
                    center_y = y + h // 2
                    
                    # Check if new vehicle (avoid duplicate counting)
                    current_time = time.time()
                    if current_time - self.last_count_time > 2.0:
                        self.vehicle_count += 1
                        self.last_count_time = current_time
                        
                        # Log vehicle
                        timestamp = datetime.now()
                        position = {"x": center_x, "y": center_y, "w": w, "h": h}
                        record = self.log_vehicle(self.vehicle_count, timestamp, position)
                        detected_vehicles.append({
                            "bbox": (x, y, w, h),
                            "center": (center_x, center_y),
                            "area": area,
                            "record": record
                        })
                    else:
                        # Just draw, don't count
                        detected_vehicles.append({
                            "bbox": (x, y, w, h),
                            "center": (center_x, center_y),
                            "area": area,
                            "record": None
                        })
        
        return detected_vehicles, fgmask
    
    def draw_detection_info(self, frame, vehicles, fgmask):
        """Draw detection information on frame"""
        # Draw detected vehicles
        for vehicle in vehicles:
            x, y, w, h = vehicle["bbox"]
            center_x, center_y = vehicle["center"]
            
            # Draw bounding box
            color = (0, 255, 0) if vehicle["record"] else (0, 200, 200)
            thickness = 2 if vehicle["record"] else 1
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, thickness)
            
            # Draw center point
            cv2.circle(frame, (center_x, center_y), 4, (0, 0, 255), -1)
            
            # If counted vehicle, show ID
            if vehicle["record"]:
                cv2.putText(frame, f"#{vehicle['record']['id']}", 
                           (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
        
        # Draw detection line
        detection_line_y = 320
        cv2.line(frame, (0, detection_line_y), (640, detection_line_y), (0, 255, 255), 2)
        cv2.putText(frame, "Detection Line", (10, detection_line_y - 10),
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
        
        # Display statistics
        stats_y = 30
        cv2.putText(frame, f"Vehicles: {self.vehicle_count}", 
                   (10, stats_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        
        # Display FPS
        self.frame_count += 1
        if self.frame_count % 30 == 0:
            fps = self.frame_count / (time.time() - self.start_time)
            cv2.putText(frame, f"FPS: {fps:.1f}", 
                       (10, stats_y + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
        
        # Display current time
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cv2.putText(frame, current_time, 
                   (350, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        
        # Display today's date
        date_str = datetime.now().strftime("%Y-%m-%d")
        cv2.putText(frame, f"Today: {date_str}", 
                   (350, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        
        # Display log status
        log_status = f"Log: {os.path.basename(self.log_file)}"
        cv2.putText(frame, log_status, 
                   (10, stats_y + 80), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 255), 1)
        
        return frame
    
    def generate_daily_report(self):
        """Generate daily report"""
        if not self.vehicle_records:
            return
        
        # Count by hour
        hourly_counts = {}
        for record in self.vehicle_records:
            hour = datetime.fromtimestamp(record["unix_time"]).strftime("%H:00")
            hourly_counts[hour] = hourly_counts.get(hour, 0) + 1
        
        # Generate report file
        report_file = self.log_file.replace('.txt', '_report.txt')
        with open(report_file, 'w') as f:
            f.write("=" * 60 + "\n")
            f.write(f"Daily Vehicle Detection Report\n")
            f.write(f"Date: {datetime.now().strftime('%Y-%m-%d')}\n")
            f.write("=" * 60 + "\n\n")
            
            f.write(f"Total Vehicles Detected: {self.vehicle_count}\n")
            f.write(f"Detection Start Time: {datetime.fromtimestamp(self.start_time).strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            
            f.write("Hourly Statistics:\n")
            f.write("-" * 30 + "\n")
            for hour in sorted(hourly_counts.keys()):
                f.write(f"{hour}: {hourly_counts[hour]} vehicles\n")
            
            f.write("\nDetailed Records:\n")
            f.write("-" * 60 + "\n")
            for i, record in enumerate(self.vehicle_records, 1):
                f.write(f"{i:3d}. [{record['time']}] Vehicle #{record['id']:04d}\n")
        
        print(f"Daily report generated: {report_file}")
    
    def run(self):
        """Main detection loop"""
        print("Vehicle Detection System Starting")
        print("Controls:")
        print("  'q' - Quit program")
        print("  'r' - Reset counter")
        print("  's' - Save current frame")
        print("  'p' - Generate daily report")
        print("  '+' - Increase sensitivity")
        print("  '-' - Decrease sensitivity")
        print("-" * 50)
        
        # Start camera
        self.picam2.start()
        time.sleep(1)  # Let camera stabilize
        
        try:
            while True:
                # Capture frame
                frame = self.picam2.capture_array()
                frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
                
                # Detect and count vehicles
                vehicles, fgmask = self.detect_and_count(frame)
                
                # Draw detection info
                frame = self.draw_detection_info(frame, vehicles, fgmask)
                
                # Display frames
                cv2.imshow("Vehicle Detector with Logger", frame)
                cv2.imshow("Motion Mask", fgmask)
                
                # Handle keyboard input
                key = cv2.waitKey(1) & 0xFF
                if key == ord('q'):
                    print("\nQuitting program")
                    break
                elif key == ord('r'):
                    self.vehicle_count = 0
                    self.vehicle_records.clear()
                    self.last_count_time = time.time()
                    self.fgbg = cv2.createBackgroundSubtractorMOG2(history=50, varThreshold=25)
                    print("Counter reset")
                elif key == ord('s'):
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"snapshot_{timestamp}.jpg"
                    cv2.imwrite(filename, frame)
                    print(f"Frame saved: {filename}")
                elif key == ord('p'):
                    self.generate_daily_report()
                elif key == ord('+'):
                    # Increase sensitivity
                    self.fgbg.setVarThreshold(max(10, self.fgbg.getVarThreshold() - 5))
                    print(f"Sensitivity increased: varThreshold={self.fgbg.getVarThreshold()}")
                elif key == ord('-'):
                    # Decrease sensitivity
                    self.fgbg.setVarThreshold(min(100, self.fgbg.getVarThreshold() + 5))
                    print(f"Sensitivity decreased: varThreshold={self.fgbg.getVarThreshold()}")
                
        except KeyboardInterrupt:
            print("\nUser interrupted")
        
        finally:
            # Cleanup resources
            self.picam2.stop()
            cv2.destroyAllWindows()
            
            # Save statistics
            self.save_daily_stats()
            
            # Generate final report
            self.generate_daily_report()
            
            # Output summary
            total_time = time.time() - self.start_time
            fps = self.frame_count / total_time if total_time > 0 else 0
            
            print("\n" + "=" * 60)
            print("Detection System Stopped")
            print("=" * 60)
            print(f"Total Runtime: {total_time:.1f} seconds")
            print(f"Frames Processed: {self.frame_count}")
            print(f"Average FPS: {fps:.1f}")
            print(f"Total Vehicles Detected: {self.vehicle_count}")
            print(f"Log File: {self.log_file}")
            print(f"JSON Data: {self.log_file.replace('.txt', '.json')}")
            print("=" * 60)

def main():
    """Main function"""
    print("=" * 60)
    print("Raspberry Pi Vehicle Detection System - With Logging")
    print("=" * 60)
    
    # Create detector and run
    detector = VehicleDetectorLogger()
    detector.run()

if __name__ == "__main__":
    main()

Monday, September 29, 2025

Hysplit: CONC.CFG

Breakdown of Parameters in CONC.CFG

Breakdown of Parameters in CONC.CFG

The CONC.CFG file is a crucial configuration file that controls advanced settings for the HYSPLIT concentration (dispersion) model. It defines how calculations are performed and what output is generated, complementing the CONTROL file used in your MATLAB script.

Here's a breakdown of the CONC.CFG file structure and parameters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
&SETUP
 tratio = 0.75,
 delt = 0.0,
 initd = 0,
 kpuff = 0,
 khmax = 9999,
 khinp = 0,
 numpar = 2500,
 maxpar = 10000,
 nbptyp = 1,
 qcycle = 0.0,
 efile = '',
 k10m = 1,
 kdef = 0,
 krand = 2,
 kzmix = 0,
 kbls = 1,
 kblt = 0,
 isot = -99,
 idsp = 1,
 wvert = .TRUE.,
 plrise = 1,
 area = 0,
 vscale = 200.0,
 vscales = 5.0,
 vscaleu = 200.0,
 hscale = 10800.0,
 capemin = -1.0,
 tkemin = 0.001,
 uratio = 5.873300076,
 tvmix = 1.00,
 tkerd = 0.18,
 tkern = 0.18,
 kmix0 = 150,
 kmixd = 0,
 ninit = 1,
 ndump = 0,
 ncycl = 0,
 pinbc = 'PARINBC',
 pinpf = 'PARINIT',
 poutf = 'PARDUMP',
 messg = 'MESSAGE',
 vdist = 'VMSDIST',
 mgmin = 10,
 conage = 24,
 gemage = 48,
 kmsl = 0,
 kwet = 1,
 ichem = 0,
 cpack = 1,
 cmass = 0,
 kspl = 1,
 krnd = 6,
 frhmax = 3.00,
 splitf = 1.00,
 frhs = 1.00,
 frvs = 0.01,
 frts = 0.10,
 dxf = 1.00,
 dyf = 1.00,
 dzf = 0.01,
 /

Parameter Explanations

Core Simulation Parameters

  • tratio = 0.75 - Time step ratio (stability factor). HYSPLIT adjusts its internal time step so a particle/puff doesn't travel more than 75% of a grid cell in one step. Potential values: 0.0 to 1.0 (typically 0.5–0.9). Affects how your pollutant (e.g., SO2) disperses in the atmosphere.
  • delt = 0.0 - Fixed time step (minutes). 0.0 means HYSPLIT uses a variable time step controlled by tratio. Potential values: 0.0 (auto) or positive values (e.g., 1.0). Ensures efficient computation for your 48-hour simulation.
  • initd = 0 - Particle/puff initialization method. 0 = 3D particle mode (pure Lagrangian, tracks individual particles), 1 = Gaussian horizontal puff, vertical particle, 2 = Top-hat horizontal puff, vertical particle, 3 = Gaussian puff (3D), 4 = Top-hat puff (3D). Suitable for detailed dispersion tracking in your SO2 simulation.
  • kpuff = 0 - Horizontal puff growth option. 0 = Linear growth with time, 1 = Growth proportional to square root of time. Ignored since initd = 0. Not applicable in your current setup.
  • khmax = 9999 - Maximum duration (hours) for a particle/puff. 9999 means "no limit". Potential values: Positive integers. Matches your 48-hour forward run (param.runTime).
  • khinp = 0 - Input flag for puff splitting. 0 = No special input. Typically unused unless puff-splitting files are used. Not relevant unless customizing puff behavior.

Particle and Emission Parameters

  • numpar = 2500 - Number of particles or puffs released per emission cycle. Potential values: Positive integers (e.g., 1000–10000). Controls how finely your SO2 emission (param.emissionRate = 1000 kg/hr) is resolved.
  • maxpar = 10000 - Maximum total number of particles/puffs allowed. Potential values: Positive integers (e.g., 1000–100000). Ensures your simulation doesn’t crash due to too many particles.
  • nbptyp = 1 - Number of bytes per particle in the output file (affects PARDUMP file size). Potential values: 1, 2, or 4. Affects the PARDUMP file if used (not in your script’s output).
  • qcycle = 0.0 - Emission cycle time (hours). 0.0 = Continuous emission during emissionHours. Potential values: 0.0 or positive values (e.g., 1.0 for hourly pulses). Matches your 1-hour emission event (param.emissionHours = 1).
  • efile = '' - Path to an emission input file for complex source configurations. Potential values: Empty string ('') or a file path. Not needed since your script specifies param.emissionRate.

Turbulence and Boundary Layer Parameters

  • k10m = 1 - Use 10m wind data for turbulence calculations. Potential values: 0 (no), 1 (yes). Enhances accuracy near your 10m emission altitude (alt = 10).
  • kdef = 0 - Horizontal turbulence deformation method. 0 = Based on velocity variances, 1 = Based on deformation field. Suitable for your general-purpose SO2 dispersion.
  • krand = 2 - Random number generator for turbulence. Potential values: 1, 2, or 3. 2 is robust for your run.
  • kzmix = 0 - Vertical mixing method. 0 = Use meteorology data, 1 = Scale by boundary layer depth. Matches your use of GDAS1 files in metPath.
  • kbls = 1 - Boundary layer stability method. 0 = Use input meteorology, 1 = Compute from heat and momentum fluxes. Enhances realism for your SO2 dispersion.
  • kblt = 0 - Boundary layer turbulence parameterization. 0 = Beljaars-Holtslag for stable, Kanthar-Clayson for unstable, 1 = Shortwave radiation-based. Good default for your simulation.
  • isot = -99 - Isotropic turbulence flag. -99 = Disabled. Ignored in your run, safe to leave as is.
  • idsp = 1 - Dispersion method. 0 = No dispersion (advection only), 1 = Dispersion with mixing. Essential for modeling SO2 spread in your script.
  • wvert = .TRUE. - Enable vertical velocity in dispersion calculations. Potential values: .TRUE., .FALSE. Enhances vertical dispersion in your simulation.
  • plrise = 1 - Plume rise calculation method. 0 = No plume rise, 1 = Briggs plume rise. Suitable if your SO2 source is a point source like a factory.
  • area = 0 - Area source size (m²). 0 = Point source. Potential values: 0 or positive value. Matches your single-point emission (lat = 37.5, lon = -120.0, alt = 10).
  • vscale, vscales, vscaleu = 200.0, 5.0, 200.0 - Turbulence velocity scales (m/s) for general, stable, and unstable conditions. Potential values: Positive values (e.g., 5.0–500.0). Affects how widely your SO2 disperses vertically.
  • hscale = 10800.0 - Horizontal turbulence scale (seconds). Potential values: Positive values (e.g., 1000–10800). Influences horizontal spread of pollutants in your simulation.
  • capemin = -1.0 - Minimum convective available potential energy (J/kg) for plume rise. -1.0 = Disabled. Simplifies your run, relying on plrise.
  • tkemin = 0.001 - Minimum turbulent kinetic energy (m²/s²). Potential values: Small positive values (e.g., 0.001–0.1). Ensures turbulence in calm conditions.
  • uratio = 5.873300076 - Ratio of wind speed to turbulence velocity. Potential values: Positive values (default ~5.87). Affects turbulence; default is fine.
  • tvmix = 1.00 - Vertical mixing coefficient. Potential values: 0.0–1.0. Ensures realistic vertical dispersion.
  • tkerd, tkern = 0.18, 0.18 - Daytime and nighttime turbulence ratios. Potential values: 0.1–0.5. Suitable for your run.
  • kmix0 = 150 - Minimum mixing depth (m). Potential values: Positive integers (e.g., 50–500). Reasonable for near-surface emissions.

Initialization and Output Control

  • kmixd = 0 - Mixing depth source. 0 = Use met data, 1 = Compute internally. Matches your reliance on GDAS1 files.
  • ninit = 1 - Initialization of particles from PARINIT file. 0 = None, 1 = Read PARINIT if exists. Not used unless you specify pinpf.
  • ndump = 0 - Interval (hours) for writing PARDUMP file. 0 = None. Potential values: Positive integers. Reduces output file size in your run.
  • ncycl = 0 - Particle release cycle interval (hours). 0 = Continuous. Consistent with your 1-hour emission.
  • pinbc = 'PARINBC' - Filename for boundary condition input. Potential values: File names or empty. Not used in your script.
  • pinpf = 'PARINIT' - Filename for particle initialization. Potential values: File names or empty. Not used in your script.
  • poutf = 'PARDUMP' - Filename for particle dump output. Potential values: File names or empty. Not used in your script.
  • messg = 'MESSAGE' - Names the detailed log file generated by HYSPLIT. Potential values: File name or empty. Default is fine.
  • vdist = 'VMSDIST' - Vertical distribution method. Potential values: String (default 'VMSDIST'). Controls vertical particle distribution; default is standard.
  • mgmin = 10 - Minimum number of particles per grid cell for concentration output. Potential values: Positive integers. Ensures statistical reliability in your grid.
  • conage = 24 - Maximum age (hours) for concentration calculations. Potential values: Positive integers. Fits your 48-hour run, limiting older contributions.
  • gemage = 48 - Maximum age (hours) for particle transport. Potential values: Positive integers. Matches your runTime, ensuring particles don’t persist beyond your simulation.
  • kmsl = 0 - Altitude input type. 0 = Meters above ground level (AGL), 1 = Meters above sea level (ASL). Matches your MATLAB input (alt = 10).

Deposition and Chemistry

  • kwet = 1 - Enable wet deposition. 0 = Off, 1 = On. Ignored unless you modify HYSPLIT_writeControlConc.m to include deposition parameters.
  • ichem = 0 - Chemistry module. 0 = None. Potential values: Other integers (see HYSPLIT docs). Suitable for your simple SO2 simulation.

Output File Parameters

  • cpack = 1 - Concentration output packing. 0 = No packing, 1 = Packed binary output. Matches your cdump_test output.
  • cmass = 0 - Concentration output type. 0 = Concentration (e.g., kg/m³), 1 = Mass loading (e.g., kg). Appropriate for analyzing SO2 concentrations.
  • kspl = 1 - Particle/puff splitting interval (hours). 0 = No splitting. Enhances accuracy in your simulation.
  • krnd = 6 - Random number seed control. Potential values: Positive integers. Ensures reproducible results.
  • frhmax = 3.00 - Maximum horizontal puff growth factor. Potential values: Positive values (e.g., 1.0–5.0). Ignored since initd = 0.
  • splitf, frhs, frvs, frts = 1.00, 1.00, 0.01, 0.10 - Splitting factors for puffs (horizontal, vertical, time). Potential values: Positive values. Ignored since initd = 0.
  • dxf, dyf, dzf = 1.00, 1.00, 0.01 - Scaling factors for horizontal and vertical components of concentration output. Potential values: Positive values. Matches your grid settings (gridSpacing = 0.1).

Note: This configuration is set up for a standard concentration simulation with 2500 particles, continuous emission for 1 hour, and output in a packed binary cdump file. It uses 3D particle mode (initd = 0) for precise dispersion tracking, suitable for your SO2 simulation in MATLAB.

HYSPLIT CONC.CFG Configuration Guide | Understanding HYSPLIT Concentration Model Settings

Monday, September 8, 2025

Hysplit: TRAJ.CFG

Understanding the HYSPLIT TRAJ.CFG Configuration File

The TRAJ.CFG file is a crucial configuration file that controls advanced settings for the HYSPLIT trajectory model. It defines how calculations are performed and what output is generated.

Here's a breakdown of the TRAJ.CFG file structure and parameters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
&SETUP
 tratio = 0.75,
 delt = 0.0,
 mgmin = 10,
 khmax = 9999,
 kmixd = 0,
 kmsl = 0,
 kagl = 1,
 k10m = 1,
 nstr = 0,
 mhrs = 9999,
 nver = 0,
 tout = 60,
 tm_pres = 1,
 tm_tpot = 0,
 tm_tamb = 0,
 tm_rain = 0,
 tm_mixd = 0,
 tm_relh = 0,
 tm_sphu = 0,
 tm_mixr = 0,
 tm_dswf = 0,
 tm_terr = 0,
 tm_uwnd = 0,
 tm_vwnd = 0,
 dxf = 1.00,
 dyf = 1.00,
 dzf = 0.01,
 messg = 'MESSAGE',
 /

Parameter Explanations

Core Simulation Parameters

  • tratio = 0.75 - Time step ratio (stability factor). HYSPLIT adjusts its internal time step so an air parcel doesn't travel more than 75% of a grid cell in one step.
  • delt = 0.0 - Fixed time step (minutes). 0.0 means HYSPLIT uses variable time step controlled by tratio.
  • mgmin = 10 - Minimum number of grid cells for met data. Sanity check to prevent errors with bad met files.
  • khmax = 9999 - Maximum duration (hours) for a trajectory. 9999 means "no limit".

Vertical Motion & Starting Height

  • kmixd = 0 - Boundary Layer option. 0 = Ignore mixing depth.
  • kmsl = 0 - Input starting height reference. 0 = meters above ground level (AGL).
  • kagl = 1 - Output height reference. 1 = meters above ground level (AGL).
  • k10m = 1 - Use 10m meteorological data for surface-based trajectories.

Output Control

  • nstr = 0 - Number of special starting locations. 0 means not used.
  • mhrs = 9999 - Maximum duration for meteorological data. 9999 means "no limit".
  • nver = 0 - Vertical motion output flag. 0 = Do not include vertical velocity.
  • tout = 60 - Output frequency. 60 = Save trajectory position every 60 minutes.

Meteorological Output Variables (tm_ flags)

These control what additional meteorological data is written to the output file:

  • tm_pres = 1 - Pressure (hPa or mb) - INCLUDED
  • tm_tpot = 0 - Potential Temperature (K) - Excluded
  • tm_tamb = 0 - Ambient Temperature (K) - Excluded
  • tm_rain = 0 - Rainfall/Precipitation - Excluded
  • tm_mixd = 0 - Mixing Depth (m) - Excluded
  • tm_relh = 0 - Relative Humidity (%) - Excluded
  • tm_sphu = 0 - Specific Humidity (g/kg) - Excluded
  • tm_mixr = 0 - Water Mixing Ratio (g/kg) - Excluded
  • tm_dswf = 0 - Downward ShortWave Radiation Flux (W/m²) - Excluded
  • tm_terr = 0 - Terrain Height (m) - Excluded
  • tm_uwnd = 0 - U-Wind Component (m/s) - Excluded
  • tm_vwnd = 0 - V-Wind Component (m/s) - Excluded

Output File Scaling Factors

  • dxf = 1.00, dyf = 1.00 - Scaling factors for horizontal components of trajectory dispersion.
  • dzf = 0.01 - Scaling factor for vertical component of trajectory dispersion.

Log File Control

  • messg = 'MESSAGE' - Names the detailed log file generated by HYSPLIT.

Note: This configuration is set up for a standard, single, backward trajectory with output in meters AGL, saved every 60 minutes, with pressure as the only additional meteorological variable.

HYSPLIT TRAJ.CFG Configuration Guide | Understanding HYSPLIT Model Settings