//!写入配置 bool VisionMainFrame::write_config(const QString §ion, const QString &key, const QVariant &data) { QFile json_file(".\\cfg\\local_config.json"); bool rd_ok = json_file.open(QIODevice::ReadWrite); if (!rd_ok) { QMessageBox::critical(VisionMainFrame::instance(), QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("本地配置文件[.\\cfg\\local_config.json]无法正确读取,请检查")); return false; } //读取Json QByteArray b = json_file.readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(b, &json_error); QVariantMap key_result; QVariantMap section_result = json_doc.toVariant().toMap(); QVariantMap::const_iterator iter_find = section_result.find(section); if (section_result.end() == iter_find) { key_result.insert(key, data); section_result.insert(section, key_result); } else { key_result = iter_find->toMap(); key_result[key] = data; section_result.insert(section, key_result); } QJsonDocument write_doc = QJsonDocument::fromVariant(section_result); json_file.resize(0); qint64 wt_ok = json_file.write(write_doc.toJson()); if (wt_ok <= 0) { QMessageBox::critical(VisionMainFrame::instance(), QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("本地配置文件[.\\cfg\\local_config.json]无法正确写入,请检查")); return false; } json_file.close(); return true; }
error environment_properties::get_json_environment_file( std::string& _env_file, std::string& _session_file ) { // capture parent process id for use in creation of 'session' // file which contains the cwd for a given session. this cwd // is only updated by the icd command which writes a new irods // CFG_IRODS_CWD_KW to the session dir which repaves the existing // one in the original irodsEnv file. std::stringstream ppid_str; ppid_str << getppid(); // if a json version exists, then attempt to capture // that std::string json_file( IRODS_HOME_DIRECTORY ); std::string json_session_file( IRODS_HOME_DIRECTORY ); std::string env_var = to_env( CFG_IRODS_ENVIRONMENT_FILE_KW ); char* irods_env = getenv( to_env( CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() ); if ( irods_env && strlen( irods_env ) > 0 ) { json_file = irods_env; // "cwd" is used in this case instead of the ppid given the // assumption that scripts will set the env file var to allow // for more complex interactions possibly yielding complex pid // hierarchies. this routes all references to the same session // for this given use case json_session_file = json_file + ".cwd"; } else { char* home_dir = getenv( "HOME" ); // if home env exists, prefer that for run in place // or use of existing irods service accound if ( home_dir ) { json_file = home_dir; } json_file += JSON_ENV_FILE; json_session_file = json_file + "." + ppid_str.str(); } _env_file = json_file; _session_file = json_session_file; return SUCCESS(); } // get_json_environment_file
void compile_json_to_source( const fc::path& source_file_name, const fc::path& prologue_file_name, const fc::path& json_file_name, const fc::path& epilogue_file_name ) { fc::mutable_variant_object template_context; template_context[ "source_file_name"] = source_file_name.string(); template_context["prologue_file_name"] = prologue_file_name.string(); template_context[ "json_file_name"] = json_file_name.string(); template_context["epilogue_file_name"] = epilogue_file_name.string(); std::ofstream source_file(source_file_name.string()); if (prologue_file_name.string() != "") { std::ifstream prologue_file(prologue_file_name.string()); std::stringstream ss_prologue_file; ss_prologue_file << prologue_file.rdbuf(); source_file << format_string(ss_prologue_file.str(), template_context); } std::ifstream json_file(json_file_name.string()); std::string line; bool first = true; while (std::getline(json_file, line)) { if (first) first = false; else source_file << ",\n"; source_file << " " << bts::utilities::escape_string_for_c_source_code(line); } if (epilogue_file_name.string() != "") { std::ifstream epilogue_file(epilogue_file_name.string()); std::stringstream ss_epilogue_file; ss_epilogue_file << epilogue_file.rdbuf(); source_file << format_string(ss_epilogue_file.str(), template_context); } return; }
void Config::loadJSONFromFile(QJsonObject *obj, QString file_name){ QFile json_file(file_name); if (json_file.open(QIODevice::ReadOnly)) { QJsonParseError error; *obj = QJsonDocument::fromJson(json_file.readAll(), &error).object(); if (error.error != QJsonParseError::NoError) { qDebug() << "Could not load the JSON data from file " << file_name << "error " << error.error << error.offset; } else { qDebug() << "JSON data Loaded from " << file_name; } json_file.close(); } else { qDebug() << "Could not open the file containing JSON data: " << file_name; } //qDebug() << QJsonDocument(*obj).toJson(); }
bool VisionMainFrame::read_config(const QString §ion, const QString &key, QVariant &data) { QFile json_file(".\\cfg\\local_config.json"); bool rd_ok = json_file.open(QIODevice::ReadOnly); if (!rd_ok) { return false; } //读取Json QByteArray b = json_file.readAll(); QJsonParseError json_error; QJsonDocument json_doc = QJsonDocument::fromJson(b, &json_error); if (json_error.error != QJsonParseError::NoError) { return false; } if (!json_doc.isObject()) { return false; } QVariantMap section_result = json_doc.toVariant().toMap(); QVariantMap::const_iterator iter_find = section_result.find(section); if (section_result.end() == iter_find) { return false; } QVariantMap key_result = iter_find->toMap(); iter_find = key_result.find(key); if (key_result.end() == iter_find) { return false; } //终于找到了 data = *iter_find; return true; }
/** * Initiates snake instance from json config */ Snake::Snake(std::string json_file_path) { std::ifstream json_file(json_file_path); std::string json_string((std::istreambuf_iterator<char>(json_file)), std::istreambuf_iterator<char>()); std::string err_text; auto json = json11::Json::parse(json_string, err_text); std::string vid_path = json["vid_path"].string_value(); tension = json["tension"].number_value(); stiffness = json["stiffness"].number_value(); atom = json["atom"].number_value(); closed = json["closed"].bool_value(); implicit = json["implicit"].int_value(); line_weight = json["line_weight"].number_value(); edge_weight = json["edge_weight"].number_value(); term_weight = json["term_weight"].number_value(); tick = json["tick"].number_value(); fixed = json["fixed"].bool_value(); threshold = json["threshold"].number_value(); vid = cv::VideoCapture(vid_path); if (!vid.isOpened()) { std::cout << "Could not open or find the video specified in config.\n"; std::exit(0); } img = cv::Mat(vid.get(CV_CAP_PROP_FRAME_HEIGHT), vid.get(CV_CAP_PROP_FRAME_WIDTH), vid.get(CV_CAP_PROP_FORMAT)); raw_img_size = img.total() * 4; raw_img = std::vector<uchar>(raw_img_size); if (!shift_frame(true)) { std::cout << "Could not read the frame.\n"; std::exit(0); } }
/* Runs through each test case, pulls in the correct files, validates, and outputs the results */ int validateTestCases(const std::string &hw_id, const std::string &rcsid, int subnum, const std::string &subtime) { std::string grade_path = ".submit.grade"; std::ofstream gradefile(grade_path.c_str()); gradefile << "Grade for: " << rcsid << std::endl; gradefile << " submission#: " << subnum << std::endl; int penalty = -std::min(submission_penalty,int(std::ceil(std::max(0,subnum-max_submissions)/10.0))); assert (penalty >= -submission_penalty && penalty <= 0); if (penalty != 0) { gradefile << " penalty for excessive submissions: " << penalty << " points" << std::endl; } int nonhidden_auto_pts = penalty; int hidden_auto_pts = penalty; int nonhidden_extra_credit = 0; int hidden_extra_credit = 0; int nonhidden_possible_pts = 0; int hidden_possible_pts = 0; int possible_ta_pts = ta_pts; std::stringstream testcase_json; std::vector<std::string> all_testcases; // LOOP OVER ALL TEST CASES for (int i = 0; i < testcases.size(); ++i) { std::cout << "------------------------------------------\n" << testcases[i].title() << " - points: " << testcases[i].points() << std::endl; // START JSON FOR TEST CASE std::vector<std::string> testcase_vector; testcase_vector.push_back("\t\t\t\"test_name\": \"" + testcases[i].title() + "\""); testcase_vector.push_back("\t\t\t\"execute_logfile\": \"" + testcases[i].prefix() + "_execute_logfile.txt\""); int testcase_pts = 0; std::string message = ""; // FILE EXISTS & COMPILATION TESTS DON'T HAVE FILE COMPARISONS if (testcases[i].isFileExistsTest()) { std::cerr << "THIS IS A FILE EXISTS TEST! " << testcases[i].getFilename() << std::endl; assert (testcases[i].getFilename() != ""); if ( access( (std::string("")+testcases[i].getFilename()).c_str(), F_OK|R_OK|W_OK ) != -1 ) { /* file exists */ std::cerr << "file does exist: " << testcases[i].getFilename() << std::endl; testcase_pts = testcases[i].points(); } else { std::cerr << "ERROR file DOES NOT exist: " << testcases[i].getFilename() << std::endl; message += "Error: " + testcases[i].getFilename() + " was not found!"; } } else if (testcases[i].isCompilationTest()) { std::cerr << "THIS IS A COMPILATION! " << std::endl; if ( access( testcases[i].getFilename().c_str(), F_OK|R_OK|W_OK ) != -1 ) { /* file exists */ std::cerr << "file does exist: " << testcases[i].getFilename() << std::endl; testcase_pts = testcases[i].points(); } else { std::cerr << "ERROR file DOES NOT exist: " << testcases[i].getFilename() << std::endl; message += "Error: compilation was not successful!"; } if (testcases[i].isCompilationTest()) { testcase_vector.push_back("\t\t\t\"compilation_output\": \"" + testcases[i].prefix() + "_STDERR.txt\""); } } else { // ALL OTHER TESTS HAVE 1 OR MORE FILE COMPARISONS std::vector<std::string> diff_vectors; double pts_helper = 0.0; double fraction_sum = 0.0; for (int j = 0; j < testcases[i].numFileGraders(); j++) { std::vector<std::string> diff_vector; std::cerr << "comparison #" << j << std::endl; std::string helper_message = ""; TestResults *result = testcases[i].do_the_grading(j,helper_message); // PREPARE THE JSON DIFF FILE std::stringstream diff_path; diff_path << testcases[i].prefix() << "_" << j << "_diff.json"; std::ofstream diff_stream(diff_path.str().c_str()); if (result != NULL) { // THE GRADE (will be compiled across all comparisons) std::cout << "result->getGrade() " << result->getGrade() << std::endl; double pts_fraction = testcases[i].test_case_grader[j]->points_fraction; std::cout << "pts_fraction " << pts_fraction << std::endl; if (pts_fraction < -0.5) { pts_fraction = 1 / double(testcases[i].numFileGraders()); } fraction_sum += pts_fraction; pts_helper += pts_fraction*result->getGrade(); result->printJSON(diff_stream); helper_message += " " + result->get_message(); // CLEANUP THIS COMPARISON delete result; } // JSON FOR THIS COMPARISON diff_vector.push_back("\t\t\t\t\t\"diff_id\":\"" + testcases[i].prefix() + "_" + std::to_string(j) + "_diff\""); diff_vector.push_back("\t\t\t\t\t\"student_file\":\"" + testcases[i].filename(j) + "\""); std::string expected = ""; if (testcases[i].test_case_grader[j] != NULL) { expected = testcases[i].test_case_grader[j]->getExpected(); } if (expected != "") { std::stringstream expected_path; std::string id = hw_id; std::string expected_out_dir = "test_output/" + id + "/"; expected_path << expected_out_dir << expected; diff_vector.push_back("\t\t\t\t\t\"instructor_file\":\"" + expected_path.str() + "\""); //diff_vector.push_back("\t\t\t\t\t\"difference\":\"" + testcases[i].prefix() + "_" + std::to_string(j) + "_diff.json\",\n"); diff_vector.push_back("\t\t\t\t\t\"difference\":\"" + testcases[i].prefix() + "_" + std::to_string(j) + "_diff.json\""); } diff_vector.push_back("\t\t\t\t\t\"description\": \"" + testcases[i].description(j) + "\""); if (helper_message != "") { diff_vector.push_back("\t\t\t\t\t\"message\": \"" + helper_message + "\""); } diff_vectors.push_back("\t\t\t\t{\n" + join(diff_vector) + "\t\t\t\t}"); } // END COMPARISON LOOP testcase_vector.push_back("\t\t\t\"diffs\": [\n" + join(diff_vectors) + "\t\t\t]"); if (fraction_sum < 0.99 || fraction_sum > 1.01) { std::cout << "Fraction sum " << fraction_sum << std::endl; } assert (fraction_sum > 0.99 && fraction_sum < 1.01); assert (pts_helper >= -0.00001 && pts_helper <= 1.000001); pts_helper = std::max(0.0,std::min(1.0,pts_helper)); testcase_pts = (int)floor(pts_helper * testcases[i].points()); } // end if/else of test case type // output grade & message std::cout << "Grade: " << testcase_pts << std::endl; // TODO: LOGIC NEEDS TO BE TESTED WITH MORE COMPLEX HOMEWORK! if (!testcases[i].hidden()) { nonhidden_auto_pts += testcase_pts; if (testcases[i].extracredit()) { nonhidden_extra_credit += testcase_pts; //testcases[i].points(); } else { nonhidden_possible_pts += testcases[i].points(); } } hidden_auto_pts += testcase_pts; if (testcases[i].extracredit()) { hidden_extra_credit += testcase_pts; //testcases[i].points(); } else { hidden_possible_pts += testcases[i].points(); } testcase_vector.push_back("\t\t\t\"points_awarded\": " + std::to_string(testcase_pts)); if (message != "") { testcase_vector.push_back("\t\t\t\"message\": \"" + message + "\""); } all_testcases.push_back("\t\t{\n" + join(testcase_vector) + "\t\t}"); gradefile << " Test " << std::setw(2) << std::right << i+1 << ":" << std::setw(30) << std::left << testcases[i].just_title() << " " << std::setw(2) << std::right << testcase_pts << " / " << std::setw(2) << std::right << testcases[i].points() << std::endl; } // end test case loop int total_possible_pts = possible_ta_pts + hidden_possible_pts; std::cout << "penalty " << penalty << std::endl; std::cout << "nonhidden auto pts " << nonhidden_auto_pts << std::endl; std::cout << "hidden auto pts " << hidden_auto_pts << std::endl; std::cout << "nonhidden extra credit " << nonhidden_extra_credit << std::endl; std::cout << "hidden extra credit " << hidden_extra_credit << std::endl; std::cout << "nonhidden possible pts " << nonhidden_possible_pts << std::endl; std::cout << "hidden possible pts " << hidden_possible_pts << std::endl; std::cout << "possible ta pts " << possible_ta_pts << std::endl; std::cout << "total possible pts " << total_possible_pts << std::endl; assert (total_possible_pts == total_pts); /* Generate submission.json */ std::ofstream json_file("submission.json"); json_file << "{\n" << "\t\"submission_number\": " << subnum << ",\n" << "\t\"points_awarded\": " << hidden_auto_pts << ",\n" << "\t\"nonhidden_points_awarded\": " << nonhidden_auto_pts << ",\n" << "\t\"extra_credit_points_awarded\": " << hidden_extra_credit << ",\n" << "\t\"non_extra_credit_points_awarded\": " << hidden_auto_pts - hidden_extra_credit << ",\n" << "\t\"submission_time\": \"" << subtime << "\",\n" << "\t\"testcases\": [\n"; json_file << join(all_testcases) << "\t]\n" << "}"; json_file.close(); gradefile << "Automatic extra credit (w/o hidden): " << "+ " << nonhidden_extra_credit << " points" << std::endl; gradefile << "Automatic grading total (w/o hidden): " << nonhidden_auto_pts << " / " << nonhidden_possible_pts << std::endl; gradefile << "Max possible hidden automatic grading points: " << hidden_possible_pts - nonhidden_possible_pts << std::endl; gradefile << "Automatic extra credit: " << "+ " << hidden_extra_credit << " points" << std::endl; gradefile << "Automatic grading total: " << hidden_auto_pts << " / " << hidden_possible_pts << std::endl; gradefile << "Remaining points to be graded by TA: " << possible_ta_pts << std::endl; gradefile << "Max points for assignment (excluding extra credit):" << total_possible_pts << std::endl; return 0; }
int main(int argc, char **argv) { args::ArgumentParser parser( "Calculates T1/B1 maps from MP2/3-RAGE data\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> input_path(parser, "INPUT FILE", "Path to complex MP-RAGE data"); args::HelpFlag help(parser, "HELP", "Show this help message", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlag<int> threads(parser, "THREADS", "Use N threads (default=4, 0=hardware limit)", {'T', "threads"}, QI::GetDefaultThreads()); args::ValueFlag<std::string> outarg( parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlag<std::string> json_file( parser, "FILE", "Read JSON input from file instead of stdin", {"file"}); args::ValueFlag<float> beta_arg( parser, "BETA", "Regularisation factor for robust contrast calculation " "(https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0099676)", {'b', "beta"}, 0.0); args::Flag t1(parser, "T1", "Calculate T1 map via spline look-up", {'t', "t1"}); QI::ParseArgs(parser, argc, argv, verbose, threads); auto inFile = QI::ReadImage<QI::SeriesXF>(QI::CheckPos(input_path), verbose); auto ti_1 = itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXF>::New(); auto ti_2 = itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXF>::New(); auto region = inFile->GetLargestPossibleRegion(); region.GetModifiableSize()[3] = 0; ti_1->SetExtractionRegion(region); ti_1->SetDirectionCollapseToSubmatrix(); ti_1->SetInput(inFile); region.GetModifiableIndex()[3] = 1; ti_2->SetExtractionRegion(region); ti_2->SetDirectionCollapseToSubmatrix(); ti_2->SetInput(inFile); QI::Log(verbose, "Generating MP2 contrasts"); using BinaryFilter = itk::BinaryGeneratorImageFilter<QI::VolumeXF, QI::VolumeXF, QI::VolumeF>; auto MP2Filter = BinaryFilter::New(); MP2Filter->SetInput1(ti_1->GetOutput()); MP2Filter->SetInput2(ti_2->GetOutput()); const float &beta = beta_arg.Get(); MP2Filter->SetFunctor([&](const std::complex<float> &p1, const std::complex<float> &p2) { return MP2Contrast(p1, p2, beta); }); MP2Filter->Update(); const std::string out_prefix = outarg ? outarg.Get() : QI::StripExt(input_path.Get()); QI::WriteImage(MP2Filter->GetOutput(), out_prefix + "_MP2" + QI::OutExt(), verbose); if (t1) { QI::Log(verbose, "Reading sequence information"); rapidjson::Document input = json_file ? QI::ReadJSON(json_file.Get()) : QI::ReadJSON(std::cin); QI::MP2RAGESequence mp2rage_sequence(input["MP2RAGE"]); QI::Log(verbose, "Building look-up spline"); int num_entries = 100; Eigen::ArrayXd T1_values = Eigen::ArrayXd::LinSpaced(num_entries, 0.25, 4.0); Eigen::ArrayXd MP2_values(num_entries); for (int i = 0; i < num_entries; i++) { const auto sig = One_MP2RAGE(1., T1_values[i], 1., mp2rage_sequence); const float mp2 = MP2Contrast(sig[0], sig[1]); if ((i > 0) && (mp2 > MP2_values[i - 1])) { num_entries = i; break; } else { MP2_values[i] = mp2; } } QI::Log(verbose, "Lookup table length = {}", num_entries); QI::SplineInterpolator mp2_to_t1(MP2_values.head(num_entries), T1_values.head(num_entries)); if (beta) { QI::Log(verbose, "Recalculating unregularised MP2 image"); MP2Filter->SetFunctor( [&](const std::complex<float> &p1, const std::complex<float> &p2) { return MP2Contrast(p1, p2, 0.0); }); MP2Filter->Update(); } using UnaryFilter = itk::UnaryGeneratorImageFilter<QI::VolumeF, QI::VolumeF>; auto T1LookupFilter = UnaryFilter::New(); T1LookupFilter->SetInput(MP2Filter->GetOutput()); auto lookup = [&](const float &p) { return mp2_to_t1(p); }; T1LookupFilter->SetFunctor(lookup); QI::Log(verbose, "Calculating T1"); T1LookupFilter->Update(); QI::WriteImage(T1LookupFilter->GetOutput(), out_prefix + "_MP2_T1" + QI::OutExt(), verbose); } QI::Log(verbose, "Finished."); return EXIT_SUCCESS; }