Optimal Energy Management For Microgrids