### Install DSSATTools Package Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Install the DSSATTools library using pip. This command is for Linux environments; Windows users may need WSL or Google Colab. ```bash pip install DSSATTools ``` -------------------------------- ### Run DSSAT Simulation with DSSATTools Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Example demonstrating how to set up and run a DSSAT simulation using DSSATTools. Requires importing necessary classes and configuring field, crop, planting, fertilizer, and simulation control parameters. ```python from DSSATTools.crop import Sorghum from DSSATTools.weather import WeatherStation from DSSATTools.soil import SoilProfile from DSSATTools.filex import ( Planting, SimulationControls, Fertilizer, Field ) cultivar = Sorghum('IB0026') weather_station = WeatherStation( insi='UNCU', lat=4.34, long=-74.40, elev=1800, table=df_with_data ) soil = SoilProfile.from_file('IBSG910085', 'SOIL.SOL') field = Field( id_field='ITHY0001', wsta=weather_station, flob=0, fldd=0, flds=0, id_soil=soil, fldt='DR000' ) planting = Planting( pdate=date(1980, 6, 17), ppop=18, ppoe=18, plme='S', plds='R', plrs=45, plrd=0, pldp=5 ) fertilizer = Fertilizer(table=[ FertilizerEvent( fdate=date(1980, 7, 4), fmcd='FE005', fdep=5, famn=80, facd='AP002' ) ]) simulation_controls = SimulationControls( general=SCGeneral(sdate=date(1980, 6, 17)) ) dssat = DSSAT() results = dssat.run_treatment( field=field, cultivar=cultivar, planting=planting, fertilizer=fertilizer, simulation_controls=simulation_controls ) dssat.close() # Terminate the simulation environment ``` -------------------------------- ### Configure DSSAT Simulation Controls Source: https://context7.com/daquinterop/py_dssattools/llms.txt Sets up simulation controls including general parameters, options, methods, management, and output settings. Requires a SCGeneral instance with the simulation start date. ```python from DSSATTools.filex import ( SimulationControls, SCGeneral, SCOptions, SCMethods, SCManagement, SCOutputs ) from datetime import date simulation_controls = SimulationControls( general=SCGeneral( sdate=date(1980, 6, 13), # simulation start date nyers=1, # number of years nreps=1, # number of repetitions ), options=SCOptions( water='Y', # water balance enabled nitro='Y', # nitrogen balance enabled symbi='N', # symbiosis (N fixation) disabled co2='M', # CO2 from Mauna Loa data ), methods=SCMethods( evapo='R', # ET: Priestley-Taylor infil='S', # infiltration: SCS mesom='P', # SOM method: Century (Parton) ), management=SCManagement( irrig='D', # irrigation: on days after planting ferti='R', # fertilization: on reported dates harvs='M', # harvest: at maturity ), outputs=SCOutputs( grout='Y', # plant growth output waout='Y', # soil water output niout='Y', # soil nitrogen output fropt=1, # output interval (daily) fmopt='A', # format: text ) ) ``` -------------------------------- ### Define Simulation Controls Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Create a SimulationControls object, initializing it with general simulation parameters such as the start date. ```python >>> simulation_controls = SimulationControls( >>> general=SCGeneral(sdate=date(1980, 6, 1)) >>> ) ``` -------------------------------- ### Load DSSAT Experiment Data for Maize Simulation Source: https://context7.com/daquinterop/py_dssattools/llms.txt This example demonstrates loading various components of a DSSAT experiment, including cultivar, soil profile, weather data, and treatments, for a maize simulation. It shows how to inject live objects into the treatment structure. ```python from DSSATTools.crop import Maize from DSSATTools.soil import SoilProfile from DSSATTools.weather import WeatherStation from DSSATTools.filex import read_filex from DSSATTools.run import DSSAT import numpy as np # Load inputs cultivar = Maize('IB0171') soil = SoilProfile.from_file('BRPI020001', 'Soil/BR.SOL') weather = WeatherStation.from_files(['Weather/BRPI0201.WTH']) treatments = read_filex('Maize/BRPI0202.MZX') treatment = treatments[1] # Inject live objects treatment['Field']['id_soil'] = soil treatment['Field']['wsta'] = weather ``` -------------------------------- ### Run DSSAT Simulation and Get Results Source: https://context7.com/daquinterop/py_dssattools/llms.txt Instantiate the DSSAT class, run a simulation with specified parameters, and access the results. Ensure the DSSAT executable is available in the system's PATH. Close the DSSAT instance when done. ```python dssat = DSSAT('/tmp/dssat_sorghum') results = dssat.run_treatment( field=field, cultivar=cultivar, planting=planting, initial_conditions=initial_conditions, fertilizer=fertilizer, simulation_controls=simulation_controls ) # results = {'harwt': 6334, 'topwt': 12450, 'flo': 1980213, 'mat': 1980260, ...} print(f"Harvest weight: {results['harwt']} kg/ha") plant_gro_df = dssat.output_tables['PlantGro'] print(plant_gro_df.head()) dssat.close() ``` -------------------------------- ### Get Available Cultivars for a Crop Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Retrieve a list of all available cultivars for a specific crop using the `cultivar_list` class function. ```python >>> available_cultivars = Sorghum.cultivar_list() ``` -------------------------------- ### Initialize DSSAT Simulation Environment Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Create a DSSAT instance by providing a path for the simulation environment. This sets up the necessary directory structure for running the model. ```python >>> dssat = DSSAT("/tmp/dssat_test") ``` -------------------------------- ### Create WeatherStation from Files Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Instantiate a WeatherStation object by reading data from DSSAT weather files. The input must be a list of files corresponding to the same station. ```python >>> weather = WeatherStation.from_files(["UAFD9001.WTH", "UAFD9101.WTH"]) ``` -------------------------------- ### Modify Crop Cultivar Parameters Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Update cultivar parameters by assigning new values to the crop object's keys. For example, setting 'p1' and 'g1'. ```python >>> crop['p1'] = 450. >>> crop['g1'] = 0.1 ``` -------------------------------- ### Initialize DSSAT Simulation Environment Source: https://context7.com/daquinterop/py_dssattools/llms.txt Instantiate the DSSAT class to create a simulation environment. An explicit path can be provided, or it defaults to a directory in /tmp. Access output files and tables after running simulations. Remember to close the environment to remove the working directory. ```python from DSSATTools.run import DSSAT import os, tempfile # Use an explicit path or let it auto-create one in /tmp dssat = DSSAT(os.path.join(tempfile.gettempdir(), "dssat_run")) # Output: /tmp/dssat_run created. # After running (see run_treatment below): # Access raw output files as strings overview_str = dssat.output_files['OVERVIEW'] # Access parsed time-series tables as DataFrames plant_growth = dssat.output_tables['PlantGro'] # daily plant growth soil_water = dssat.output_tables['SoilWat'] # daily soil water soil_org = dssat.output_tables['SoilOrg'] # daily soil organic matter weather_out = dssat.output_tables['Weather'] # daily weather soil_ni = dssat.output_tables['SoilNi'] # daily soil nitrogen (layer-based) dssat.close() # removes the working directory ``` -------------------------------- ### Create Soil Profile from Scratch Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Instantiate `SoilProfile` and `SoilLayer` to build a soil profile manually. This method allows detailed customization of soil properties and layers. ```python >>> soil = SoilProfile( >>> name='IBMZ910214', soil_series_name='Millhopper Fine Sand', >>> site='Gainesville', country='USA', lat=29.6, long=-82.37, >>> soil_data_source='Gainesville', soil_clasification='S', >>> scs_family='Loamy,silic,hyperth Arnic Paleudult', scom='', salb=0.18, >>> slu1=2.0, sldr=0.65, slro=60.0, slnf=1.0, slpf=0.92, smhb='IB001', >>> smpx='IB001', smke='IB001', >>> table = [ >>> SoilLayer( >>> slb=5.0, slmh='', slll=0.026, sdul=0.096, ssat=0.345, srgf=1.0, >>> ssks=7.4, sbdm=1.66, sloc=0.67, slcl=1.7, slsi=0.9, slcf=0.0, >>> slhw=7.0, scec=20.0 >>> ), >>> SoilLayer( >>> slb=15.0, slmh='', slll=0.025, sdul=0.105, ssat=0.345, srgf=1.0, >>> ssks=7.4, sbdm=1.66, sloc=0.67, slcl=1.7, slsi=0.9, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=30.0, slmh='', slll=0.075, sdul=0.12, ssat=0.345, srgf=0.7, >>> ssks=14.8, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=45.0, slmh='', slll=0.025, sdul=0.086, ssat=0.345, srgf=0.3, >>> ssks=3.7, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=60.0, slmh='', slll=0.025, sdul=0.072, ssat=0.345, srgf=0.3, >>> ssks=3.7, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=90.0, slmh='', slll=0.028, sdul=0.072, ssat=0.345, srgf=0.1, >>> ssks=3.7, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=120.0, slmh='', slll=0.028, sdul=0.08, ssat=0.345, srgf=0.1, >>> ssks=0.1, sbdm=1.66, sloc=0.18, slcl=7.7, slsi=3.1, slcf=0.0, >>> slhw=7.0, >>> ), >>> SoilLayer( >>> slb=150.0, slmh='', slll=0.029, sdul=0.09, ssat=0.345, srgf=0.05, >>> ssks=0.1, sbdm=1.66, sloc=0.15, slcl=7.7, slsi=3.1, slcf=0.0, >>> slhw=7.0 >>> ), >>> SoilLayer( >>> slb=180.0, slmh='', slll=0.029, sdul=0.09, ssat=0.345, srgf=0.05, >>> ssks=0.1, sbdm=1.66, sloc=0.1, slcl=7.7, slsi=3.1, slcf=0.0, >>> slhw=7.0 >>> ) >>> ] >>> ) ``` ``` -------------------------------- ### Create WeatherStation from WeatherRecord objects Source: https://context7.com/daquinterop/py_dssattools/llms.txt Instantiate a WeatherStation object using a list of individual WeatherRecord objects. This allows for programmatic creation of weather data. ```python from DSSATTools.weather import WeatherStation, WeatherRecord from datetime import date import pandas as pd # --- Option 3: From individual WeatherRecord objects --- records = [ WeatherRecord( date=date(1985, 1, 1), srad=10.2, tmax=5.0, tmin=-2.0, rain=0.0, wind=120.0 ), # ... ] ws2 = WeatherStation(lat=38.96, long=-92.36, table=records) ``` -------------------------------- ### Load Soil Profile from File Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Use `SoilProfile.from_file` to load an existing DSSAT soil profile. Specify the soil name and the soil file name. ```python >>> soil = SoilProfile.from_file("IBMZ910214", "SOIL.SOL") ``` -------------------------------- ### Define Initial Soil Conditions Source: https://context7.com/daquinterop/py_dssattools/llms.txt Sets up initial soil conditions using a pandas DataFrame for soil layers. Columns include depth, water content, NH4, and NO3. Requires previous crop code and measurement date. ```python from DSSATTools.filex import InitialConditions from datetime import date import pandas as pd initial_conditions = InitialConditions( pcr='SG', # previous crop code (Sorghum) icdat=date(1980, 6, 13), # measurement date icrt=500, # root weight, kg/ha icnd=0, # nodule weight, kg/ha icrn=1, icre=1, # rhizobia number and effectivity (0-1) icres=1300, icren=0.5, # residue weight (kg/ha) and N% icrep=0, icrip=100, icrid=10, # residue P%, incorporation%, depth cm table=pd.DataFrame([ (10, 0.060, 2.5, 1.8), (22, 0.060, 2.5, 1.8), (52, 0.195, 3.0, 4.5), (82, 0.210, 3.5, 5.0), (112, 0.200, 2.0, 2.0), (142, 0.200, 1.0, 0.7), (172, 0.200, 1.0, 0.6), ], columns=['icbl', 'sh2o', 'snh4', 'sno3']) # depth water NH4 NO3 # cm cm3/cm3 g/Mg g/Mg ) ``` -------------------------------- ### Create WeatherStation from DataFrame Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Instantiate a WeatherStation object using data from a pandas DataFrame. Ensure the DataFrame's column names match DSSAT weather parameter names. ```python >>> weather_station = WeatherStation( >>> insi='UNCU', lat=4.34, long=-74.40, elev=1800, >>> table=df_with_data >>> ) ``` -------------------------------- ### DSSAT Simulation Run Source: https://context7.com/daquinterop/py_dssattools/llms.txt This snippet demonstrates how to initialize a DSSAT simulation object, run a treatment with various parameters, access output tables, and close the simulation. ```APIDOC ## `DSSAT.run_treatment(...)` ### Description Runs a DSSAT simulation for a specified treatment. ### Parameters - **field**: Field parameters for the simulation. - **cultivar**: Cultivar parameters. - **planting**: Planting details. - **initial_conditions**: Initial soil and crop conditions. - **fertilizer**: Fertilizer application details. - **simulation_controls**: Controls for the simulation run. ### Returns A dictionary containing simulation results, including harvest weight ('harwt') and total biomass ('topwt'). ### Example ```python dssat = DSSAT('/tmp/dssat_sorghum') results = dssat.run_treatment( field=field, cultivar=cultivar, planting=planting, initial_conditions=initial_conditions, fertilizer=fertilizer, simulation_controls=simulation_controls ) print(f"Harvest weight: {results['harwt']} kg/ha") plant_gro_df = dssat.output_tables['PlantGro'] print(plant_gro_df.head()) dssat.close() ``` ``` -------------------------------- ### DSSAT(run_path=None) Source: https://context7.com/daquinterop/py_dssattools/llms.txt Represents a single simulation environment. Instantiation creates a working directory for DSSAT CSM input/output files. The `run_path` is immutable after initialization. It also provides access to output files and tables after a simulation run. ```APIDOC ## DSSAT(run_path=None) ### Description Initializes a DSSAT simulation environment. Creates a working directory (defaults to `/tmp`) for DSSAT CSM input/output files. The `run_path` parameter specifies the directory for these files and is immutable after initialization. ### Parameters * **run_path** (string, optional) - The path to the directory where DSSAT input and output files will be stored. If not provided, a temporary directory will be used. ### Attributes * **output_files** (dict) - A dictionary containing raw output files as strings after a simulation run. Keys are file names (e.g., 'OVERVIEW'). * **output_tables** (dict) - A dictionary containing parsed time-series output tables as pandas DataFrames after a simulation run. Keys are table names (e.g., 'PlantGro', 'SoilWat'). ### Methods * **close()** - Removes the working directory created by the DSSAT environment. ### Example ```python from DSSATTools.run import DSSAT import os, tempfile # Use an explicit path or let it auto-create one in /tmp dssat = DSSAT(os.path.join(tempfile.gettempdir(), "dssat_run")) # Access output after running a simulation (see run_treatment) # overview_str = dssat.output_files['OVERVIEW'] # plant_growth = dssat.output_tables['PlantGro'] dssat.close() # removes the working directory ``` ``` -------------------------------- ### Define Planting Section Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Instantiate a Planting object with specific date and population parameters. Ensure the date is a valid Python date object. ```python >>> planting = Planting( >>> pdate=date(1980, 6, 17), ppop=18, ppoe=18, >>> plme='S', plds='R', plrs=45, plrd=0, pldp=5 >>> ) ``` -------------------------------- ### Run a Single DSSAT Treatment Source: https://context7.com/daquinterop/py_dssattools/llms.txt Execute a single DSSAT treatment using the run_treatment method. This requires essential parameters like cultivar, soil, weather, field, initial conditions, planting, fertilizer, and simulation controls. All other management sections are optional. ```python from datetime import date, timedelta from DSSATTools.crop import Sorghum from DSSATTools.weather import WeatherStation from DSSATTools.soil import SoilProfile from DSSATTools.filex import ( Field, Planting, Fertilizer, FertilizerEvent, InitialConditions, SimulationControls, SCGeneral, SCOptions, SCMethods, SCManagement ) from DSSATTools.run import DSSAT import pandas as pd # --- Crop --- cultivar = Sorghum('IB0026') # --- Soil (from existing DSSAT .SOL file) --- soil = SoilProfile.from_file('IBSG910085', 'SOIL.SOL') # --- Weather (from a DataFrame with DSSAT column names) --- df = pd.read_csv('ITHY8001.WTH', skiprows=3, sep=r'\s+') df.columns = ['date', 'srad', 'tmax', 'tmin', 'rain'] df['date'] = pd.to_datetime(df.date, format='%y%j') weather_station = WeatherStation( lat=17.530, long=78.270, elev=0, tav=25.8, amp=11.8, refht=2., wndht=3., table=df ) # --- Field --- field = Field( id_field='ITHY0001', wsta=weather_station, flob=0, fldt='DR000', fldd=0, flds=0, id_soil=soil ) # --- Initial conditions --- initial_conditions = InitialConditions( pcr='SG', icdat=date(1980, 6, 13), icrt=500, icnd=0, icrn=1, icre=1, icres=1300, icren=.5, icrep=0, icrip=100, icrid=10, table=pd.DataFrame([ (10, .06, 2.5, 1.8), (22, .06, 2.5, 1.8), (52, .195, 3., 4.5), (82, .21, 3.5, 5.0), ], columns=['icbl', 'sh2o', 'snh4', 'sno3']) ) # --- Planting --- planting = Planting( pdate=date(1980, 6, 17), ppop=18, ppoe=18, plme='S', plds='R', plrs=45, plrd=0, pldp=5 ) # --- Fertilizer --- fertilizer = Fertilizer(table=[ FertilizerEvent( fdate=date(1980, 7, 3), fmcd='FE005', fdep=5, famn=80, facd='AP002' ) ]) # --- Simulation controls --- simulation_controls = SimulationControls( general=SCGeneral(sdate=date(1980, 6, 13)), options=SCOptions(water='Y', nitro='Y', symbi='N'), methods=SCMethods(infil='S'), management=SCManagement(irrig='N', ferti='R', resid='N', harvs='M') ) ``` -------------------------------- ### DSSAT.run_treatment(...) Source: https://context7.com/daquinterop/py_dssattools/llms.txt Executes the DSSAT CSM in 'C' mode for a single treatment. It requires essential FileX sections like field, cultivar, planting, and simulation controls. It returns a dictionary of scalar harvest summary values. ```APIDOC ## DSSAT.run_treatment(...) ### Description Executes the DSSAT CSM in 'C' mode (one treatment at a time) with the provided FileX sections. Returns a dictionary of scalar harvest summary values (e.g., `harwt`, `topwt`, `flo`, `mat`, `rain`). Required parameters are `field`, `cultivar`, `planting`, and `simulation_controls`. All other management sections are optional. ### Parameters * **field** (Field object) - Represents the field information. * **cultivar** (Crop object) - The crop cultivar to be simulated. * **planting** (Planting object) - Details about the planting event. * **simulation_controls** (SimulationControls object) - Controls for the simulation parameters. * **weather_station** (WeatherStation object, optional) - The weather data for the simulation. * **initial_conditions** (InitialConditions object, optional) - Initial soil conditions. * **fertilizer** (Fertilizer object, optional) - Fertilizer applications. * **other_management** (list of objects, optional) - Other management practices. ### Returns A dictionary containing scalar harvest summary values. ### Example ```python from datetime import date, timedelta from DSSATTools.crop import Sorghum from DSSATTools.weather import WeatherStation from DSSATTools.soil import SoilProfile from DSSATTools.filex import ( Field, Planting, Fertilizer, FertilizerEvent, InitialConditions, SimulationControls, SCGeneral, SCOptions, SCMethods, SCManagement ) from DSSATTools.run import DSSAT import pandas as pd # --- Crop --- cultivar = Sorghum('IB0026') # --- Soil --- soil = SoilProfile.from_file('IBSG910085', 'SOIL.SOL') # --- Weather --- df = pd.read_csv('ITHY8001.WTH', skiprows=3, sep=r'\s+') df.columns = ['date', 'srad', 'tmax', 'tmin', 'rain'] df['date'] = pd.to_datetime(df.date, format='%y%j') weather_station = WeatherStation( lat=17.530, long=78.270, elev=0, tav=25.8, amp=11.8, refht=2., wndht=3., table=df ) # --- Field --- field = Field( id_field='ITHY0001', wsta=weather_station, flob=0, fldt='DR000', fldd=0, flds=0, id_soil=soil ) # --- Initial conditions --- initial_conditions = InitialConditions( pcr='SG', icdat=date(1980, 6, 13), icrt=500, icnd=0, icrn=1, icre=1, icres=1300, icren=.5, icrep=0, icrip=100, icrid=10, table=pd.DataFrame([ (10, .06, 2.5, 1.8), (22, .06, 2.5, 1.8), (52, .195, 3., 4.5), (82, .21, 3.5, 5.0), ], columns=['icbl', 'sh2o', 'snh4', 'sno3']) ) # --- Planting --- planting = Planting( pdate=date(1980, 6, 17), ppop=18, ppoe=18, plme='S', plds='R', plrs=45, plrd=0, pldp=5 ) # --- Fertilizer --- fertilizer = Fertilizer(table=[ FertilizerEvent( fdate=date(1980, 7, 3), fmcd='FE005', fdep=5, famn=80, facd='AP002' ) ]) # --- Simulation controls --- simulation_controls = SimulationControls( general=SCGeneral(sdate=date(1980, 6, 13)), options=SCOptions(water='Y', nitro='Y', symbi='N'), methods=SCMethods(infil='S'), management=SCManagement(irrig='N', ferti='R', resid='N', harvs='M') ) # --- Run simulation --- dssat = DSSAT() summary_results = dssat.run_treatment( field=field, cultivar=cultivar, planting=planting, simulation_controls=simulation_controls, weather_station=weather_station, initial_conditions=initial_conditions, fertilizer=fertilizer ) print(summary_results) ``` ``` -------------------------------- ### Define Initial Conditions with DataFrame Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Initialize an InitialConditions object using a pandas DataFrame for soil layers. The DataFrame columns must match the expected parameters for soil layers. ```python >>> initial_conditions = InitialConditions( >>> pcr='SG', icdat=date(1980, 6, 1), icrt=500, icnd=0, >>> icrn=1, icre=1, icres=1300, icren=.5, icrep=0, icrip=100, icrid=10, >>> table=pd.DataFrame([ >>> (10, .06, 2.5, 1.8), >>> (22, .06, 2.5, 1.8), >>> (52, .195, 3., 4.5), >>> (82, .21, 3.5, 5.0), >>> (112, 0.2, 2., 2.0), >>> (142, 0.2, 1., 0.7), >>> (172, 0.2, 1., 0.6), >>> ], columns=['icbl', 'sh2o', 'snh4', 'sno3']) >>> ) ``` -------------------------------- ### Create WeatherStation from DataFrame Source: https://context7.com/daquinterop/py_dssattools/llms.txt Construct a WeatherStation object using a pandas DataFrame. The DataFrame must contain a 'date' column and DSSAT weather variable columns like 'srad', 'tmax', 'tmin', and 'rain'. ```python from DSSATTools.weather import WeatherStation, WeatherRecord from datetime import date import pandas as pd # --- Option 2: From a DataFrame --- df = pd.DataFrame({ 'date': pd.date_range('1985-01-01', periods=365), 'srad': [18.5] * 365, # MJ m-2 day-1 'tmax': [28.0] * 365, # °C 'tmin': [15.0] * 365, # °C 'rain': [2.5] * 365, # mm day-1 }) weather_station = WeatherStation( insi='CLMO', # 4-character institute+site code lat=38.96, long=-92.36, elev=274, tav=12.5, amp=15.0, # long-term annual mean and amplitude, °C refht=2.0, wndht=3.0, # measurement heights, m table=df ) ``` -------------------------------- ### Planting Source: https://context7.com/daquinterop/py_dssattools/llms.txt Defines a single planting event within a DSSAT FileX. ```APIDOC ## `Planting(pdate, ppop, plrs, ...)` — Planting section Defines a single planting event. Date parameters use Python `datetime.date` objects. ### Parameters - **pdate** (`datetime.date`) - Planting date. - **ppop** (float) - Plant population at seeding, m-2. - **ppoe** (float) - Plant population at emergence, m-2. - **plme** (str) - Planting method: 'S' for seed, 'I' for in-row. - **plds** (str) - Distribution: 'R' for row. - **plrs** (float) - Row spacing, cm. - **plrd** (float) - Row direction, degrees from N. - **pldp** (float) - Planting depth, cm. - **plwt** (float, optional) - Planting material dry weight, kg/ha. Used for transplanted crops. - **sprl** (float, optional) - Initial sprout length, cm. Used for transplanted crops. ### Example ```python from DSSATTools.filex import Planting from datetime import date # Example for seeded crops planting = Planting( pdate=date(1980, 6, 17), # planting date ppop=18, # plant population at seeding, m-2 ppoe=18, # plant population at emergence, m-2 plme='S', # planting method: S=seed plds='R', # distribution: R=row plrs=45, # row spacing, cm plrd=0, # row direction, degrees from N pldp=5, # planting depth, cm ) # For transplanted crops (e.g. Potato), set plwt and sprl potato_planting = Planting( pdate=date(2013, 4, 10), ppop=4.5, plrs=75, plme='I', # I=in-row plwt=1500, # planting material dry weight, kg/ha sprl=5.0, # initial sprout length, cm ) ``` ``` -------------------------------- ### Instantiate and Modify Crop Cultivar Parameters Source: https://context7.com/daquinterop/py_dssattools/llms.txt Instantiates crop classes (e.g., Sorghum, Maize) with a cultivar code to load parameters. Parameters can be accessed and modified via dictionary syntax. Use `cultivar_list()` to see available options. ```python from DSSATTools.crop import Sorghum, Maize, Wheat, Soybean # List available cultivars cultivars = Sorghum.cultivar_list() print(cultivars[:3]) # ['IB0001', 'IB0002', 'IB0026', ...] # Instantiate and inspect crop = Sorghum('IB0026') print(crop['p1']) # base photothermal time, °C·d print(crop['eco#']['topt']) # optimal temperature for growth, °C # Modify cultivar parameters crop['p1'] = 450.0 crop['g1'] = 0.1 # Modify ecotype parameters crop['eco#']['topt'] = 35.5 # Other crops follow the same pattern maize = Maize('IB0171') wheat = Wheat('IB0488') soybean = Soybean('IB0001') ``` -------------------------------- ### Instantiate Crop with Cultivar Code Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Create a crop object by providing the cultivar code. The resulting object behaves like a dictionary for accessing and modifying cultivar parameters. ```python >>> crop = Sorghum('IB0026') ``` -------------------------------- ### Define SoilProfile from scratch Source: https://context7.com/daquinterop/py_dssattools/llms.txt Construct a SoilProfile object programmatically using a list of SoilLayer objects. This allows for detailed customization of soil properties. ```python from DSSATTools.soil import SoilProfile, SoilLayer soil = SoilProfile( name='IBMZ910214', # must be exactly 10 characters soil_series_name='Millhopper Fine Sand', site='Gainesville', country='USA', lat=29.6, long=-82.37, soil_data_source='Gainesville', soil_clasification='S', scs_family='Loamy,silic,hyperth Arnic Paleudult', scom='', salb=0.18, slu1=2.0, sldr=0.65, slro=60.0, slnf=1.0, slpf=0.92, smhb='IB001', smpx='IB001', smke='IB001', table=[ SoilLayer(slb=5.0, slll=0.026, sdul=0.096, ssat=0.345, srgf=1.0, ssks=7.4, sbdm=1.66, sloc=0.67, slcl=1.7, slsi=0.9, slcf=0.0, slhw=7.0, scec=20.0), SoilLayer(slb=30.0, slll=0.075, sdul=0.12, ssat=0.345, srgf=0.7, ssks=14.8, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, slhw=7.0), SoilLayer(slb=60.0, slll=0.025, sdul=0.072, ssat=0.345, srgf=0.3, ssks=3.7, sbdm=1.66, sloc=0.17, slcl=2.4, slsi=2.6, slcf=0.0, slhw=7.0), SoilLayer(slb=120.0, slll=0.028, sdul=0.08, ssat=0.345, srgf=0.1, ssks=0.1, sbdm=1.66, sloc=0.18, slcl=7.7, slsi=3.1, slcf=0.0, slhw=7.0), SoilLayer(slb=180.0, slll=0.029, sdul=0.09, ssat=0.345, srgf=0.05, ssks=0.1, sbdm=1.66, sloc=0.1, slcl=7.7, slsi=3.1, slcf=0.0, slhw=7.0), ] ) ``` -------------------------------- ### Run DSSAT Treatment and Analyze Results Source: https://context7.com/daquinterop/py_dssattools/llms.txt This snippet demonstrates how to run a DSSAT simulation for a specific treatment and access various simulation outputs. It includes error handling and cleanup. ```python dssat = DSSAT('/tmp/dssat_maize') try: results = dssat.run_treatment( field=treatment['Field'], cultivar=cultivar, planting=treatment['Planting'], initial_conditions=treatment['InitialConditions'], fertilizer=treatment['Fertilizer'], simulation_controls=treatment['SimulationControls'], verbose=True, ) print(f"Harvest weight : {results['harwt']} kg/ha") print(f"Flowering DOY : {results['flo']}") print(f"Maturity DOY : {results['mat']}") print(f"Total rainfall : {results['rain']} mm") # Time-series output plant_df = dssat.output_tables['PlantGro'] print(plant_df[['CWAD', 'LAID', 'GSTD']].tail()) # Raw output files print(dssat.output_files['OVERVIEW'][:500]) except RuntimeError as e: print(f"Simulation failed: {e}") # Check dssat.output_files['ERROR'] if available finally: dssat.close() ``` -------------------------------- ### SoilProfile.from_file Source: https://context7.com/daquinterop/py_dssattools/llms.txt Loads a soil profile from a DSSAT SOL file using a class method. ```APIDOC ## `SoilProfile.from_file(profile, file)` ### Description Class method that reads a named soil profile from a standard DSSAT `.SOL` file and returns a `SoilProfile` object. ### Parameters - **profile**: The 10-character profile code to load. - **file**: The path to the DSSAT `.SOL` file. ### Returns A `SoilProfile` object containing the soil data. ### Example ```python from DSSATTools.soil import SoilProfile soil = SoilProfile.from_file('IBMZ910214', 'SOIL.SOL') print(soil['name'].str) print(soil['soil_depth'].str) print(len(soil.table)) ``` ``` -------------------------------- ### read_filex Source: https://context7.com/daquinterop/py_dssattools/llms.txt Parses an existing DSSAT experiment file (.MZX, .WHX, .SBX, etc.) into a dictionary structure. ```APIDOC ## `read_filex(filexpath)` — Parse an existing DSSAT FileX Reads a DSSAT experiment file (`.MZX`, `.WHX`, `.SBX`, etc.) and returns a dictionary mapping integer treatment numbers to dictionaries of Python objects, one per FileX section. Each section key is the class name (e.g., `'Field'`, `'Planting'`, `'Fertilizer'`, `'SimulationControls'`). ### Parameters - **filexpath** (str) - Path to the DSSAT FileX file. ### Returns - **dict** - A dictionary where keys are treatment numbers and values are dictionaries of FileX section objects. ### Example ```python from DSSATTools.filex import read_filex treatments = read_filex('Maize/BRPI0202.MZX') # Access treatment 1 t = treatments[1] print(t.keys()) # dict_keys(['Field', 'Planting', 'Cultivar', 'InitialConditions', # 'Fertilizer', 'SimulationControls']) # Swap in live objects before running from DSSATTools.soil import SoilProfile from DSSATTools.weather import WeatherStation soil = SoilProfile.from_file('BRPI000001', 'BR.SOL') weather = WeatherStation.from_files(['Weather/BRPI0201.WTH']) t['Field']['id_soil'] = soil t['Field']['wsta'] = weather # The cultivar object from the FileX can be used directly cultivar = t['Cultivar'].crop # returns the Crop subclass instance ``` ``` -------------------------------- ### Run DSSAT Simulation Treatment Source: https://github.com/daquinterop/py_dssattools/blob/main/README.md Execute a DSSAT simulation run using the `run_treatment` method. Pass various DSSAT FileX sections as arguments to configure the simulation. ```python >>> results = dssat.run_treatment( >>> field=field, cultivar=crop, planting=planting, >>> initial_conditions=initial_conditions, fertilizer=fertilizer, >>> simulation_controls=simulation_controls >>> ) ``` -------------------------------- ### WeatherStation Class Source: https://context7.com/daquinterop/py_dssattools/llms.txt Represents a DSSAT WTH (weather) file and provides methods to create a WeatherStation object from various sources. ```APIDOC ## `WeatherStation(table, lat, long, ...)` ### Description Represents a DSSAT WTH (weather) file. The `table` parameter accepts either a `list[WeatherRecord]` objects or a pandas `DataFrame` with columns matching DSSAT weather variable names (`date`, `srad`, `tmax`, `tmin`, `rain`, and optionally `dewp`, `wind`, `par`, `evap`, `rhum`). ### Class Methods #### `from_files(file_paths: list[str])` Loads weather data from one or more DSSAT WTH files. ### Parameters - **table**: A list of `WeatherRecord` objects or a pandas `DataFrame`. - **lat**: Latitude of the weather station. - **long**: Longitude of the weather station. - **insi**: 4-character institute+site code (optional). - **elev**: Elevation in meters (optional). - **tav**: Long-term annual mean temperature in °C (optional). - **amp**: Long-term annual temperature amplitude in °C (optional). - **refht**: Measurement height for reference in meters (optional). - **wndht**: Measurement height for wind in meters (optional). ### Example (from DataFrame) ```python import pandas as pd from DSSATTools.weather import WeatherStation df = pd.DataFrame({ 'date': pd.date_range('1985-01-01', periods=365), 'srad': [18.5] * 365, # MJ m-2 day-1 'tmax': [28.0] * 365, # °C 'tmin': [15.0] * 365, # °C 'rain': [2.5] * 365, # mm day-1 }) weather_station = WeatherStation( insi='CLMO', lat=38.96, long=-92.36, elev=274, tav=12.5, amp=15.0, refht=2.0, wndht=3.0, table=df ) ``` ### Example (from files) ```python from DSSATTools.weather import WeatherStation weather = WeatherStation.from_files([ 'Weather/KSAS8101.WTH', 'Weather/KSAS8201.WTH', ]) ``` ### Example (from WeatherRecord objects) ```python from DSSATTools.weather import WeatherStation, WeatherRecord from datetime import date records = [ WeatherRecord( date=date(1985, 1, 1), srad=10.2, tmax=5.0, tmin=-2.0, rain=0.0, wind=120.0 ), ] ws2 = WeatherStation(lat=38.96, long=-92.36, table=records) ``` ```