<commit_before>#include <iostream>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
#include "hsl.h"
using namespace std;
using namespace demoloop;

float t = 0;
const float CYCLE_LENGTH = 10;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {
    glDisable(GL_DEPTH_TEST);
  }

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const int num_vertices = 5;
    const float interval = (DEMOLOOP_M_PI * 2) / num_vertices;
    float xCoords[num_vertices];
    float yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    setColor(color);
    polygon(gl, xCoords, yCoords, num_vertices);

    const int dot_count = 20;
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (int t = 0; t < dot_count; ++t) {
        float i = t;
        const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

        const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        setColor(0, 0, 0, 255 * interval_cycle_ratio);
        circle(gl, x1 + ox, y1 + oy, 3);

        if (t == 0) {
          const int n = (v + 1) % num_vertices;
          const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
          const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;

          setColor(0, 0, 0);
          line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);
          line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);
        }
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
      const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;

      setColor(0, 0, 0);
      circle(gl, x1 + ox, y1 + oy, 3);
    }
  }

private:
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<commit_msg>greatly increase loop 5 rendering speed<commit_after>#include <iostream>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
using namespace std;
using namespace demoloop;

float t = 0;
const float CYCLE_LENGTH = 10;

const int num_circle_verts = 10;
const int num_vertices = 5;
const int dot_count = 20;

class Loop5 : public Demoloop {
public:
  Loop5() : Demoloop(150, 150, 150) {
    glDisable(GL_DEPTH_TEST);
  }

  void Update(float dt) {
    t += dt;

    const float RADIUS = height / 3;

    float cycle = fmod(t, CYCLE_LENGTH);
    float cycle_ratio = cycle / CYCLE_LENGTH;
    int ox = width / 2, oy = height / 2;

    const float interval = (DEMOLOOP_M_PI * 2) / num_vertices;
    float xCoords[num_vertices];
    float yCoords[num_vertices];
    for (int i = 0; i < num_vertices; ++i) {
      float t = i;
      xCoords[i] = cos(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + ox;
      yCoords[i] = sin(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + oy;
    }

    auto color = hsl2rgb(cycle_ratio, 1, 0.5);
    setColor(color);
    polygon(gl, xCoords, yCoords, num_vertices);

    int count = 0;

    const RGB black = {0, 0, 0};
    setColor(black);
    for (int v = 0; v < num_vertices; ++v) {
      const float angularOffset = interval * v;
      for (int t = 0; t < dot_count; ++t) {
        const float interval_cycle_ratio = fmod(static_cast<float>(t) / dot_count + cycle_ratio, 1);

        const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
        const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;

        Matrix4 m;
        m.translate(x1 + ox, y1 + oy);
        for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {
          circleVerts[count].x = cosf(0) * 3;
          circleVerts[count].y = sinf(0) * 3;
          circleVerts[count].z = 1;
          circleVerts[count].a = 255 * interval_cycle_ratio;
          applyColor(circleVerts[count], black);
          applyMatrix(circleVerts[count], m);
          count++;

          circleVerts[count].x = cosf(interval * i) * 3;
          circleVerts[count].y = sinf(interval * i) * 3;
          circleVerts[count].z = 1;
          circleVerts[count].a = 255 * interval_cycle_ratio;
          applyColor(circleVerts[count], black);
          applyMatrix(circleVerts[count], m);
          count++;

          circleVerts[count].x = cosf(interval * (i + 1)) * 3;
          circleVerts[count].y = sinf(interval * (i + 1)) * 3;
          circleVerts[count].z = 1;
          circleVerts[count].a = 255 * interval_cycle_ratio;
          applyColor(circleVerts[count], black);
          applyMatrix(circleVerts[count], m);
          count++;
        }

        if (t == 0) {
          const int n = (v + 1) % num_vertices;
          const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
          const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
          const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;

          line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);
          line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);
        }
      }
    }

    for (float i = 0; i < dot_count; ++i) {
      const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);

      const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
      const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;

      Matrix4 m;
      m.translate(x1 + ox, y1 + oy);
      for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {
        circleVerts[count].x = cosf(0) * 3;
        circleVerts[count].y = sinf(0) * 3;
        circleVerts[count].z = 1;
        applyColor(circleVerts[count], black);
        applyMatrix(circleVerts[count], m);
        count++;

        circleVerts[count].x = cosf(interval * i) * 3;
        circleVerts[count].y = sinf(interval * i) * 3;
        circleVerts[count].z = 1;
        applyColor(circleVerts[count], black);
        applyMatrix(circleVerts[count], m);
        count++;

        circleVerts[count].x = cosf(interval * (i + 1)) * 3;
        circleVerts[count].y = sinf(interval * (i + 1)) * 3;
        circleVerts[count].z = 1;
        applyColor(circleVerts[count], black);
        applyMatrix(circleVerts[count], m);
        count++;
      }
    }

    gl.triangles(circleVerts, count);
  }

private:
  Vertex circleVerts[(num_circle_verts - 1) * 3 * dot_count * (num_vertices + 1)];
};

int main(int, char**){
  Loop5 loop;
  loop.Run();

  return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
  nucBedMain.cpp

  (c) 2009 - Aaron Quinlan
  Hall Laboratory
  Department of Biochemistry and Molecular Genetics
  University of Virginia
  aaronquinlan@gmail.com

  Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "nucBed.h"
#include "version.h"

using namespace std;

// define our program name
#define PROGRAM_NAME "bedtools nuc"

// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)

// function declarations
void nuc_help(void);

int nuc_main(int argc, char* argv[]) {

    // our configuration variables
    bool showHelp = false;

    // input files
    string fastaDbFile;
    string bedFile;
    string pattern;

    // checks for existence of parameters
    bool haveFastaDb   = false;
    bool haveBed       = false;
    bool printSeq      = false;
    bool hasPattern    = false;
    bool forceStrand   = false;
    bool ignoreCase    = false;
    bool useFullHeader = false;

    // check to see if we should print out some help
    if(argc <= 1) showHelp = true;

    for(int i = 1; i < argc; i++) {
        int parameterLength = (int)strlen(argv[i]);

        if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
        (PARAMETER_CHECK("--help", 5, parameterLength))) {
            showHelp = true;
        }
    }

    if(showHelp) nuc_help();

    // do some parsing (all of these parameters require 2 strings)
    for(int i = 1; i < argc; i++) {

        int parameterLength = (int)strlen(argv[i]);

        if(PARAMETER_CHECK("-fi", 3, parameterLength)) {
            if ((i+1) < argc) {
                haveFastaDb = true;
                fastaDbFile = argv[i + 1];
                i++;
            }
        }
        else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
            if ((i+1) < argc) {
                haveBed = true;
                bedFile = argv[i + 1];
                i++;
            }
        }
        else if(PARAMETER_CHECK("-seq", 4, parameterLength)) {
            printSeq = true;
        }
        else if(PARAMETER_CHECK("-s", 2, parameterLength)) {
            forceStrand = true;
        }
        else if(PARAMETER_CHECK("-C", 2, parameterLength)) {
            ignoreCase = true;
        }
        else if(PARAMETER_CHECK("-pattern", 8, parameterLength)) {
            if ((i+1) < argc) {
                hasPattern = true;
                pattern = argv[i + 1];
                i++;
            }
	}
        else if(PARAMETER_CHECK("-useFullHeader", 11, parameterLength)) {
            useFullHeader = true;
        }
        else {
            cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
            showHelp = true;
        }
    }

    if (!haveFastaDb || !haveBed) {
        showHelp = true;
    }

    if (!showHelp) {

        NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq,
                                 hasPattern, pattern, forceStrand, ignoreCase,
				 useFullHeader);
        delete nuc;
    }
    else {
        nuc_help();
    }
    return 0;
}

void nuc_help(void) {

    cerr << "\nTool:    bedtools nuc (aka nucBed)" << endl;
    cerr << "Version: " << VERSION << "\n";
    cerr << "Summary: Profiles the nucleotide content of intervals in a fasta file." << endl << endl;

    cerr << "Usage:   " << PROGRAM_NAME << " [OPTIONS] -fi <fasta> -bed <bed/gff/vcf>" << endl << endl;

    cerr << "Options: " << endl;

    cerr << "\t-fi\tInput FASTA file" << endl << endl;

    cerr << "\t-bed\tBED/GFF/VCF file of ranges to extract from -fi" << endl << endl;

    cerr << "\t-s\tProfile the sequence according to strand." << endl << endl;

    cerr << "\t-seq\tPrint the extracted sequence" << endl << endl;

    cerr << "\t-pattern\tReport the number of times a user-defined sequence" << endl;
    cerr << "\t\t\tis observed (case-sensitive)." << endl << endl;

    cerr << "\t-C\tIgnore case when matching -pattern. By defaulty, case matters." << endl << endl;

    cerr << "\t-fullHeader\tUse full fasta header." << endl;
    cerr << "\t\t- By default, only the word before the first space or tab "
	 << "is used." << endl << endl;

    cerr << "Output format: " << endl;
    cerr << "\tThe following information will be reported after each BED entry:" << endl;
    cerr << "\t    1) %AT content" << endl;
    cerr << "\t    2) %GC content" << endl;
    cerr << "\t    3) Number of As observed" << endl;
    cerr << "\t    4) Number of Cs observed" << endl;
    cerr << "\t    5) Number of Gs observed" << endl;
    cerr << "\t    6) Number of Ts observed" << endl;
    cerr << "\t    7) Number of Ns observed" << endl;
    cerr << "\t    8) Number of other bases observed" << endl;
    cerr << "\t    9) The length of the explored sequence/interval." << endl;
    cerr << "\t    10) The seq. extracted from the FASTA file. (opt., if -seq is used)" << endl;
    cerr << "\t    11) The number of times a user's pattern was observed." << endl;
    cerr << "\t        (opt., if -pattern is used.)" << endl << endl;
    // end the program here
    exit(1);

}
<commit_msg>typo on option -useFullHeader<commit_after>/*****************************************************************************
  nucBedMain.cpp

  (c) 2009 - Aaron Quinlan
  Hall Laboratory
  Department of Biochemistry and Molecular Genetics
  University of Virginia
  aaronquinlan@gmail.com

  Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "nucBed.h"
#include "version.h"

using namespace std;

// define our program name
#define PROGRAM_NAME "bedtools nuc"

// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)

// function declarations
void nuc_help(void);

int nuc_main(int argc, char* argv[]) {

    // our configuration variables
    bool showHelp = false;

    // input files
    string fastaDbFile;
    string bedFile;
    string pattern;

    // checks for existence of parameters
    bool haveFastaDb   = false;
    bool haveBed       = false;
    bool printSeq      = false;
    bool hasPattern    = false;
    bool forceStrand   = false;
    bool ignoreCase    = false;
    bool useFullHeader = false;

    // check to see if we should print out some help
    if(argc <= 1) showHelp = true;

    for(int i = 1; i < argc; i++) {
        int parameterLength = (int)strlen(argv[i]);

        if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
        (PARAMETER_CHECK("--help", 5, parameterLength))) {
            showHelp = true;
        }
    }

    if(showHelp) nuc_help();

    // do some parsing (all of these parameters require 2 strings)
    for(int i = 1; i < argc; i++) {

        int parameterLength = (int)strlen(argv[i]);

        if(PARAMETER_CHECK("-fi", 3, parameterLength)) {
            if ((i+1) < argc) {
                haveFastaDb = true;
                fastaDbFile = argv[i + 1];
                i++;
            }
        }
        else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
            if ((i+1) < argc) {
                haveBed = true;
                bedFile = argv[i + 1];
                i++;
            }
        }
        else if(PARAMETER_CHECK("-seq", 4, parameterLength)) {
            printSeq = true;
        }
        else if(PARAMETER_CHECK("-s", 2, parameterLength)) {
            forceStrand = true;
        }
        else if(PARAMETER_CHECK("-C", 2, parameterLength)) {
            ignoreCase = true;
        }
        else if(PARAMETER_CHECK("-pattern", 8, parameterLength)) {
            if ((i+1) < argc) {
                hasPattern = true;
                pattern = argv[i + 1];
                i++;
            }
	}
        else if(PARAMETER_CHECK("-fullHeader", 11, parameterLength)) {
            useFullHeader = true;
        }
        else {
            cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
            showHelp = true;
        }
    }

    if (!haveFastaDb || !haveBed) {
        showHelp = true;
    }

    if (!showHelp) {

        NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq,
                                 hasPattern, pattern, forceStrand, ignoreCase,
				 useFullHeader);
        delete nuc;
    }
    else {
        nuc_help();
    }
    return 0;
}

void nuc_help(void) {

    cerr << "\nTool:    bedtools nuc (aka nucBed)" << endl;
    cerr << "Version: " << VERSION << "\n";
    cerr << "Summary: Profiles the nucleotide content of intervals in a fasta file." << endl << endl;

    cerr << "Usage:   " << PROGRAM_NAME << " [OPTIONS] -fi <fasta> -bed <bed/gff/vcf>" << endl << endl;

    cerr << "Options: " << endl;

    cerr << "\t-fi\tInput FASTA file" << endl << endl;

    cerr << "\t-bed\tBED/GFF/VCF file of ranges to extract from -fi" << endl << endl;

    cerr << "\t-s\tProfile the sequence according to strand." << endl << endl;

    cerr << "\t-seq\tPrint the extracted sequence" << endl << endl;

    cerr << "\t-pattern\tReport the number of times a user-defined sequence" << endl;
    cerr << "\t\t\tis observed (case-sensitive)." << endl << endl;

    cerr << "\t-C\tIgnore case when matching -pattern. By defaulty, case matters." << endl << endl;

    cerr << "\t-fullHeader\tUse full fasta header." << endl;
    cerr << "\t\t- By default, only the word before the first space or tab "
	 << "is used." << endl << endl;

    cerr << "Output format: " << endl;
    cerr << "\tThe following information will be reported after each BED entry:" << endl;
    cerr << "\t    1) %AT content" << endl;
    cerr << "\t    2) %GC content" << endl;
    cerr << "\t    3) Number of As observed" << endl;
    cerr << "\t    4) Number of Cs observed" << endl;
    cerr << "\t    5) Number of Gs observed" << endl;
    cerr << "\t    6) Number of Ts observed" << endl;
    cerr << "\t    7) Number of Ns observed" << endl;
    cerr << "\t    8) Number of other bases observed" << endl;
    cerr << "\t    9) The length of the explored sequence/interval." << endl;
    cerr << "\t    10) The seq. extracted from the FASTA file. (opt., if -seq is used)" << endl;
    cerr << "\t    11) The number of times a user's pattern was observed." << endl;
    cerr << "\t        (opt., if -pattern is used.)" << endl << endl;
    // end the program here
    exit(1);

}
<|endoftext|>


<commit_before>#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QWidget>

#include <cstdlib>
#include <iostream>

#include "GlowneOkno.hpp"
#include "WyborPortu.hpp"
#include "KodyWyjsciowe.hpp"

const char* bledy[14]=
{
	"Brak błędu",
	"Nie znaleziono urządzenia",
	"Brak uprawnień (być może port jest używany przez inny program)",
	"Port jest już otwarty",
	"Błąd parzystości",
	"Błąd ramki",
	"Błąd stanu przerwy (rodzaj błędu ramki)",
	"Ogólny błąd wysyłania",
	"Ogólny błąd odczytu",
	"Błąd zasobów (np. port został odłączony w czasie pracy programu)",
	"Niedozwolona operacja",
	"Nieznany błąd",
	"Upłynął limit czasu oczekiwania",
	"Port nie został prawidłowo otwarty"
};

GlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)
{
	setupRS();

	setupOkno();
    setupRozklad();
    setupWyslij();
    setupReset();
    setupTemperatura();
    setupWykres();

    okno_->show();
}

GlowneOkno::~GlowneOkno()
{
	zadanaTemperatura_->setValue(0);
	ustawTemperature();
    rs232_->close();

    delete rs232_;
    delete zadanaTemperatura_;
    delete wyslij_;
    delete reset_;
    delete wykres_;
    //delete danePomiaroweWykres_;

    czas_.clear();
    temperatura_.clear();

    delete okno_;
}

void GlowneOkno::setupOkno(void)
{
	okno_=new QWidget();
	okno_->resize(800,600);
	okno_->setWindowTitle("Kontroler temperatury");
}

void GlowneOkno::setupRozklad(void)
{
	glownyRozmieszczacz_=new QVBoxLayout(okno_);
	okno_->setLayout(glownyRozmieszczacz_);
}

void GlowneOkno::setupRS(void)
{
	rs232_=new QSerialPort(this);
	QStringList itemList;
	int wybor=QMessageBox::Retry;
	do
	{
		itemList.clear();
		Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
		{
			itemList<<port.portName();
			qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
		}
		if(itemList.isEmpty())
		{
			QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", "Nie wykryto żadnego portu szeregowego! \nSprawdź czy port jest dostępny i podejmij ponowną próbę konfiguracji lub zakończ program.", QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
			wybor=pytanie.exec();

			if(wybor==QMessageBox::Abort)
			{
				QMessageBox(QMessageBox::Critical, "Brak portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
				exit(BRAK_PORTU);
			}
		}
	}
	while(itemList.isEmpty()&&wybor!=QMessageBox::Ignore);

	WyborPortu dialog(itemList);

	int wynik;
	do
	{
		wynik=dialog.exec();
		rs232_->setPortName(dialog.poleKombi()->currentText());
		if(wynik==QDialog::Rejected)
		{
			QMessageBox(QMessageBox::Critical, "Nie wybrano portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
			exit(2);
		}
	}
	while(wynik != QDialog::Accepted);

	rs232_->open (QIODevice::ReadWrite);
	rs232_->setBaudRate (QSerialPort::Baud57600);
	rs232_->setDataBits (QSerialPort::Data8);
	rs232_->setStopBits (QSerialPort::OneStop);
	rs232_->setParity (QSerialPort::NoParity);
	rs232_->setFlowControl (QSerialPort::NoFlowControl);
	rs232_->clear();
    std::cerr<<rs232_->error()<<std::endl;

    QObject::connect(rs232_, SIGNAL(readyRead()),this, SLOT(odbierzDane()));
}

void GlowneOkno::setupTemperatura(void)
{
	zadanaTemperatura_=new QSpinBox;
	glownyRozmieszczacz_->addWidget(zadanaTemperatura_);
    zadanaTemperatura_->setRange(0, 999);
    zadanaTemperatura_->setSingleStep(1);
    zadanaTemperatura_->setSuffix(" ℃");
}

void GlowneOkno::setupWyslij(void)
{
	wyslij_=new QPushButton("Ustaw");
	wyslij_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(wyslij_);

	QObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));
}

void GlowneOkno::setupZatrzymajGrzanie(void)
{
	zatrzymajGrzanie_=new QPushButton("ZatrzymajGrzanie");
	zatrzymajGrzanie_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);
}

void GlowneOkno::setupReset(void)
{
	reset_=new QPushButton("Reset");
	reset_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(reset_);

	QObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));
}

void GlowneOkno::setupWykres(void)
{
	wykres_=new QwtPlot;
	glownyRozmieszczacz_->addWidget(wykres_);
	wykres_->setTitle ("Bieżąca temperatura próbki");
	wykres_->setAxisTitle (QwtPlot::xBottom, "Czas /s");
	wykres_->setAxisTitle (QwtPlot::yLeft, "Temperatura /℃");
	wykres_->setCanvasBackground(QBrush (Qt::white));
	wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
	wykres_->setAxisScale (QwtPlot::yLeft, 0, 800);

	danePomiaroweWykres_=new QwtPlotCurve;

	danePomiaroweWykres_->setTitle("Temperatura");
	danePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),
	danePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);
}

bool GlowneOkno::wyslijRozkaz(const char* rozkaz)
{
	QSerialPort::SerialPortError error;
	bool stan=true;
	do
	{
		error=rs232_->error();
		if(error!=QSerialPort::NoError)
		{
			stan=obsluzBladRS(error);
		}
		else
		{
			stan=false;
		}
	}
	while(stan);

	if(error==QSerialPort::NoError)
	{
		rs232_->write(rozkaz);
		return OK;
	}
	return BLAD_PORTU;
}

void GlowneOkno::ustawTemperature(void)
{
	char tmp[4];
	int t=zadanaTemperatura_->value();
	sprintf(tmp,"T%03i",t);

	if(wyslijRozkaz(tmp)==OK)
		std::cerr<<tmp<<std::endl;
}

void GlowneOkno::odbierzDane(void)
{
	char tmpTekst[1024];
	char tmp[256];
	uint32_t tmpCzas=0;
	uint32_t tmpTemperatura=0;

	rs232_->readLine(tmpTekst,1023);
	rs232_->clear();
	sscanf(tmpTekst,"%u,%u,%s",&(tmpCzas),&(tmpTemperatura),tmp);

	czas_.push_back((double)tmpCzas);
	temperatura_.push_back((double)tmpTemperatura);

	danePomiaroweWykres_->setSamples(czas_,temperatura_);
	danePomiaroweWykres_->attach(wykres_);

	if(czas_.last()>120)
		wykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());
	else
		wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);

	wykres_->replot();
	std::cout<<tmpCzas<<" "<<tmpTemperatura<<std::endl;
}

bool GlowneOkno::obsluzBladRS(QSerialPort::SerialPortError kod_bledu)
{
	char opis_bledu[128];
	sprintf(opis_bledu,"Błąd portu szeregowego %i:\n%s.",kod_bledu,bledy[kod_bledu]);
	QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", opis_bledu, QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
	std::cerr<<opis_bledu<<std::endl;

	int wynik=pytanie.exec();

	if(wynik==QMessageBox::Abort)
	{
		QMessageBox(QMessageBox::Critical, "Błąd portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
		exit(BLAD_PORTU);
		return false;
	}
	if(wynik==QMessageBox::Retry)
	{
		return true;
	}
	//jeśli ani abort ani retry, to ignore
	return false;
}

void GlowneOkno::zrestartujUrzadenie(void)
{
	if(wyslijRozkaz("R")==OK)
	{
		czas_.clear();
		temperatura_.clear();
	}
}

#include "GlowneOkno.moc"
<commit_msg>Przy odbiorze komunikatów z układu program będzie sprawdzał, czy wysyłana wiadomość jest wynikiem pomiaru. Ponieważ wyniki pomiarów mają stałą długość (liczby są uzupełniane zerami), to można kontrolować zgodność przez sprawdzenie, czy przecinki rozdzielające wartości występują w konkretnych punktach łańcucha znaków.<commit_after>#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QWidget>

#include <cstdlib>
#include <iostream>

#include "GlowneOkno.hpp"
#include "WyborPortu.hpp"
#include "KodyWyjsciowe.hpp"

const char* bledy[14]=
{
	"Brak błędu",
	"Nie znaleziono urządzenia",
	"Brak uprawnień (być może port jest używany przez inny program)",
	"Port jest już otwarty",
	"Błąd parzystości",
	"Błąd ramki",
	"Błąd stanu przerwy (rodzaj błędu ramki)",
	"Ogólny błąd wysyłania",
	"Ogólny błąd odczytu",
	"Błąd zasobów (np. port został odłączony w czasie pracy programu)",
	"Niedozwolona operacja",
	"Nieznany błąd",
	"Upłynął limit czasu oczekiwania",
	"Port nie został prawidłowo otwarty"
};

GlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)
{
	setupRS();

	setupOkno();
    setupRozklad();
    setupWyslij();
    setupReset();
    setupTemperatura();
    setupWykres();

    okno_->show();
}

GlowneOkno::~GlowneOkno()
{
	zadanaTemperatura_->setValue(0);
	ustawTemperature();
    rs232_->close();

    delete rs232_;
    delete zadanaTemperatura_;
    delete wyslij_;
    delete reset_;
    delete wykres_;
    //delete danePomiaroweWykres_;

    czas_.clear();
    temperatura_.clear();

    delete okno_;
}

void GlowneOkno::setupOkno(void)
{
	okno_=new QWidget();
	okno_->resize(800,600);
	okno_->setWindowTitle("Kontroler temperatury");
}

void GlowneOkno::setupRozklad(void)
{
	glownyRozmieszczacz_=new QVBoxLayout(okno_);
	okno_->setLayout(glownyRozmieszczacz_);
}

void GlowneOkno::setupRS(void)
{
	rs232_=new QSerialPort(this);
	QStringList itemList;
	int wybor=QMessageBox::Retry;
	do
	{
		itemList.clear();
		Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
		{
			itemList<<port.portName();
			qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
		}
		if(itemList.isEmpty())
		{
			QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", "Nie wykryto żadnego portu szeregowego! \nSprawdź czy port jest dostępny i podejmij ponowną próbę konfiguracji lub zakończ program.", QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
			wybor=pytanie.exec();

			if(wybor==QMessageBox::Abort)
			{
				QMessageBox(QMessageBox::Critical, "Brak portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
				exit(BRAK_PORTU);
			}
		}
	}
	while(itemList.isEmpty()&&wybor!=QMessageBox::Ignore);

	WyborPortu dialog(itemList);

	int wynik;
	do
	{
		wynik=dialog.exec();
		rs232_->setPortName(dialog.poleKombi()->currentText());
		if(wynik==QDialog::Rejected)
		{
			QMessageBox(QMessageBox::Critical, "Nie wybrano portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
			exit(2);
		}
	}
	while(wynik != QDialog::Accepted);

	rs232_->open (QIODevice::ReadWrite);
	rs232_->setBaudRate (QSerialPort::Baud57600);
	rs232_->setDataBits (QSerialPort::Data8);
	rs232_->setStopBits (QSerialPort::OneStop);
	rs232_->setParity (QSerialPort::NoParity);
	rs232_->setFlowControl (QSerialPort::NoFlowControl);
	rs232_->clear();
    std::cerr<<rs232_->error()<<std::endl;

    QObject::connect(rs232_, SIGNAL(readyRead()),this, SLOT(odbierzDane()));
}

void GlowneOkno::setupTemperatura(void)
{
	zadanaTemperatura_=new QSpinBox;
	glownyRozmieszczacz_->addWidget(zadanaTemperatura_);
    zadanaTemperatura_->setRange(0, 999);
    zadanaTemperatura_->setSingleStep(1);
    zadanaTemperatura_->setSuffix(" ℃");
}

void GlowneOkno::setupWyslij(void)
{
	wyslij_=new QPushButton("Ustaw");
	wyslij_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(wyslij_);

	QObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));
}

void GlowneOkno::setupZatrzymajGrzanie(void)
{
	zatrzymajGrzanie_=new QPushButton("ZatrzymajGrzanie");
	zatrzymajGrzanie_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);
}

void GlowneOkno::setupReset(void)
{
	reset_=new QPushButton("Reset");
	reset_->setFixedSize(100,20);
	glownyRozmieszczacz_->addWidget(reset_);

	QObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));
}

void GlowneOkno::setupWykres(void)
{
	wykres_=new QwtPlot;
	glownyRozmieszczacz_->addWidget(wykres_);
	wykres_->setTitle ("Bieżąca temperatura próbki");
	wykres_->setAxisTitle (QwtPlot::xBottom, "Czas /s");
	wykres_->setAxisTitle (QwtPlot::yLeft, "Temperatura /℃");
	wykres_->setCanvasBackground(QBrush (Qt::white));
	wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
	wykres_->setAxisScale (QwtPlot::yLeft, 0, 800);

	danePomiaroweWykres_=new QwtPlotCurve;

	danePomiaroweWykres_->setTitle("Temperatura");
	danePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),
	danePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);
}

bool GlowneOkno::wyslijRozkaz(const char* rozkaz)
{
	QSerialPort::SerialPortError error;
	bool stan=true;
	do
	{
		error=rs232_->error();
		if(error!=QSerialPort::NoError)
		{
			stan=obsluzBladRS(error);
		}
		else
		{
			stan=false;
		}
	}
	while(stan);

	if(error==QSerialPort::NoError)
	{
		rs232_->write(rozkaz);
		return OK;
	}
	return BLAD_PORTU;
}

void GlowneOkno::ustawTemperature(void)
{
	char tmp[4];
	int t=zadanaTemperatura_->value();
	sprintf(tmp,"T%03i",t);

	if(wyslijRozkaz(tmp)==OK)
		std::cerr<<tmp<<std::endl;
}

void GlowneOkno::odbierzDane(void)
{
	char tmpTekst[1024];
	char tmp[256];
	uint32_t tmpCzas=0;
	uint32_t tmpTemperatura=0;

	rs232_->readLine(tmpTekst,1023);
	rs232_->clear();

	if((tmpTekst[10]==',')&&(tmpTekst[17]==','))
	{
		sscanf(tmpTekst,"%u,%u,%s",&(tmpCzas),&(tmpTemperatura),tmp);

		czas_.push_back((double)tmpCzas);
		temperatura_.push_back((double)tmpTemperatura);

		danePomiaroweWykres_->setSamples(czas_,temperatura_);
		danePomiaroweWykres_->attach(wykres_);

		if(czas_.last()>120)
			wykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());
		else
			wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);

		wykres_->replot();
		std::cout<<tmpCzas<<" "<<tmpTemperatura<<std::endl;
	}
	else
	{
		std::cout<<tmpTekst;
	}
}

bool GlowneOkno::obsluzBladRS(QSerialPort::SerialPortError kod_bledu)
{
	char opis_bledu[128];
	sprintf(opis_bledu,"Błąd portu szeregowego %i:\n%s.",kod_bledu,bledy[kod_bledu]);
	QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", opis_bledu, QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
	std::cerr<<opis_bledu<<std::endl;

	int wynik=pytanie.exec();

	if(wynik==QMessageBox::Abort)
	{
		QMessageBox(QMessageBox::Critical, "Błąd portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
		exit(BLAD_PORTU);
		return false;
	}
	if(wynik==QMessageBox::Retry)
	{
		return true;
	}
	//jeśli ani abort ani retry, to ignore
	return false;
}

void GlowneOkno::zrestartujUrzadenie(void)
{
	if(wyslijRozkaz("R")==OK)
	{
		czas_.clear();
		temperatura_.clear();
	}
}

#include "GlowneOkno.moc"
<|endoftext|>


<commit_before>#include "seatest.h"

#include <stdlib.h>

#include "picture.h"

//////////////////////////////////////////////////////////////////////////
// EXTERNAL FUNCTIONS
unsigned get_block_sad(picture *pic, picture *ref,
                       int pic_x, int pic_y, int ref_x, int ref_y,
                       int block_width, int block_height);

//////////////////////////////////////////////////////////////////////////
// DEFINES
#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)

//////////////////////////////////////////////////////////////////////////
// GLOBALS
const uint8_t ref_data[64] = {
  1,2,2,2,2,2,2,3,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  7,8,8,8,8,8,8,9
};

const uint8_t pic_data[64] = {
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1
};

picture *g_pic = 0;
picture *g_ref = 0;

//////////////////////////////////////////////////////////////////////////
// SETUP, TEARDOWN AND HELPER FUNCTIONS
void sad_setup(void)
{
  unsigned i;
  g_pic = picture_init(8, 8, 1, 1);
  for (i = 0; i < 64; ++i) {
    g_pic->y_data[i] = pic_data[i] + 48;
  }

  g_ref = picture_init(8, 8, 1, 1);
  for (i = 0; i < 64; ++i) {
    g_ref->y_data[i] = ref_data[i] + 48;
  }
}

void sad_teardown(void)
{
  free(g_pic); g_pic = 0;
  free(g_ref); g_ref = 0;
}

//////////////////////////////////////////////////////////////////////////
// TESTS
void test_topleft(void)
{
  assert_ulong_equal(
    1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(-3, -3));
}

void test_top(void)
{
  assert_ulong_equal(
    (1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,
    TEST_SAD(0, -3));
}

void test_topright(void)
{
  assert_ulong_equal(
    3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(3, -3));
}

void test_left(void)
{
  assert_ulong_equal(
    (1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,
    TEST_SAD(-3, 0));
}

void test_no_offset(void)
{
  assert_ulong_equal(
    (1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,
    TEST_SAD(0, 0));
}

void test_right(void)
{
  assert_ulong_equal(
    (3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,
    TEST_SAD(3, 0));
}

void test_bottomleft(void)
{
  assert_ulong_equal(
    7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(-3, 3));
}

void test_bottom(void)
{
  assert_ulong_equal(
    (7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,
    TEST_SAD(0, 3));
}

void test_bottomright(void)
{
  assert_ulong_equal(
    9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(3, 3));
}

//////////////////////////////////////////////////////////////////////////
// TEST FIXTURES
void sad_tests(void)
{
  test_fixture_start();
  fixture_setup(sad_setup);

  run_test(test_topleft);
  run_test(test_top);
  run_test(test_topright);

  run_test(test_left);
  run_test(test_no_offset);
  run_test(test_right);

  run_test(test_bottomleft);
  run_test(test_bottom);
  run_test(test_bottomright);

  fixture_teardown(sad_teardown);
  test_fixture_end();
}

<commit_msg>Add tests for movement vectors that are completely out of frame.<commit_after>#include "seatest.h"

#include <stdlib.h>

#include "picture.h"

//////////////////////////////////////////////////////////////////////////
// EXTERNAL FUNCTIONS
unsigned get_block_sad(picture *pic, picture *ref,
                       int pic_x, int pic_y, int ref_x, int ref_y,
                       int block_width, int block_height);

//////////////////////////////////////////////////////////////////////////
// DEFINES
#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)

//////////////////////////////////////////////////////////////////////////
// GLOBALS
const uint8_t ref_data[64] = {
  1,2,2,2,2,2,2,3,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  4,5,5,5,5,5,5,6,
  7,8,8,8,8,8,8,9
};

const uint8_t pic_data[64] = {
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1
};

picture *g_pic = 0;
picture *g_ref = 0;

//////////////////////////////////////////////////////////////////////////
// SETUP, TEARDOWN AND HELPER FUNCTIONS
void sad_setup(void)
{
  unsigned i;
  g_pic = picture_init(8, 8, 1, 1);
  for (i = 0; i < 64; ++i) {
    g_pic->y_data[i] = pic_data[i] + 48;
  }

  g_ref = picture_init(8, 8, 1, 1);
  for (i = 0; i < 64; ++i) {
    g_ref->y_data[i] = ref_data[i] + 48;
  }
}

void sad_teardown(void)
{
  free(g_pic); g_pic = 0;
  free(g_ref); g_ref = 0;
}

//////////////////////////////////////////////////////////////////////////
// OVERLAPPING BOUNDARY TESTS
void test_topleft(void)
{
  assert_ulong_equal(
    1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(-3, -3));
}

void test_top(void)
{
  assert_ulong_equal(
    (1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,
    TEST_SAD(0, -3));
}

void test_topright(void)
{
  assert_ulong_equal(
    3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(3, -3));
}

void test_left(void)
{
  assert_ulong_equal(
    (1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,
    TEST_SAD(-3, 0));
}

void test_no_offset(void)
{
  assert_ulong_equal(
    (1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,
    TEST_SAD(0, 0));
}

void test_right(void)
{
  assert_ulong_equal(
    (3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,
    TEST_SAD(3, 0));
}

void test_bottomleft(void)
{
  assert_ulong_equal(
    7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(-3, 3));
}

void test_bottom(void)
{
  assert_ulong_equal(
    (7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,
    TEST_SAD(0, 3));
}

void test_bottomright(void)
{
  assert_ulong_equal(
    9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,
    TEST_SAD(3, 3));
}

//////////////////////////////////////////////////////////////////////////
// OUT OF FRAME TESTS

void test_topleft_out(void)
{
  assert_ulong_equal(
    1*(8*8) - 64,
    TEST_SAD(-8, -8));
}

void test_top_out(void)
{
  assert_ulong_equal(
    (1+3)*8 + 2*(6*8) - 64,
    TEST_SAD(0, -8));
}

void test_topright_out(void)
{
  assert_ulong_equal(
    3*(8*8) - 64,
    TEST_SAD(8, -8));
}

void test_left_out(void)
{
  assert_ulong_equal(
    (1+7)*8 + 4*(6*8) - 64,
    TEST_SAD(-8, 0));
}

void test_right_out(void)
{
  assert_ulong_equal(
    (3+9)*8 + 6*(6*8) - 64,
    TEST_SAD(8, 0));
}

void test_bottomleft_out(void)
{
  assert_ulong_equal(
    7*(8*8) - 64,
    TEST_SAD(-8, 8));
}

void test_bottom_out(void)
{
  assert_ulong_equal(
    (7+9)*8 + 8*(6*8) - 64,
    TEST_SAD(0, 8));
}

void test_bottomright_out(void)
{
  assert_ulong_equal(
    9*(8*8) - 64,
    TEST_SAD(8, 8));
}

//////////////////////////////////////////////////////////////////////////
// TEST FIXTURES
void sad_tests(void)
{
  test_fixture_start();
  fixture_setup(sad_setup);

  // Tests for movement vectors that overlap frame.
  run_test(test_topleft);
  run_test(test_top);
  run_test(test_topright);

  run_test(test_left);
  run_test(test_no_offset);
  run_test(test_right);

  run_test(test_bottomleft);
  run_test(test_bottom);
  run_test(test_bottomright);

  // Tests for movement vectors that are outside the frame.
  run_test(test_topleft_out);
  run_test(test_top_out);
  run_test(test_topright_out);

  run_test(test_left_out);
  run_test(test_right_out);

  run_test(test_bottomleft_out);
  run_test(test_bottom_out);
  run_test(test_bottomright_out);

  fixture_teardown(sad_teardown);
  test_fixture_end();
}

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <math.h>

using namespace std;

int main(int argc, char* argv[]) {
    string line;
	int linenumber = 0;
	int category =0;
	double value = 0.0;
	int errors = 0;

    if(argc < 2) {
        cerr << "provide at least one argument" << endl;
        return 1;
        }
    cout << "* trying to open and read: " << argv[1] << endl;

    ifstream f (argv[1]);

	double absValOne = 0.0;

	double aV1_1 = 0.0;
	double aV1_2 = 0.0;

    double absValTwo = 0.0;

    double aV2_1 = 0.0;
    double aV2_2 = 0.0;

    int wB1 = 0;
    int wB2 = 0;

	int cntOne = 0;
	int cntTwo = 0;

    int track = 0;

    while(getline(f, line)) {
		size_t posr;
        track++;

		if((posr = line.find("#")) == 0){
			//std::cout << "ignoring line" << std::endl;
			continue;
		}

		if(line[0] == '\n'){
			//std::cout << "ignoring line" << std::endl;
			continue;
		}

        std::string s = line;
		std::string delimiter = ";";

		int cat = 0;
		size_t pos = 0;
		std::string token;

		while ((pos = s.find(delimiter)) != std::string::npos) {

			token = s.substr(0, pos);

			if(cat==0){
				try{
					linenumber = std::stoi(token);
				}catch(...){
					errors++;
                    //std::cout << "linenumber" << std::endl;
                    //std::cout << track << std::endl;
					break;
				}
				cat=1;
				s.erase(0, pos + delimiter.length());
			}

			else if(cat==1){
				try{
					category = std::stoi(token);
				}catch(...){
					errors++;
                    //std::cout << "cat" << std::endl;
                    // std::cout << track << std::endl;
					break;
				}

				s.erase(0, pos + delimiter.length());

				try{
					value = std::stod(s);

					//Checking if value is a proper double format
					if(!(value < 0.0 || value >= 0.0)){
						errors++;
						break;
					}

                    if(value<=0){
                        //std::cout << "errsth0" << std::endl;
                        break;
                    }

				}catch(...){
					errors++;
                    //std::cout << "val" << std::endl;
                    //std::cout << track << std::endl;
					break;
				}

				if(category==1){
					cntOne++;
					absValOne+= log(value);

				}
				else if(category==2){
					cntTwo++;
					absValTwo += log(value);

				}
                else break;
				cat=0;

			}

		}

		/*if(linenumber%100000==0){
					std::cout << linenumber << std::endl;
					std::cout << "Category One" << std::endl;
					std::cout << aV1_1 << std::endl;
					std::cout << aV1_2 << std::endl;
					std::cout << cntOne << std::endl;
					std::cout << absValOne/cntOne << std::endl;
					std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;

					std::cout << "Category Two" << std::endl;
					std::cout << aV2_1 << std::endl;
					std::cout << aV2_2 << std::endl;
					std::cout << cntTwo << std::endl;
					std::cout << absValTwo/cntTwo << std::endl;
					std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;

					std::cout << "Errors occured" << std::endl;
					std::cout << errors << std::endl;
					std::cout << "\n" << std::endl;
			}*/

    }

	f.close();
    std::cout << "Results:" << std::endl;
	std::cout << "Category One" << std::endl;
	std::cout << "Valid lines: ";
	std::cout << cntOne << std::endl;
	std::cout << "Geo Mean: ";
	//std::cout << exp(aV1_1/cntOne + aV1_2/cntOne) << std::endl;
	std::cout << exp(absValOne/cntOne) << std::endl;
	std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;

	std::cout << "Category Two" << std::endl;
	std::cout << "Valid lines: ";
	std::cout << cntTwo << std::endl;
	std::cout << "Geo Mean: ";
	//std::cout << exp(aV2_1/cntOne + aV2_2/cntOne) << std::endl;
	std::cout << exp(absValTwo/cntTwo) << std::endl;
	std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;

	std::cout << "Errors occured" << std::endl;
	std::cout << errors << std::endl;

    return 0;
}

<commit_msg>Delete ass01_01.cpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
//            ------------------------------------------------
//            Extrapolation Miniapp: PDE-based extrapolation
//            ------------------------------------------------
//
// Compile with: make extrapolate
//
// Sample runs:
//     mpirun -np 4 extrapolate -o 3
//     mpirun -np 4 extrapolate -rs 3 -dt 0.002 -o 2 -p 1

#include <fstream>
#include <iostream>
#include "../common/mfem-common.hpp"
#include "marking.hpp"

using namespace std;
using namespace mfem;

int problem = 0;

double domainLS(const Vector &coord)
{
   // Map from [0,1] to [-1,1].
   const int dim = coord.Size();
   const double x = coord(0)*2.0 - 1.0,
                y = coord(1)*2.0 - 1.0,
                z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
   switch(problem)
   {
      case 0:
      {
         // 2d circle.
         return 0.75 - sqrt(x*x + y*y + 1e-12);
      }
      case 1:
      {
         // 2d star.
         return 0.60 - sqrt(x*x + y*y + 1e-12) +
                0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) /
                       pow(x*x + y*y + 1e-12, 2.5);
      }
      default: MFEM_ABORT("Bad option for --problem!"); return 0.0;
   }
}

double solution0(const Vector &coord)
{
   // Map from [0,1] to [-1,1].
   const int dim = coord.Size();
   const double x = coord(0)*2.0 - 1.0,
                y = coord(1)*2.0 - 1.0,
                z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;

   if (domainLS(coord) > 0.0)
   {
      return std::cos(M_PI * x) * std::sin(M_PI * y);
   }
   else { return 0.0; }
}

class LevelSetNormalGradCoeff : public VectorCoefficient
{
private:
   const ParGridFunction &ls_gf;

public:
   LevelSetNormalGradCoeff(const ParGridFunction &ls) :
      VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip)
   {
      Vector grad_ls(vdim), n(vdim);
      ls_gf.GetGradient(T, grad_ls);
      const double norm_grad = grad_ls.Norml2();
      V = grad_ls;
      if (norm_grad > 0.0) { V /= norm_grad; }

      // Since positive level set values correspond to the known region, we
      // transport into the opposite direction of the gradient.
      V *= -1;
   }
};

class NormalGradCoeff : public Coefficient
{
private:
   const ParGridFunction &u_gf;
   LevelSetNormalGradCoeff &n_coeff;

public:
   NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :
      u_gf(u), n_coeff(n) { }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   {
      const int dim = T.GetDimension();
      Vector n(dim), grad_u(dim);
      n_coeff.Eval(n, T, ip);
      u_gf.GetGradient(T, grad_u);
      return n * grad_u;
   }

};

class Extrapolator : public TimeDependentOperator
{
private:
   Array<bool> &active_zones;
   ParBilinearForm &M, &K;
   const Vector &b;
   Solver *M_prec;
   CGSolver M_solver;

public:
   Extrapolator(Array<bool> &zones,
                ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)
      : TimeDependentOperator(Mbf.Size()),
        active_zones(zones),
        M(Mbf), K(Kbf),
        b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }

   virtual void Mult(const Vector &x, Vector &dx) const
   {
      K.BilinearForm::operator=(0.0);
      K.Assemble();

      ParFiniteElementSpace &pfes = *M.ParFESpace();
      const int NE = pfes.GetNE();
      const int nd = pfes.GetFE(0)->GetDof();

      Vector rhs(x.Size());
      HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());
      K_mat->Mult(x, rhs);
      rhs += b;

      Array<int> dofs(nd);
      DenseMatrix M_loc(nd);
      DenseMatrixInverse M_loc_inv(&M_loc);
      Vector rhs_loc(nd), dx_loc(nd);
      for (int k = 0; k < NE; k++)
      {
         pfes.GetElementDofs(k, dofs);

         if (active_zones[k] == false)
         {
            dx.SetSubVector(dofs, 0.0);
            continue;
         }

         rhs.GetSubVector(dofs, rhs_loc);
         M.SpMat().GetSubMatrix(dofs, dofs, M_loc);
         M_loc_inv.Factor();
         M_loc_inv.Mult(rhs_loc, dx_loc);
         dx.SetSubVector(dofs, dx_loc);
      }
   }
};

int main(int argc, char *argv[])
{
   // Initialize MPI.
   MPI_Session mpi;
   int myid = mpi.WorldRank();

   // Parse command-line options.
   const char *mesh_file = "../../data/inline-quad.mesh";
   int rs_levels = 2;
   int order = 2;
   int ode_solver_type = 2;
   double dt = 0.005;
   bool visualization = true;
   int vis_steps = 5;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&rs_levels, "-rs", "--refine-serial",
                  "Number of times to refine the mesh uniformly in serial.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&ode_solver_type, "-s", "--ode-solver",
                  "ODE solver: 1 - Forward Euler,\n\t"
                  "            2 - RK2 SSP,\n\t"
                  "            3 - RK3 SSP");
   args.AddOption(&problem, "-p", "--problem",
                  "0 - 2D circle,\n\t"
                  "1 - 2D star");
   args.AddOption(&dt, "-dt", "--time-step", "Time step.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.AddOption(&vis_steps, "-vs", "--visualization-steps",
                  "Visualize every n-th timestep.");
   args.Parse();
   if (!args.Good())
   {
      if (myid == 0) { args.PrintUsage(cout); }
      return 1;
   }
   if (myid == 0) { args.PrintOptions(cout); }

   char vishost[] = "localhost";
   int  visport   = 19916, wsize = 500;
   socketstream sock_grad_u_n, sock_u;

   // Refine the mesh.
   Mesh mesh(mesh_file, 1, 1);
   for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }

   // MPI distribution.
   ParMesh pmesh(MPI_COMM_WORLD, mesh);
   mesh.Clear();
   const int dim = pmesh.Dimension(), NE = pmesh.GetNE();

   FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);

   L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);
   ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);
   ParGridFunction u(&pfes_L2);
   u.ProjectCoefficient(u0_coeff);

   // Initialize the level set.
   H1_FECollection fec(order, dim);
   ParFiniteElementSpace pfes_H1(&pmesh, &fec);
   ParGridFunction level_set(&pfes_H1);
   level_set.ProjectCoefficient(ls_coeff);
   if (visualization)
   {
      socketstream sol_sock_w;
      common::VisualizeField(sol_sock_w, vishost, visport, level_set,
                             "Domain level set", 0, 0, wsize, wsize,
                             "rRjmm********A");
      MPI_Barrier(pmesh.GetComm());
   }
   // Setup a VectorCoefficient for n = - grad_ls / |grad_ls|.
   // The sign makes it point out of the known region.
   LevelSetNormalGradCoeff ls_n_coeff(level_set);

   // Mark elements.
   Array<int> elem_marker, dofs;
   ShiftedFaceMarker marker(pmesh, pfes_L2, false);
   level_set.ExchangeFaceNbrData();
   marker.MarkElements(level_set, elem_marker);

   // Trim to the known values (only elements inside the known region).
   ParGridFunction u_known(u);
   for (int k = 0; k < NE; k++)
   {
      pfes_L2.GetElementDofs(k, dofs);
      if (elem_marker[k] != ShiftedFaceMarker::INSIDE)
      { u_known.SetSubVector(dofs, 0.0); }
   }
   if (visualization)
   {
      socketstream sol_socks;
      common::VisualizeField(sol_socks, vishost, visport, u_known,
                             "Fixed (known) u values", wsize, 0, wsize, wsize,
                             "rRjmm********A");
   }
   u = u_known;

   // Normal derivative function.
   ParGridFunction grad_u_n(&pfes_L2);
   NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);
   grad_u_n.ProjectCoefficient(grad_u_n_coeff);
   if (visualization)
   {
      socketstream sol_sock;
      common::VisualizeField(sol_sock, vishost, visport, grad_u_n,
                             "grad_u n", 2*wsize, 0, wsize, wsize,
                             "rRjmm********A");
   }

   // The active zones are where we extrapolate (where the PDE is solved).
   Array<bool> active_zones(NE);
   for (int k = 0; k < NE; k++)
   {
      // Extrapolation is done in zones that are CUT or OUTSIDE.
      active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;
   }

   ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);
   lhs_bf.AddDomainIntegrator(new MassIntegrator);
   const double alpha = -1.0;
   rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));
   auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);
   rhs_bf.AddInteriorFaceIntegrator(trace_i);
   rhs_bf.KeepNbrBlock(true);

   lhs_bf.Assemble();
   lhs_bf.Finalize();
   rhs_bf.Assemble(0);
   rhs_bf.Finalize(0);

   Vector rhs(pfes_L2.GetVSize());
   rhs = 0.0;

   // Time loop
   double t = 0.0;
   ODESolver *ode_solver = NULL;
   switch (ode_solver_type)
   {
      case 1: ode_solver = new ForwardEulerSolver; break;
      case 2: ode_solver = new RK2Solver(1.0); break;
      case 3: ode_solver = new RK3SSPSolver; break;
      default:
      {
         if (myid == 0)
         { cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; }
         return 3;
      }
   }

   Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);
   ode_solver->Init(ext);

   bool done = false;
   const double t_final = 0.4;
   for (int ti = 0; !done;)
   {
      double dt_real = min(dt, t_final - t);
      ode_solver->Step(grad_u_n, t, dt_real);
      ti++;

      done = (t >= t_final - 1e-8*dt);

      if (done || ti % vis_steps == 0)
      {
         if (myid == 0)
         {
            cout << "time step: " << ti << ", time: " << t << endl;
         }

         if (visualization)
         {
            common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,
                                   "Solution", 2*wsize, 570, wsize, wsize,
                                   "rRjmm********A");
            MPI_Barrier(pmesh.GetComm());
         }
      }
   }

   lhs_bf.Mult(grad_u_n, rhs);
   done = false;
   t = 0.0;
   for (int ti = 0; !done;)
   {
      double dt_real = min(dt, t_final - t);
      ode_solver->Step(u, t, dt_real);
      ti++;

      done = (t >= t_final - 1e-8*dt);

      if (done || ti % vis_steps == 0)
      {
         if (myid == 0)
         {
            cout << "time step: " << ti << ", time: " << t << endl;
         }

         if (visualization)
         {
            common::VisualizeField(sock_u, vishost, visport, u,
                                   "Solution", wsize, 570, wsize, wsize,
                                   "rRjmm********A");
            MPI_Barrier(pmesh.GetComm());
         }
      }
   }

   // ParaView output.
   ParaViewDataCollection dacol("ParaViewExtrapolate", &pmesh);
   dacol.SetLevelsOfDetail(order);
   dacol.RegisterField("filtered_level_set", &level_set);
   dacol.SetTime(1.0);
   dacol.SetCycle(1);
   dacol.Save();

   return 0;
}
<commit_msg>Automatic dt calculation.<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
//            ------------------------------------------------
//            Extrapolation Miniapp: PDE-based extrapolation
//            ------------------------------------------------
//
// Compile with: make extrapolate
//
// Sample runs:
//     mpirun -np 4 extrapolate -o 3
//     mpirun -np 4 extrapolate -rs 3 -o 2 -p 1

#include <fstream>
#include <iostream>
#include "../common/mfem-common.hpp"
#include "marking.hpp"

using namespace std;
using namespace mfem;

int problem = 0;

double domainLS(const Vector &coord)
{
   // Map from [0,1] to [-1,1].
   const int dim = coord.Size();
   const double x = coord(0)*2.0 - 1.0,
                y = coord(1)*2.0 - 1.0,
                z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
   switch(problem)
   {
      case 0:
      {
         // 2d circle.
         return 0.75 - sqrt(x*x + y*y + 1e-12);
      }
      case 1:
      {
         // 2d star.
         return 0.60 - sqrt(x*x + y*y + 1e-12) +
                0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) /
                       pow(x*x + y*y + 1e-12, 2.5);
      }
      default: MFEM_ABORT("Bad option for --problem!"); return 0.0;
   }
}

double solution0(const Vector &coord)
{
   // Map from [0,1] to [-1,1].
   const int dim = coord.Size();
   const double x = coord(0)*2.0 - 1.0,
                y = coord(1)*2.0 - 1.0,
                z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;

   if (domainLS(coord) > 0.0)
   {
      return std::cos(M_PI * x) * std::sin(M_PI * y);
   }
   else { return 0.0; }
}

class LevelSetNormalGradCoeff : public VectorCoefficient
{
private:
   const ParGridFunction &ls_gf;

public:
   LevelSetNormalGradCoeff(const ParGridFunction &ls) :
      VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }

   virtual void Eval(Vector &V, ElementTransformation &T,
                     const IntegrationPoint &ip)
   {
      Vector grad_ls(vdim), n(vdim);
      ls_gf.GetGradient(T, grad_ls);
      const double norm_grad = grad_ls.Norml2();
      V = grad_ls;
      if (norm_grad > 0.0) { V /= norm_grad; }

      // Since positive level set values correspond to the known region, we
      // transport into the opposite direction of the gradient.
      V *= -1;
   }
};

class NormalGradCoeff : public Coefficient
{
private:
   const ParGridFunction &u_gf;
   LevelSetNormalGradCoeff &n_coeff;

public:
   NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :
      u_gf(u), n_coeff(n) { }

   virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
   {
      const int dim = T.GetDimension();
      Vector n(dim), grad_u(dim);
      n_coeff.Eval(n, T, ip);
      u_gf.GetGradient(T, grad_u);
      return n * grad_u;
   }

};

class Extrapolator : public TimeDependentOperator
{
private:
   Array<bool> &active_zones;
   ParBilinearForm &M, &K;
   const Vector &b;
   Solver *M_prec;
   CGSolver M_solver;

public:
   Extrapolator(Array<bool> &zones,
                ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)
      : TimeDependentOperator(Mbf.Size()),
        active_zones(zones),
        M(Mbf), K(Kbf),
        b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }

   virtual void Mult(const Vector &x, Vector &dx) const
   {
      K.BilinearForm::operator=(0.0);
      K.Assemble();

      ParFiniteElementSpace &pfes = *M.ParFESpace();
      const int NE = pfes.GetNE();
      const int nd = pfes.GetFE(0)->GetDof();

      Vector rhs(x.Size());
      HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());
      K_mat->Mult(x, rhs);
      rhs += b;

      Array<int> dofs(nd);
      DenseMatrix M_loc(nd);
      DenseMatrixInverse M_loc_inv(&M_loc);
      Vector rhs_loc(nd), dx_loc(nd);
      for (int k = 0; k < NE; k++)
      {
         pfes.GetElementDofs(k, dofs);

         if (active_zones[k] == false)
         {
            dx.SetSubVector(dofs, 0.0);
            continue;
         }

         rhs.GetSubVector(dofs, rhs_loc);
         M.SpMat().GetSubMatrix(dofs, dofs, M_loc);
         M_loc_inv.Factor();
         M_loc_inv.Mult(rhs_loc, dx_loc);
         dx.SetSubVector(dofs, dx_loc);
      }
   }
};

int main(int argc, char *argv[])
{
   // Initialize MPI.
   MPI_Session mpi;
   int myid = mpi.WorldRank();

   // Parse command-line options.
   const char *mesh_file = "../../data/inline-quad.mesh";
   int rs_levels = 2;
   int order = 2;
   int ode_solver_type = 2;
   bool visualization = true;
   int vis_steps = 5;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&rs_levels, "-rs", "--refine-serial",
                  "Number of times to refine the mesh uniformly in serial.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&ode_solver_type, "-s", "--ode-solver",
                  "ODE solver: 1 - Forward Euler,\n\t"
                  "            2 - RK2 SSP,\n\t"
                  "            3 - RK3 SSP");
   args.AddOption(&problem, "-p", "--problem",
                  "0 - 2D circle,\n\t"
                  "1 - 2D star");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.AddOption(&vis_steps, "-vs", "--visualization-steps",
                  "Visualize every n-th timestep.");
   args.Parse();
   if (!args.Good())
   {
      if (myid == 0) { args.PrintUsage(cout); }
      return 1;
   }
   if (myid == 0) { args.PrintOptions(cout); }

   char vishost[] = "localhost";
   int  visport   = 19916, wsize = 500;
   socketstream sock_grad_u_n, sock_u;

   // Refine the mesh.
   Mesh mesh(mesh_file, 1, 1);
   for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }

   // MPI distribution.
   ParMesh pmesh(MPI_COMM_WORLD, mesh);
   mesh.Clear();
   const int dim = pmesh.Dimension(), NE = pmesh.GetNE();

   FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);

   L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);
   ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);
   ParGridFunction u(&pfes_L2);
   u.ProjectCoefficient(u0_coeff);

   // Initialize the level set.
   H1_FECollection fec(order, dim);
   ParFiniteElementSpace pfes_H1(&pmesh, &fec);
   ParGridFunction level_set(&pfes_H1);
   level_set.ProjectCoefficient(ls_coeff);
   if (visualization)
   {
      socketstream sol_sock_w;
      common::VisualizeField(sol_sock_w, vishost, visport, level_set,
                             "Domain level set", 0, 0, wsize, wsize,
                             "rRjmm********A");
      MPI_Barrier(pmesh.GetComm());
   }
   // Setup a VectorCoefficient for n = - grad_ls / |grad_ls|.
   // The sign makes it point out of the known region.
   LevelSetNormalGradCoeff ls_n_coeff(level_set);

   // Mark elements.
   Array<int> elem_marker, dofs;
   ShiftedFaceMarker marker(pmesh, pfes_L2, false);
   level_set.ExchangeFaceNbrData();
   marker.MarkElements(level_set, elem_marker);

   // Trim to the known values (only elements inside the known region).
   ParGridFunction u_known(u);
   for (int k = 0; k < NE; k++)
   {
      pfes_L2.GetElementDofs(k, dofs);
      if (elem_marker[k] != ShiftedFaceMarker::INSIDE)
      { u_known.SetSubVector(dofs, 0.0); }
   }
   if (visualization)
   {
      socketstream sol_socks;
      common::VisualizeField(sol_socks, vishost, visport, u_known,
                             "Fixed (known) u values", wsize, 0, wsize, wsize,
                             "rRjmm********A");
   }
   u = u_known;

   // Normal derivative function.
   ParGridFunction grad_u_n(&pfes_L2);
   NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);
   grad_u_n.ProjectCoefficient(grad_u_n_coeff);
   if (visualization)
   {
      socketstream sol_sock;
      common::VisualizeField(sol_sock, vishost, visport, grad_u_n,
                             "grad_u n", 2*wsize, 0, wsize, wsize,
                             "rRjmm********A");
   }

   // The active zones are where we extrapolate (where the PDE is solved).
   Array<bool> active_zones(NE);
   for (int k = 0; k < NE; k++)
   {
      // Extrapolation is done in zones that are CUT or OUTSIDE.
      active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;
   }

   ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);
   lhs_bf.AddDomainIntegrator(new MassIntegrator);
   const double alpha = -1.0;
   rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));
   auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);
   rhs_bf.AddInteriorFaceIntegrator(trace_i);
   rhs_bf.KeepNbrBlock(true);

   lhs_bf.Assemble();
   lhs_bf.Finalize();
   rhs_bf.Assemble(0);
   rhs_bf.Finalize(0);

   Vector rhs(pfes_L2.GetVSize());
   rhs = 0.0;

   // Compute a CFL time step.
   double h_min = std::numeric_limits<double>::infinity();
   for (int k = 0; k < NE; k++)
   {
      h_min = std::min(h_min, pmesh.GetElementSize(k));
   }
   MPI_Allreduce(MPI_IN_PLACE, &h_min, 1, MPI_DOUBLE, MPI_MIN,
                 pfes_L2.GetComm());
   h_min /= order;
   // The propagation speed is 1.
   double dt = 0.25 * h_min / 1.0;

   // Time loop
   double t = 0.0;
   ODESolver *ode_solver = NULL;
   switch (ode_solver_type)
   {
      case 1: ode_solver = new ForwardEulerSolver; break;
      case 2: ode_solver = new RK2Solver(1.0); break;
      case 3: ode_solver = new RK3SSPSolver; break;
      default:
      {
         if (myid == 0)
         { cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; }
         return 3;
      }
   }

   Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);
   ode_solver->Init(ext);

   bool done = false;
   const double t_final = 0.4;
   for (int ti = 0; !done;)
   {
      double dt_real = min(dt, t_final - t);
      ode_solver->Step(grad_u_n, t, dt_real);
      ti++;

      done = (t >= t_final - 1e-8*dt);

      if (done || ti % vis_steps == 0)
      {
         if (myid == 0)
         {
            cout << "time step: " << ti << ", time: " << t << endl;
         }

         if (visualization)
         {
            common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,
                                   "Solution", 2*wsize, 570, wsize, wsize,
                                   "rRjmm********A");
            MPI_Barrier(pmesh.GetComm());
         }
      }
   }

   lhs_bf.Mult(grad_u_n, rhs);
   done = false;
   t = 0.0;
   for (int ti = 0; !done;)
   {
      double dt_real = min(dt, t_final - t);
      ode_solver->Step(u, t, dt_real);
      ti++;

      done = (t >= t_final - 1e-8*dt);

      if (done || ti % vis_steps == 0)
      {
         if (myid == 0)
         {
            cout << "time step: " << ti << ", time: " << t << endl;
         }

         if (visualization)
         {
            common::VisualizeField(sock_u, vishost, visport, u,
                                   "Solution", wsize, 570, wsize, wsize,
                                   "rRjmm********A");
            MPI_Barrier(pmesh.GetComm());
         }
      }
   }

   // ParaView output.
   ParaViewDataCollection dacol("ParaViewExtrapolate", &pmesh);
   dacol.SetLevelsOfDetail(order);
   dacol.RegisterField("filtered_level_set", &level_set);
   dacol.SetTime(1.0);
   dacol.SetCycle(1);
   dacol.Save();

   return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <list>
#include <vector>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include "player.h"

using namespace std;

void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster);

//use is ./program.exe file.csv rosters.txt
int main(int argc, char* argv[])
{
	ifstream statsin(argv[1]);    // input player stats .csv file
	ifstream playersin(argv[2]);  // input team rosters

	string x;
	vector<string> input;         // vector of player stats
	vector<string> players;       //
	vector<string> roster;        // vector of team roster
	vector<Player> obs;           // vector of player objects
	vector<string> nums;          // vecotr of available numbers
	vector<string> teams;         //

	init(nums, teams, input, roster);     // initialize player numbers and NFL teams

	for(int i=0; i<input.size(); ++i)
	{
		for(int j=0; j<10; ++j)
		{

			if(input[i][0]==nums[j][0]&& input[i][0+1]=='-'||input[i][0]==nums[j][0]&& input[i][0+2]=='-')
			{
				string name;
				int count =0;
				players.push_back(input[i]);
			}
		}
	}

	for(int i=0; i<players.size(); ++i)
	{
		string pnum="";
		if(players[i][1]=='-')
		{
			pnum+= players[i][0];
		}
		else
		{
			pnum+= players[i][0];
			pnum+= players[i][1];
		}

		for(int j=0; j<roster.size(); ++j)
		{
			if(pnum[0] == roster[j][0])
			{

				if (players[i][2]== roster[j+2][0]||players[i][3]== roster[j+2][0])
				{
					Player nextone= Player(roster[j+2], roster[j+1], roster[j+3], "ATL",roster[j]);
					bool flag = false;
					for(int q=0; q<obs.size(); ++q)
					{
						if(obs[q].get_fname()==roster[j+2] && obs[q].get_lname()==roster[j+1])
						{
							flag=true;
						}
					}

					if(!flag)
					{
						obs.push_back(nextone);
					}

				}
			}
		}
	}
	cout<<obs.size()<<endl;

	for(int i=0; i<10; ++i)
	{
		string name = obs[i].get_fname()+" "+obs[i].get_lname();
		string num = obs[i].get_num();
		for (int z= 0; z<name.size(); ++z)
    	{
        	if (ispunct(name[z]))
        	{
            	name.erase(z--, 1);
        	}
    	}
    	for (int z= 0; z<num.size(); ++z)
    	{
        	if (ispunct(num[z]))
        	{
            	num.erase(z--, 1);
        	}
    	}
		cout<<"{"<<endl;
		cout<<"\t'name':'"+name+"',"<<endl;
		cout<<"\t'POS':'"+obs[i].get_pos()+"',"<<endl;
		cout<<"\t'team':'"+obs[i].get_team()+"',"<<endl;
		cout<<"\t'num':'"+num+"',"<<endl;
		cout<<"\t'gp':"<<obs[i].get_gp()<<","<<endl;
		cout<<"\t'att':"<<obs[i].get_att()<<","<<endl;
		cout<<"\t'rushyards':"<<obs[i].get_rushyards()<<","<<endl;
		cout<<"\t'rushtuddies':"<<obs[i].get_rushtds()<<","<<endl;
		cout<<"\t'recs':"<<obs[i].get_recs()<<","<<endl;
		cout<<"\t'tars':"<<obs[i].get_tars()<<","<<endl;
		cout<<"\t'recyards':"<<obs[i].get_recyards()<<","<<endl;
		cout<<"\t'rectuddies':"<<obs[i].get_rectds()<<","<<endl;
		cout<<"\t'comp':"<<obs[i].get_comp()<<","<<endl;
		cout<<"\t'passatt':"<<obs[i].get_patts()<<","<<endl;
		cout<<"\t'pyards':"<<obs[i].get_pyards()<<","<<endl;
		cout<<"\t'ptds':"<<obs[i].get_ptds()<<","<<endl;
		cout<<"\t'ints':"<<obs[i].get_interceptions()<<","<<endl;
		cout<<"\t'fum':"<<obs[i].get_fum()<<","<<endl;
		cout<<"\t'fumlost':"<<obs[i].get_fumlost()<<","<<endl;
		cout<<"},"<<endl;
	}
}

void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster){
	nums.push_back("1");
	nums.push_back("2");
	nums.push_back("3");
	nums.push_back("4");
	nums.push_back("5");
	nums.push_back("6");
	nums.push_back("7");
	nums.push_back("8");
	nums.push_back("9");
	nums.push_back("0");
	teams.push_back("ARI");
	teams.push_back("ATL");
	teams.push_back("BAL");
	teams.push_back("BUF");
	teams.push_back("CAR");
	teams.push_back("CHI");
	teams.push_back("CIN");
	teams.push_back("CLE");
	teams.push_back("DAL");
	teams.push_back("DEN");
	teams.push_back("DET");
	teams.push_back("GB");
	teams.push_back("HOU");
	teams.push_back("IND");
	teams.push_back("JAX");
	teams.push_back("KC");
	teams.push_back("MIA");
	teams.push_back("MIN");
	teams.push_back("NE");
	teams.push_back("NO");
	teams.push_back("NYG");
	teams.push_back("NYJ")
	teams.push_back("OAK");
	teams.push_back("PHI");
	teams.push_back("PIT");
	teams.push_back("SD");
	teams.push_back("SEA");
	teams.push_back("SF");
	teams.push_back("STL");
	teams.push_back("TB");
	teams.push_back("TEN");
	teams.push_back("WAS");

	while(statsin >> x)           // pushback player stats to a vector
	{
		input.push_back(x);
	}
	while(playersin >> x)         // pushback player names to a vector
	{
		roster.push_back(x);
	}
}

<commit_msg>Minor fix<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <list>
#include <vector>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include "player.h"

using namespace std;

void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster, ifstream &statsin, ifstream &playersin);

//use is ./program.exe file.csv rosters.txt
int main(int argc, char* argv[])
{
	ifstream statsin(argv[1]);    // input player stats .csv file
	ifstream playersin(argv[2]);  // input team rosters

	vector<string> input;         // vector of player stats
	vector<string> players;       //
	vector<string> roster;        // vector of team roster
	vector<Player> obs;           // vector of player objects
	vector<string> nums;          // vecotr of available numbers
	vector<string> teams;         //

	init(nums, teams, input, roster,statsin,playersin);     // initialize player numbers and NFL teams

	for(int i=0; i<input.size(); ++i)
	{
		for(int j=0; j<10; ++j)
		{

			if(input[i][0]==nums[j][0]&& input[i][0+1]=='-'||input[i][0]==nums[j][0]&& input[i][0+2]=='-')
			{
				string name;
				int count =0;
				players.push_back(input[i]);
			}
		}
	}

	for(int i=0; i<players.size(); ++i)
	{
		string pnum="";
		if(players[i][1]=='-')
		{
			pnum+= players[i][0];
		}
		else
		{
			pnum+= players[i][0];
			pnum+= players[i][1];
		}

		for(int j=0; j<roster.size(); ++j)
		{
			if(pnum[0] == roster[j][0])
			{

				if (players[i][2]== roster[j+2][0]||players[i][3]== roster[j+2][0])
				{
					Player nextone= Player(roster[j+2], roster[j+1], roster[j+3], "ATL",roster[j]);
					bool flag = false;
					for(int q=0; q<obs.size(); ++q)
					{
						if(obs[q].get_fname()==roster[j+2] && obs[q].get_lname()==roster[j+1])
						{
							flag=true;
						}
					}

					if(!flag)
					{
						obs.push_back(nextone);
					}

				}
			}
		}
	}
	cout<<obs.size()<<endl;

	for(int i=0; i<10; ++i)
	{

		string name = obs[i].get_fname()+" "+obs[i].get_lname();
		string num = obs[i].get_num();
		//remove punctuation from name and num
		for (int z= 0; z<name.size(); ++z)
    	{
        	if (ispunct(name[z]))
        	{
            	name.erase(z--, 1);
        	}
    	}
    	for (int z= 0; z<num.size(); ++z)
    	{
        	if (ispunct(num[z]))
        	{
            	num.erase(z--, 1);
        	}
    	}
		cout<<"{"<<endl;
		cout<<"\t'name':'"+name+"',"<<endl;
		cout<<"\t'POS':'"+obs[i].get_pos()+"',"<<endl;
		cout<<"\t'team':'"+obs[i].get_team()+"',"<<endl;
		cout<<"\t'num':'"+num+"',"<<endl;
		cout<<"\t'gp':"<<obs[i].get_gp()<<","<<endl;
		cout<<"\t'att':"<<obs[i].get_att()<<","<<endl;
		cout<<"\t'rushyards':"<<obs[i].get_rushyards()<<","<<endl;
		cout<<"\t'rushtuddies':"<<obs[i].get_rushtds()<<","<<endl;
		cout<<"\t'recs':"<<obs[i].get_recs()<<","<<endl;
		cout<<"\t'tars':"<<obs[i].get_tars()<<","<<endl;
		cout<<"\t'recyards':"<<obs[i].get_recyards()<<","<<endl;
		cout<<"\t'rectuddies':"<<obs[i].get_rectds()<<","<<endl;
		cout<<"\t'comp':"<<obs[i].get_comp()<<","<<endl;
		cout<<"\t'passatt':"<<obs[i].get_patts()<<","<<endl;
		cout<<"\t'pyards':"<<obs[i].get_pyards()<<","<<endl;
		cout<<"\t'ptds':"<<obs[i].get_ptds()<<","<<endl;
		cout<<"\t'ints':"<<obs[i].get_interceptions()<<","<<endl;
		cout<<"\t'fum':"<<obs[i].get_fum()<<","<<endl;
		cout<<"\t'fumlost':"<<obs[i].get_fumlost()<<","<<endl;
		cout<<"},"<<endl;
	}
}

void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster, ifstream &statsin, ifstream &playersin)
{
	string x;
	nums.push_back("1");
	nums.push_back("2");
	nums.push_back("3");
	nums.push_back("4");
	nums.push_back("5");
	nums.push_back("6");
	nums.push_back("7");
	nums.push_back("8");
	nums.push_back("9");
	nums.push_back("0");
	teams.push_back("ARI");
	teams.push_back("ATL");
	teams.push_back("BAL");
	teams.push_back("BUF");
	teams.push_back("CAR");
	teams.push_back("CHI");
	teams.push_back("CIN");
	teams.push_back("CLE");
	teams.push_back("DAL");
	teams.push_back("DEN");
	teams.push_back("DET");
	teams.push_back("GB");
	teams.push_back("HOU");
	teams.push_back("IND");
	teams.push_back("JAX");
	teams.push_back("KC");
	teams.push_back("MIA");
	teams.push_back("MIN");
	teams.push_back("NE");
	teams.push_back("NO");
	teams.push_back("NYG");
	teams.push_back("NYJ");
	teams.push_back("OAK");
	teams.push_back("PHI");
	teams.push_back("PIT");
	teams.push_back("SD");
	teams.push_back("SEA");
	teams.push_back("SF");
	teams.push_back("STL");
	teams.push_back("TB");
	teams.push_back("TEN");
	teams.push_back("WAS");

	while(statsin >> x)           // pushback player stats to a vector
	{
		input.push_back(x);
	}
	while(playersin >> x)         // pushback player names to a vector
	{
		roster.push_back(x);
	}
}
<|endoftext|>


<commit_before>#include "material.h"

#include <math.h>

#include "comp_math.h"
#include "context.h"
#include "decayer.h"
#include "error.h"
#include "logger.h"

namespace cyclus {

const ResourceType Material::kType = "Material";

Material::~Material() {}

Material::Ptr Material::Create(Agent* creator, double quantity,
                               Composition::Ptr c) {
  Material::Ptr m(new Material(creator->context(), quantity, c));
  m->tracker_.Create(creator);
  return m;
}

Material::Ptr Material::CreateUntracked(double quantity,
                                        Composition::Ptr c) {
  Material::Ptr m(new Material(NULL, quantity, c));
  return m;
}

int Material::qual_id() const {
  return comp_->id();
}

const ResourceType Material::type() const {
  return Material::kType;
}

Resource::Ptr Material::Clone() const {
  Material* m = new Material(*this);
  Resource::Ptr c(m);
  m->tracker_.DontTrack();
  return c;
}

void Material::Record(Context* ctx) const {
  // Note that no time field is needed because the resource ID changes
  // every time the resource changes - state_id by itself is already unique.
  ctx_->NewDatum("MaterialInfo")
      ->AddVal("ResourceId", state_id())
      ->AddVal("PrevDecayTime", prev_decay_time_)
      ->Record();

  comp_->Record(ctx);
}

std::string Material::units() const {
  return "kg";
}

double Material::quantity() const {
  return qty_;
}

Resource::Ptr Material::ExtractRes(double qty) {
  return boost::static_pointer_cast<Resource>(ExtractQty(qty));
}

Material::Ptr Material::ExtractQty(double qty) {
  return ExtractComp(qty, comp_);
}

Material::Ptr Material::ExtractComp(double qty, Composition::Ptr c,
                                    double threshold) {
  if (qty_ < qty) {
    throw ValueError("mass extraction causes negative quantity");
  }
  if (comp_ != c) {
    CompMap v(comp_->mass());
    compmath::Normalize(&v, qty_);
    CompMap otherv(c->mass());
    compmath::Normalize(&otherv, qty);
    CompMap newv = compmath::Sub(v, otherv);
    compmath::ApplyThreshold(&newv, threshold);
    comp_ = Composition::CreateFromMass(newv);
  }

  qty_ -= qty;

  Material::Ptr other(new Material(ctx_, qty, c));

  tracker_.Extract(&other->tracker_);

  return other;
}

void Material::Absorb(Material::Ptr mat) {
  if (comp_ != mat->comp()) {
    CompMap v(comp_->mass());
    compmath::Normalize(&v, qty_);
    CompMap otherv(mat->comp()->mass());
    compmath::Normalize(&otherv, mat->quantity());
    comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));
  }
  qty_ += mat->qty_;
  mat->qty_ = 0;
  tracker_.Absorb(&mat->tracker_);
}

void Material::Transmute(Composition::Ptr c) {
  comp_ = c;
  tracker_.Modify();
}

void Material::Decay(int curr_time) {
  int dt = curr_time - prev_decay_time_;
  double eps = 1e-3;
  bool decay = false;

  const CompMap c = comp_->atom();
  if (c.size() > 100) {
    decay = true;
  } else {
    CompMap::const_iterator it;
    for (it = c.end(); it != c.begin(); --it) {
      int nuc = it->first;
      // 2419200 == secs / month
      double lambda_months = pyne::decay_const(nuc) * 2419200;

      if (eps <= 1 - std::exp(-lambda_months * dt)) {
        decay = true;
        break;
      }
    }
  }

  if (decay) {
    prev_decay_time_ = curr_time;
    if (dt > 0) {
      Transmute(comp_->Decay(dt));
    }
  }
}

Composition::Ptr Material::comp() const {
  return comp_;
}

Material::Material(Context* ctx, double quantity, Composition::Ptr c)
    : qty_(quantity),
      comp_(c),
      tracker_(ctx, this),
      ctx_(ctx),
      prev_decay_time_(0) {
  if (ctx != NULL) {
    prev_decay_time_ = ctx->time();
  } else {
    tracker_.DontTrack();
  }
}

Material::Ptr NewBlankMaterial(double quantity) {
  Composition::Ptr comp = Composition::CreateFromMass(CompMap());
  return Material::CreateUntracked(quantity, comp);
}

}  // namespace cyclus
<commit_msg>only decay if decayallowed is true<commit_after>#include "material.h"

#include <math.h>

#include "comp_math.h"
#include "context.h"
#include "decayer.h"
#include "error.h"
#include "logger.h"

namespace cyclus {

const ResourceType Material::kType = "Material";

Material::~Material() {}

Material::Ptr Material::Create(Agent* creator, double quantity,
                               Composition::Ptr c) {
  Material::Ptr m(new Material(creator->context(), quantity, c));
  m->tracker_.Create(creator);
  return m;
}

Material::Ptr Material::CreateUntracked(double quantity,
                                        Composition::Ptr c) {
  Material::Ptr m(new Material(NULL, quantity, c));
  return m;
}

int Material::qual_id() const {
  return comp_->id();
}

const ResourceType Material::type() const {
  return Material::kType;
}

Resource::Ptr Material::Clone() const {
  Material* m = new Material(*this);
  Resource::Ptr c(m);
  m->tracker_.DontTrack();
  return c;
}

void Material::Record(Context* ctx) const {
  // Note that no time field is needed because the resource ID changes
  // every time the resource changes - state_id by itself is already unique.
  ctx_->NewDatum("MaterialInfo")
      ->AddVal("ResourceId", state_id())
      ->AddVal("PrevDecayTime", prev_decay_time_)
      ->Record();

  comp_->Record(ctx);
}

std::string Material::units() const {
  return "kg";
}

double Material::quantity() const {
  return qty_;
}

Resource::Ptr Material::ExtractRes(double qty) {
  return boost::static_pointer_cast<Resource>(ExtractQty(qty));
}

Material::Ptr Material::ExtractQty(double qty) {
  return ExtractComp(qty, comp_);
}

Material::Ptr Material::ExtractComp(double qty, Composition::Ptr c,
                                    double threshold) {
  if (qty_ < qty) {
    throw ValueError("mass extraction causes negative quantity");
  }
  if (comp_ != c) {
    CompMap v(comp_->mass());
    compmath::Normalize(&v, qty_);
    CompMap otherv(c->mass());
    compmath::Normalize(&otherv, qty);
    CompMap newv = compmath::Sub(v, otherv);
    compmath::ApplyThreshold(&newv, threshold);
    comp_ = Composition::CreateFromMass(newv);
  }

  qty_ -= qty;

  Material::Ptr other(new Material(ctx_, qty, c));

  tracker_.Extract(&other->tracker_);

  return other;
}

void Material::Absorb(Material::Ptr mat) {
  if (comp_ != mat->comp()) {
    CompMap v(comp_->mass());
    compmath::Normalize(&v, qty_);
    CompMap otherv(mat->comp()->mass());
    compmath::Normalize(&otherv, mat->quantity());
    comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));
  }
  qty_ += mat->qty_;
  mat->qty_ = 0;
  tracker_.Absorb(&mat->tracker_);
}

void Material::Transmute(Composition::Ptr c) {
  comp_ = c;
  tracker_.Modify();
}

void Material::Decay(int curr_time) {
  if (context()->decay() == true) {
    int dt = curr_time - prev_decay_time_;
    double eps = 1e-3;
    bool decay = false;

    const CompMap c = comp_->atom();
    if (c.size() > 100) {
      decay = true;
    } else {
      CompMap::const_iterator it;
      for (it = c.end(); it != c.begin(); --it) {
        int nuc = it->first;
        // 2419200 == secs / month
        double lambda_months = pyne::decay_const(nuc) * 2419200;

        if (eps <= 1 - std::exp(-lambda_months * dt)) {
          decay = true;
          break;
        }
      }
    }

    if (decay) {
      prev_decay_time_ = curr_time;
      if (dt > 0) {
        Transmute(comp_->Decay(dt));
      }
    }
  }
}

Composition::Ptr Material::comp() const {
  return comp_;
}

Material::Material(Context* ctx, double quantity, Composition::Ptr c)
    : qty_(quantity),
      comp_(c),
      tracker_(ctx, this),
      ctx_(ctx),
      prev_decay_time_(0) {
  if (ctx != NULL) {
    prev_decay_time_ = ctx->time();
  } else {
    tracker_.DontTrack();
  }
}

Material::Ptr NewBlankMaterial(double quantity) {
  Composition::Ptr comp = Composition::CreateFromMass(CompMap());
  return Material::CreateUntracked(quantity, comp);
}

}  // namespace cyclus
<|endoftext|>