Ejemplo n.º 1
0
int main(int argc, char** argv)
{
    DynareParams params(argc, argv);
    if (params.help) {
        params.printHelp();
        return 0;
    }
    if (params.version) {
        printf("Dynare++ v. %s. Copyright (C) 2004-2011, Ondra Kamenik\n",
               DYNVERSION);
        printf("Dynare++ comes with ABSOLUTELY NO WARRANTY and is distributed under\n");
        printf("GPL: modules integ, tl, kord, sylv, src, extern and documentation\n");
        printf("LGPL: modules parser, utils\n");
        printf(" for GPL  see http://www.gnu.org/licenses/gpl.html\n");
        printf(" for LGPL see http://www.gnu.org/licenses/lgpl.html\n");
        return 0;
    }
    THREAD_GROUP::max_parallel_threads = params.num_threads;

    try {
        // make journal name and journal
        std::string jname(params.basename);
        jname += ".jnl";
        Journal journal(jname.c_str());

        // make dynare object
        Dynare dynare(params.modname, params.order, params.ss_tol, journal);
        // make list of shocks for which we will do IRFs
        vector<int> irf_list_ind;
        if (params.do_irfs_all)
            for (int i = 0; i < dynare.nexog(); i++)
                irf_list_ind.push_back(i);
        else
            irf_list_ind = ((const DynareNameList&)dynare.getExogNames()).selectIndices(params.irf_list);

        // write matlab files
        FILE* mfd;
        std::string mfile1(params.basename);
        mfile1 += "_f.m";
        if (NULL == (mfd=fopen(mfile1.c_str(), "w"))) {
            fprintf(stderr, "Couldn't open %s for writing.\n", mfile1.c_str());
            exit(1);
        }
        ogdyn::MatlabSSWriter writer0(dynare.getModel(), params.basename.c_str());
        writer0.write_der0(mfd);
        fclose(mfd);

        std::string mfile2(params.basename);
        mfile2 += "_ff.m";
        if (NULL == (mfd=fopen(mfile2.c_str(), "w"))) {
            fprintf(stderr, "Couldn't open %s for writing.\n", mfile2.c_str());
            exit(1);
        }
        ogdyn::MatlabSSWriter writer1(dynare.getModel(), params.basename.c_str());
        writer1.write_der1(mfd);
        fclose(mfd);

        // open mat file
        std::string matfile(params.basename);
        matfile += ".mat";
        mat_t* matfd = Mat_Create(matfile.c_str(), NULL);
        if (matfd == NULL) {
            fprintf(stderr, "Couldn't open %s for writing.\n", matfile.c_str());
            exit(1);
        }

        // write info about the model (dimensions and variables)
        dynare.writeMat(matfd, params.prefix);
        // write the dump file corresponding to the input
        dynare.writeDump(params.basename);


        system_random_generator.initSeed(params.seed);

        tls.init(dynare.order(),
                 dynare.nstat()+2*dynare.npred()+3*dynare.nboth()+
                 2*dynare.nforw()+dynare.nexog());

        Approximation app(dynare, journal, params.num_steps, params.do_centralize, params.qz_criterium);
        try {
            app.walkStochSteady();
        } catch (const KordException& e) {
            // tell about the exception and continue
            printf("Caught (not yet fatal) Kord exception: ");
            e.print();
            JournalRecord rec(journal);
            rec << "Solution routine not finished (" << e.get_message()
                << "), see what happens" << endrec;
        }

        std::string ss_matrix_name(params.prefix);
        ss_matrix_name += "_steady_states";
        ConstTwoDMatrix(app.getSS()).writeMat(matfd, ss_matrix_name.c_str());

        // check the approximation
        if (params.check_along_path || params.check_along_shocks
                || params.check_on_ellipse) {
            GlobalChecker gcheck(app, THREAD_GROUP::max_parallel_threads, journal);
            if (params.check_along_shocks)
                gcheck.checkAlongShocksAndSave(matfd, params.prefix,
                                               params.getCheckShockPoints(),
                                               params.getCheckShockScale(),
                                               params.check_evals);
            if (params.check_on_ellipse)
                gcheck.checkOnEllipseAndSave(matfd, params.prefix,
                                             params.getCheckEllipsePoints(),
                                             params.getCheckEllipseScale(),
                                             params.check_evals);
            if (params.check_along_path)
                gcheck.checkAlongSimulationAndSave(matfd, params.prefix,
                                                   params.getCheckPathPoints(),
                                                   params.check_evals);
        }

        // write the folded decision rule to the Mat-4 file
        app.getFoldDecisionRule().writeMat(matfd, params.prefix);

        // simulate conditional
        if (params.num_condper > 0 && params.num_condsim > 0) {
            SimResultsDynamicStats rescond(dynare.numeq(), params.num_condper, 0);
            ConstVector det_ss(app.getSS(),0);
            rescond.simulate(params.num_condsim, app.getFoldDecisionRule(), det_ss, dynare.getVcov(), journal);
            rescond.writeMat(matfd, params.prefix);
        }

        // simulate unconditional
        //const DecisionRule& dr = app.getUnfoldDecisionRule();
        const DecisionRule& dr = app.getFoldDecisionRule();
        if (params.num_per > 0 && params.num_sim > 0) {
            SimResultsStats res(dynare.numeq(), params.num_per, params.num_burn);
            res.simulate(params.num_sim, dr, dynare.getSteady(), dynare.getVcov(), journal);
            res.writeMat(matfd, params.prefix);

            // impulse response functions
            if (! irf_list_ind.empty()) {
                IRFResults irf(dynare, dr, res, irf_list_ind, journal);
                irf.writeMat(matfd, params.prefix);
            }
        }

        // simulate with real-time statistics
        if (params.num_rtper > 0 && params.num_rtsim > 0) {
            RTSimResultsStats rtres(dynare.numeq(), params.num_rtper, params.num_burn);
            rtres.simulate(params.num_rtsim, dr, dynare.getSteady(), dynare.getVcov(), journal);
            rtres.writeMat(matfd, params.prefix);
        }

        Mat_Close(matfd);

    } catch (const KordException& e) {
        printf("Caugth Kord exception: ");
        e.print();
        return e.code();
    } catch (const TLException& e) {
        printf("Caugth TL exception: ");
        e.print();
        return 255;
    } catch (SylvException& e) {
        printf("Caught Sylv exception: ");
        e.printMessage();
        return 255;
    } catch (const DynareException& e) {
        printf("Caught Dynare exception: %s\n", e.message());
        return 255;
    } catch (const ogu::Exception& e) {
        printf("Caught ogu::Exception: ");
        e.print();
        return 255;
    } catch (const ogp::ParserException& e) {
        printf("Caught parser exception: %s\n", e.message());
        return 255;
    }

    return 0;
}
Ejemplo n.º 2
0
    /**
     * This test runs multiple crypt simulations and records whether
     * or not labelled cells are in a randomly chosen crypt section.
     */
    void TestMultipleCryptSimulations() throw (Exception)
    {
        std::string output_directory = "MakeMoreMeinekeGraphs";

        double crypt_length = 22.0;

        // Create mesh
        unsigned cells_across = 13;
        unsigned cells_up = 25;
        double crypt_width = 12.1;
        unsigned thickness_of_ghost_layer = 3;

        unsigned num_simulations = 2;

        // Guess of maximum number of cells a crypt section may contain
        unsigned max_length_of_crypt_section = 5 * (unsigned)sqrt(pow(cells_across/2.0+1,2.0) + pow((double)cells_up,2.0));

        std::vector<unsigned> labelled_cells_counter(max_length_of_crypt_section);

        for (unsigned i=0; i<max_length_of_crypt_section; i++)
        {
            labelled_cells_counter[i] = 0;
        }

        double time_of_each_run;
        std::vector<bool> labelled;

        CryptStatistics* p_crypt_statistics;

        // Create cell population
        MeshBasedCellPopulationWithGhostNodes<2>* p_crypt;

        CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer, crypt_width/cells_across);
        std::vector<unsigned> location_indices;

        Cylindrical2dMesh* p_mesh;
        SimulationTime* p_simulation_time;

        // Loop over the number of simulations
        for (unsigned simulation_index=0; simulation_index<num_simulations; simulation_index++)
        {
            // Create new structures for each simulation
            p_mesh = generator.GetCylindricalMesh();
            location_indices = generator.GetCellLocationIndices();

            // Reset start time
            SimulationTime::Destroy();
            p_simulation_time = SimulationTime::Instance();
            p_simulation_time->SetStartTime(0.0);

            // Set up cells
            std::vector<CellPtr> temp_cells;
            CryptCellsGenerator<StochasticDurationGenerationBasedCellCycleModel> cells_generator;
            cells_generator.Generate(temp_cells, p_mesh, std::vector<unsigned>(), true, 0.3, 2.0, 3.0, 4.0, true);

            // This awkward way of setting up the cells is a result of #430
            std::vector<CellPtr> cells;
            for (unsigned i=0; i<location_indices.size(); i++)
            {
                cells.push_back(temp_cells[location_indices[i]]);
            }

            // Set up crypt
            p_crypt = new MeshBasedCellPopulationWithGhostNodes<2>(*p_mesh, cells, location_indices);

            // Set cell population to output cell types
            p_crypt->AddPopulationWriter<CellMutationStatesCountWriter>();

            // Set up crypt simulation
            CryptSimulation2d simulator(*p_crypt, false, false);
            simulator.SetOutputDirectory(output_directory);

            // Set length of simulation here
            time_of_each_run = 10.0*simulator.GetDt(); // for each run
            simulator.SetEndTime(time_of_each_run);

            // Create a force laws and pass it to the simulation
            MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force);
            p_linear_force->SetMeinekeSpringStiffness(30.0); // normally 15.0;
            simulator.AddForce(p_linear_force);

            // Set up cell killer
            MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&simulator.rGetCellPopulation(), crypt_length));
            simulator.AddCellKiller(p_killer);

            simulator.UseJiggledBottomCells();

            // Set up crypt statistics
            p_crypt_statistics = new CryptStatistics(*p_crypt);

            // Run for a bit
            simulator.Solve();
            p_crypt_statistics->LabelSPhaseCells();

            simulator.SetEndTime(2.0*time_of_each_run);
            simulator.Solve();

            std::vector<CellPtr> crypt_section = p_crypt_statistics->GetCryptSection(crypt_length + 2.0, 8.0, 8.0);
            labelled = p_crypt_statistics->AreCryptSectionCellsLabelled(crypt_section);

            // Store information from this simulation in a global vector
            for (unsigned cell_index=0; cell_index < labelled.size(); cell_index++)
            {
                TS_ASSERT(cell_index < labelled_cells_counter.size());

                if (labelled[cell_index])
                {
                    labelled_cells_counter[cell_index]++;
                }
            }

            // Tidy up
            cells.clear();
            labelled.clear();
            WntConcentration<2>::Destroy();

            delete p_crypt_statistics;
            delete p_crypt;
        }

        // Calculate percentage of labelled cells at each position in 'labelled_cells_counter'
        std::vector<double> percentage_of_labelled_cells(max_length_of_crypt_section);
        for (unsigned index=0; index < max_length_of_crypt_section; index ++)
        {
            percentage_of_labelled_cells[index] = (double) labelled_cells_counter[index]/num_simulations;
        }

        // Write data to file
        SimpleDataWriter writer1(output_directory, "percentage_of_labelled_cells.dat", percentage_of_labelled_cells, false);

        // Test against previous run
        // ... and checking visualization of labelled cells against previous run
        OutputFileHandler handler(output_directory, false);
        std::string results_file = handler.GetOutputDirectoryFullPath() + "percentage_of_labelled_cells.dat";
        FileComparison( results_file, "crypt/test/data/MakeMoreMeinekeGraphs/percentage_of_labelled_cells.dat").CompareFiles();

        RandomNumberGenerator::Destroy();
    }