Sexsomnia refers to a wide range of sleep related sexual behaviors that includes masturbation, fondling, sexual intercourse with climax, and sexual assault/rape.
There are three possibilities why this happens:
1) Confusional arousals during which complex behaviors may occur when a sleeping person is suddenly aroused out of deep sleep.
2) Co-existing sleep disorders: other factors that may increase the risk of sexsomnia include the use of alcohol, sleep disruption such as caused by obstructive sleep apnea and sleep deprivation.
3) Sleep related epilepsy that can result in sexual arousal, pelvic thrusting and orgasms.