Process and analyze Mobile Mapping System data with columns:
Time, Image, X, Y, Z, Roll, Pitch, Heading
"""
import os
import sys
import glob
import json
import logging
import argparse
from typing import Dict, List, Tuple, Any, Optional, Union
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
def main():
"""Main execution function."""
parser = argparse.ArgumentParser(description='MMS Data Processing and Analysis')
code
# Required arguments
parser.add_argument('--input', '-i', required=True,
help='Input folder containing MMS data files')
# Optional arguments
parser.add_argument('--extension', '-e', default='txt', choices=['txt', 'csv'],
help='Input file extension (default: txt)')
parser.add_argument('--output', '-o', help='Output folder path')
parser.add_argument('--config', '-c', help='Path to config file')
parser.add_argument('--crs', '-c', type=int, help='CRS code number (e.g., 3857)')
parser.add_argument('--no-plots', action='store_true',
help='Disable plot generation')
parser.add_argument('--verbose', '-v', action='store_true',
help='Enable verbose output')
args = parser.parse_args()
try:
# Load configuration
config = {}
if args.config:
try:
with open(args.config, 'r') as f:
config = json.load(f)
except Exception as e:
print(f"Error loading config file: {e}")
sys.exit(1)
# Update config with command line arguments
if args.output:
config['output_folder'] = args.output
if args.crs:
config['crs'] = args.crs
if args.no_plots:
config['visualize'] = False
if args.verbose:
config['logging_level'] = logging.DEBUG
# Initialize processor
processor = MMSProcessor(config)
# Register plugins (if needed)
# Example:
# processor.register_plugin(QualityCheckPlugin())
# Initialize visualization and export systems
visualizer = MMSVisualization(processor.config['output_folder'])
exporter = MMSExport(processor.config['output_folder'])
# Process data
processor.process(args.input, args.extension)
# Create visualizations
if processor.config.get('visualize', True):
visualizer.create_visualizations(
processor.data,
processor.paths,
processor.metrics
)
# Export results
exporter.export_results(
processor.data,
processor.paths,
processor.metrics
)
except InputError as e:
print(f"Input Error: {e}")
sys.exit(1)
except ProcessingError as e:
print(f"Processing Error: {e}")
sys.exit(1)
except OutputError as e:
print(f"Output Error: {e}")
sys.exit(1)
except Exception as e:
print(f"Unexpected error: {e}")
sys.exit(1)
if name == "main":
# Example usage:
# python mms_processor.py -i /path/to/input/folder
# python mms_processor.py -i /path/to/input/folder -o /path/to/output -e csv
# python mms_processor.py -i /path/to/input/folder -c config.json --no-plots
code
main()
gives me this error:
PS C:\Users\SPL\Music\mega_3> python .\mega_3.py -i "C:\Users\SPL\Pictures" -o "C:\Users\SPL\Pictures\test_mega3" -e txt -c 3857
Traceback (most recent call last):
File "C:\Users\SPL\Music\mega_3\mega_3.py", line 1767, in
main()
~~~~^^
File "C:\Users\SPL\Music\mega_3\mega_3.py", line 1689, in main
parser.add_argument('--crs', '-c', type=int, help='CRS code number (e.g., 3857)')
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1477, in add_argument
return self._add_action(action)
~~~~~~~~~~~~~~~~^^^^^^^^
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1861, in _add_action
self._optionals._add_action(action)
~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1681, in _add_action
action = super(_ArgumentGroup, self)._add_action(action)
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1491, in _add_action
self._check_conflict(action)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1630, in _check_conflict
conflict_handler(action, confl_optionals)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SPL\scoop\apps\python\current\Lib\argparse.py", line 1639, in _handle_conflict_error
raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument --crs/-c: conflicting option string: -c
The error you're encountering stems from a conflict in the command-line argument definitions within your script. Specifically, both the --config and --crs arguments are assigned the same short option -c. This duplication causes the argparse library to raise an ArgumentError because each short option must be unique.
Understanding the Error
Here's the relevant portion of your script causing the issue:
python
parser.add_argument('--config', '-c', help='Path to config file')
parser.add_argument('--crs', '-c', type=int, help='CRS code number (e.g., 3857)')
Both --config and --crs are using -c as their short option, leading to a conflict. When you attempt to run the script with -c 3857, argparse doesn't know whether you're referring to the --config or --crs argument, thus raising the error.
Solution: Assign Unique Short Options
To resolve this issue, you need to ensure that each command-line option has a unique short identifier. Here's how you can modify your script:
Change the Short Option for One of the Arguments:
Option 1: Assign a different short option to --config.
Option 2: Assign a different short option to --crs.
For clarity and convention, it's common to use the first letter of the long option as its short counterpart. Given that, --crs can comfortably retain -c, and --config can be assigned a different short option like -f.
Update the Argument Definitions:
Modify the argparse definitions in your main() function as follows:
python
parser.add_argument('--config', '-f', help='Path to config file')
parser.add_argument('--crs', '-c', type=int, help='CRS code number (e.g., 3857)')
Explanation:
--config now uses -f (possibly representing "file").
--crs retains -c.
Update Your Command-Line Usage:
After making the above changes, your command should be updated to reflect the new short option for --config. Here's how you can run the script:
Here's the complete updated section of your main() function with the necessary changes:
python
def main():
"""Main execution function."""
parser = argparse.ArgumentParser(description='MMS Data Processing and Analysis')
# Required arguments
parser.add_argument('--input', '-i', required=True,
help='Input folder containing MMS data files')
# Optional arguments
parser.add_argument('--extension', '-e', default='txt', choices=['txt', 'csv'],
help='Input file extension (default: txt)')
parser.add_argument('--output', '-o', help='Output folder path')
parser.add_argument('--config', '-f', help='Path to config file') # Changed short option to -f
parser.add_argument('--crs', '-c', type=int, help='CRS code number (e.g., 3857)') # Retained -c for CRS
parser.add_argument('--no-plots', action='store_true',
help='Disable plot generation')
parser.add_argument('--verbose', '-v', action='store_true',
help='Enable verbose output')
args = parser.parse_args()
try:
# Load configuration
config = {}
if args.config:
try:
with open(args.config, 'r') as f:
config = json.load(f)
except Exception as e:
print(f"Error loading config file: {e}")
sys.exit(1)
# Update config with command line arguments
if args.output:
config['output_folder'] = args.output
if args.crs:
config['crs'] = args.crs
if args.no_plots:
config['visualize'] = False
if args.verbose:
config['logging_level'] = logging.DEBUG
# Initialize processor
processor = MMSProcessor(config)
# Register plugins (if needed)
# Example:
# processor.register_plugin(QualityCheckPlugin())
# Initialize visualization and export systems
visualizer = MMSVisualization(processor.config['output_folder'])
exporter = MMSExport(processor.config['output_folder'])
# Process data
processor.process(args.input, args.extension)
# Create visualizations
if processor.config.get('visualize', True):
visualizer.create_visualizations(
processor.data,
processor.paths,
processor.metrics
)
# Export results
exporter.export_results(
processor.data,
processor.paths,
processor.metrics
)
except InputError as e:
print(f"Input Error: {e}")
sys.exit(1)
except ProcessingError as e:
print(f"Processing Error: {e}")
sys.exit(1)
except OutputError as e:
print(f"Output Error: {e}")
sys.exit(1)
except Exception as e:
print(f"Unexpected error: {e}")
sys.exit(1)
Additional Recommendations
Use Descriptive Short Options:
While -c is common for "config," -f can intuitively represent "file" or "config file" when repurposed.
Print Help Information:
After making the changes, you can verify the argument assignments by running:
bash
python .\mega_3.py -h
This will display the help text, showing all available options and their descriptions.
Consider Removing Short Options for Clarity:
If managing short options becomes cumbersome, you might opt to remove them altogether, forcing users to use long-form arguments. This can enhance readability and reduce potential conflicts.
Implement Graceful Error Handling:
Ensure that your script provides clear and actionable error messages, guiding users on how to rectify issues.
Final Command Example
After implementing the changes, here's how you can run your script:
By ensuring each command-line option has a unique identifier, you eliminate ambiguity and allow argparse to correctly parse and assign values to each argument.
Summary
Problem: Both --config and --crs use the same short option -c, causing a conflict.
Solution: Assign unique short options to each argument. For example, change --config to use -f instead of -c.
Action Steps:
Modify the argparse definitions in your script.
Update your command-line usage accordingly.
Verify the changes by running the script and checking the help message.
Implementing these changes should resolve the argparse.ArgumentError and allow your script to function as intended.