Stacked intelligent metasurfaces (SIMs) extend the concept of reconfigurable intelligent surfaces by cascading multiple programmable layers, enabling advanced electromagnetic wave transformations for communication and sensing applications. However, most existing optimization frameworks rely on simplified channel abstractions that may overlook key electromagnetic effects such as multiport coupling, circuit losses, and non-ideal hardware behavior. In this paper, we develop a modeling and optimization framework for SIMs based on a multiport network representation using scattering parameters. The proposed formulation captures realistic circuit characteristics and mutual interactions among SIM ports while remaining amenable to optimization. The resulting models are validated through electromagnetic simulations, enabling a systematic comparison between idealized and practical SIM configurations. Numerical results for communication and sensing scenarios confirm that the proposed framework provides accurate performance predictions and enables the effective design of SIM configurations under realistic electromagnetic conditions.