<commit_before>// Copyright (c) 2021 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cxx/ast.h>
#include <cxx/codegen.h>
#include <cxx/statement_codegen.h>

#include <stdexcept>

namespace cxx {

StatementCodegen::StatementCodegen(Codegen* cg) : cg(cg) {}

void StatementCodegen::gen(StatementAST* ast) {
  if (ast) ast->accept(this);
}

// StatementAST
void StatementCodegen::visit(LabeledStatementAST* ast) {
  throw std::runtime_error("visit(LabeledStatementAST): not implemented");
}

void StatementCodegen::visit(CaseStatementAST* ast) {
  throw std::runtime_error("visit(CaseStatementAST): not implemented");
}

void StatementCodegen::visit(DefaultStatementAST* ast) {
  throw std::runtime_error("visit(DefaultStatementAST): not implemented");
}

void StatementCodegen::visit(ExpressionStatementAST* ast) {
  if (ast->expression) {
    auto expr = cg->expression(ast->expression);
  }
}

void StatementCodegen::visit(CompoundStatementAST* ast) {
  for (auto it = ast->statementList; it; it = it->next) {
    cg->statement(it->value);
  }
}

void StatementCodegen::visit(IfStatementAST* ast) {
  if (ast->elseStatement) {
    auto iftrue = cg->createBlock();
    auto iffalse = cg->createBlock();
    auto endif = cg->createBlock();
    cg->condition(ast->condition, iftrue, iffalse);
    cg->place(iftrue);
    cg->statement(ast->statement);
    cg->emitJump(endif);
    cg->place(iffalse);
    cg->statement(ast->elseStatement);
    cg->place(endif);
    return;
  }

  auto iftrue = cg->createBlock();
  auto endif = cg->createBlock();
  cg->condition(ast->condition, iftrue, endif);
  cg->place(iftrue);
  cg->statement(ast->statement);
  cg->place(endif);
}

void StatementCodegen::visit(SwitchStatementAST* ast) {
  throw std::runtime_error("visit(SwitchStatementAST): not implemented");
}

void StatementCodegen::visit(WhileStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueblock = cg->changeContinueBlock(topLoop);

  cg->place(topLoop);
  cg->condition(ast->condition, bodyLoop, endLoop);
  cg->place(bodyLoop);
  cg->statement(ast->statement);
  cg->emitJump(topLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueblock);
}

void StatementCodegen::visit(DoStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto continueLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueblock = cg->changeContinueBlock(continueLoop);

  cg->place(topLoop);
  cg->statement(ast->statement);
  cg->place(continueLoop);
  cg->condition(ast->expression, topLoop, endLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueblock);
}

void StatementCodegen::visit(ForRangeStatementAST* ast) {
  throw std::runtime_error("visit(ForRangeStatementAST): not implemented");
}

void StatementCodegen::visit(ForStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto continueLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueBlock = cg->changeContinueBlock(continueLoop);

  cg->statement(ast->initializer);
  cg->place(topLoop);
  cg->condition(ast->condition, bodyLoop, endLoop);
  cg->place(bodyLoop);
  cg->statement(ast->statement);
  cg->place(continueLoop);
  cg->expression(ast->expression);
  cg->emitJump(topLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueBlock);
}

void StatementCodegen::visit(BreakStatementAST* ast) {
  cg->emitJump(cg->breakBlock());
}

void StatementCodegen::visit(ContinueStatementAST* ast) {
  cg->emitJump(cg->continueBlock());
}

void StatementCodegen::visit(ReturnStatementAST* ast) {
  if (ast->expression) {
    auto value = cg->expression(ast->expression);
    cg->emitMove(cg->createTemp(cg->result()), value);
  }

  cg->emitJump(cg->exitBlock());
}

void StatementCodegen::visit(GotoStatementAST* ast) {
  throw std::runtime_error("visit(GotoStatementAST): not implemented");
}

void StatementCodegen::visit(CoroutineReturnStatementAST* ast) {
  throw std::runtime_error(
      "visit(CoroutineReturnStatementAST): not implemented");
}

void StatementCodegen::visit(DeclarationStatementAST* ast) {
  if (auto simpleDecl = dynamic_cast<SimpleDeclarationAST*>(ast->declaration)) {
    simpleDecl->accept(this);
  }
}

void StatementCodegen::visit(TryBlockStatementAST* ast) {
  throw std::runtime_error("visit(TryBlockStatementAST): not implemented");
}

void StatementCodegen::visit(SimpleDeclarationAST* ast) {
  for (auto it = ast->initDeclaratorList; it; it = it->next) {
    auto initDeclarator = it->value;
    auto initializer = accept(initDeclarator->initializer);
  }
}

ir::Expr* StatementCodegen::accept(InitializerAST* ast) {
  if (ast) ast->accept(this);
  return nullptr;
}

void StatementCodegen::visit(EqualInitializerAST* ast) {
  throw std::runtime_error("visit(TryBlockStatementAST): not implemented");
}

void StatementCodegen::visit(BracedInitListAST* ast) {
  throw std::runtime_error("visit(TryBlockStatementAST): not implemented");
}

}  // namespace cxx
<commit_msg>Fix the exception messages<commit_after>// Copyright (c) 2021 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cxx/ast.h>
#include <cxx/codegen.h>
#include <cxx/statement_codegen.h>

#include <stdexcept>

namespace cxx {

StatementCodegen::StatementCodegen(Codegen* cg) : cg(cg) {}

void StatementCodegen::gen(StatementAST* ast) {
  if (ast) ast->accept(this);
}

// StatementAST
void StatementCodegen::visit(LabeledStatementAST* ast) {
  throw std::runtime_error("visit(LabeledStatementAST): not implemented");
}

void StatementCodegen::visit(CaseStatementAST* ast) {
  throw std::runtime_error("visit(CaseStatementAST): not implemented");
}

void StatementCodegen::visit(DefaultStatementAST* ast) {
  throw std::runtime_error("visit(DefaultStatementAST): not implemented");
}

void StatementCodegen::visit(ExpressionStatementAST* ast) {
  if (ast->expression) {
    auto expr = cg->expression(ast->expression);
  }
}

void StatementCodegen::visit(CompoundStatementAST* ast) {
  for (auto it = ast->statementList; it; it = it->next) {
    cg->statement(it->value);
  }
}

void StatementCodegen::visit(IfStatementAST* ast) {
  if (ast->elseStatement) {
    auto iftrue = cg->createBlock();
    auto iffalse = cg->createBlock();
    auto endif = cg->createBlock();
    cg->condition(ast->condition, iftrue, iffalse);
    cg->place(iftrue);
    cg->statement(ast->statement);
    cg->emitJump(endif);
    cg->place(iffalse);
    cg->statement(ast->elseStatement);
    cg->place(endif);
    return;
  }

  auto iftrue = cg->createBlock();
  auto endif = cg->createBlock();
  cg->condition(ast->condition, iftrue, endif);
  cg->place(iftrue);
  cg->statement(ast->statement);
  cg->place(endif);
}

void StatementCodegen::visit(SwitchStatementAST* ast) {
  throw std::runtime_error("visit(SwitchStatementAST): not implemented");
}

void StatementCodegen::visit(WhileStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueblock = cg->changeContinueBlock(topLoop);

  cg->place(topLoop);
  cg->condition(ast->condition, bodyLoop, endLoop);
  cg->place(bodyLoop);
  cg->statement(ast->statement);
  cg->emitJump(topLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueblock);
}

void StatementCodegen::visit(DoStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto continueLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueblock = cg->changeContinueBlock(continueLoop);

  cg->place(topLoop);
  cg->statement(ast->statement);
  cg->place(continueLoop);
  cg->condition(ast->expression, topLoop, endLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueblock);
}

void StatementCodegen::visit(ForRangeStatementAST* ast) {
  throw std::runtime_error("visit(ForRangeStatementAST): not implemented");
}

void StatementCodegen::visit(ForStatementAST* ast) {
  auto topLoop = cg->createBlock();
  auto bodyLoop = cg->createBlock();
  auto continueLoop = cg->createBlock();
  auto endLoop = cg->createBlock();

  auto previousBreakBlock = cg->changeBreakBlock(endLoop);
  auto previousContinueBlock = cg->changeContinueBlock(continueLoop);

  cg->statement(ast->initializer);
  cg->place(topLoop);
  cg->condition(ast->condition, bodyLoop, endLoop);
  cg->place(bodyLoop);
  cg->statement(ast->statement);
  cg->place(continueLoop);
  cg->expression(ast->expression);
  cg->emitJump(topLoop);
  cg->place(endLoop);

  cg->changeBreakBlock(previousBreakBlock);
  cg->changeContinueBlock(previousContinueBlock);
}

void StatementCodegen::visit(BreakStatementAST* ast) {
  cg->emitJump(cg->breakBlock());
}

void StatementCodegen::visit(ContinueStatementAST* ast) {
  cg->emitJump(cg->continueBlock());
}

void StatementCodegen::visit(ReturnStatementAST* ast) {
  if (ast->expression) {
    auto value = cg->expression(ast->expression);
    cg->emitMove(cg->createTemp(cg->result()), value);
  }

  cg->emitJump(cg->exitBlock());
}

void StatementCodegen::visit(GotoStatementAST* ast) {
  throw std::runtime_error("visit(GotoStatementAST): not implemented");
}

void StatementCodegen::visit(CoroutineReturnStatementAST* ast) {
  throw std::runtime_error(
      "visit(CoroutineReturnStatementAST): not implemented");
}

void StatementCodegen::visit(DeclarationStatementAST* ast) {
  if (auto simpleDecl = dynamic_cast<SimpleDeclarationAST*>(ast->declaration)) {
    simpleDecl->accept(this);
  }
}

void StatementCodegen::visit(TryBlockStatementAST* ast) {
  throw std::runtime_error("visit(TryBlockStatementAST): not implemented");
}

void StatementCodegen::visit(SimpleDeclarationAST* ast) {
  for (auto it = ast->initDeclaratorList; it; it = it->next) {
    auto initDeclarator = it->value;
    auto initializer = accept(initDeclarator->initializer);
  }
}

ir::Expr* StatementCodegen::accept(InitializerAST* ast) {
  if (ast) ast->accept(this);
  return nullptr;
}

void StatementCodegen::visit(EqualInitializerAST* ast) {
  throw std::runtime_error("visit(EqualInitializerAST): not implemented");
}

void StatementCodegen::visit(BracedInitListAST* ast) {
  throw std::runtime_error("visit(BracedInitListAST): not implemented");
}

}  // namespace cxx
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File ADRSolverTests.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Run a series of tests on the ADR Solver
//
///////////////////////////////////////////////////////////////////////////////
#include "../../Auxiliary/RegressBase.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>

void RunL2RegressionTest(std::string demo, std::string input, std::string info);
void MakeOkFile(std::string demo, std::string input, std::string info);

#ifdef MAKE_OK_FILE
#define Execute($1,$2,$3)  MakeOkFile($1,$2,$3)
#else
#define Execute($1,$2,$3)  RunL2RegressionTest($1,$2,$3)
#endif

#ifdef _WINDOWS
#define COPY_COMMAND "copy "

#else
#define COPY_COMMAND "cp "
#endif

static int tests_total = 0;
static int tests_passed = 0;
static int tests_failed = 0;
static bool verbose = false;
static bool quiet = false;

int main(int argc, char* argv[])
{
    if (argc > 2)
    {
        std::cout << "Usage: " << argv[0] << " [-v|-q]" << std::endl;
        return -1;
    }
    if (argc == 2 && std::string(argv[1]) == "-v")
    {
        verbose = true;
    }
    if (argc == 2 && std::string(argv[1]) == "-q")
    {
        quiet = true;
    }

    // //Test Steady Diffusion Advection
    Execute("ADRSolver","Test_Helmholtz1D_8modes.xml","1D Helmholtz/Steady Diffusion Reaction P=8");

    Execute("ADRSolver","Test_Helmholtz1D_8modes_DG.xml","1D Helmholtz/Steady Diffusion Reaction (DG) P=8");

    Execute("ADRSolver","Test_Helmholtz1D_8nodes.xml","1D Helmholtz/Steady Diffusion Reaction P=8");

    Execute("ADRSolver","Test_Helmholtz2D_modal.xml","2D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz2D_modal_DG.xml","2D Helmholtz/Steady Diffusion Reaction (DG) P=7");

    Execute("ADRSolver","Test_Helmholtz2D_nodal.xml","2D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz3D_modal.xml","3D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz3D_nodal.xml","3D Helmholtz/Steady Diffusion Reaction P=7");

	Execute("ADRSolver","Test_Helmholtz_3DHomo1D_MVM.xml","3D-Homogeneous-1D Helmholtz/Steady Diffusion (MVM)");

	Execute("ADRSolver","Test_Helmholtz_3DHomo2D_MVM.xml","3D-Homogeneous-2D Helmholtz/Steady Diffusion (MVM)");

#ifdef NEKTAR_USE_FFTW
	Execute("ADRSolver","Test_Helmholtz_3DHomo1D_FFT.xml","3D-Homogeneous-1D Helmholtz/Steady Diffusion (FFT)");

	Execute("ADRSolver","Test_Helmholtz_3DHomo2D_FFT.xml","3D-Homogeneous-2D Helmholtz/Steady Diffusion (FFT)");
#endif

    // Test Steady Advection Diffusion Reaction
    Execute("ADRSolver","Test_SteadyAdvDiffReact2D_modal.xml","2D Steady Advection Diffusion Reaction P=9");

    Execute("ADRSolver","Test_Advection1D_m8_Order1.xml","1D unsteady advection, order 1, P=8");

    Execute("ADRSolver","Test_Advection1D_m12_Order2.xml","1D unsteady advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection1D_m14_Order4.xml","1D unsteady advection, order 4, P=14");

    Execute("ADRSolver","Test_Advection_m12_Order1.xml","2D unsteady advection, order 1, P=12");

    Execute("ADRSolver","Test_Advection_m12_Order2.xml","2D unsteady advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection_m14_Order4.xml","2D unsteady advection, order 4, P=14");

    Execute("ADRSolver","Test_Advection_m12_DG_Order1.xml","2D unsteady DG advection, order 1, P=12");

    Execute("ADRSolver","Test_Advection_m12_DG_Order2.xml","2D unsteady DG advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection_m14_DG_Order4.xml","2D unsteady DG advection, order 4, P=14");

    Execute("ADRSolver","Test_ImDiffusion_m6.xml","2D unsteady DG implicit diffusion, order 3, P=6");

    Execute("ADRSolver","Test_ImDiffusion_m12.xml","2D unsteady DG implicit diffusion, order 3, P=12");

    Execute("ADRSolver","Test_ExDiffusion_m3.xml","2D unsteady DG explicit diffusion, order 4, P=3");

    Execute("ADRSolver","Test_ExDiffusion_m8.xml","2D unsteady DG explicit diffusion, order 4, P=8");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order1_001.xml","2D unsteady advection-diffusion, IMEXOrder1, P=9, dt=0.001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order1_0001.xml","2D unsteady advection-diffusion, IMEXOrder1, P=9, dt=0.0001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order2_001.xml","2D unsteady advection-diffusion, IMEXOrder2, P=9, dt=0.001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order2_0001.xml","2D unsteady advection-diffusion, IMEXOrder2, P=9, dt=0.0001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo1D_MVM.xml","3D-Homogeneous-1D unsteady advection-diffusion (MVM)");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo2D_MVM.xml","3D-Homogeneous-2D unsteady advection-diffusion (MVM)");

#ifdef NEKTAR_USE_FFTW
	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo1D_FFT.xml","3D-Homogeneous-1D unsteady advection-diffusion (FFT)");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo2D_FFT.xml","3D-Homogeneous-2D unsteady advection-diffusion (FFT)");
#endif

    if (tests_failed && !quiet)
    {
        std::cout << "WARNING: " << tests_failed << " test(s) failed." << std::endl;
    }
    else if (verbose)
    {
        std::cout << "All tests passed successfully!" << std::endl;
    }
    return tests_failed;
}

void RunL2RegressionTest(std::string Demo, std::string input, std::string info)
{
    tests_total++;
    if (!quiet)
    {
        std::cout << "TESTING: " << Demo << std::flush;
    }
	std::string NektarSolverDir =std::string("") +  NEKTAR_SOLVER_DIR + "/dist/bin/";
    RegressBase Test(NektarSolverDir.c_str(),Demo,input,"Solvers/ADRSolver/OkFiles/");
    int fail;

    // Copy input file to current location
	boost::filesystem::path sourceFile(std::string(REG_PATH) + "Solvers/ADRSolver/InputFiles/" + input);
    std::string syscommand = std::string(COPY_COMMAND) + sourceFile.file_string() + " .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.TestL2()) // test failed
    {
        if (!quiet)
        {
            std::cout << "\rFAILED: " << Demo << " " << input << " (" << info << ")" << std::endl;
            std::cout << "===========================================================\n";
            // Explain cause of error if available
            Test.PrintTestError(fail);
            std::cout << "===========================================================\n";
        }
        tests_failed++;
    }
    else
    {
        if (verbose)
        {
            std::cout << "\rPASSED: " << Demo << " " << input << " (" << info << ")" << std::endl;
        }
        else if (quiet)
        {
            // print nothing
        }
        else {
            std::cout << "\rPASSED: " << Demo << " (" << info << ")" << std::endl;
        }
        tests_passed++;
    }

#ifdef _WINDOWS
	std::string cleanup = "del /Q *.xml *.fld *.chk *.his";
#else
    std::string cleanup = "rm -f *.xml *.fld *.chk *.his";
#endif
    system(cleanup.c_str());
};

void MakeOkFile(std::string Demo, std::string input, std::string info)
{
    tests_total++;
    std::string NektarSolverDir =std::string("") +  NEKTAR_SOLVER_DIR + "ADRSolver/";
    RegressBase Test(NektarSolverDir,Demo,input,"Solvers/ADRSolver/OkFiles/");
    int fail;

    // Copy input file to current location
	boost::filesystem::path sourceFile(std::string(REG_PATH) + "Solvers/ADRSolver/InputFiles/" + input);
    std::string syscommand = std::string(COPY_COMMAND) + sourceFile.file_string() +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.MakeOkFile())
    {
        std::cout << "Failed to make OK file\n";
        // Explain cause of error if available
        std::cout << "===========================================================\n";
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
        tests_failed++;
	}
#ifdef _WINDOWS
	std::string cleanup = "del /Q *.xml *.fld *.chk *.his";
#else
    std::string cleanup = "rm -f *.xml *.fld *.chk *.his";
#endif
    system(cleanup.c_str());

}

<commit_msg>Fixed FFTW regression tests usage. Using the proper Cmake variable.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File ADRSolverTests.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Run a series of tests on the ADR Solver
//
///////////////////////////////////////////////////////////////////////////////
#include "../../Auxiliary/RegressBase.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>

void RunL2RegressionTest(std::string demo, std::string input, std::string info);
void MakeOkFile(std::string demo, std::string input, std::string info);

#ifdef MAKE_OK_FILE
#define Execute($1,$2,$3)  MakeOkFile($1,$2,$3)
#else
#define Execute($1,$2,$3)  RunL2RegressionTest($1,$2,$3)
#endif

#ifdef _WINDOWS
#define COPY_COMMAND "copy "

#else
#define COPY_COMMAND "cp "
#endif

static int tests_total = 0;
static int tests_passed = 0;
static int tests_failed = 0;
static bool verbose = false;
static bool quiet = false;

int main(int argc, char* argv[])
{
    if (argc > 2)
    {
        std::cout << "Usage: " << argv[0] << " [-v|-q]" << std::endl;
        return -1;
    }
    if (argc == 2 && std::string(argv[1]) == "-v")
    {
        verbose = true;
    }
    if (argc == 2 && std::string(argv[1]) == "-q")
    {
        quiet = true;
    }

    // //Test Steady Diffusion Advection
    Execute("ADRSolver","Test_Helmholtz1D_8modes.xml","1D Helmholtz/Steady Diffusion Reaction P=8");

    Execute("ADRSolver","Test_Helmholtz1D_8modes_DG.xml","1D Helmholtz/Steady Diffusion Reaction (DG) P=8");

    Execute("ADRSolver","Test_Helmholtz1D_8nodes.xml","1D Helmholtz/Steady Diffusion Reaction P=8");

    Execute("ADRSolver","Test_Helmholtz2D_modal.xml","2D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz2D_modal_DG.xml","2D Helmholtz/Steady Diffusion Reaction (DG) P=7");

    Execute("ADRSolver","Test_Helmholtz2D_nodal.xml","2D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz3D_modal.xml","3D Helmholtz/Steady Diffusion Reaction P=7");

    Execute("ADRSolver","Test_Helmholtz3D_nodal.xml","3D Helmholtz/Steady Diffusion Reaction P=7");

	Execute("ADRSolver","Test_Helmholtz_3DHomo1D_MVM.xml","3D-Homogeneous-1D Helmholtz/Steady Diffusion (MVM)");

	Execute("ADRSolver","Test_Helmholtz_3DHomo2D_MVM.xml","3D-Homogeneous-2D Helmholtz/Steady Diffusion (MVM)");

#ifdef NEKTAR_USING_FFTW
	Execute("ADRSolver","Test_Helmholtz_3DHomo1D_FFT.xml","3D-Homogeneous-1D Helmholtz/Steady Diffusion (FFT)");

	Execute("ADRSolver","Test_Helmholtz_3DHomo2D_FFT.xml","3D-Homogeneous-2D Helmholtz/Steady Diffusion (FFT)");
#endif

    // Test Steady Advection Diffusion Reaction
    Execute("ADRSolver","Test_SteadyAdvDiffReact2D_modal.xml","2D Steady Advection Diffusion Reaction P=9");

    Execute("ADRSolver","Test_Advection1D_m8_Order1.xml","1D unsteady advection, order 1, P=8");

    Execute("ADRSolver","Test_Advection1D_m12_Order2.xml","1D unsteady advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection1D_m14_Order4.xml","1D unsteady advection, order 4, P=14");

    Execute("ADRSolver","Test_Advection_m12_Order1.xml","2D unsteady advection, order 1, P=12");

    Execute("ADRSolver","Test_Advection_m12_Order2.xml","2D unsteady advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection_m14_Order4.xml","2D unsteady advection, order 4, P=14");

    Execute("ADRSolver","Test_Advection_m12_DG_Order1.xml","2D unsteady DG advection, order 1, P=12");

    Execute("ADRSolver","Test_Advection_m12_DG_Order2.xml","2D unsteady DG advection, order 2, P=12");

    Execute("ADRSolver","Test_Advection_m14_DG_Order4.xml","2D unsteady DG advection, order 4, P=14");

    Execute("ADRSolver","Test_ImDiffusion_m6.xml","2D unsteady DG implicit diffusion, order 3, P=6");

    Execute("ADRSolver","Test_ImDiffusion_m12.xml","2D unsteady DG implicit diffusion, order 3, P=12");

    Execute("ADRSolver","Test_ExDiffusion_m3.xml","2D unsteady DG explicit diffusion, order 4, P=3");

    Execute("ADRSolver","Test_ExDiffusion_m8.xml","2D unsteady DG explicit diffusion, order 4, P=8");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order1_001.xml","2D unsteady advection-diffusion, IMEXOrder1, P=9, dt=0.001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order1_0001.xml","2D unsteady advection-diffusion, IMEXOrder1, P=9, dt=0.0001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order2_001.xml","2D unsteady advection-diffusion, IMEXOrder2, P=9, dt=0.001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_Order2_0001.xml","2D unsteady advection-diffusion, IMEXOrder2, P=9, dt=0.0001");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo1D_MVM.xml","3D-Homogeneous-1D unsteady advection-diffusion (MVM)");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo2D_MVM.xml","3D-Homogeneous-2D unsteady advection-diffusion (MVM)");

#ifdef NEKTAR_USING_FFTW
	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo1D_FFT.xml","3D-Homogeneous-1D unsteady advection-diffusion (FFT)");

	Execute("ADRSolver","Test_UnsteadyAdvectionDiffusion_3DHomo2D_FFT.xml","3D-Homogeneous-2D unsteady advection-diffusion (FFT)");
#endif

    if (tests_failed && !quiet)
    {
        std::cout << "WARNING: " << tests_failed << " test(s) failed." << std::endl;
    }
    else if (verbose)
    {
        std::cout << "All tests passed successfully!" << std::endl;
    }
    return tests_failed;
}

void RunL2RegressionTest(std::string Demo, std::string input, std::string info)
{
    tests_total++;
    if (!quiet)
    {
        std::cout << "TESTING: " << Demo << std::flush;
    }
	std::string NektarSolverDir =std::string("") +  NEKTAR_SOLVER_DIR + "/dist/bin/";
    RegressBase Test(NektarSolverDir.c_str(),Demo,input,"Solvers/ADRSolver/OkFiles/");
    int fail;

    // Copy input file to current location
	boost::filesystem::path sourceFile(std::string(REG_PATH) + "Solvers/ADRSolver/InputFiles/" + input);
    std::string syscommand = std::string(COPY_COMMAND) + sourceFile.file_string() + " .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.TestL2()) // test failed
    {
        if (!quiet)
        {
            std::cout << "\rFAILED: " << Demo << " " << input << " (" << info << ")" << std::endl;
            std::cout << "===========================================================\n";
            // Explain cause of error if available
            Test.PrintTestError(fail);
            std::cout << "===========================================================\n";
        }
        tests_failed++;
    }
    else
    {
        if (verbose)
        {
            std::cout << "\rPASSED: " << Demo << " " << input << " (" << info << ")" << std::endl;
        }
        else if (quiet)
        {
            // print nothing
        }
        else {
            std::cout << "\rPASSED: " << Demo << " (" << info << ")" << std::endl;
        }
        tests_passed++;
    }

#ifdef _WINDOWS
	std::string cleanup = "del /Q *.xml *.fld *.chk *.his";
#else
    std::string cleanup = "rm -f *.xml *.fld *.chk *.his";
#endif
    system(cleanup.c_str());
};

void MakeOkFile(std::string Demo, std::string input, std::string info)
{
    tests_total++;
    std::string NektarSolverDir =std::string("") +  NEKTAR_SOLVER_DIR + "ADRSolver/";
    RegressBase Test(NektarSolverDir,Demo,input,"Solvers/ADRSolver/OkFiles/");
    int fail;

    // Copy input file to current location
	boost::filesystem::path sourceFile(std::string(REG_PATH) + "Solvers/ADRSolver/InputFiles/" + input);
    std::string syscommand = std::string(COPY_COMMAND) + sourceFile.file_string() +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.MakeOkFile())
    {
        std::cout << "Failed to make OK file\n";
        // Explain cause of error if available
        std::cout << "===========================================================\n";
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
        tests_failed++;
	}
#ifdef _WINDOWS
	std::string cleanup = "del /Q *.xml *.fld *.chk *.his";
#else
    std::string cleanup = "rm -f *.xml *.fld *.chk *.his";
#endif
    system(cleanup.c_str());

}

<|endoftext|>


<commit_before>// Copyright 2017 Global Phasing Ltd.

#include "gemmi/grid.hpp"
#include "gemmi/util.hpp"  // for trim_str
#include "input.h"
#include <cstdlib>   // for strtod
#include <cstdio>    // for fprintf
#include <algorithm> // for nth_element
#define USE_UNICODE
#ifdef USE_UNICODE
#include <clocale>  // for setlocale
#include <cwchar>  // for wchar_t
#endif
#define EXE_NAME "gemmi-map"
#include "options.h"

namespace mol = gemmi::mol;

enum OptionIndex { Unknown, Verbose, OutputMode };

static const option::Descriptor Usage[] = {
  { Unknown, 0, "", "", Arg::None,
    "Usage:\n " EXE_NAME " [options] CCP4_MAP[...]\n" },
  { Help, 0, "h", "help", Arg::None, "  -h, --help  \tPrint usage and exit." },
  { Version, 0, "V", "version", Arg::None,
    "  -V, --version  \tPrint version and exit." },
  { Verbose, 0, "", "verbose", Arg::None, "  --verbose  \tVerbose output." },
  { 0, 0, 0, 0, 0, 0 }
};

template<typename T>
void print_histogram(const std::vector<T>& data, double min, double max) {
#ifdef USE_UNICODE
  std::setlocale(LC_ALL, "");
#endif
  int bins[81] = {0};
  double delta = max - min;
  for (T d : data) {
    int n = gemmi::iround((d - min) * (80 / delta));
    bins[n]++;
  }
  double max_h = *std::max_element(std::begin(bins), std::end(bins));
  const int rows = 24;
  for (int i = rows; i > 0; --i) {
    for (int j = 0; j < 80; ++j) {
      double h = bins[j] / max_h * rows;
#ifdef USE_UNICODE
      wchar_t c = ' ';
      if (h > i) {
        c = 0x2588; // 0x2581 = one eighth block, ..., 0x2588 = full block
      } else if (h > i - 1) {
        c = 0x2581 + static_cast<int>((h - (i - 1)) * 7);
      }
      printf("%lc", c);
#else
      std::putchar(h > i + 0.5 ? '#' : ' ');
#endif
    }
    std::putchar('\n');
  }
}

template<typename T>
void print_info(const gemmi::Grid<T>& grid) {
  std::printf("Map mode: %d\n", grid.header_i32(4));
  std::printf("Number of columns, rows, sections: %5d %5d %5d %8s %d points\n",
              grid.nu, grid.nv, grid.nw, "->", grid.nu * grid.nv * grid.nw);
  int u0 = grid.header_i32(5);
  int v0 = grid.header_i32(6);
  int w0 = grid.header_i32(7);
  std::printf("                             from: %5d %5d %5d\n", u0, v0, w0);
  std::printf("                               to: %5d %5d %5d\n",
              u0 + grid.nu - 1, v0 + grid.nv - 1, w0 + grid.nw - 1);
  const char* xyz = "?XYZ";
  std::printf("Fast, medium, slow axes: %c %c %c\n",
              xyz[grid.header_i32(17)],
              xyz[grid.header_i32(18)],
              xyz[grid.header_i32(19)]);
  int mx = grid.header_i32(8);
  int my = grid.header_i32(9);
  int mz = grid.header_i32(10);
  std::printf("Grid sampling on x, y, z: %5d %5d %5d          %8s %d points\n",
              mx, my, mz, "->", mx * my * mz);
  const mol::UnitCell& cell = grid.unit_cell;
  std::printf("Space group number: %d\n", grid.header_i32(23));
  std::printf("Cell dimensions: %g %g %g  %g %g %g\n",
              cell.a, cell.b, cell.c, cell.alpha, cell.beta, cell.gamma);
  int origin[3] = {
    grid.header_i32(50),
    grid.header_i32(51),
    grid.header_i32(52)
  };
  if (origin[0] != 0 || origin[1] != 0 || origin[2] != 0)
    std::printf("Non-zero origin: %d %d %d\n", origin[0], origin[1], origin[2]);

  std::printf("\nStatistics from HEADER and DATA\n");
  gemmi::GridStats st = grid.calculate_statistics();
  std::printf("Minimum: %12.5f  %12.5f\n", grid.stats.dmin, st.dmin);
  std::printf("Maximum: %12.5f  %12.5f\n", grid.stats.dmax, st.dmax);
  std::printf("Mean:    %12.5f  %12.5f\n", grid.stats.dmean, st.dmean);
  std::printf("RMS:     %12.5f  %12.5f\n", grid.stats.rms, st.rms);
  std::vector<T> data = grid.data;
  size_t mpos = data.size() / 2;
  std::nth_element(data.begin(), data.begin() + mpos, data.end());
  std::printf("Median:                %12.5f\n", data[mpos]);
  print_histogram(data, st.dmin, st.dmax);
  int nlabl = grid.header_i32(56);
  if (nlabl != 0)
    std::printf("\n");
  for (int i = 0; i < nlabl && i < 10; ++i) {
    std::string label = gemmi::trim_str(grid.header_str(57 + i * 20));
    std::printf("Label #%d\n%s\n", i, label.c_str());
  }
  int nsymbt = grid.header_i32(24);
  if (nsymbt != 0)
    std::printf("\n");
  for (int i = 0; i * 80 < nsymbt; i++) {
    std::string symop = grid.header_str(256 + i * 20 /*words not bytes*/, 80);
    std::printf("Sym op #%d: %s\n", i + 1, gemmi::trim_str(symop).c_str());
  }
}

int main(int argc, char **argv) {
  OptParser parse;
  auto options = parse.simple_parse(argc, argv, Usage);
  bool verbose = options[Verbose];

  if (parse.nonOptionsCount() == 0) {
    std::fprintf(stderr, "No input files. Nothing to do.\n");
    return 0;
  }

  try {
    for (int i = 0; i < parse.nonOptionsCount(); ++i) {
      const char* input = parse.nonOption(i);
      gemmi::Grid<> grid;
      if (verbose)
        std::fprintf(stderr, "Reading %s ...\n", input);
      grid.read_ccp4(input);
      print_info(grid);
    }
  } catch (std::runtime_error& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  }
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>%lc actually corresponds to wint_t<commit_after>// Copyright 2017 Global Phasing Ltd.

#include "gemmi/grid.hpp"
#include "gemmi/util.hpp"  // for trim_str
#include "input.h"
#include <cstdlib>   // for strtod
#include <cstdio>    // for fprintf
#include <algorithm> // for nth_element
#define USE_UNICODE
#ifdef USE_UNICODE
#include <clocale>  // for setlocale
#include <cwchar>  // for wint_t
#endif
#define EXE_NAME "gemmi-map"
#include "options.h"

namespace mol = gemmi::mol;

enum OptionIndex { Unknown, Verbose, OutputMode };

static const option::Descriptor Usage[] = {
  { Unknown, 0, "", "", Arg::None,
    "Usage:\n " EXE_NAME " [options] CCP4_MAP[...]\n" },
  { Help, 0, "h", "help", Arg::None, "  -h, --help  \tPrint usage and exit." },
  { Version, 0, "V", "version", Arg::None,
    "  -V, --version  \tPrint version and exit." },
  { Verbose, 0, "", "verbose", Arg::None, "  --verbose  \tVerbose output." },
  { 0, 0, 0, 0, 0, 0 }
};

template<typename T>
void print_histogram(const std::vector<T>& data, double min, double max) {
#ifdef USE_UNICODE
  std::setlocale(LC_ALL, "");
#endif
  int bins[81] = {0};
  double delta = max - min;
  for (T d : data) {
    int n = gemmi::iround((d - min) * (80 / delta));
    bins[n]++;
  }
  double max_h = *std::max_element(std::begin(bins), std::end(bins));
  const int rows = 24;
  for (int i = rows; i > 0; --i) {
    for (int j = 0; j < 80; ++j) {
      double h = bins[j] / max_h * rows;
#ifdef USE_UNICODE
      wint_t c = ' ';
      if (h > i) {
        c = 0x2588; // 0x2581 = one eighth block, ..., 0x2588 = full block
      } else if (h > i - 1) {
        c = 0x2581 + static_cast<int>((h - (i - 1)) * 7);
      }
      printf("%lc", c);
#else
      std::putchar(h > i + 0.5 ? '#' : ' ');
#endif
    }
    std::putchar('\n');
  }
}

template<typename T>
void print_info(const gemmi::Grid<T>& grid) {
  std::printf("Map mode: %d\n", grid.header_i32(4));
  std::printf("Number of columns, rows, sections: %5d %5d %5d %8s %d points\n",
              grid.nu, grid.nv, grid.nw, "->", grid.nu * grid.nv * grid.nw);
  int u0 = grid.header_i32(5);
  int v0 = grid.header_i32(6);
  int w0 = grid.header_i32(7);
  std::printf("                             from: %5d %5d %5d\n", u0, v0, w0);
  std::printf("                               to: %5d %5d %5d\n",
              u0 + grid.nu - 1, v0 + grid.nv - 1, w0 + grid.nw - 1);
  const char* xyz = "?XYZ";
  std::printf("Fast, medium, slow axes: %c %c %c\n",
              xyz[grid.header_i32(17)],
              xyz[grid.header_i32(18)],
              xyz[grid.header_i32(19)]);
  int mx = grid.header_i32(8);
  int my = grid.header_i32(9);
  int mz = grid.header_i32(10);
  std::printf("Grid sampling on x, y, z: %5d %5d %5d          %8s %d points\n",
              mx, my, mz, "->", mx * my * mz);
  const mol::UnitCell& cell = grid.unit_cell;
  std::printf("Space group number: %d\n", grid.header_i32(23));
  std::printf("Cell dimensions: %g %g %g  %g %g %g\n",
              cell.a, cell.b, cell.c, cell.alpha, cell.beta, cell.gamma);
  int origin[3] = {
    grid.header_i32(50),
    grid.header_i32(51),
    grid.header_i32(52)
  };
  if (origin[0] != 0 || origin[1] != 0 || origin[2] != 0)
    std::printf("Non-zero origin: %d %d %d\n", origin[0], origin[1], origin[2]);

  std::printf("\nStatistics from HEADER and DATA\n");
  gemmi::GridStats st = grid.calculate_statistics();
  std::printf("Minimum: %12.5f  %12.5f\n", grid.stats.dmin, st.dmin);
  std::printf("Maximum: %12.5f  %12.5f\n", grid.stats.dmax, st.dmax);
  std::printf("Mean:    %12.5f  %12.5f\n", grid.stats.dmean, st.dmean);
  std::printf("RMS:     %12.5f  %12.5f\n", grid.stats.rms, st.rms);
  std::vector<T> data = grid.data;
  size_t mpos = data.size() / 2;
  std::nth_element(data.begin(), data.begin() + mpos, data.end());
  std::printf("Median:                %12.5f\n", data[mpos]);
  print_histogram(data, st.dmin, st.dmax);
  int nlabl = grid.header_i32(56);
  if (nlabl != 0)
    std::printf("\n");
  for (int i = 0; i < nlabl && i < 10; ++i) {
    std::string label = gemmi::trim_str(grid.header_str(57 + i * 20));
    std::printf("Label #%d\n%s\n", i, label.c_str());
  }
  int nsymbt = grid.header_i32(24);
  if (nsymbt != 0)
    std::printf("\n");
  for (int i = 0; i * 80 < nsymbt; i++) {
    std::string symop = grid.header_str(256 + i * 20 /*words not bytes*/, 80);
    std::printf("Sym op #%d: %s\n", i + 1, gemmi::trim_str(symop).c_str());
  }
}

int main(int argc, char **argv) {
  OptParser parse;
  auto options = parse.simple_parse(argc, argv, Usage);
  bool verbose = options[Verbose];

  if (parse.nonOptionsCount() == 0) {
    std::fprintf(stderr, "No input files. Nothing to do.\n");
    return 0;
  }

  try {
    for (int i = 0; i < parse.nonOptionsCount(); ++i) {
      const char* input = parse.nonOption(i);
      gemmi::Grid<> grid;
      if (verbose)
        std::fprintf(stderr, "Reading %s ...\n", input);
      grid.read_ccp4(input);
      print_info(grid);
    }
  } catch (std::runtime_error& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  }
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/accessibility/accessibility_tree_formatter.h"

#include <oleacc.h>

#include <string>

#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/accessibility/accessibility_tree_formatter_utils_win.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/browser_accessibility_win.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/base/win/atl_module.h"

using base::StringPrintf;

namespace content {

const char* ALL_ATTRIBUTES[] = {
    "name",
    "value",
    "states",
    "attributes",
    "role_name",
    "currentValue",
    "minimumValue",
    "maximumValue",
    "description",
    "default_action",
    "keyboard_shortcut",
    "location",
    "size",
    "index_in_parent",
    "n_relations",
    "group_level",
    "similar_items_in_group",
    "position_in_group",
    "table_rows",
    "table_columns",
    "row_index",
    "column_index",
    "n_characters",
    "caret_offset",
    "n_selections",
    "selection_start",
    "selection_end"
};

void AccessibilityTreeFormatter::Initialize() {
  ui::win::CreateATLModuleIfNeeded();
}

void AccessibilityTreeFormatter::AddProperties(
    const BrowserAccessibility& node, base::DictionaryValue* dict) {
  dict->SetInteger("id", node.GetId());
  BrowserAccessibilityWin* acc_obj =
      const_cast<BrowserAccessibility*>(&node)->ToBrowserAccessibilityWin();

  VARIANT variant_self;
  variant_self.vt = VT_I4;
  variant_self.lVal = CHILDID_SELF;

  dict->SetString("role", IAccessible2RoleToString(acc_obj->ia2_role()));

  CComBSTR msaa_variant;
  HRESULT hresult = acc_obj->get_accName(variant_self, &msaa_variant);
  if (hresult == S_OK)
    dict->SetString("name", msaa_variant.m_str);
  hresult = acc_obj->get_accValue(variant_self, &msaa_variant);
  if (hresult == S_OK)
    dict->SetString("value", msaa_variant.m_str);

  std::vector<base::string16> state_strings;
  int32 ia_state = acc_obj->ia_state();

  // Avoid flakiness: these states depend on whether the window is focused
  // and the position of the mouse cursor.
  ia_state &= ~STATE_SYSTEM_HOTTRACKED;
  ia_state &= ~STATE_SYSTEM_OFFSCREEN;

  IAccessibleStateToStringVector(ia_state, &state_strings);
  IAccessible2StateToStringVector(acc_obj->ia2_state(), &state_strings);
  base::ListValue* states = new base::ListValue;
  for (std::vector<base::string16>::const_iterator it = state_strings.begin();
       it != state_strings.end();
       ++it) {
    states->AppendString(base::UTF16ToUTF8(*it));
  }
  dict->Set("states", states);

  const std::vector<base::string16>& ia2_attributes = acc_obj->ia2_attributes();
  base::ListValue* attributes = new base::ListValue;
  for (std::vector<base::string16>::const_iterator it = ia2_attributes.begin();
       it != ia2_attributes.end();
       ++it) {
    attributes->AppendString(base::UTF16ToUTF8(*it));
  }
  dict->Set("attributes", attributes);

  dict->SetString("role_name", acc_obj->role_name());

  VARIANT currentValue;
  if (acc_obj->get_currentValue(&currentValue) == S_OK)
    dict->SetDouble("currentValue", V_R8(&currentValue));

  VARIANT minimumValue;
  if (acc_obj->get_minimumValue(&minimumValue) == S_OK)
    dict->SetDouble("minimumValue", V_R8(&minimumValue));

  VARIANT maximumValue;
  if (acc_obj->get_maximumValue(&maximumValue) == S_OK)
    dict->SetDouble("maximumValue", V_R8(&maximumValue));

  hresult = acc_obj->get_accDescription(variant_self, &msaa_variant);
  if (hresult == S_OK)
    dict->SetString("description", msaa_variant.m_str);

  hresult = acc_obj->get_accDefaultAction(variant_self, &msaa_variant);
  if (hresult == S_OK)
    dict->SetString("default_action", msaa_variant.m_str);

  hresult = acc_obj->get_accKeyboardShortcut(variant_self, &msaa_variant);
  if (hresult == S_OK)
    dict->SetString("keyboard_shortcut", msaa_variant.m_str);

  hresult = acc_obj->get_accHelp(variant_self, &msaa_variant);
  if (S_OK == hresult)
    dict->SetString("help", msaa_variant.m_str);

  BrowserAccessibility* root = node.manager()->GetRoot();
  LONG left, top, width, height;
  LONG root_left, root_top, root_width, root_height;
  if (acc_obj->accLocation(&left, &top, &width, &height, variant_self)
      != S_FALSE
      && root->ToBrowserAccessibilityWin()->accLocation(
          &root_left, &root_top, &root_width, &root_height, variant_self)
      != S_FALSE) {
    base::DictionaryValue* location = new base::DictionaryValue;
    location->SetInteger("x", left - root_left);
    location->SetInteger("y", top - root_top);
    dict->Set("location", location);

    base::DictionaryValue* size = new base::DictionaryValue;
    size->SetInteger("width", width);
    size->SetInteger("height", height);
    dict->Set("size", size);
  }

  LONG index_in_parent;
  if (acc_obj->get_indexInParent(&index_in_parent) == S_OK)
    dict->SetInteger("index_in_parent", index_in_parent);

  LONG n_relations;
  if (acc_obj->get_nRelations(&n_relations) == S_OK)
    dict->SetInteger("n_relations", n_relations);

  LONG group_level, similar_items_in_group, position_in_group;
  if (acc_obj->get_groupPosition(&group_level,
                                 &similar_items_in_group,
                                 &position_in_group) == S_OK) {
    dict->SetInteger("group_level", group_level);
    dict->SetInteger("similar_items_in_group", similar_items_in_group);
    dict->SetInteger("position_in_group", position_in_group);
  }
  LONG table_rows;
  if (acc_obj->get_nRows(&table_rows) == S_OK)
    dict->SetInteger("table_rows", table_rows);
  LONG table_columns;
  if (acc_obj->get_nRows(&table_columns) == S_OK)
    dict->SetInteger("table_columns", table_columns);
  LONG row_index;
  if (acc_obj->get_rowIndex(&row_index) == S_OK)
    dict->SetInteger("row_index", row_index);
  LONG column_index;
  if (acc_obj->get_columnIndex(&column_index) == S_OK)
    dict->SetInteger("column_index", column_index);
  LONG n_characters;
  if (acc_obj->get_nCharacters(&n_characters) == S_OK)
    dict->SetInteger("n_characters", n_characters);
  LONG caret_offset;
  if (acc_obj->get_caretOffset(&caret_offset) == S_OK)
    dict->SetInteger("caret_offset", caret_offset);
  LONG n_selections;
  if (acc_obj->get_nSelections(&n_selections) == S_OK) {
    dict->SetInteger("n_selections", n_selections);
    if (n_selections > 0) {
      LONG start, end;
      if (acc_obj->get_selection(0, &start, &end) == S_OK) {
        dict->SetInteger("selection_start", start);
        dict->SetInteger("selection_end", end);
      }
    }
  }
}

base::string16 AccessibilityTreeFormatter::ToString(
    const base::DictionaryValue& dict) {
  base::string16 line;

  if (show_ids_) {
    int id_value;
    dict.GetInteger("id", &id_value);
    WriteAttribute(true, base::IntToString16(id_value), &line);
  }

  base::string16 role_value;
  dict.GetString("role", &role_value);
  WriteAttribute(true, base::UTF16ToUTF8(role_value), &line);

  for (int i = 0; i < arraysize(ALL_ATTRIBUTES); i++) {
    const char* attribute_name = ALL_ATTRIBUTES[i];
    const base::Value* value;
    if (!dict.Get(attribute_name, &value))
      continue;

    switch (value->GetType()) {
      case base::Value::TYPE_STRING: {
        base::string16 string_value;
        value->GetAsString(&string_value);
        WriteAttribute(false,
                       StringPrintf(L"%ls='%ls'",
                                    base::UTF8ToUTF16(attribute_name).c_str(),
                                    string_value.c_str()),
                       &line);
        break;
      }
      case base::Value::TYPE_INTEGER: {
        int int_value;
        value->GetAsInteger(&int_value);
        WriteAttribute(false,
                       base::StringPrintf(L"%ls=%d",
                                          base::UTF8ToUTF16(
                                              attribute_name).c_str(),
                                          int_value),
                       &line);
        break;
      }
      case base::Value::TYPE_DOUBLE: {
        double double_value;
        value->GetAsDouble(&double_value);
        WriteAttribute(false,
                       base::StringPrintf(L"%ls=%.2f",
                                          base::UTF8ToUTF16(
                                              attribute_name).c_str(),
                                          double_value),
                       &line);
        break;
      }
      case base::Value::TYPE_LIST: {
        // Currently all list values are string and are written without
        // attribute names.
        const base::ListValue* list_value;
        value->GetAsList(&list_value);
        for (base::ListValue::const_iterator it = list_value->begin();
             it != list_value->end();
             ++it) {
          base::string16 string_value;
          if ((*it)->GetAsString(&string_value))
            WriteAttribute(false, string_value, &line);
        }
        break;
      }
      case base::Value::TYPE_DICTIONARY: {
        // Currently all dictionary values are coordinates.
        // Revisit this if that changes.
        const base::DictionaryValue* dict_value;
        value->GetAsDictionary(&dict_value);
        if (strcmp(attribute_name, "size") == 0) {
          WriteAttribute(false,
                         FormatCoordinates("size", "width", "height",
                                           *dict_value),
                         &line);
        } else if (strcmp(attribute_name, "location") == 0) {
          WriteAttribute(false,
                         FormatCoordinates("location", "x", "y", *dict_value),
                         &line);
        }
        break;
      }
      default:
        NOTREACHED();
        break;
    }
  }

  return line;
}

// static
const base::FilePath::StringType
AccessibilityTreeFormatter::GetActualFileSuffix() {
  return FILE_PATH_LITERAL("-actual-win.txt");
}

// static
const base::FilePath::StringType
AccessibilityTreeFormatter::GetExpectedFileSuffix() {
  return FILE_PATH_LITERAL("-expected-win.txt");
}

// static
const std::string AccessibilityTreeFormatter::GetAllowEmptyString() {
  return "@WIN-ALLOW-EMPTY:";
}

// static
const std::string AccessibilityTreeFormatter::GetAllowString() {
  return "@WIN-ALLOW:";
}

// static
const std::string AccessibilityTreeFormatter::GetDenyString() {
  return "@WIN-DENY:";
}

}  // namespace content
<commit_msg>Cleanup of accessibility_tree_formatter_win.cc.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/accessibility/accessibility_tree_formatter.h"

#include <oleacc.h>

#include <string>

#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "content/browser/accessibility/accessibility_tree_formatter_utils_win.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/browser_accessibility_win.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/base/win/atl_module.h"

using base::StringPrintf;

namespace content {

const char* ALL_ATTRIBUTES[] = {
    "name",
    "value",
    "states",
    "attributes",
    "role_name",
    "currentValue",
    "minimumValue",
    "maximumValue",
    "description",
    "default_action",
    "keyboard_shortcut",
    "location",
    "size",
    "index_in_parent",
    "n_relations",
    "group_level",
    "similar_items_in_group",
    "position_in_group",
    "table_rows",
    "table_columns",
    "row_index",
    "column_index",
    "n_characters",
    "caret_offset",
    "n_selections",
    "selection_start",
    "selection_end"
};

void AccessibilityTreeFormatter::Initialize() {
  ui::win::CreateATLModuleIfNeeded();
}

void AccessibilityTreeFormatter::AddProperties(
    const BrowserAccessibility& node, base::DictionaryValue* dict) {
  dict->SetInteger("id", node.GetId());
  BrowserAccessibilityWin* ax_object =
      const_cast<BrowserAccessibility*>(&node)->ToBrowserAccessibilityWin();
  DCHECK(ax_object);

  VARIANT variant_self;
  variant_self.vt = VT_I4;
  variant_self.lVal = CHILDID_SELF;

  dict->SetString("role", IAccessible2RoleToString(ax_object->ia2_role()));

  base::win::ScopedBstr temp_bstr;
  if (SUCCEEDED(ax_object->get_accName(variant_self, temp_bstr.Receive())))
    dict->SetString("name", base::string16(temp_bstr, temp_bstr.Length()));
  temp_bstr.Reset();

  if (SUCCEEDED(ax_object->get_accValue(variant_self, temp_bstr.Receive())))
    dict->SetString("value", base::string16(temp_bstr, temp_bstr.Length()));
  temp_bstr.Reset();

  std::vector<base::string16> state_strings;
  int32 ia_state = ax_object->ia_state();

  // Avoid flakiness: these states depend on whether the window is focused
  // and the position of the mouse cursor.
  ia_state &= ~STATE_SYSTEM_HOTTRACKED;
  ia_state &= ~STATE_SYSTEM_OFFSCREEN;

  IAccessibleStateToStringVector(ia_state, &state_strings);
  IAccessible2StateToStringVector(ax_object->ia2_state(), &state_strings);
  base::ListValue* states = new base::ListValue;
  for (auto it = state_strings.begin(); it != state_strings.end(); ++it)
    states->AppendString(base::UTF16ToUTF8(*it));
  dict->Set("states", states);

  const std::vector<base::string16>& ia2_attributes =
      ax_object->ia2_attributes();
  base::ListValue* attributes = new base::ListValue;
  for (auto it = ia2_attributes.begin(); it != ia2_attributes.end(); ++it)
    attributes->AppendString(base::UTF16ToUTF8(*it));
  dict->Set("attributes", attributes);

  dict->SetString("role_name", ax_object->role_name());

  VARIANT currentValue;
  if (ax_object->get_currentValue(&currentValue) == S_OK)
    dict->SetDouble("currentValue", V_R8(&currentValue));

  VARIANT minimumValue;
  if (ax_object->get_minimumValue(&minimumValue) == S_OK)
    dict->SetDouble("minimumValue", V_R8(&minimumValue));

  VARIANT maximumValue;
  if (ax_object->get_maximumValue(&maximumValue) == S_OK)
    dict->SetDouble("maximumValue", V_R8(&maximumValue));

  if (SUCCEEDED(ax_object->get_accDescription(variant_self,
      temp_bstr.Receive()))) {
    dict->SetString("description", base::string16(temp_bstr,
        temp_bstr.Length()));
  }
  temp_bstr.Reset();

  if (SUCCEEDED(ax_object->get_accDefaultAction(variant_self,
      temp_bstr.Receive()))) {
    dict->SetString("default_action", base::string16(temp_bstr,
        temp_bstr.Length()));
  }
  temp_bstr.Reset();

  if (SUCCEEDED(
      ax_object->get_accKeyboardShortcut(variant_self, temp_bstr.Receive()))) {
    dict->SetString("keyboard_shortcut", base::string16(temp_bstr,
        temp_bstr.Length()));
  }
  temp_bstr.Reset();

  if (SUCCEEDED(ax_object->get_accHelp(variant_self, temp_bstr.Receive())))
    dict->SetString("help", base::string16(temp_bstr, temp_bstr.Length()));
  temp_bstr.Reset();

  BrowserAccessibility* root = node.manager()->GetRoot();
  LONG left, top, width, height;
  LONG root_left, root_top, root_width, root_height;
  if (SUCCEEDED(ax_object->accLocation(
          &left, &top, &width, &height, variant_self)) &&
      SUCCEEDED(root->ToBrowserAccessibilityWin()->accLocation(
          &root_left, &root_top, &root_width, &root_height, variant_self))) {
    base::DictionaryValue* location = new base::DictionaryValue;
    location->SetInteger("x", left - root_left);
    location->SetInteger("y", top - root_top);
    dict->Set("location", location);

    base::DictionaryValue* size = new base::DictionaryValue;
    size->SetInteger("width", width);
    size->SetInteger("height", height);
    dict->Set("size", size);
  }

  LONG index_in_parent;
  if (SUCCEEDED(ax_object->get_indexInParent(&index_in_parent)))
    dict->SetInteger("index_in_parent", index_in_parent);

  LONG n_relations;
  if (SUCCEEDED(ax_object->get_nRelations(&n_relations)))
    dict->SetInteger("n_relations", n_relations);

  LONG group_level, similar_items_in_group, position_in_group;
  if (SUCCEEDED(ax_object->get_groupPosition(&group_level,
                                 &similar_items_in_group,
                                 &position_in_group))) {
    dict->SetInteger("group_level", group_level);
    dict->SetInteger("similar_items_in_group", similar_items_in_group);
    dict->SetInteger("position_in_group", position_in_group);
  }

  LONG table_rows;
  if (SUCCEEDED(ax_object->get_nRows(&table_rows)))
    dict->SetInteger("table_rows", table_rows);

  LONG table_columns;
  if (SUCCEEDED(ax_object->get_nRows(&table_columns)))
    dict->SetInteger("table_columns", table_columns);

  LONG row_index;
  if (SUCCEEDED(ax_object->get_rowIndex(&row_index)))
    dict->SetInteger("row_index", row_index);

  LONG column_index;
  if (SUCCEEDED(ax_object->get_columnIndex(&column_index)))
    dict->SetInteger("column_index", column_index);

  LONG n_characters;
  if (SUCCEEDED(ax_object->get_nCharacters(&n_characters)))
    dict->SetInteger("n_characters", n_characters);

  LONG caret_offset;
  if (ax_object->get_caretOffset(&caret_offset) == S_OK)
    dict->SetInteger("caret_offset", caret_offset);

  LONG n_selections;
  if (SUCCEEDED(ax_object->get_nSelections(&n_selections))) {
    dict->SetInteger("n_selections", n_selections);
    if (n_selections > 0) {
      LONG start, end;
      if (SUCCEEDED(ax_object->get_selection(0, &start, &end))) {
        dict->SetInteger("selection_start", start);
        dict->SetInteger("selection_end", end);
      }
    }
  }
}

base::string16 AccessibilityTreeFormatter::ToString(
    const base::DictionaryValue& dict) {
  base::string16 line;

  if (show_ids_) {
    int id_value;
    dict.GetInteger("id", &id_value);
    WriteAttribute(true, base::IntToString16(id_value), &line);
  }

  base::string16 role_value;
  dict.GetString("role", &role_value);
  WriteAttribute(true, base::UTF16ToUTF8(role_value), &line);

  for (int i = 0; i < arraysize(ALL_ATTRIBUTES); i++) {
    const char* attribute_name = ALL_ATTRIBUTES[i];
    const base::Value* value;
    if (!dict.Get(attribute_name, &value))
      continue;

    switch (value->GetType()) {
      case base::Value::TYPE_STRING: {
        base::string16 string_value;
        value->GetAsString(&string_value);
        WriteAttribute(false,
                       StringPrintf(L"%ls='%ls'",
                                    base::UTF8ToUTF16(attribute_name).c_str(),
                                    string_value.c_str()),
                       &line);
        break;
      }
      case base::Value::TYPE_INTEGER: {
        int int_value;
        value->GetAsInteger(&int_value);
        WriteAttribute(false,
                       base::StringPrintf(L"%ls=%d",
                                          base::UTF8ToUTF16(
                                              attribute_name).c_str(),
                                          int_value),
                       &line);
        break;
      }
      case base::Value::TYPE_DOUBLE: {
        double double_value;
        value->GetAsDouble(&double_value);
        WriteAttribute(false,
                       base::StringPrintf(L"%ls=%.2f",
                                          base::UTF8ToUTF16(
                                              attribute_name).c_str(),
                                          double_value),
                       &line);
        break;
      }
      case base::Value::TYPE_LIST: {
        // Currently all list values are string and are written without
        // attribute names.
        const base::ListValue* list_value;
        value->GetAsList(&list_value);
        for (base::ListValue::const_iterator it = list_value->begin();
             it != list_value->end();
             ++it) {
          base::string16 string_value;
          if ((*it)->GetAsString(&string_value))
            WriteAttribute(false, string_value, &line);
        }
        break;
      }
      case base::Value::TYPE_DICTIONARY: {
        // Currently all dictionary values are coordinates.
        // Revisit this if that changes.
        const base::DictionaryValue* dict_value;
        value->GetAsDictionary(&dict_value);
        if (strcmp(attribute_name, "size") == 0) {
          WriteAttribute(false,
                         FormatCoordinates("size", "width", "height",
                                           *dict_value),
                         &line);
        } else if (strcmp(attribute_name, "location") == 0) {
          WriteAttribute(false,
                         FormatCoordinates("location", "x", "y", *dict_value),
                         &line);
        }
        break;
      }
      default:
        NOTREACHED();
        break;
    }
  }

  return line;
}

// static
const base::FilePath::StringType
AccessibilityTreeFormatter::GetActualFileSuffix() {
  return FILE_PATH_LITERAL("-actual-win.txt");
}

// static
const base::FilePath::StringType
AccessibilityTreeFormatter::GetExpectedFileSuffix() {
  return FILE_PATH_LITERAL("-expected-win.txt");
}

// static
const std::string AccessibilityTreeFormatter::GetAllowEmptyString() {
  return "@WIN-ALLOW-EMPTY:";
}

// static
const std::string AccessibilityTreeFormatter::GetAllowString() {
  return "@WIN-ALLOW:";
}

// static
const std::string AccessibilityTreeFormatter::GetDenyString() {
  return "@WIN-DENY:";
}

}  // namespace content
<|endoftext|>


<commit_before>#include "set_battery.hpp"
#include "file_to.hpp"
#include <string.h>
#include <time.h>

using namespace std;

int set_battery (bar_config &my_bar_config) {
    int return_value = 99;
    string path, status, width;
    long e_now, e_full ,p_now, seconds;
    char buffer[128];
    tm *tpoint;
    path = my_bar_config.input.device + "/capacity";
    if (!file_to_int (path.c_str(), my_bar_config.output.integer)) {
        return_value = -1;
        goto close;
    }
    path = my_bar_config.input.device + "/power_now";
    if (!file_to_long (path.c_str(), p_now)) {
        return_value = 1;
        goto close;
    }
    if (p_now != 0) {
        path = my_bar_config.input.device + "/status";
        if (!file_to_string (path.c_str(), status)) {
            return_value = 2;
            goto close;
        }
        path = my_bar_config.input.device + "/energy_now";
        if (!file_to_long (path.c_str(), e_now)) {
            return_value = 3;
            goto close;
        }
        if (strcmp (status.c_str(), "Discharging\n") == 0)
            seconds = e_now * 3600 / p_now;
        else {
            path = my_bar_config.input.device + "/energy_full";
            if (!file_to_long (path.c_str(), e_full)) {
                return_value = 4;
                goto close;
            }
            seconds = (e_full - e_now) * 3600 / p_now;
        }
    } else
        seconds = 0;
    tpoint = gmtime (&seconds);
    strftime (buffer, 128, "%H:%M", tpoint);
    my_bar_config.output.output = buffer;
    my_bar_config.output.output += " " + to_string (my_bar_config.output.integer) + "%";
    my_bar_config.output.integer = 100 - my_bar_config.output.integer;
    return_value = 0;
close:
    return return_value;
}
<commit_msg>fix charging battery color<commit_after>#include "set_battery.hpp"
#include "file_to.hpp"
#include <string.h>
#include <time.h>

using namespace std;

int set_battery (bar_config &my_bar_config) {
    bool charging = false;
    int return_value = 99;
    string path, status, width;
    long e_now, e_full ,p_now, seconds;
    char buffer[128];
    tm *tpoint;
    path = my_bar_config.input.device + "/capacity";
    if (!file_to_int (path.c_str(), my_bar_config.output.integer)) {
        return_value = -1;
        goto close;
    }
    path = my_bar_config.input.device + "/power_now";
    if (!file_to_long (path.c_str(), p_now)) {
        return_value = 1;
        goto close;
    }
    if (p_now != 0) {
        path = my_bar_config.input.device + "/status";
        if (!file_to_string (path.c_str(), status)) {
            return_value = 2;
            goto close;
        }
        path = my_bar_config.input.device + "/energy_now";
        if (!file_to_long (path.c_str(), e_now)) {
            return_value = 3;
            goto close;
        }
        if (strcmp (status.c_str(), "Discharging\n") == 0)
            seconds = e_now * 3600 / p_now;
        else {
            charging = true;
            path = my_bar_config.input.device + "/energy_full";
            if (!file_to_long (path.c_str(), e_full)) {
                return_value = 4;
                goto close;
            }
            seconds = (e_full - e_now) * 3600 / p_now;
        }
    } else
        seconds = 0;
    tpoint = gmtime (&seconds);
    strftime (buffer, 128, "%H:%M", tpoint);
    my_bar_config.output.output = buffer;
    my_bar_config.output.output += " " + to_string (my_bar_config.output.integer) + "%";
    if (charging)
        my_bar_config.output.integer = -1;
    else
        my_bar_config.output.integer = 100 - my_bar_config.output.integer;
    return_value = 0;
close:
    return return_value;
}
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Tracked vehicle model built from subsystems.
//  Location of subsystems hard-coded for M113 vehicle
//  TODO: specify this w/ JSON input data file
//
// =============================================================================

#include <cstdio>

#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "physics/ChGlobal.h"

#include "TrackVehicle.h"

#include "subsys/trackSystem/TrackSystem.h"
#include "subsys/driveline/TrackDriveline.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables
const size_t TrackVehicle::m_num_tracks = 2;    // number of trackSystems to create
const size_t TrackVehicle::m_num_engines = 1;   // number of powertrains (and drivelines) to create

const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, 0.83475);   // relative to chassis c-sys
const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475);  //

const double     TrackVehicle::m_mass = 5489.2;   // chassis sprung mass
const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0., 0.);  // COM location, relative to body Csys REF frame
const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2);  // chassis inertia (roll,yaw,pitch)

const std::string TrackVehicle::m_meshName("M113_mesh");
const std::string TrackVehicle::m_meshFile = utils::GetModelDataFile("data/M113_hull.obj");
const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));
const ChVector<> TrackVehicle::m_chassisBoxSize(4.0 *0.5, 2.0 *0.5, 3.0 *0.5);  // length, height, width HALF DIMS

/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
TrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide)
  : m_vis(chassisVis), m_collide(chassisCollide)
{
  // Integration and Solver settings
  SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
  SetIterLCPmaxItersSpeed(150);
  SetIterLCPmaxItersStab(150);
  SetMaxPenetrationRecoverySpeed(4.0);

  // create the chassis body
  m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);
  m_chassis->SetIdentifier(0);
  m_chassis->SetNameString(name);
  m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));
  // basic body info
  m_chassis->SetMass(m_mass);
  m_chassis->SetInertiaXX(m_inertia);

  // add visualization assets to the chassis
  AddVisualization();

  m_chassis->SetBodyFixed(false);
  // add the chassis body to the system
  Add(m_chassis);

  // resize all vectors for the number of track systems
  m_TrackSystems.resize(m_num_tracks);
  m_TrackSystem_locs.resize(m_num_tracks);
  // Right and Left track System relative locations, respectively
  m_TrackSystem_locs[0] = m_trackPos_Right;
  m_TrackSystem_locs[1] = m_trackPos_Left;

  // Each trackSystem has its own driveline and powertrain, so the left and right
  // sides can have power applied independently
  m_drivelines.resize(m_num_tracks);
  m_ptrains.resize(m_num_tracks);

  // create track systems
  for (int i = 0; i < m_num_tracks; i++) {
    m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i));
  }

  // create the powertrain and drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j))  );
    m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) );

  }

  // TODO: add brakes. Perhaps they are a part of the suspension subsystem?

}

// Set any collision geometry on the hull, then Initialize() all subsystems
void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)
{
  // move the chassis REF frame to the specified initial position/orientation
  m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));

  // add collision geometry to the chassis
  AddCollisionGeometry();

  // initialize the subsystems with the initial c-sys and specified offsets
  for (int i = 0; i < m_num_tracks; i++)
  {
    m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);
  }

  // initialize the powertrain, drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    size_t driveGear_L_idx = 2*j;
    size_t driveGear_R_idx = 2*j + 1;
    m_drivelines[j]->Initialize(m_chassis,
      m_TrackSystems[driveGear_L_idx]->GetDriveGear(),
      m_TrackSystems[driveGear_R_idx]->GetDriveGear());
    m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());
  }

}

void TrackVehicle::Update(double	time,
                          const std::vector<double>&  throttle,
                          const std::vector<double>&  braking)
{

  // update left and right powertrains, with the new left and right throttle/shaftspeed
  m_ptrains[0]->Update(time, throttle[0], m_drivelines[0]->GetDriveshaftSpeed() );
  m_ptrains[1]->Update(time, throttle[1], m_drivelines[1]->GetDriveshaftSpeed() );
}

void TrackVehicle::AddVisualization()
{
  // add visual geometry asset to the chassis, if enabled
  switch (m_vis) {
  case VisualizationType::PRIMITIVES:
  {
    // put a sphere at the chassis COM and at the REF point
    ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape);
    COMsphere->GetSphereGeometry().rad = 0.1;
    COMsphere->Pos = m_COM;
    // make the COM sphere blue
    COMsphere->SetColor(ChColor(0.1f, 0.2f, 0.8f));
    m_chassis->AddAsset(COMsphere);

    ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape);
    REFsphere->GetSphereGeometry().rad = 0.1;
    REFsphere->Pos = ChVector<>(0,0,0); // REF should be at the body c-sys origin
    // make the REF sphere red
    REFsphere->SetColor(ChColor(0.8f, 0.2f, 0.1f));
    m_chassis->AddAsset(REFsphere);

    break;
  }
  case VisualizationType::MESH:
  {
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(utils::GetModelDataFile(m_meshFile), false, false);

    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(trimesh);
    trimesh_shape->SetName("chassis triMesh");
    m_chassis->AddAsset(trimesh_shape);

    break;
  }
  } // end switch

}

void TrackVehicle::AddCollisionGeometry()
{
  // add collision geometrey to the chassis, if enabled
  m_chassis->SetCollide(true);
  m_chassis->GetCollisionModel()->ClearModel();

  switch (m_collide) {
  case CollisionType::PRIMITIVES:
  {
    // use a simple box
    m_chassis->GetCollisionModel()->AddBox(m_chassisBoxSize.x, m_chassisBoxSize.y, m_chassisBoxSize.z);

    break;
  }
  case CollisionType::MESH:
  {
    // use a triangle mesh

		geometry::ChTriangleMeshSoup temp_trianglemesh;

    // TODO: fill the triangleMesh here with some track shoe geometry

		m_chassis->GetCollisionModel()->SetSafeMargin(0.004);	// inward safe margin
		m_chassis->GetCollisionModel()->SetEnvelope(0.010);		// distance of the outward "collision envelope"
		m_chassis->GetCollisionModel()->ClearModel();

    // is there an offset??
    double shoelength = 0.2;
    ChVector<> mesh_displacement(shoelength*0.5,0,0);  // since mesh origin is not in body center of mass
    m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);

    break;
  }
  case CollisionType::CONVEXHULL:
  {
    // use convex hulls, loaded from file
    ChStreamInAsciiFile chull_file(GetChronoDataFile("track_shoe.chulls").c_str());
    // transform the collision geometry as needed
    double mangle = 45.0; // guess
    ChQuaternion<>rot;
    rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
    ChMatrix33<> rot_offset(rot);
    ChVector<> disp_offset(0,0,0);  // no displacement offset
    m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
    break;
  }
  } // end switch

  // set the collision family
  m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL );
  // don't collide with rolling elements or tracks
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::GEARS) );
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) );
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) );

  m_chassis->GetCollisionModel()->BuildModel();
}

void TrackVehicle::Advance(double step)
{
  double t = 0;
  while (t < step) {
    double h = std::min<>(m_stepsize, step - t);
    DoStepDynamics(h);
    t += h;
  }
}

} // end namespace chrono
<commit_msg>spacing<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Tracked vehicle model built from subsystems.
//  Location of subsystems hard-coded for M113 vehicle
//  TODO: specify this w/ JSON input data file
//
// =============================================================================

#include <cstdio>

#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"
#include "physics/ChGlobal.h"

#include "TrackVehicle.h"

#include "subsys/trackSystem/TrackSystem.h"
#include "subsys/driveline/TrackDriveline.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables
const size_t TrackVehicle::m_num_tracks = 2;    // number of trackSystems to create
const size_t TrackVehicle::m_num_engines = 1;   // number of powertrains (and drivelines) to create

const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, 0.83475);   // relative to chassis c-sys
const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475);  //

const double     TrackVehicle::m_mass = 5489.2;   // chassis sprung mass
const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0., 0.);  // COM location, relative to body Csys REF frame
const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2);  // chassis inertia (roll,yaw,pitch)

const std::string TrackVehicle::m_meshName("M113_mesh");
const std::string TrackVehicle::m_meshFile = utils::GetModelDataFile("data/M113_hull.obj");
const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));
const ChVector<> TrackVehicle::m_chassisBoxSize(4.0 *0.5, 2.0 *0.5, 3.0 *0.5);  // length, height, width HALF DIMS

/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
TrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide)
  : m_vis(chassisVis), m_collide(chassisCollide)
{
  // Integration and Solver settings
  SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
  SetIterLCPmaxItersSpeed(150);
  SetIterLCPmaxItersStab(150);
  SetMaxPenetrationRecoverySpeed(4.0);

  // create the chassis body
  m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);
  m_chassis->SetIdentifier(0);
  m_chassis->SetNameString(name);
  m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));
  // basic body info
  m_chassis->SetMass(m_mass);
  m_chassis->SetInertiaXX(m_inertia);

  // add visualization assets to the chassis
  AddVisualization();

  m_chassis->SetBodyFixed(false);
  // add the chassis body to the system
  Add(m_chassis);

  // resize all vectors for the number of track systems
  m_TrackSystems.resize(m_num_tracks);
  m_TrackSystem_locs.resize(m_num_tracks);
  // Right and Left track System relative locations, respectively
  m_TrackSystem_locs[0] = m_trackPos_Right;
  m_TrackSystem_locs[1] = m_trackPos_Left;

  // Each trackSystem has its own driveline and powertrain, so the left and right
  // sides can have power applied independently
  m_drivelines.resize(m_num_tracks);
  m_ptrains.resize(m_num_tracks);

  // create track systems
  for (int i = 0; i < m_num_tracks; i++) {
    m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i) );
  }

  // create the powertrain and drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j)) );
    m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) );

  }

  // TODO: add brakes. Perhaps they are a part of the suspension subsystem?

}

// Set any collision geometry on the hull, then Initialize() all subsystems
void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)
{
  // move the chassis REF frame to the specified initial position/orientation
  m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));

  // add collision geometry to the chassis
  AddCollisionGeometry();

  // initialize the subsystems with the initial c-sys and specified offsets
  for (int i = 0; i < m_num_tracks; i++)
  {
    m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);
  }

  // initialize the powertrain, drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    size_t driveGear_L_idx = 2*j;
    size_t driveGear_R_idx = 2*j + 1;
    m_drivelines[j]->Initialize(m_chassis,
      m_TrackSystems[driveGear_L_idx]->GetDriveGear(),
      m_TrackSystems[driveGear_R_idx]->GetDriveGear());
    m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());
  }

}

void TrackVehicle::Update(double	time,
                          const std::vector<double>&  throttle,
                          const std::vector<double>&  braking)
{

  // update left and right powertrains, with the new left and right throttle/shaftspeed
  m_ptrains[0]->Update(time, throttle[0], m_drivelines[0]->GetDriveshaftSpeed() );
  m_ptrains[1]->Update(time, throttle[1], m_drivelines[1]->GetDriveshaftSpeed() );
}

void TrackVehicle::AddVisualization()
{
  // add visual geometry asset to the chassis, if enabled
  switch (m_vis) {
  case VisualizationType::PRIMITIVES:
  {
    // put a sphere at the chassis COM and at the REF point
    ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape);
    COMsphere->GetSphereGeometry().rad = 0.1;
    COMsphere->Pos = m_COM;
    // make the COM sphere blue
    COMsphere->SetColor(ChColor(0.1f, 0.2f, 0.8f));
    m_chassis->AddAsset(COMsphere);

    ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape);
    REFsphere->GetSphereGeometry().rad = 0.1;
    REFsphere->Pos = ChVector<>(0,0,0); // REF should be at the body c-sys origin
    // make the REF sphere red
    REFsphere->SetColor(ChColor(0.8f, 0.2f, 0.1f));
    m_chassis->AddAsset(REFsphere);

    break;
  }
  case VisualizationType::MESH:
  {
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(utils::GetModelDataFile(m_meshFile), false, false);

    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(trimesh);
    trimesh_shape->SetName("chassis triMesh");
    m_chassis->AddAsset(trimesh_shape);

    break;
  }
  } // end switch

}

void TrackVehicle::AddCollisionGeometry()
{
  // add collision geometrey to the chassis, if enabled
  m_chassis->SetCollide(true);
  m_chassis->GetCollisionModel()->ClearModel();

  switch (m_collide) {
  case CollisionType::PRIMITIVES:
  {
    // use a simple box
    m_chassis->GetCollisionModel()->AddBox(m_chassisBoxSize.x, m_chassisBoxSize.y, m_chassisBoxSize.z);

    break;
  }
  case CollisionType::MESH:
  {
    // use a triangle mesh

		geometry::ChTriangleMeshSoup temp_trianglemesh;

    // TODO: fill the triangleMesh here with some track shoe geometry

		m_chassis->GetCollisionModel()->SetSafeMargin(0.004);	// inward safe margin
		m_chassis->GetCollisionModel()->SetEnvelope(0.010);		// distance of the outward "collision envelope"
		m_chassis->GetCollisionModel()->ClearModel();

    // is there an offset??
    double shoelength = 0.2;
    ChVector<> mesh_displacement(shoelength*0.5,0,0);  // since mesh origin is not in body center of mass
    m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);

    break;
  }
  case CollisionType::CONVEXHULL:
  {
    // use convex hulls, loaded from file
    ChStreamInAsciiFile chull_file(GetChronoDataFile("track_shoe.chulls").c_str());
    // transform the collision geometry as needed
    double mangle = 45.0; // guess
    ChQuaternion<>rot;
    rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
    ChMatrix33<> rot_offset(rot);
    ChVector<> disp_offset(0,0,0);  // no displacement offset
    m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
    break;
  }
  } // end switch

  // set the collision family
  m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL );
  // don't collide with rolling elements or tracks
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::GEARS) );
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) );
  m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) );

  m_chassis->GetCollisionModel()->BuildModel();
}

void TrackVehicle::Advance(double step)
{
  double t = 0;
  while (t < step) {
    double h = std::min<>(m_stepsize, step - t);
    DoStepDynamics(h);
    t += h;
  }
}

} // end namespace chrono
<|endoftext|>