Since no one seems to know how moodle works well enough to answer my question, here is my solution:
$emptygrades = array();
$ungradedsql = "SELECT * "
. "FROM {grade_items} "
. "WHERE courseid = :courseid "
. "AND id NOT IN ("
. "SELECT itemid FROM {grade_grades} "
. "WHERE userid = :userid)";
$results = $DB->get_records_sql($ungradedsql, array('courseid' => $course->id, 'userid' => $USER->id));
$fieldmap = array(
'itemid' => 'id',
'rawgrademax' => 'grademax',
'rawgrademin' => 'grademin',
'rawscaleid' => 'scaleid',
'hidden' => 'hidden',
'locked' => 'locked',
'locktime' => 'locktime',
);
foreach ($results as $grade_item) {
$grade = array(
'userid' => $USER->id,
'rawgrade' => 0,
'usermodified' => null,
'finalgrade' => 0,
'exported' => 0,
'overridden' => 0,
'excluded' => 0,
'feedback' => 'No attempts before course was closed',
'feedbackformat' => FORMAT_MOODLE,
'information' => null,
'informationformat' => 0,
'timecreated' => time(),
'timemodified' => time()
);
foreach ($fieldmap as $grade_field => $item_field) {
$grade[$grade_field] = $grade_item->$item_field;
}
if (!array_key_exists($grade_item->itemmodule, $emptygrades)) {
$emptygrades[$grade_item->itemmodule] = array();
}
$emptygrades[$grade_item->itemmodule][$grade_item->iteminstance] = $grade;
}
$modinfo = get_fast_modinfo($course->id);
foreach($modinfo->cms as $module) {
if (array_key_exists($module->modname, $emptygrades)
&& array_key_exists($module->instance, $emptygrades[$module->modname])) {
$grades = array($USER->id => $emptygrades[$module->modname][$module->instance]);
grade_update('mod/' . $module->modname, $course->id, 'mod', $module->modname, $module->instance, 0, $grades);
}
}