Esempio n. 1
0
void assert_no_locals(name const & n, expr const & e) {
     if (!has_local(e))
        return;
    collected_locals ls;
    collect_locals(e, ls);

    lean_trace(name({"debug", "inductive_compiler"}),
               tout() << "\n\nerror: found locals in '" << n << "'\n" << e << "\n";
               for (expr const & l : ls.get_collected()) {
                   tout() << mlocal_name(l) << "." << mlocal_pp_name(l) << " : " << mlocal_type(l) << "\n";
               });
Esempio n. 2
0
bool KMLpdManager::savePrinttoolCfgFile(const QString& templatefile, const QString& dirname, const QMap<QString,QString>& options)
{
	// defines input and output file
	QString	fname = QFileInfo(templatefile).fileName();
	fname.replace(QRegExp("\\.in$"),QString::fromLatin1(""));
	QFile	fin(templatefile);
	QFile	fout(dirname + "/" + fname);
	if (fin.exists() && fin.open(IO_ReadOnly) && fout.open(IO_WriteOnly))
	{
		QTextStream	tin(&fin), tout(&fout);
		QString		line, name;
		int		p(-1);
		while (!tin.eof())
		{
			line = tin.readLine().stripWhiteSpace();
			if (line.isEmpty() || line[0] == '#')
			{
				tout << line << endl;
				continue;
			}
			if (line.startsWith("export "))
			{
				tout << "export ";
				line.replace(0,7,QString::fromLatin1(""));
			}
			if ((p=line.find('=')) != -1)
			{
				name = line.left(p);
				tout << name << '=' << options[name] << endl;
			}
		}
		return true;
	}
	else return false;
}
Esempio n. 3
0
 /** \brief Return true iff all recursive applications in \c e are structurally smaller than \c m_pattern. */
 bool check_rhs(expr const & e) {
     switch (e.kind()) {
     case expr_kind::Var:   case expr_kind::Meta:
     case expr_kind::Local: case expr_kind::Constant:
     case expr_kind::Sort:
         return true;
     case expr_kind::Macro:
         for (unsigned i = 0; i < macro_num_args(e); i++)
             if (!check_rhs(macro_arg(e, i)))
                 return false;
         return true;
     case expr_kind::App: {
         buffer<expr> args;
         expr const & fn = get_app_args(e, args);
         if (!check_rhs(fn))
             return false;
         for (unsigned i = 0; i < args.size(); i++)
             if (!check_rhs(args[i]))
                 return false;
         if (is_local(fn) && mlocal_name(fn) == mlocal_name(m_fn)) {
             /* recusive application */
             if (m_arg_idx < args.size()) {
                 expr const & arg = args[m_arg_idx];
                 /* arg must be structurally smaller than m_pattern */
                 if (!is_lt(arg, m_pattern)) {
                     trace_struct_aux(tout() << "structural recursion on argument #" << (m_arg_idx+1)
                                      << " was not used "
                                      << "for '" << m_fn << "'\nargument #" << (m_arg_idx+1)
                                      << " in the application\n  "
                                      << e << "\nis not structurally smaller than the one occurring in "
                                      << "the equation left-hand-side\n  "
                                      << m_lhs << "\n";);
                     return false;
                 }
             } else {
Esempio n. 4
0
    RunEnvironment::~RunEnvironment()
    {
      if (!m_processCommandLine_invoked)
        {
          throw std::runtime_error("RunEnvironment:: you must now invoke processCommandLine after constructing a RunEnvironment");
        }
      stk_classic::report_deferred_messages(m_comm);

      // Stop stk_percept root timer
      timer().stop();

      stk_classic::diag::printTimersTable(out(), timer(), stk_classic::diag::METRICS_CPU_TIME | stk_classic::diag::METRICS_WALL_TIME, false, m_comm);

      stk_classic::diag::deleteRootTimer(timer());

      static_cast<stk_classic::indent_streambuf *>(dwout().rdbuf())->redirect(std::cout.rdbuf());

      stk_classic::unregister_ostream(tout());
      stk_classic::unregister_ostream(dout());
      stk_classic::unregister_ostream(pout());
      stk_classic::unregister_ostream(out());

      stk_classic::unregister_log_ostream(std::cerr);
      stk_classic::unregister_log_ostream(std::cout);

      if (m_argv_new) delete[] m_argv_new;
      if (m_argv) delete[] m_argv;

      if (m_need_to_finalize) {
        //stk_classic::parallel_machine_finalize();
      }
    }
Esempio n. 5
0
void DatabaseDlg::SaveDefault()
{	
	if (!m_dbtree) return;

	wxString expath = wxStandardPaths::Get().GetExecutablePath();
	expath = expath.BeforeLast(GETSLASH(),NULL);
#ifdef _WIN32
	wxString dft = expath + "\\catalog_list.set";
	wxString dft2 = wxStandardPaths::Get().GetUserConfigDir() + "\\catalog_list.set";
	if (!wxFileExists(dft) && wxFileExists(dft2))
		dft = dft2;
#else
    wxString dft = expath + "/../Resources/" + "catalog_list.set";
#endif
	wxFileOutputStream os(dft);
	if (os.IsOk())
	{
		wxTextOutputStream tout(os);

		std::vector<DBCatalog> *cat = m_dbtree->GetCatalogDataIndex();
		if (cat && !cat->empty())
		{
			for (int i = 0; i < cat->size(); i++)
				tout << (*cat)[i].path << "\n";
		}
	}
}
Esempio n. 6
0
 virtual void BeforeBackprop(const std::vector<layer::Node<xpu>*> &nodes_in,
                             const std::vector<layer::Node<xpu>*> &nodes_out) {
   if (fullc_gather != 0) {
     utils::Check(update_on_server == 0, "GatherUpdate can not use update_on_server");
     utils::Check(nodes_in.size() == 1, "fullc_gather can only work with fullc");
     utils::Check(nodes_out.size() == 1, "fullc_gather can only work with fullc");
     mshadow::Tensor<xpu, 2> in = nodes_in[0]->mat();
     mshadow::Tensor<xpu, 2> out = nodes_out[0]->mat();
     num_in = in.size(1); num_out = out.size(1);
     tnode.Resize(mshadow::Shape2(total_batch_size, num_in + num_out));      
     // manually hslice
     mshadow::Tensor<xpu, 2> tin(tnode.dptr_,
                                 mshadow::Shape2(total_batch_size, num_in),
                                 tnode.stride_, tnode.stream_);
     mshadow::Tensor<xpu, 2> tout(tnode.dptr_ + num_in,
                                  mshadow::Shape2(total_batch_size, num_out),
                                  tnode.stride_, tnode.stream_);
     local_batch_size = in.size(0);
     utils::Check(local_batch_size <= total_batch_size,
                  "local_batch_size bigger than total_batch_size");
     utils::Check(total_batch_size % local_batch_size == 0,
                  "when you use fullc_gather mode, the batch_size "\
                  "must be multiple of number of devices");
     mshadow::Copy(tin.Slice(0, local_batch_size), in, tnode.stream_);
     mshadow::Copy(tout.Slice(0, local_batch_size), out, tnode.stream_);      
   }
 }
Esempio n. 7
0
 inline void CalcDelta(mshadow::Stream<xpu> *stream) {
   dw.set_stream(stream);
   mshadow::Tensor<xpu, 2> tin(tnode.dptr_,
                               mshadow::Shape2(total_batch_size, num_in),
                               tnode.stride_, stream);
   mshadow::Tensor<xpu, 2> tout(tnode.dptr_ + num_in,
                                mshadow::Shape2(total_batch_size, num_out),
                                tnode.stride_, stream);
   dw += dot(tout.T(), tin);
 }
Esempio n. 8
0
void discr_tree::insert_erase(expr const & k, expr const & v, bool ins) {
    // insert & erase operations.
    // The erase operation is not optimal because it does not eliminate dead branches from the tree.
    // If this becomes an issue, we can remove dead branches from time to time and/or reconstruct
    // the tree from time to time.
    buffer<pair<expr, bool>> todo;
    buffer<pair<node, node>> skip;
    todo.push_back(mk_pair(k, false));
    m_root = insert_erase(m_root.steal(), true, todo, v, skip, ins);
    lean_trace("discr_tree", tout() << "\n"; trace(););
void ApprExpansionDatabase::doWrite(wxOutputStream& out) {
	wxTextOutputStream tout(out, wxEOL_DOS);
	// write in order first
	FOR_EACH(c, order) {
		String code = c;
		if (code.GetChar(0) != _('-')) {
			// but not the rarities
			tout << code << _("-") << expansions[c] << _("\n");
			expansions.erase(c);
		}
	}
int MainWindow::createImportParameterFile( const QString &s_FilenameParameterImport, const int i_Codec, const bool b_match_against_WoRMS, QStringList &sl_ListParameterNew )
{
    QFile fout( s_FilenameParameterImport );

    if ( !fout.open( QIODevice::WriteOnly | QIODevice::Text ) )
        return( -121 );

    QTextStream tout( &fout );

    switch ( i_Codec )
    {
    case _SYSTEM_: // nothing
        break;

    case _APPLEROMAN_:
        tout.setCodec( QTextCodec::codecForName( "Apple Roman" ) );
        break;

    case _LATIN1_:
        tout.setCodec( QTextCodec::codecForName( "ISO 8859-1" ) );
        break;

    default:
        tout.setCodec( QTextCodec::codecForName( "UTF-8" ) );
        break;
    }

// **********************************************************************************************

    tout << tr( "ParameterName\tAbbreviation\tUnit\tLowerLimit\tUpperLimit\tDefaultFormat\t" );
    tout << tr( "DefaultMethodID\tDefaultDataType\tReferenceID\tDescription\tURL Parameter" );

    if ( b_match_against_WoRMS == true )
        tout << tr( "\tSpecies name" );

    tout << endl;

    sl_ListParameterNew.sort();

    tout << sl_ListParameterNew.at( 0 ) << endl;

    if ( sl_ListParameterNew.count() > 1 )
    {
        for( int i=1; i<sl_ListParameterNew.count(); i++ )
        {
            if ( sl_ListParameterNew.at( i ) != sl_ListParameterNew.at( i-1 ) )
                tout << sl_ListParameterNew.at( i ) << endl;
        }
    }

    fout.close();

    return( _NOERROR_ );
}
Esempio n. 11
0
backward_lemma_index::backward_lemma_index(type_context & ctx):
    m_index(get_intro_attribute().get_instances_by_prio(ctx.env())) {
    buffer<name> lemmas;
    get_intro_attribute().get_instances(ctx.env(), lemmas);
    unsigned i = lemmas.size();
    while (i > 0) {
        --i;
        optional<head_index> target = get_backward_target(ctx, lemmas[i]);
        if (!target || target->kind() != expr_kind::Constant) {
            lean_trace(name({"tactic", "back_chaining"}),
                       tout() << "discarding [intro] lemma '" << lemmas[i] << "', failed to find target type\n";);
        } else {
Esempio n. 12
0
static int
handle_kqueue_timeout(struct poller *p,pollfd_state *state){
	typeof(state->timeoutfxn) tout = state->timeoutfxn;
	int ret = 0;

	if(tout == NULL){
		bitch("No timeout callback for POLLOUT on %d\n",state->pfd.fd);
	}else{
		ret |= tout(p,state);
	}
	return ret;
}
Esempio n. 13
0
/** Implement two different signatures:
    1) throwable -> options -> format
    2) throwable -> unit -> format */
vm_obj throwable_to_format(vm_obj const & _ex, vm_obj const & _opts) {
    throwable * ex = to_throwable(_ex);
    if (!ex)
        return to_obj(format("null-exception"));

    if (auto kex = dynamic_cast<ext_exception*>(ex)) {
        if (is_simple(_opts)) {
            io_state_stream ios = tout();
            formatter fmt = ios.get_formatter();
            return to_obj(kex->pp(fmt));
        } else {
            options opts = to_options(_opts);
            scope_trace_env scope1(opts);
            io_state_stream ios = tout();
            formatter fmt = ios.get_formatter();
            return to_obj(kex->pp(fmt));
        }
    } else if (auto fex = dynamic_cast<formatted_exception*>(ex)) {
        return to_obj(fex->pp());
    } else {
        return to_obj(format(ex->what()));
    }
}
Esempio n. 14
0
void ReachingDefAna::ComputeINOUTIterative(){
    BasicBlock* entry = *pr->get_begin();
    bool changed = true;
    int i = 0;
    do{
        map <BasicBlock*,bool> visitedFlag;
        queue <BasicBlock*> toVisit;    
        toVisit.push(entry);
        visitedFlag[entry] = true;
        cout<<"\n## Iteration "<<i++<<" ##\n";

        while(!toVisit.empty()){
            BasicBlock* cBB = toVisit.front();
            toVisit.pop();
            for(list<BasicBlock*>::iterator it = cBB->get_begin_succ(), end = cBB->get_end_succ(); it != end; ++it){
                if(visitedFlag.find(*it) == visitedFlag.end()){
                    toVisit.push(*it);
                    visitedFlag[*it] = true;
                }
            }
            bitvec in = cBB->getIn();
            bitvec out = cBB->getOut();
            bitvec tin(in.getSize()); 
            bitvec tout(out.getSize());
            for(list<BasicBlock*>::iterator pit = cBB->get_begin_pred(), pend = cBB->get_end_pred(); pit != pend; ++pit){
                tin = tin | (*pit)->getOut();
            }
            tout = tin - cBB->getKill();
            tout = tout | cBB->getGen();
            if( (in == tin) && (out == tout) )
                changed = false;
            else{
                changed = true;
                cBB->setIn(tin);
                cBB->setOut(tout);
            }
            printBB(cBB);
        } 
        //ts.append("1");
        string ts("Iteration");
        createDotFile(ts.append(std::to_string(i)));

    }while(changed);

}
Esempio n. 15
0
 bool is_cases_applicable(expr const & mvar, expr const & H) {
     type_context ctx = mk_type_context_for(mvar);
     expr t = whnf_inductive(ctx, ctx.infer(H));
     buffer<expr> args;
     expr const & fn = get_app_args(t, args);
     if (!is_constant(fn))
         return false;
     if (!is_ginductive(m_env, const_name(fn)))
         return false;
     if (!m_env.find(name{const_name(fn), "cases_on"}) || !m_env.find(get_eq_name()))
         return false;
     if (!m_env.find(get_heq_name()))
         return false;
     init_inductive_info(const_name(fn));
     if (args.size() != m_nindices + m_nparams)
         return false;
     lean_cases_trace(mvar, tout() << "inductive type: " << const_name(fn) <<
                      ", num. params: " << m_nparams << ", num. indices: " << m_nindices << "\n";);
Esempio n. 16
0
vm_obj caching_user_attribute_get_cache(vm_obj const &, vm_obj const & vm_attr, vm_obj const & vm_s) {
    tactic_state const & s       = to_tactic_state(vm_s);
    name const & n               = to_name(cfield(vm_attr, 0));
    vm_obj const & cache_handler = cfield(vm_attr, 2);
    list<name> const & deps      = to_list_name(cfield(vm_attr, 3));
    LEAN_TACTIC_TRY;
    environment const & env = s.env();
    attribute const & attr  = get_attribute(env, n);
    user_attr_cache & cache = get_user_attribute_cache();
    auto it = cache.m_cache.find(attr.get_name());
    if (it != cache.m_cache.end()) {
        if (it->second.m_fingerprint == attr.get_fingerprint(env) &&
            check_dep_fingerprints(env, deps, it->second.m_dep_fingerprints)) {
            return mk_tactic_success(it->second.m_val, s);
        }
        lean_trace("user_attributes_cache", tout() << "cached result for [" << attr.get_name() << "] "
                   << "has been found, but cache fingerprint does not match\n";);
    } else {
Esempio n. 17
0
static void trace_if_unsupported(type_context & ctx, expr const & fn,
                                 buffer<expr> const & args, unsigned prefix_sz, ss_param_infos const & result) {
    lean_assert(args.size() >= length(result));
    if (!is_fun_info_trace_enabled())
        return;
    fun_info info = get_fun_info(ctx, fn, args.size());
    buffer<param_info> pinfos;
    to_buffer(info.get_params_info(), pinfos);
    buffer<ss_param_info> ssinfos;
    to_buffer(get_subsingleton_info(ctx, fn, args.size()), ssinfos);
    lean_assert(pinfos.size() == ssinfos.size());
    /* Check if all remaining arguments are nondependent or
       dependent (but all forward dependencies are subsingletons) */
    unsigned i = prefix_sz;
    for (; i < pinfos.size(); i++) {
        param_info const & pinfo = pinfos[i];
        if (!pinfo.has_fwd_deps())
            continue; /* nondependent argument */
        if (has_nonsubsingleton_fwd_dep(i, pinfos, ssinfos))
            break; /* failed i-th argument has a forward dependent that is not a prop nor a subsingleton */
    }
    if (i == pinfos.size())
        return; // It is *cheap* case

    /* Expensive case */
    /* We generate a trace message IF it would be possible to compute more precise information.
       That is, there is an argument that is a proposition and/or subsingleton, but
       the corresponding pinfo is not a marked a prop/subsingleton.
    */
    i = 0;
    for (ss_param_info const & ssinfo : result) {
        if (ssinfo.is_subsingleton())
            continue;
        expr arg_type = ctx.infer(args[i]);
        if (ctx.mk_subsingleton_instance(arg_type)) {
            lean_trace_fun_info(
                tout() << "approximating function information for '" << fn
                << "', this may affect the effectiveness of the simplifier and congruence closure modules, "
                << "more precise information can be efficiently computed if all parameters are moved to the "
                << "beginning of the function\n";);
            return;
        }
Esempio n. 18
0
int main (int argc,const char *argv[])
{
	CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

	assert(argc == 2);
	std::ofstream	xml(argv[1]);

	CppUnit::TestResult controller;
	CppUnit::TestResultCollector result;
	controller.addListener( &result );

	CppUnit::TestRunner runner;
	runner.addTest(suite);
	runner.run(controller);

	CppUnit::XmlOutputter xout( &result, xml );
	CppUnit::CompilerOutputter tout( &result, std::cout);
	xout.write();
	tout.write();

	return result.wasSuccessful() ? 0 : 1 ;
}
Esempio n. 19
0
 expr operator()(expr const & e) {
     unpack_eqns ues(m_ctx, e);
     buffer<expr> old_fns;
     bool modified = false;
     for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) {
         expr const & fn = ues.get_fn(fidx);
         old_fns.push_back(fn);
         unsigned arity = ues.get_arity_of(fidx);
         if (arity > 1) {
             expr new_type = pack_as_unary(m_ctx.infer(fn), arity);
             ues.update_fn_type(fidx, new_type);
             modified = true;
         }
     }
     if (!modified) return e;
     update_apps_fn updt(m_ctx, old_fns, ues);
     for (unsigned fidx = 0; fidx < ues.get_num_fns(); fidx++) {
         buffer<expr> & eqs = ues.get_eqns_of(fidx);
         for (expr & eq : eqs)
             eq = updt(eq);
     }
     expr r = ues.repack();
     lean_trace("eqn_compiler", tout() << "making function(s) unary:\n" << r << "\n";);
Esempio n. 20
0
void ReachingDefAna::ComputeINOUTWtList(){
    map <BasicBlock*,bool> visitedFlag;
    queue <BasicBlock*> toVisit;    
    for( list<BasicBlock*>::iterator it = pr->get_begin(), end = pr->get_end(); it != end; ++it){
        toVisit.push(*it);
        visitedFlag[*it] = true;
    }
    while( !toVisit.empty() ){
        BasicBlock* cBB = toVisit.front();
        cout << "\n::VISITING " << cBB->getBBLabel() << " ::\n";
        toVisit.pop();
        visitedFlag[cBB] = false;
        bitvec in = cBB->getIn();
        bitvec out = cBB->getOut();
        bitvec tin(in.getSize()); 
        bitvec tout(out.getSize());
        for(list<BasicBlock*>::iterator pit = cBB->get_begin_pred(), pend = cBB->get_end_pred(); pit != pend; ++pit){
            tin = tin | (*pit)->getOut();
        }
        tout = tin - cBB->getKill();
        tout = tout | cBB->getGen();
        cBB->setIn(tin);
        if( out != tout ){
            cBB->setOut(tout);
            for(list<BasicBlock*>::iterator it = cBB->get_begin_succ(), end = cBB->get_end_succ(); it != end; ++it){
                if(visitedFlag[*it] == false){
                    visitedFlag[*it] = true;
                    toVisit.push(*it);
                }
            }
        }
        printBB(cBB);
    }
    string ts("ReachingDefWtList");
    createDotFile(ts);
}
Esempio n. 21
0
int MainWindow::findArea( const QString &s_FilenameIn, const QString &s_FilenameOut, const int i_CodecInput, const int i_CodecOutput, const int i_EOL, QVector<AreaItem> &v_Area, QVector<PositionItem> &v_Position, const bool b_DeleteInputFile, const int i_NumOfFiles)
{
    int             i                   = 1;
    int             j                   = 0;
    int             n                   = 0;
    int             m                   = 0;
    int             i_LatID             = -1;
    int             i_LongID            = -1;
    int             stopProgress        = -1;

    double          d_Latitude_dummy    = -1000.;
    double          d_Longitude_dummy   = -1000.;
    double          d_Latitude          = -1000.;
    double          d_Longitude         = -1000.;

    QString         s_AreaName          = "???";
    QString         s_EOL               = setEOLChar( i_EOL );

    QStringList     sl_Input;

// **********************************************************************************************
// read file

    if ( ( n = readFile( s_FilenameIn, sl_Input, i_CodecInput ) ) < 1 )
        return( n );

    m = NumOfSections( sl_Input.at( 0 ) );

    j = 0;
    while ( ( i_LatID < 0 ) && ( j < m ) )
    {
        if ( sl_Input.at( 0 ).section( "\t", j, j ).contains( "Latitude", Qt::CaseInsensitive ) == true )
            i_LatID = j;
        else
            j++;
    }

    j = 0;
    while ( ( i_LongID < 0 ) && ( j < m ) )
    {
        if ( sl_Input.at( 0 ).section( "\t", j, j ).contains( "Longitude", Qt::CaseInsensitive ) == true )
            i_LongID = j;
        else
            j++;
    }

    if ( ( i_LatID < 0 ) || ( i_LongID < 0 ) )
        return( -40 );

// **********************************************************************************************
// open output file

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text) == false )
        return( -20 );

    QTextStream tout( &fout );

    switch ( i_CodecOutput )
    {
    case _SYSTEM_:
        break;
    case _LATIN1_:
        tout.setCodec( QTextCodec::codecForName( "ISO 8859-1" ) );
        break;
    case _APPLEROMAN_:
        tout.setCodec( QTextCodec::codecForName( "Apple Roman" ) );
        break;
    default:
        tout.setCodec( QTextCodec::codecForName( "UTF-8" ) );
        break;
    }

// **********************************************************************************************

    initProgress( i_NumOfFiles, s_FilenameIn, tr( "Finding areas..." ), sl_Input.count() );

// **********************************************************************************************

    tout << "Area\t" << sl_Input.at( 0 ) << s_EOL;

    while ( ( i < n ) && ( stopProgress != _APPBREAK_ ) )
    {
        d_Latitude  = (double) qMin( sl_Input.at( i ).section( "\t", i_LatID, i_LatID ).toFloat() + 90., 179.99 );     // 0 - 179.99
        d_Longitude = (double) qMin( sl_Input.at( i ).section( "\t", i_LongID, i_LongID ).toFloat() + 180., 359.99 );  // 0 - 359.99

        if ( ( d_Latitude-d_Latitude_dummy > 0.001 ) || ( d_Longitude-d_Longitude_dummy > 0.001 ) || ( d_Latitude-d_Latitude_dummy < -0.001 ) || ( d_Longitude-d_Longitude_dummy < -0.001 ) )
        {
            int     j               = 0;
            int     k               = 0;
            int     i_InPolygon     = 0;

            while ( j < v_Area.count() )
            {
                if ( ( v_Area.at( j ).maxLatitude() > d_Latitude ) && ( d_Latitude > v_Area.at( j ).minLatitude() ) )
                {
                    if ( ( v_Area.at( j ).maxLongitude() > d_Longitude ) && ( d_Longitude > v_Area.at( j ).minLongitude() ) )
                    {
                        i_InPolygon = PtInPolygon( d_Latitude, d_Longitude, v_Area.at( j ).StartPosition(), v_Area.at( j ).NumOfPoints(), v_Position );

                        if ( i_InPolygon == 1 )
                        {
                            s_AreaName = v_Area.at( j ).AreaName();
                            s_AreaName.replace( ", western part", "" );
                            s_AreaName.replace( ", eastern part", "" );

                            d_Latitude_dummy  = d_Latitude;
                            d_Longitude_dummy = d_Longitude;

                            tout << s_AreaName << "\t" << sl_Input.at( i ) << s_EOL;

                            j = v_Area.count() - 1;
                        }
                    }
                }

                k += v_Area.at( j ).NumOfPoints();
                j += 1;
            }

            if ( i_InPolygon < 1 )
            {
                d_Latitude_dummy  = d_Latitude;
                d_Longitude_dummy = d_Longitude;

                if ( d_Latitude > 160. )
                    s_AreaName = "Arctic Ocean";
                else
                    s_AreaName = "???";

                tout << s_AreaName << "\t" << sl_Input.at( i ) << s_EOL;
            }
        }
        else
        {
            tout << s_AreaName << "\t" << sl_Input.at( i ) << s_EOL;
        }

        stopProgress = incProgress( i_NumOfFiles, ++i );
    }

//--------------------------------------------------------------------------------------------

    resetProgress( i_NumOfFiles );

    fout.close();

    if ( stopProgress == _APPBREAK_ )
        return( _APPBREAK_ );

    if ( b_DeleteInputFile == true )
        removeFile( s_FilenameIn );

    return( _NOERROR_ );
}
Esempio n. 22
0
int MainWindow::saveFilelist( const QString &s_FilenameOut, const QStringList &sl_FilenameList, const int i_CodecOutput, const QString &s_LocalDataDir, const QString &s_ExternalWebPath, const int i_EOL )
{
    QString     s_FilePath  = "";
    QString     s_EOL       = setEOLChar( i_EOL );

    QDateTime   CreationDateTime;

// **********************************************************************************************
// open output file

    QFileInfo fi_FilenameOut( s_FilenameOut );
    QFileInfo fi_LocalDataDir( s_LocalDataDir );

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text) == false )
        return( -20 );

    QTextStream tout( &fout );

    switch ( i_CodecOutput )
    {
    case _SYSTEM_:
        break;
    case _LATIN1_:
        tout.setCodec( QTextCodec::codecForName( "ISO 8859-1" ) );
        break;
    case _APPLEROMAN_:
        tout.setCodec( QTextCodec::codecForName( "Apple Roman" ) );
        break;
    default:
        tout.setCodec( QTextCodec::codecForName( "UTF-8" ) );
        break;
    }

// **********************************************************************************************

    if ( s_ExternalWebPath.isEmpty() == true )
    {
        for ( int i=0; i<sl_FilenameList.count(); i++ )
        {
            fi_FilenameOut.setFile( sl_FilenameList.at( i ) );

            CreationDateTime.setDate( fi_FilenameOut.created().date() );
            CreationDateTime.setTime( fi_FilenameOut.created().time() );

            tout << QDir::toNativeSeparators( fi_FilenameOut.absoluteFilePath() ) << "\t";
            tout << QDir::toNativeSeparators( fi_FilenameOut.absolutePath() + "/" ) << "\t";
            tout << fi_FilenameOut.fileName() << "\t";
            tout << fi_FilenameOut.completeBaseName() << "\t";
            tout << fi_FilenameOut.suffix() << "\t";
            tout << fi_FilenameOut.size() << "\t";
            tout << CreationDateTime.toString( "yyyy-MM-ddThh:mm:ss" );
            tout << s_EOL;
        }
    }
    else
    {
        tout << "Event label\tFile content []\tFile name []\tFile name []\tFile format []\tFile size [kByte]\tURL file []" << s_EOL;

        for ( int i=0; i<sl_FilenameList.count(); i++ )
        {
            fi_FilenameOut.setFile( sl_FilenameList.at( i ) );

            tout << "???" << "\t";                      // Event label
            tout << "\t";                               // File content
            tout << fi_FilenameOut.fileName() << "\t";              // File name
            tout << fi_FilenameOut.completeBaseName() << "\t";      // File name
            tout << fi_FilenameOut.suffix().toUpper() << "\t";      // File format
            tout << QString( "%1").arg( (float) fi_FilenameOut.size()/1024., 0,'f', 3 ) << "\t";    // File size in KByte
            tout << s_ExternalWebPath << fi_FilenameOut.absoluteFilePath().replace( fi_LocalDataDir.absolutePath().section( "/", 0, fi_LocalDataDir.absolutePath().count( "/" ) ) + "/" , "" );    // External web path plus file name
            tout << s_EOL;
        }
    }

    fout.close();

    return( _NOERROR_ );
}
Esempio n. 23
0
void MainWindow::saveParameterStatistic( const QString &s_FilenameIn, const QVector<PlotSettings> &v_PS, const int i_Format )
{
    QPrinter        printer;
    QTextDocument   textDocu;
    QFont           textFont            = QFont( gf_HeaderTextFont.family(), 10, 0, false );

    QFileInfo fi( s_FilenameIn );

    QString         s_FilenameParamStat = fi.absolutePath() + "/" + fi.baseName() + "_param_stat.";
    QString         s_FileDescr         = "";

// **********************************************************************************************

    switch ( i_Format )
    {
    case _FORMATPDF_:
        s_FilenameParamStat.append( "pdf" );
        s_FileDescr = tr( "Portable document format (*.pdf)" );
        break;
    default:
        s_FilenameParamStat.append( "txt" );
        s_FileDescr = tr( "Text (*.txt)" );
        break;
    }

    #if defined(Q_OS_LINUX)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    #if defined(Q_OS_WIN)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    #if defined(Q_OS_MAC)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    switch ( i_Format )
    {
    case _FORMATPDF_:
        printer.setOrientation( QPrinter::Landscape );
        printer.setOutputFileName( s_FilenameParamStat );

        textDocu.setHtml( createParameterStatisticOutputText( fi.fileName(), v_PS ) );
        textDocu.setDefaultFont( textFont );
        textDocu.print( &printer );
        break;

    default:
        QFile fout( s_FilenameParamStat );

        if ( fout.open( QIODevice::WriteOnly | QIODevice::Text ) == true )
        {
            QTextStream tout( &fout );

            tout << "Parameter settings of:\t" << fi.fileName() << endl << endl;

            tout << "Parameter name" << "\t" << "Minimum" << "\t" << "Maximum" << "\t" << "Median" << "\t" << "Mean" << "\t" << "Std dev" << "\t" << "Type" << endl;

            for ( int i=0; i<v_PS.count(); i++ )
            {
                tout << v_PS.at( i ).Parameter() << "\t";

                if ( v_PS.at( i ).Type() == isDateTime )
                {
                    tout << QString( "%1" ).arg( QDate::fromJulianDay( (int) v_PS.at( i ).YMinimum() ).toString( Qt::ISODate ) ) << "\t";
                    tout << QString( "%1" ).arg( QDate::fromJulianDay( (int) v_PS.at( i ).YMaximum() ).toString( Qt::ISODate ) ) << "\t";
                    tout << "\t" << "\t" << "\t";
                    tout << "Date/Time" << endl;
                }
                else
                {
                    if ( v_PS.at( i ).Type() != isText )
                    {
                        if ( v_PS.at( i ).YMinimum() < 10E99 )
                            tout << QString( "%1" ).arg( v_PS.at( i ).YMinimum() ) << "\t";
                        else
                            tout << "\t";

                        if ( v_PS.at( i ).YMaximum() > -10E99 )
                            tout << QString( "%1" ).arg( v_PS.at( i ).YMaximum() ) << "\t";
                        else
                            tout << "\t";

                        if ( v_PS.at( i ).isGeocode() == false )
                        {
                            if ( v_PS.at( i ).Median() != -999. )
                                tout  << QString( "%1" ).arg( v_PS.at( i ).Median() ) << "\t";
                            else
                                tout << "\t";

                            if ( v_PS.at( i ).Mean() != -999. )
                                tout  << QString( "%1" ).arg( v_PS.at( i ).Mean() ) << "\t";
                            else
                                tout << "\t";

                            if ( v_PS.at( i ).StandardDeviation() != -999. )
                                tout << QString( "%1" ).arg( v_PS.at( i ).StandardDeviation() ) << "\t";
                            else
                                tout << "\t";
                        }
                    }

                    if ( v_PS.at( i ).Type() == isNumeric )
                        tout << "Numeric";

                    if ( v_PS.at( i ).Type() == isText )
                        tout << "\t" << "\t" << "\t" << "\t" << "\t" << "Text";

                    tout << endl;
                }
            }

            fout.close();
        }
        break;
    }
}
Esempio n. 24
0
int MainWindow::convertSPE( const QString &s_FilenameIn, const QString &s_FilenameOut, const int i_CodecInput, const int i_CodecOutput, const int i_EOL, const int i_NumOfFiles )
{
    int         i               = 1;
    int         j               = 0;
    int         k               = 0;
    int         n               = 0;

    int			stopProgress	= 0;

    bool        b_datafound     = false;

    QString     tempStr         = "";
    QString     s_EOL           = setEOLChar( i_EOL );

    QStringList sl_Input;

// **********************************************************************************************
// read file

    if ( ( n = readFile( s_FilenameIn, sl_Input, i_CodecInput ) ) < 1 )
        return( -10 );

// **********************************************************************************************
// open output file

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text) == false )
        return( -20 );

    QTextStream tout( &fout );

    switch ( i_CodecOutput )
    {
    case _SYSTEM_:
        break;
    case _LATIN1_:
        tout.setCodec( QTextCodec::codecForName( "ISO 8859-1" ) );
        break;
    case _APPLEROMAN_:
        tout.setCodec( QTextCodec::codecForName( "Apple Roman" ) );
        break;
    default:
        tout.setCodec( QTextCodec::codecForName( "UTF-8" ) );
        break;
    }

// **********************************************************************************************

    initProgress( i_NumOfFiles, s_FilenameIn, tr( "Converting SPE data..." ), sl_Input.count() );

// **********************************************************************************************

    while ( ( b_datafound == false ) && ( i<sl_Input.count() ) && ( stopProgress != _APPBREAK_ ) )
    {
        if ( sl_Input.at( i ).startsWith( "$DATA:") == true )
            b_datafound = true;

        stopProgress = incProgress( i_NumOfFiles, ++i );
    }

    if ( b_datafound == true )
    {
        tempStr = sl_Input.at( i++ ).split( QRegularExpression( "\\s+" ) ).join( "\t" );
        k       = tempStr.section( "\t", 1, 1 ).toInt();

        tout << "Channel" << "\t" << "cps" << s_EOL;

        while ( ( i<sl_Input.count() ) && ( stopProgress != _APPBREAK_ ) )
        {
            tempStr = sl_Input.at( i ).split( QRegularExpression( "\\s+" ) ).join( "\t" );

            n = NumOfSections( tempStr );

            for ( j=1; j<n; j++ )
                tout << QString( "%1\t%2" ).arg( k++ ).arg( tempStr.section( "\t", j, j ) ) << s_EOL;

            stopProgress = incProgress( i_NumOfFiles, ++i );
        }
    }
    else
    {
        tout << "No data found! Wrong format." << s_EOL;
    }

// **********************************************************************************************

    fout.close();

    resetProgress( i_NumOfFiles );

    if ( stopProgress == _APPBREAK_ )
        return( _APPBREAK_ );

    return( _NOERROR_ );
}
Esempio n. 25
0
 void display(buffer<procedure> const & procs) {
     for (auto const & p : procs) {
         tout() << ">> " << p.m_name << "\n" << p.m_code << "\n";
     }
 }
Esempio n. 26
0
int MainWindow::addLine( const QString &s_FilenameIn, const QString &s_FilenameOut, const int i_CodecInput, const int i_CodecOutput, const int i_EOL,
                         const QStringList &sl_Text, const int i_LineNo,  const bool b_AddFilename, const bool b_AddFullPath, const bool b_AddOrdinalNumber,
                         const bool b_PrependMetadataColumn, const bool b_AppendMetadataColumn, const bool b_SkipEmptyLines, const bool b_SkipCommentLines, const int i_NumOfFiles )
{
    int         i               = 0;
    int         k               = 0;
    int         n               = 0;
    int         e               = 0;
    int         stopProgress    = 0;

    QString     s_EOL           = setEOLChar( i_EOL );

    QStringList sl_Input;

// **********************************************************************************************
// read file

    if ( ( n = readFile( s_FilenameIn, sl_Input, i_CodecInput ) ) < 1 )
        return( n );

// **********************************************************************************************
// open output file

    QFile fout( s_FilenameOut );

    if ( fout.open( QIODevice::WriteOnly | QIODevice::Text) == false )
        return( -20 );

    QTextStream tout( &fout );

    switch ( i_CodecOutput )
    {
    case _SYSTEM_:
        break;
    case _LATIN1_:
        tout.setCodec( QTextCodec::codecForName( "ISO 8859-1" ) );
        break;
    case _APPLEROMAN_:
        tout.setCodec( QTextCodec::codecForName( "Apple Roman" ) );
        break;
    default:
        tout.setCodec( QTextCodec::codecForName( "UTF-8" ) );
        break;
    }

    QFileInfo fi( s_FilenameIn );

// **********************************************************************************************

    initProgress( i_NumOfFiles, s_FilenameIn, tr( "Adding lines..." ), sl_Input.count() );

    e = i_LineNo - 1;

    if ( b_PrependMetadataColumn == true )
    {
        if ( b_AddFilename == true )
            tout << "Event label" << "\t";

        if ( b_AddFullPath == true )
            tout << "Filename" << "\t";

        if ( b_AddOrdinalNumber == true )
            tout << "No" << "\t";
    }

    tout << sl_Input.at( 0 );

    if ( b_AppendMetadataColumn == true )
    {
        if ( b_AddFilename == true )
            tout << "\t" << "Event label";

        if ( b_AddFullPath == true )
            tout << "\t"<< "Filename";

        if ( b_AddOrdinalNumber == true )
            tout << "\t" << "No";
    }

    tout << s_EOL;

    stopProgress = incProgress( i_NumOfFiles, ++i );

    while ( ( i<e ) && ( stopProgress != _APPBREAK_ ) )
    {
        if ( LineCanBeWritten( sl_Input.at( i ), b_SkipEmptyLines, b_SkipCommentLines ) == true )
        {
            if ( b_PrependMetadataColumn == true )
            {
                if ( b_AddFilename == true )
                    tout << fi.baseName() << "\t";

                if ( b_AddFullPath == true )
                    tout << fi.absoluteFilePath() << "\t";

                if ( b_AddOrdinalNumber == true )
                    tout << QString( "%1" ).arg( ++k ) << "\t";
            }

            tout << sl_Input.at( i );

            if ( b_AppendMetadataColumn == true )
            {
                if ( b_AddFilename == true )
                    tout << "\t" << fi.baseName();

                if ( b_AddFullPath == true )
                    tout << "\t" << fi.absoluteFilePath();

                if ( b_AddOrdinalNumber == true )
                {
                    if ( b_PrependMetadataColumn == false )
                        tout << "\t" << QString( "%1" ).arg( ++k );
                    else
                        tout << "\t" << QString( "%1" ).arg( k );
                }
            }

            tout << s_EOL;
        }

        stopProgress = incProgress( i_NumOfFiles, ++i );
    }

    for ( int j=0; j<sl_Text.count(); j++ )
    {
        if ( b_PrependMetadataColumn == true )
        {
            if ( b_AddFilename == true )
                tout << fi.baseName() << "\t";

            if ( b_AddFullPath == true )
                tout << fi.absoluteFilePath() << "\t";

            if ( b_AddOrdinalNumber == true )
                tout << QString( "%1" ).arg( ++k ) << "\t";
        }

        tout << sl_Text.at( j );

        if ( b_AppendMetadataColumn == true )
        {
            if ( b_AddFilename == true )
                tout << "\t" << fi.baseName();

            if ( b_AddFullPath == true )
                tout << "\t" << fi.absoluteFilePath();

            if ( b_AddOrdinalNumber == true )
            {
                if ( b_PrependMetadataColumn == false )
                    tout << "\t" << QString( "%1" ).arg( ++k );
                else
                    tout << "\t" << QString( "%1" ).arg( k );
            }
        }

        tout << s_EOL;
    }

    while ( ( i < n ) && ( stopProgress != _APPBREAK_ ) )
    {
        if ( LineCanBeWritten( sl_Input.at( i ), b_SkipEmptyLines, b_SkipCommentLines ) == true )
        {
            if ( b_PrependMetadataColumn == true )
            {
                if ( b_AddFilename == true )
                    tout << fi.baseName() << "\t";

                if ( b_AddFullPath == true )
                    tout << fi.absoluteFilePath() << "\t";

                if ( b_AddOrdinalNumber == true )
                    tout << QString( "%1" ).arg( ++k ) << "\t";
            }

            tout << sl_Input.at( i );

            if ( b_AppendMetadataColumn == true )
            {
                if ( b_AddFilename == true )
                    tout << "\t" << fi.baseName();

                if ( b_AddFullPath == true )
                    tout << "\t" << fi.absoluteFilePath();

                if ( b_AddOrdinalNumber == true )
                {
                    if ( b_PrependMetadataColumn == false )
                        tout << "\t" << QString( "%1" ).arg( ++k );
                    else
                        tout << "\t" << QString( "%1" ).arg( k );
                }
            }

            tout << s_EOL;
        }

        stopProgress = incProgress( i_NumOfFiles, ++i );
    }

    resetProgress( i_NumOfFiles );

// **********************************************************************************************

    fout.close();

    if ( stopProgress == _APPBREAK_ )
        return( _APPBREAK_ );

    return( _NOERROR_ );
}
Esempio n. 27
0
int
main(int ac, char* av[])
{
  KokkosGuard kokkos(ac, av);

  typedef PHX::MDField<PHAL::AlbanyTraits::Residual::ScalarT>::size_type
                                                size_type;
  typedef PHAL::AlbanyTraits::Residual          Residual;
  typedef PHAL::AlbanyTraits::Residual::ScalarT ScalarT;
  typedef PHAL::AlbanyTraits                    Traits;
  std::cout.precision(15);
  //
  // Create a command line processor and parse command line options
  //
  Teuchos::CommandLineProcessor command_line_processor;

  command_line_processor.setDocString(
      "Material Point Simulator.\n"
      "For testing material models in LCM.\n");

  std::string input_file = "materials.xml";
  command_line_processor.setOption("input", &input_file, "Input File Name");

  std::string timing_file = "timing.csv";
  command_line_processor.setOption("timing", &timing_file, "Timing File Name");

  int workset_size = 1;
  command_line_processor.setOption("wsize", &workset_size, "Workset Size");

  int num_pts = 1;
  command_line_processor.setOption(
      "npoints", &num_pts, "Number of Gaussian Points");

  size_t memlimit = 1024;  // 1GB heap limit by default
  command_line_processor.setOption(
      "memlimit", &memlimit, "Heap memory limit in MB for CUDA kernels");

  // Throw a warning and not error for unrecognized options
  command_line_processor.recogniseAllOptions(true);

  // Don't throw exceptions for errors
  command_line_processor.throwExceptions(false);

  // Parse command line
  Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
      command_line_processor.parse(ac, av);

  std::ofstream tout(timing_file.c_str());

  if (parse_return == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED) {
    return 0;
  }

  if (parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
    return 1;
  }

  util::TimeMonitor& tmonitor =
      util::PerformanceContext::instance().timeMonitor();
  Teuchos::RCP<Teuchos::Time> total_time   = tmonitor["MPS: Total Time"];
  Teuchos::RCP<Teuchos::Time> compute_time = tmonitor["MPS: Compute Time"];

  //
  // Process material.xml file
  // Read into materialDB and get material model name
  //

  // A mpi object must be instantiated before using the comm to read
  // material file
  Teuchos::GlobalMPISession        mpi_session(&ac, &av);
  Teuchos::RCP<const Teuchos_Comm> commT =
      Albany::createTeuchosCommFromMpiComm(Albany_MPI_COMM_WORLD);

  Teuchos::RCP<Albany::MaterialDatabase> material_db;
  material_db = Teuchos::rcp(new Albany::MaterialDatabase(input_file, commT));

  // Get the name of the material model to be used (and make sure there is one)
  std::string element_block_name = "Block0";
  std::string material_model_name;
  material_model_name =
      material_db->getElementBlockSublist(element_block_name, "Material Model")
          .get<std::string>("Model Name");
  TEUCHOS_TEST_FOR_EXCEPTION(
      material_model_name.length() == 0,
      std::logic_error,
      "A material model must be defined for block: " + element_block_name);

  //
  // Preloading stage setup
  // set up evaluators, create field and state managers
  //

  // Set up the data layout
  // const int workset_size = 1;
  const int                           num_dims     = 3;
  const int                           num_vertices = 8;
  const int                           num_nodes    = 8;
  const Teuchos::RCP<Albany::Layouts> dl = Teuchos::rcp(new Albany::Layouts(
      workset_size, num_vertices, num_nodes, num_pts, num_dims));

  // create field name strings
  LCM::FieldNameMap                                field_name_map(false);
  Teuchos::RCP<std::map<std::string, std::string>> fnm =
      field_name_map.getMap();

  //---------------------------------------------------------------------------
  // Deformation gradient
  // initially set the deformation gradient to the identity

  Teuchos::ArrayRCP<ScalarT> def_grad(workset_size * num_pts * 9);
  for (int i = 0; i < workset_size; ++i) {
    for (int j = 0; j < num_pts; ++j) {
      int base = i * num_pts * 9 + j * 9;
      for (int k = 0; k < 9; ++k) def_grad[base + k] = 0.0;

      def_grad[base + 0] = 1.0;
      def_grad[base + 4] = 1.0;
      def_grad[base + 8] = 1.0;
    }
  }
  // SetField evaluator, which will be used to manually assign a value
  // to the def_grad field
  Teuchos::ParameterList setDefGradP("SetFieldDefGrad");
  setDefGradP.set<std::string>("Evaluated Field Name", "F");
  setDefGradP.set<Teuchos::RCP<PHX::DataLayout>>(
      "Evaluated Field Data Layout", dl->qp_tensor);
  setDefGradP.set<Teuchos::ArrayRCP<ScalarT>>("Field Values", def_grad);
  auto setFieldDefGrad =
      Teuchos::rcp(new LCM::SetField<Residual, Traits>(setDefGradP));

  //---------------------------------------------------------------------------
  // Det(deformation gradient)
  Teuchos::ArrayRCP<ScalarT> detdefgrad(workset_size * num_pts);
  for (int i = 0; i < workset_size * num_pts; ++i) detdefgrad[i] = 1.0;
  // SetField evaluator, which will be used to manually assign a value
  // to the detdefgrad field
  Teuchos::ParameterList setDetDefGradP("SetFieldDetDefGrad");
  setDetDefGradP.set<std::string>("Evaluated Field Name", "J");
  setDetDefGradP.set<Teuchos::RCP<PHX::DataLayout>>(
      "Evaluated Field Data Layout", dl->qp_scalar);
  setDetDefGradP.set<Teuchos::ArrayRCP<ScalarT>>("Field Values", detdefgrad);
  auto setFieldDetDefGrad =
      Teuchos::rcp(new LCM::SetField<Residual, Traits>(setDetDefGradP));

  //---------------------------------------------------------------------------
  // Small strain tensor
  // initially set the strain tensor to zeros

  Teuchos::ArrayRCP<ScalarT> strain(workset_size * num_pts * 9);
  for (int i = 0; i < workset_size; ++i) {
    for (int j = 0; j < num_pts; ++j) {
      int base = i * num_pts * 9 + j * 9;
      for (int k = 0; k < 9; ++k) strain[base + k] = 0.0;
    }
  }

  // SetField evaluator, which will be used to manually assign a value
  // to the strain field
  Teuchos::ParameterList setStrainP("SetFieldStrain");
  setStrainP.set<std::string>("Evaluated Field Name", "Strain");
  setStrainP.set<Teuchos::RCP<PHX::DataLayout>>(
      "Evaluated Field Data Layout", dl->qp_tensor);
  setStrainP.set<Teuchos::ArrayRCP<ScalarT>>("Field Values", strain);
  auto setFieldStrain =
      Teuchos::rcp(new LCM::SetField<Residual, Traits>(setStrainP));
  //---------------------------------------------------------------------------
  // Instantiate a field manager
  PHX::FieldManager<Traits> fieldManager;

  // Instantiate a field manager for States
  PHX::FieldManager<Traits> stateFieldManager;

  // Register the evaluators with the field manager
  fieldManager.registerEvaluator<Residual>(setFieldDefGrad);
  fieldManager.registerEvaluator<Residual>(setFieldDetDefGrad);
  fieldManager.registerEvaluator<Residual>(setFieldStrain);

  // Register the evaluators with the state field manager
  stateFieldManager.registerEvaluator<Residual>(setFieldDefGrad);
  stateFieldManager.registerEvaluator<Residual>(setFieldDetDefGrad);
  stateFieldManager.registerEvaluator<Residual>(setFieldStrain);

  // Instantiate a state manager
  Albany::StateManager stateMgr;

  // extract the Material ParameterList for use below
  std::string matName = material_db->getElementBlockParam<std::string>(
      element_block_name, "material");
  Teuchos::ParameterList& paramList =
      material_db->getElementBlockSublist(element_block_name, matName);
  Teuchos::ParameterList& mpsParams =
      paramList.sublist("Material Point Simulator");

  // Get loading parameters from .xml file
  std::string load_case =
      mpsParams.get<std::string>("Loading Case Name", "uniaxial");
  int    number_steps = mpsParams.get<int>("Number of Steps", 10);
  double step_size    = mpsParams.get<double>("Step Size", 1.0e-2);

  std::cout << "Loading parameters:"
            << "\n  number of steps: " << number_steps
            << "\n  step_size      : " << step_size << std::endl;

  // determine if temperature is being used
  bool have_temperature = mpsParams.get<bool>("Use Temperature", false);
  std::cout << "have_temp: " << have_temperature << std::endl;
  //---------------------------------------------------------------------------
  // Temperature (optional)
  if (have_temperature) {
    Teuchos::ArrayRCP<ScalarT> temperature(workset_size);
    ScalarT                    temp = mpsParams.get<double>("Temperature", 1.0);
    for (int i = 0; i < workset_size * num_pts; ++i) temperature[0] = temp;
    // SetField evaluator, which will be used to manually assign a value
    // to the detdefgrad field
    Teuchos::ParameterList setTempP("SetFieldTemperature");
    setTempP.set<std::string>("Evaluated Field Name", "Temperature");
    setTempP.set<Teuchos::RCP<PHX::DataLayout>>(
        "Evaluated Field Data Layout", dl->qp_scalar);
    setTempP.set<Teuchos::ArrayRCP<ScalarT>>("Field Values", temperature);
    auto setFieldTemperature =
        Teuchos::rcp(new LCM::SetField<Residual, Traits>(setTempP));
    fieldManager.registerEvaluator<Residual>(setFieldTemperature);
    stateFieldManager.registerEvaluator<Residual>(setFieldTemperature);
  }

  //---------------------------------------------------------------------------
  // Time step
  Teuchos::ArrayRCP<ScalarT> delta_time(1);
  delta_time[0] = step_size;
  Teuchos::ParameterList setDTP("SetFieldTimeStep");
  setDTP.set<std::string>("Evaluated Field Name", "Delta Time");
  setDTP.set<Teuchos::RCP<PHX::DataLayout>>(
      "Evaluated Field Data Layout", dl->workset_scalar);
  setDTP.set<Teuchos::ArrayRCP<ScalarT>>("Field Values", delta_time);
  auto setFieldDT = Teuchos::rcp(new LCM::SetField<Residual, Traits>(setDTP));
  fieldManager.registerEvaluator<Residual>(setFieldDT);
  stateFieldManager.registerEvaluator<Residual>(setFieldDT);

  // check if the material wants the tangent to be computed
  bool check_stability;
  check_stability = mpsParams.get<bool>("Check Stability", false);
  paramList.set<bool>("Compute Tangent", check_stability);

  std::cout << "Check stability = " << check_stability << std::endl;

  //---------------------------------------------------------------------------
  // std::cout << "// Constitutive Model Parameters"
  //<< std::endl;
  Teuchos::ParameterList cmpPL;
  paramList.set<Teuchos::RCP<std::map<std::string, std::string>>>(
      "Name Map", fnm);
  cmpPL.set<Teuchos::ParameterList*>("Material Parameters", &paramList);
  if (have_temperature) {
    cmpPL.set<std::string>("Temperature Name", "Temperature");
    paramList.set<bool>("Have Temperature", true);
  }
  auto CMP = Teuchos::rcp(
      new LCM::ConstitutiveModelParameters<Residual, Traits>(cmpPL, dl));
  fieldManager.registerEvaluator<Residual>(CMP);
  stateFieldManager.registerEvaluator<Residual>(CMP);

  //---------------------------------------------------------------------------
  // std::cout << "// Constitutive Model Interface Evaluator"
  // << std::endl;
  Teuchos::ParameterList cmiPL;
  cmiPL.set<Teuchos::ParameterList*>("Material Parameters", &paramList);
  if (have_temperature) {
    cmiPL.set<std::string>("Temperature Name", "Temperature");
  }
  Teuchos::RCP<LCM::ConstitutiveModelInterface<Residual, Traits>> CMI =
      Teuchos::rcp(
          new LCM::ConstitutiveModelInterface<Residual, Traits>(cmiPL, dl));
  fieldManager.registerEvaluator<Residual>(CMI);
  stateFieldManager.registerEvaluator<Residual>(CMI);

  // Set the evaluated fields as required
  for (std::vector<Teuchos::RCP<PHX::FieldTag>>::const_iterator it =
           CMI->evaluatedFields().begin();
       it != CMI->evaluatedFields().end();
       ++it) {
    fieldManager.requireField<Residual>(**it);
  }

  // register state variables
  Teuchos::RCP<Teuchos::ParameterList> p;
  Teuchos::RCP<PHX::Evaluator<Traits>> ev;
  for (int sv(0); sv < CMI->getNumStateVars(); ++sv) {
    CMI->fillStateVariableStruct(sv);
    p = stateMgr.registerStateVariable(
        CMI->getName(),
        CMI->getLayout(),
        dl->dummy,
        element_block_name,
        CMI->getInitType(),
        CMI->getInitValue(),
        CMI->getStateFlag(),
        CMI->getOutputFlag());
    ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
    fieldManager.registerEvaluator<Residual>(ev);
    stateFieldManager.registerEvaluator<Residual>(ev);
  }

  //---------------------------------------------------------------------------
  if (check_stability) {
    std::string parametrization_type =
        mpsParams.get<std::string>("Parametrization Type", "Spherical");

    double parametrization_interval =
        mpsParams.get<double>("Parametrization Interval", 0.05);

    std::cout << "Bifurcation Check in Material Point Simulator:" << std::endl;
    std::cout << "Parametrization Type: " << parametrization_type << std::endl;

    Teuchos::ParameterList bcPL;
    bcPL.set<Teuchos::ParameterList*>("Material Parameters", &paramList);
    bcPL.set<std::string>("Parametrization Type Name", parametrization_type);
    bcPL.set<double>("Parametrization Interval Name", parametrization_interval);
    bcPL.set<std::string>("Material Tangent Name", "Material Tangent");
    bcPL.set<std::string>("Ellipticity Flag Name", "Ellipticity_Flag");
    bcPL.set<std::string>("Bifurcation Direction Name", "Direction");
    bcPL.set<std::string>("Min detA Name", "Min detA");
    Teuchos::RCP<LCM::BifurcationCheck<Residual, Traits>> BC =
        Teuchos::rcp(new LCM::BifurcationCheck<Residual, Traits>(bcPL, dl));
    fieldManager.registerEvaluator<Residual>(BC);
    stateFieldManager.registerEvaluator<Residual>(BC);

    // register the ellipticity flag
    p = stateMgr.registerStateVariable(
        "Ellipticity_Flag",
        dl->qp_scalar,
        dl->dummy,
        element_block_name,
        "scalar",
        0.0,
        false,
        true);
    ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
    fieldManager.registerEvaluator<Residual>(ev);
    stateFieldManager.registerEvaluator<Residual>(ev);

    // register the direction
    p = stateMgr.registerStateVariable(
        "Direction",
        dl->qp_vector,
        dl->dummy,
        element_block_name,
        "scalar",
        0.0,
        false,
        true);
    ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
    fieldManager.registerEvaluator<Residual>(ev);
    stateFieldManager.registerEvaluator<Residual>(ev);

    // register min(det(A))
    p = stateMgr.registerStateVariable(
        "Min detA",
        dl->qp_scalar,
        dl->dummy,
        element_block_name,
        "scalar",
        0.0,
        false,
        true);
    ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
    fieldManager.registerEvaluator<Residual>(ev);
    stateFieldManager.registerEvaluator<Residual>(ev);
  }

  //---------------------------------------------------------------------------
  // std::cout << "// register deformation gradient"
  // << std::endl;
  p = stateMgr.registerStateVariable(
      "F",
      dl->qp_tensor,
      dl->dummy,
      element_block_name,
      "identity",
      1.0,
      true,
      true);
  ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
  fieldManager.registerEvaluator<Residual>(ev);
  stateFieldManager.registerEvaluator<Residual>(ev);
  //---------------------------------------------------------------------------
  // std::cout << "// register small strain tensor"
  // << std::endl;
  p = stateMgr.registerStateVariable(
      "Strain",
      dl->qp_tensor,
      dl->dummy,
      element_block_name,
      "scalar",
      0.0,
      false,
      true);
  ev = Teuchos::rcp(new PHAL::SaveStateField<Residual, Traits>(*p));
  fieldManager.registerEvaluator<Residual>(ev);
  stateFieldManager.registerEvaluator<Residual>(ev);
  //---------------------------------------------------------------------------
  //
  Traits::SetupData setupData = "Test String";
  // std::cout << "Calling postRegistrationSetup" << std::endl;
  fieldManager.postRegistrationSetup(setupData);

  // std::cout << "// set the required fields for the state manager"
  //<< std::endl;
  Teuchos::RCP<PHX::DataLayout> dummy =
      Teuchos::rcp(new PHX::MDALayout<Dummy>(0));
  std::vector<std::string> responseIDs =
      stateMgr.getResidResponseIDsToRequire(element_block_name);
  std::vector<std::string>::const_iterator it;
  for (it = responseIDs.begin(); it != responseIDs.end(); it++) {
    const std::string&                              responseID = *it;
    PHX::Tag<PHAL::AlbanyTraits::Residual::ScalarT> res_response_tag(
        responseID, dummy);
    stateFieldManager.requireField<PHAL::AlbanyTraits::Residual>(
        res_response_tag);
  }
  stateFieldManager.postRegistrationSetup("");

  // std::cout << "Process using 'dot -Tpng -O <name>'\n";
  fieldManager.writeGraphvizFile<Residual>("FM", true, true);
  stateFieldManager.writeGraphvizFile<Residual>("SFM", true, true);

  //---------------------------------------------------------------------------
  // grab the output file name
  //
  std::string output_file =
      mpsParams.get<std::string>("Output File Name", "output.exo");

  //---------------------------------------------------------------------------
  // Create discretization, as required by the StateManager
  //
  Teuchos::RCP<Teuchos::ParameterList> discretizationParameterList =
      Teuchos::rcp(new Teuchos::ParameterList("Discretization"));
  discretizationParameterList->set<int>("1D Elements", workset_size);
  discretizationParameterList->set<int>("2D Elements", 1);
  discretizationParameterList->set<int>("3D Elements", 1);
  discretizationParameterList->set<std::string>("Method", "STK3D");
  discretizationParameterList->set<int>("Number Of Time Derivatives", 0);
  discretizationParameterList->set<std::string>(
      "Exodus Output File Name", output_file);
  discretizationParameterList->set<int>("Workset Size", workset_size);
  Teuchos::RCP<Tpetra_Map>    mapT = Teuchos::rcp(new Tpetra_Map(
      workset_size * num_dims * num_nodes,
      0,
      commT,
      Tpetra::LocallyReplicated));
  Teuchos::RCP<Tpetra_Vector> solution_vectorT =
      Teuchos::rcp(new Tpetra_Vector(mapT));

  int numberOfEquations = 3;
  Albany::AbstractFieldContainer::FieldContainerRequirements req;

  Teuchos::RCP<Albany::AbstractSTKMeshStruct> stkMeshStruct =
      Teuchos::rcp(new Albany::TmplSTKMeshStruct<3>(
          discretizationParameterList, Teuchos::null, commT));
  stkMeshStruct->setFieldAndBulkData(
      commT,
      discretizationParameterList,
      numberOfEquations,
      req,
      stateMgr.getStateInfoStruct(),
      stkMeshStruct->getMeshSpecs()[0]->worksetSize);

  Teuchos::RCP<Albany::AbstractDiscretization> discretization =
      Teuchos::rcp(new Albany::STKDiscretization(
          discretizationParameterList, stkMeshStruct, commT));

  //---------------------------------------------------------------------------
  // Associate the discretization with the StateManager
  //
  stateMgr.setupStateArrays(discretization);

  //---------------------------------------------------------------------------
  // Create a workset
  //
  PHAL::Workset workset;
  workset.numCells = workset_size;
  workset.stateArrayPtr =
      &stateMgr.getStateArray(Albany::StateManager::ELEM, 0);

  // create MDFields
  PHX::MDField<ScalarT, Cell, QuadPoint, Dim, Dim> stressField(
      "Cauchy_Stress", dl->qp_tensor);

  // construct the final deformation gradient based on the loading case
  std::vector<ScalarT> F_vector(9, 0.0);
  if (load_case == "uniaxial") {
    F_vector[0] = 1.0 + number_steps * step_size;
    F_vector[4] = 1.0;
    F_vector[8] = 1.0;
  } else if (load_case == "simple-shear") {
    F_vector[0] = 1.0;
    F_vector[1] = number_steps * step_size;
    F_vector[4] = 1.0;
    F_vector[8] = 1.0;
  } else if (load_case == "hydrostatic") {
    F_vector[0] = 1.0 + number_steps * step_size;
    F_vector[4] = 1.0 + number_steps * step_size;
    F_vector[8] = 1.0 + number_steps * step_size;
  } else if (load_case == "general") {
    F_vector =
        mpsParams.get<Teuchos::Array<double>>("Deformation Gradient Components")
            .toVector();
  } else {
    TEUCHOS_TEST_FOR_EXCEPTION(
        true,
        std::runtime_error,
        "Improper Loading Case in Material Point Simulator block");
  }

  minitensor::Tensor<ScalarT> F_tensor(3, &F_vector[0]);
  minitensor::Tensor<ScalarT> log_F_tensor = minitensor::log(F_tensor);

  std::cout << "F\n" << F_tensor << std::endl;
  // std::cout << "log F\n" << log_F_tensor << std::endl;

  //
  // Setup loading scenario and instantiate evaluatFields
  //
  PHX::MDField<ScalarT, Cell, QuadPoint> minDetA("Min detA", dl->qp_scalar);
  PHX::MDField<ScalarT, Cell, QuadPoint, Dim> direction(
      "Direction", dl->qp_vector);

  // Bifurcation check parameters
  double mu_0                  = 0;
  double mu_k                  = 0;
  int    bifurcationTime_rough = number_steps;
  bool   bifurcation_flag      = false;

  for (int istep(0); istep <= number_steps; ++istep) {
    util::TimeGuard total_time_guard(total_time);
    // std::cout << "****** in MPS step " << istep << " ****** " << std::endl;
    // alpha \in [0,1]
    double alpha = double(istep) / number_steps;

    // std::cout << "alpha: " << alpha << std::endl;
    minitensor::Tensor<ScalarT> scaled_log_F_tensor = alpha * log_F_tensor;
    minitensor::Tensor<ScalarT> current_F =
        minitensor::exp(scaled_log_F_tensor);

    // std::cout << "scaled log F\n" << scaled_log_F_tensor << std::endl;
    // std::cout << "current F\n" << current_F << std::endl;

    for (int i = 0; i < 3; ++i) {
      for (int j = 0; j < 3; ++j) { def_grad[3 * i + j] = current_F(i, j); }
    }

    // jacobian
    detdefgrad[0] = minitensor::det(current_F);

    // small strain tensor
    minitensor::Tensor<ScalarT> current_strain;
    current_strain = 0.5 * (current_F + minitensor::transpose(current_F)) -
                     minitensor::eye<ScalarT>(3);

    for (int i = 0; i < 3; ++i) {
      for (int j = 0; j < 3; ++j) { strain[3 * i + j] = current_strain(i, j); }
    }
    // std::cout << "current strain\n" << current_strain << std::endl;

    // Call the evaluators, evaluateFields() is the function that
    // computes stress based on deformation gradient
    compute_time->start();
    fieldManager.preEvaluate<Residual>(workset);
    fieldManager.evaluateFields<Residual>(workset);
    fieldManager.postEvaluate<Residual>(workset);
    compute_time->stop();

    stateFieldManager.getFieldData<Residual>(stressField);

    // Call the state field manager
    // std::cout << "+++ calling the stateFieldManager\n";
    compute_time->start();
    stateFieldManager.preEvaluate<Residual>(workset);
    stateFieldManager.evaluateFields<Residual>(workset);
    stateFieldManager.postEvaluate<Residual>(workset);
    compute_time->stop();

    stateMgr.updateStates();

    // output to the exodus file
    // Don't include this in timing data...
    total_time->stop();
    discretization->writeSolutionT(
        *solution_vectorT, Teuchos::as<double>(istep));

    // if check for bifurcation, adaptive step
    total_time->start();
    if (check_stability) {
      // get current minDet(A)
      stateFieldManager.getFieldData<Residual>(minDetA);

      if (istep == 0) { mu_0 = minDetA(0, 0); }

      if (minDetA(0, 0) <= 0 && !bifurcation_flag) {
        mu_k                  = minDetA(0, 0);
        bifurcationTime_rough = istep;
        bifurcation_flag      = true;

        // adaptive step begin
        std::cout << "\nAdaptive step begin - step " << istep << std::endl;

        // initialization for adaptive step
        double tol              = 1E-8;
        double alpha_local      = 1.0;
        double alpha_local_step = 0.5;

        int k            = 1;
        int maxIteration = 50;

        // small strain tensor
        minitensor::Tensor<ScalarT> current_strain;

        // iteration begin
        while (((mu_k <= 0) || (std::abs(mu_k / mu_0) > tol))) {
          alpha =
              double(bifurcationTime_rough - 1 + alpha_local) / number_steps;

          minitensor::Tensor<ScalarT> scaled_log_F_tensor =
              alpha * log_F_tensor;
          minitensor::Tensor<ScalarT> current_F =
              minitensor::exp(scaled_log_F_tensor);

          for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
              def_grad[3 * i + j] = current_F(i, j);
            }
          }

          // jacobian
          detdefgrad[0] = minitensor::det(current_F);

          current_strain =
              0.5 * (current_F + minitensor::transpose(current_F)) -
              minitensor::eye<ScalarT>(3);

          for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
              strain[3 * i + j] = current_strain(i, j);
            }
          }

          // Call the evaluators, evaluateFields() is the function that
          // computes stress based on deformation gradient
          fieldManager.preEvaluate<Residual>(workset);
          fieldManager.evaluateFields<Residual>(workset);
          fieldManager.postEvaluate<Residual>(workset);

          // Call the state field manager
          // std::cout << "+++ calling the stateFieldManager\n";
          stateFieldManager.preEvaluate<Residual>(workset);
          stateFieldManager.evaluateFields<Residual>(workset);
          stateFieldManager.postEvaluate<Residual>(workset);

          stateFieldManager.getFieldData<Residual>(minDetA);

          stateFieldManager.getFieldData<Residual>(direction);

          mu_k = minDetA(0, 0);

          if (mu_k > 0) {
            alpha_local += alpha_local_step;
          } else {
            alpha_local -= alpha_local_step;
          }

          alpha_local_step /= 2;

          k = k + 1;

          if (k >= maxIteration) {
            std::cout
                << "Adaptive step for bifurcation check not converging after "
                << k << " iterations" << std::endl;
            break;
          }

        }  // adaptive step iteration end

      }  // end adaptive step

    }  // end check bifurcation

    stateMgr.updateStates();

    //
    if (bifurcation_flag) {
      // break the loading step after adaptive time step loop
      break;
    }

    //

  }  // end loading steps

  // Summarize with AlbanyUtil performance monitors
  if (tout) {
    util::PerformanceContext::instance().timeMonitor().summarize(tout);
    tout.close();
  }
}
Esempio n. 28
0
         if (m_arg_idx < args.size()) {
             expr const & arg = args[m_arg_idx];
             /* arg must be structurally smaller than m_pattern */
             if (!is_lt(arg, m_pattern)) {
                 trace_struct_aux(tout() << "structural recursion on argument #" << (m_arg_idx+1)
                                  << " was not used "
                                  << "for '" << m_fn << "'\nargument #" << (m_arg_idx+1)
                                  << " in the application\n  "
                                  << e << "\nis not structurally smaller than the one occurring in "
                                  << "the equation left-hand-side\n  "
                                  << m_lhs << "\n";);
                 return false;
             }
         } else {
             /* function is not fully applied */
             trace_struct_aux(tout() << "structural recursion on argument #" << (m_arg_idx+1) << " was not used "
                              << "for '" << m_fn << "' because of the partial application\n  "
                              << e << "\n";);
             return false;
         }
     }
     return true;
 }
 case expr_kind::Let:
     if (!check_rhs(let_value(e))) {
         return false;
     } else {
         type_context::tmp_locals locals(m_ctx);
         return check_rhs(instantiate(let_body(e), locals.push_local_from_let(e)));
     }
 case expr_kind::Lambda:
Esempio n. 29
0
expr dsimplify_core_fn::visit(expr const & e) {
    check_system("dsimplify");
    inc_num_steps();

    lean_trace_inc_depth("dsimplify");
    lean_dsimp_trace(m_ctx, "dsimplify", tout() << e << "\n";);
Esempio n. 30
0
result simplifier::simplify(expr const & e, bool is_root) {
    check_system("simplifier");
    m_num_steps++;
    lean_trace_inc_depth("simplifier");
    lean_trace_d("simplifier", tout() << m_rel << ": " << ppb(e) << "\n";);