<commit_before>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

//Criao da estrutura para AP2
typedef struct
{
	int codigo;
	char raca[30], nome[100];
} registro;

typedef struct
{
	int codigo, offset;
} indice1;

typedef struct
{
	char vacina[30];
	int offset;
} indice2;

int Menu();
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);
void CadastraVacina(FILE **AP1, FILE **AP2);
void CadastraCachorro(FILE **AP2);
void AtualizaInfoIndice(char status, FILE **arq);
int ExisteCachorro(int codigo, FILE **AP2);
int ProcuraEspacoVazio(FILE **AP1, int tam_reg);
void AlteraCachorro(FILE **AP2);

int main()
{
    int opcao;
	FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;

	AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);
	opcao = Menu();
	while (1)
	{
	    switch(opcao)
	    {
	        case 1: CadastraCachorro(&AP2); break;
	        case 2: CadastraVacina(&AP1, &AP2); break;
			case 3: AlteraCachorro(&AP2);
                    break;
	        case 0: printf("\nSaindo do Programa...");
        	        fclose(AP1); fclose(AP2); //fecha arquivos principais
                    fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices
                    getch(); break;
	        default: printf("\nOpcao invalida!"); getch(); break;
        }
        opcao = Menu();
    }
    return 0;
}

/*
DESCRIO: Exibe as opes do menu.
RETORNO: O nmero da opo escolhida pelo usurio
*/
int Menu()
{
	int opcao;

	system("CLS");
    printf("\n 1 - Cadastra Cachorro");
    printf("\n 2 - Cadastra Vacina");
	printf("\n3 - Altera Cachorro");
	printf("\n 0 - Sair");
	printf("\n\nEscolha a opcao: ");
    scanf("%d", &opcao);

	return opcao;
}

/*
DESCRIO: Verifica  os arquivos j foram criados.
           Se no, cria-os.
PARMETROS: AP1 - Arquivo Principal 1
            AP2 - Arquivo Principal 2
	        IndPrim - Arquivo de ndice (busca por chave primria)
			IndSec1 - Arquivo de ndice 1 (busca por chave secundria)
			IndSec2 - Arquivo de ndice 2 (busca por chave secundria)
*/
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)
{
    int header = -1;
    /*No primeiro caso, ele entra no if pois o arquivo ainda no existe
    (Com o uso do r+b o arquivo tem que existir).
    A ento ele cria o arquivo com w+b*/
    if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr
    {
        *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1)
    	fwrite(&header, sizeof(int), 1, *AP1);
    	*IndPrim = fopen("IndPrim.bin", "w+b");
    	AtualizaInfoIndice('!', IndPrim);
    	*IndSec1 = fopen("IndSec1.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec1);
    	*IndSec2 = fopen("IndSec2.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec2);
	}
	/*else if (ExigeRecriaIndice(IndPrim))
	{
		RecriaIndicePrim(AP1);
		QuickSortInd1(INDEX1, 0, tam1);
	}
	else
	{
		IndPrim = fopen("IndPrim.bin", "r+b");
		CarregaIndice(IndPrim, 1);
    	IndSec1 = fopen("IndSec1.bin", "r+b");
    	CarregaIndice(IndSec1, 2);
    	IndSec2 = fopen("IndSec2.bin", "r+b");
    	CarregaIndice(IndSec2, 1);
	}*/

    if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir
        *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2)
}

/*
DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2
PARMETROS: AP2 - Arquivo Principal 2
*/
void CadastraCachorro(FILE **AP2)
{
	registro reg;

	system("CLS");
	printf("\nCodigo: ");
	scanf("%d", &reg.codigo);
	while (ExisteCachorro(reg.codigo, AP2))
	{
		system("CLS");
		printf("\nCodigo ja cadastrado. Digite novamente!");
		getch(); system("CLS");
		printf("\nCodigo: ");
        scanf("%d", &reg.codigo);
	}
	fflush(stdin);
	printf("Raca: ");
	gets(reg.raca);
	printf("Nome do Cachorro: ");
	gets(reg.nome);

	fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo.
	fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo.
}

/*
DESCRIO: Atualiza o header do ndice com o status de atualizao
PARMETROS: status - '*' - ndice atualizado
                     '!' - ndice desatualizado
            arq - ndice a ser atualizado
*/
void AtualizaInfoIndice(char status, FILE **arq)
{
	fseek(*arq, 0, SEEK_SET);
	fputc(status, *arq);
}

/*
DESCRIO: Verifica se o cdigo j existe no arquivo.
PARMETROS: codigo - Cdigo a ser verificado
            AP2 - Arquivo Principal 2
RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro
          1 - Existe um cachorro com o cdigo passado por parmetro
*/
int ExisteCachorro(int codigo, FILE **AP2)
{
	registro reg;

	rewind(*AP2);
	while (fread(&reg, sizeof(registro), 1, *AP2))
	{
		if (reg.codigo == codigo)
		{
			return 1;
			break;
		}
	}
    return 0;
}

/*
DESCRIO: Realiza o cadastro de vacinas
PARMETROS: AP1 - Arquivo principal 1
            AP2 - Arquivo principal 2
*/
void CadastraVacina(FILE **AP1, FILE **AP2)
{
    int cod_controle = 0, cod_cachorro, tam_reg, posicao, aux = 0;
    char verificador = '*', vacina[30], data[6], respo[100], registro[255];

    system("CLS");
    printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
    scanf("%d", &cod_cachorro);
    if (cod_cachorro == -1)
      CadastraCachorro(AP2);
    else
    {
        while (!ExisteCachorro(cod_cachorro, AP2))
        {
            if (!aux)
                printf("\n Cachorro inexistente. Digite novamente!");
            else
                printf("\n Nova busca..." );
            getch(); system("CLS");
            printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
            scanf("%d", &cod_cachorro);
            if (cod_cachorro == -1)
            {
                CadastraCachorro(AP2);
                aux = 1;
            }
        }
        system("CLS");
        cod_controle++;//cod_controle = pegar do INDEX1 ordenado;
        printf("\n Codigo do cachorro: %d", cod_cachorro);
        fflush(stdin);
        printf("\n\n Nome da vacina: ");
        gets(vacina);
        printf("\n Data de vacinacao <MM/AA>: ");
        gets(data);
        printf("\n Responsavel pela aplicacao: ");
        gets(respo);

        sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo);
        tam_reg = strlen(registro);
        posicao = ProcuraEspacoVazio(AP1, tam_reg);
        if (posicao != -1)
          fseek(*AP1, posicao, SEEK_SET);
        else
          fseek(*AP1, 0, SEEK_END);
        fwrite(&tam_reg, sizeof(int), 1, *AP1);
        fwrite(&verificador, sizeof(char), 1, *AP1);
        fwrite(registro, sizeof(char), tam_reg, *AP1);
    }
}

/*
DESCRIO: Retorna o espao vazio encontrado no arquivo
PARMETROS: AP1 - Arquivo principal 1
            tam_reg - tamanho do registro a ser inserido
RETORNO: posio livre para ser escrita
*/
int ProcuraEspacoVazio(FILE **AP1, int tam_reg)
{
    int offset, tam, pos;
    char ch;

    rewind(*AP1);
    fread(&offset, sizeof(int), 1, *AP1);
    if (offset == -1)
        return -1;
    else
    {
        fseek(*AP1, offset, SEEK_SET);
        pos = ftell(*AP1);
        while (fread(&tam, sizeof(int), 1, *AP1))
        {
            if (tam == -1)
            {
                return -1;
                break;
            }
            else
            {
                ch = fgetc(*AP1);
                if ((tam > tam_reg) && (ch == '!'))
                {
                   return pos;
                   break;
                }
                else
                {
                    fread(&offset, sizeof(int), 1, *AP1);
                    fseek(*AP1, offset, SEEK_SET);
                }
            }
        }
    }
}

/*
DESCRIO: Altera dados de um cachorro
PARMETRO: AP2 - arquivo principal 2
*/
void AlteraCachorro(FILE **AP2)
{
    int op, cod, i = 0;
    char raca[30], nome[100];
    registro reg;

    system("CLS");
    printf("Digite o codigo do cachorro: ");
    scanf("%d", &cod);
    while (!ExisteCachorro(cod, AP2))
    {
        system("CLS");
        printf("\n\nCachorro inexistente. Digite novamente!");
        getch();
        system("CLS");
        printf("\n\nDigite o codigo do cachorro: ");
        scanf("%d", &cod);
    }

    rewind(*AP2);
	while (fread(&reg, sizeof(reg), 1, *AP2))
	{
		if (reg.codigo == cod)
		  break;
		i++;
	}

    system("CLS");
    printf("Qual campo deseja alterar");
    printf("\n\n1 - Raca");
    printf("\n2 - Nome");
    printf("\n\nEscolha a opcao: ");
    scanf("%d", &op);
    while ((op != 1) && (op != 2))
    {
       system("CLS");
       printf("Opcao invalida. Digite novamente!");
       getch();
       system("CLS");
       printf("Qual campo deseja alterar");
       printf("\n\n1 - Raca");
       printf("\n2 - Nome");
       printf("\n\nEscolha a opcao: ");
       scanf("%d", op);
    }

    fflush(stdin);
    system("CLS");
    switch(op)
    {
        case 1: printf("Digite a nova raca: ");
                gets(raca);
                strcpy(reg.raca, raca);
                break;
        case 2: printf("Digite o novo nome: ");
                gets(nome);
                strcpy(reg.nome, nome);
                break;
    }

    fseek(*AP2, sizeof(reg)*i, SEEK_SET);
	fwrite(&reg, sizeof(reg), 1, *AP2);
}

<commit_msg>teste<commit_after>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

//Criao da estrutura para AP2
typedef struct
{
	int codigo;
	char raca[30], nome[100];
} registro;

typedef struct
{
	int codigo, offset;
} indice1;

typedef struct
{
	char vacina[30];
	int offset;
} indice2;

int Menu();
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2);
void CadastraVacina(FILE **AP1, FILE **AP2);
void CadastraCachorro(FILE **AP2);
void AtualizaInfoIndice(char status, FILE **arq);
int ExisteCachorro(int codigo, FILE **AP2);
int ProcuraEspacoVazio(FILE **AP1, int tam_reg);
void AlteraCachorro(FILE **AP2);

int main()
{
    int opcao;
	FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2;

	AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2);
	opcao = Menu();
	while (1)
	{
	    switch(opcao)
	    {
	        case 1: CadastraCachorro(&AP2); break;
	        case 2: CadastraVacina(&AP1, &AP2); break;
			case 3: AlteraCachorro(&AP2);
                    break;
	        case 0: printf("\nSaindo do Programa...");
        	        fclose(AP1); fclose(AP2); //fecha arquivos principais
                    fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices
                    getch(); break;
	        default: printf("\nOpcao invalida!"); getch(); break;
        }
        opcao = Menu();
    }
    return 0;
}

/*
DESCRIO: Exibe as opes do menu.
RETORNO: O nmero da opo escolhida pelo usurio
*/
int Menu()
{
	int opcao;

	system("CLS");
    printf("\n 1 - Cadastra Cachorro");
    printf("\n 2 - Cadastra Vacina");
	printf("\n3 - Altera Cachorro");
	printf("\n 0 - Sair");
	printf("\n\nEscolha a opcao: ");
    scanf("%d", &opcao);

	return opcao;
}

/*
DESCRIO: Verifica esssss os arquivos j foram criados.
           Se no, cria-os.
PARMETROS: AP1 - Arquivo Principal 1
            AP2 - Arquivo Principal 2
	        IndPrim - Arquivo de ndice (busca por chave primria)
			IndSec1 - Arquivo de ndice 1 (busca por chave secundria)
			IndSec2 - Arquivo de ndice 2 (busca por chave secundria)
*/
void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2)
{
    int header = -1;
    /*No primeiro caso, ele entra no if pois o arquivo ainda no existe
    (Com o uso do r+b o arquivo tem que existir).
    A ento ele cria o arquivo com w+b*/
    if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr
    {
        *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1)
    	fwrite(&header, sizeof(int), 1, *AP1);
    	*IndPrim = fopen("IndPrim.bin", "w+b");
    	AtualizaInfoIndice('!', IndPrim);
    	*IndSec1 = fopen("IndSec1.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec1);
    	*IndSec2 = fopen("IndSec2.bin", "w+b");
    	AtualizaInfoIndice('!', IndSec2);
	}
	/*else if (ExigeRecriaIndice(IndPrim))
	{
		RecriaIndicePrim(AP1);
		QuickSortInd1(INDEX1, 0, tam1);
	}
	else
	{
		IndPrim = fopen("IndPrim.bin", "r+b");
		CarregaIndice(IndPrim, 1);
    	IndSec1 = fopen("IndSec1.bin", "r+b");
    	CarregaIndice(IndSec1, 2);
    	IndSec2 = fopen("IndSec2.bin", "r+b");
    	CarregaIndice(IndSec2, 1);
	}*/

    if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir
        *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2)
}

/*
DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2
PARMETROS: AP2 - Arquivo Principal 2
*/
void CadastraCachorro(FILE **AP2)
{
	registro reg;

	system("CLS");
	printf("\nCodigo: ");
	scanf("%d", &reg.codigo);
	while (ExisteCachorro(reg.codigo, AP2))
	{
		system("CLS");
		printf("\nCodigo ja cadastrado. Digite novamente!");
		getch(); system("CLS");
		printf("\nCodigo: ");
        scanf("%d", &reg.codigo);
	}
	fflush(stdin);
	printf("Raca: ");
	gets(reg.raca);
	printf("Nome do Cachorro: ");
	gets(reg.nome);

	fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo.
	fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo.
}

/*
DESCRIO: Atualiza o header do ndice com o status de atualizao
PARMETROS: status - '*' - ndice atualizado
                     '!' - ndice desatualizado
            arq - ndice a ser atualizado
*/
void AtualizaInfoIndice(char status, FILE **arq)
{
	fseek(*arq, 0, SEEK_SET);
	fputc(status, *arq);
}

/*
DESCRIO: Verifica se o cdigo j existe no arquivo.
PARMETROS: codigo - Cdigo a ser verificado
            AP2 - Arquivo Principal 2
RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro
          1 - Existe um cachorro com o cdigo passado por parmetro
*/
int ExisteCachorro(int codigo, FILE **AP2)
{
	registro reg;

	rewind(*AP2);
	while (fread(&reg, sizeof(registro), 1, *AP2))
	{
		if (reg.codigo == codigo)
		{
			return 1;
			break;
		}
	}
    return 0;
}

/*
DESCRIO: Realiza o cadastro de vacinas
PARMETROS: AP1 - Arquivo principal 1
            AP2 - Arquivo principal 2
*/
void CadastraVacina(FILE **AP1, FILE **AP2)
{
    int cod_controle = 0, cod_cachorro, tam_reg, posicao, aux = 0;
    char verificador = '*', vacina[30], data[6], respo[100], registro[255];

    system("CLS");
    printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
    scanf("%d", &cod_cachorro);
    if (cod_cachorro == -1)
      CadastraCachorro(AP2);
    else
    {
        while (!ExisteCachorro(cod_cachorro, AP2))
        {
            if (!aux)
                printf("\n Cachorro inexistente. Digite novamente!");
            else
                printf("\n Nova busca..." );
            getch(); system("CLS");
            printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: ");
            scanf("%d", &cod_cachorro);
            if (cod_cachorro == -1)
            {
                CadastraCachorro(AP2);
                aux = 1;
            }
        }
        system("CLS");
        cod_controle++;//cod_controle = pegar do INDEX1 ordenado;
        printf("\n Codigo do cachorro: %d", cod_cachorro);
        fflush(stdin);
        printf("\n\n Nome da vacina: ");
        gets(vacina);
        printf("\n Data de vacinacao <MM/AA>: ");
        gets(data);
        printf("\n Responsavel pela aplicacao: ");
        gets(respo);

        sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo);
        tam_reg = strlen(registro);
        posicao = ProcuraEspacoVazio(AP1, tam_reg);
        if (posicao != -1)
          fseek(*AP1, posicao, SEEK_SET);
        else
          fseek(*AP1, 0, SEEK_END);
        fwrite(&tam_reg, sizeof(int), 1, *AP1);
        fwrite(&verificador, sizeof(char), 1, *AP1);
        fwrite(registro, sizeof(char), tam_reg, *AP1);
    }
}

/*
DESCRIO: Retorna o espao vazio encontrado no arquivo
PARMETROS: AP1 - Arquivo principal 1
            tam_reg - tamanho do registro a ser inserido
RETORNO: posio livre para ser escrita
*/
int ProcuraEspacoVazio(FILE **AP1, int tam_reg)
{
    int offset, tam, pos;
    char ch;

    rewind(*AP1);
    fread(&offset, sizeof(int), 1, *AP1);
    if (offset == -1)
        return -1;
    else
    {
        fseek(*AP1, offset, SEEK_SET);
        pos = ftell(*AP1);
        while (fread(&tam, sizeof(int), 1, *AP1))
        {
            if (tam == -1)
            {
                return -1;
                break;
            }
            else
            {
                ch = fgetc(*AP1);
                if ((tam > tam_reg) && (ch == '!'))
                {
                   return pos;
                   break;
                }
                else
                {
                    fread(&offset, sizeof(int), 1, *AP1);
                    fseek(*AP1, offset, SEEK_SET);
                }
            }
        }
    }
}

/*
DESCRIO: Altera dados de um cachorro
PARMETRO: AP2 - arquivo principal 2
*/
void AlteraCachorro(FILE **AP2)
{
    int op, cod, i = 0;
    char raca[30], nome[100];
    registro reg;

    system("CLS");
    printf("Digite o codigo do cachorro: ");
    scanf("%d", &cod);
    while (!ExisteCachorro(cod, AP2))
    {
        system("CLS");
        printf("\n\nCachorro inexistente. Digite novamente!");
        getch();
        system("CLS");
        printf("\n\nDigite o codigo do cachorro: ");
        scanf("%d", &cod);
    }

    rewind(*AP2);
	while (fread(&reg, sizeof(reg), 1, *AP2))
	{
		if (reg.codigo == cod)
		  break;
		i++;
	}

    system("CLS");
    printf("Qual campo deseja alterar");
    printf("\n\n1 - Raca");
    printf("\n2 - Nome");
    printf("\n\nEscolha a opcao: ");
    scanf("%d", &op);
    while ((op != 1) && (op != 2))
    {
       system("CLS");
       printf("Opcao invalida. Digite novamente!");
       getch();
       system("CLS");
       printf("Qual campo deseja alterar");
       printf("\n\n1 - Raca");
       printf("\n2 - Nome");
       printf("\n\nEscolha a opcao: ");
       scanf("%d", op);
    }

    fflush(stdin);
    system("CLS");
    switch(op)
    {
        case 1: printf("Digite a nova raca: ");
                gets(raca);
                strcpy(reg.raca, raca);
                break;
        case 2: printf("Digite o novo nome: ");
                gets(nome);
                strcpy(reg.nome, nome);
                break;
    }

    fseek(*AP2, sizeof(reg)*i, SEEK_SET);
	fwrite(&reg, sizeof(reg), 1, *AP2);
}

<|endoftext|>


<commit_before>/*
 * Jamoma RampLib Base Class
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#ifdef WIN_VERSION
 #pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION

#include "RampLib.h"
#include "ext.h"

#define thisTTClass RampUnit

RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
	: TTObject(kTTValNONE), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
	callback = aCallbackMethod;
	baton = aBaton;
	setNumValues(1);
	currentValue[0] = 0.0;
	targetValue[0] = 0.0;
	startValue[0] = 0.0;

	addAttributeWithSetter(Function, kTypeSymbol);
	setAttributeValue(TT("Function"), TT("linear"));
}

RampUnit::~RampUnit()
{
	TTObjectRelease(&functionUnit);
	delete [] currentValue;
	delete [] targetValue;
	delete [] startValue;
}

void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
	TTUInt32 i;

	stop();
	setNumValues(newNumValues);
	for (i=0; i<newNumValues; i++)
		currentValue[i] = newValues[i];
}

TTErr RampUnit::setFunction(const TTValue& functionName)
{
	TTErr		err;
	TTSymbolPtr	newFunctionName = NULL;

	functionName.get(0, &newFunctionName);

	if (newFunctionName == TT("none"))
		newFunctionName = TT("linear");

	if (newFunctionName == mFunction)
		return kTTErrNone;

	mFunction = newFunctionName;
	err = FunctionLib::createUnit(mFunction, (TTObject**)&functionUnit);
	if (err)
		logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
	return err;
}

TTErr RampUnit::getFunctionParameterNames(TTValue& names)
{
	functionUnit->getAttributeNames(names);
	return kTTErrNone;
}

TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, TTValue& newValue)
{
	functionUnit->setAttributeValue(parameterName, newValue);
	return kTTErrNone;
}

TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
	functionUnit->getAttributeValue(parameterName, value);
	return kTTErrNone;
}

void RampUnit::setNumValues(TTUInt32 newNumValues)
{
	if (newNumValues != numValues) {
		if (numValues != 0) {
			delete [] currentValue;
			delete [] targetValue;
			delete [] startValue;
		}

		currentValue = new TTFloat64[newNumValues];
		targetValue = new TTFloat64[newNumValues];
		startValue = new TTFloat64[newNumValues];
		numValues = newNumValues;
	}
	sendMessage(TT("numValuesChanged"));	// Notify sub-classes (if they respond to this message)
}

/***************************************************************************
	RampLib
 ***************************************************************************/

#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"

JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
	if (*unit)
		delete *unit;

	// These should be alphabetized
	if (unitName == TT("async"))
		*unit = (RampUnit*) new AsyncRamp(callback, baton);
	else if (unitName == TT("none"))
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	else if (unitName == TT("queue"))
		*unit = (RampUnit*) new QueueRamp(callback, baton);
	else if (unitName == TT("scheduler"))
		*unit = (RampUnit*) new SchedulerRamp(callback, baton);
	else {
		// Invalid function specified default to linear
//		TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
		error("puke");
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	}
	return JAMOMA_ERR_NONE;
}

void RampLib::getUnitNames(TTValue& unitNames)
{
	unitNames.clear();
	unitNames.append(TT("async"));
	unitNames.append(TT("none"));
	unitNames.append(TT("queue"));
	unitNames.append(TT("scheduler"));
}

<commit_msg>RampUnit: fix for uninitialized member variable (mFunction) that, if the state of the computer's memory was just right (as it was in Bug #431 from Trond) would cause a comparison to pass when it should have failed.<commit_after>/*
 * Jamoma RampLib Base Class
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#ifdef WIN_VERSION
 #pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION

#include "RampLib.h"
#include "ext.h"

#define thisTTClass RampUnit

RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton) :
	TTObject(kTTValNONE),
	mFunction(NULL),
	callback(aCallbackMethod),
	baton(aBaton),
	startValue(NULL),
	targetValue(NULL),
	currentValue(NULL),
	normalizedValue(0.0),
	numValues(0),
	functionUnit(NULL)
{
	setNumValues(1);
	currentValue[0] = 0.0;
	targetValue[0] = 0.0;
	startValue[0] = 0.0;

	addAttributeWithSetter(Function, kTypeSymbol);
	setAttributeValue(TT("Function"), TT("linear"));
}

RampUnit::~RampUnit()
{
	TTObjectRelease(&functionUnit);
	delete [] currentValue;
	delete [] targetValue;
	delete [] startValue;
}

void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
	TTUInt32 i;

	stop();
	setNumValues(newNumValues);
	for (i=0; i<newNumValues; i++)
		currentValue[i] = newValues[i];
}

TTErr RampUnit::setFunction(const TTValue& functionName)
{
	TTErr		err;
	TTSymbolPtr	newFunctionName = NULL;

	functionName.get(0, &newFunctionName);

	if (newFunctionName == TT("none"))
		newFunctionName = TT("linear");

	if (newFunctionName == mFunction)
		return kTTErrNone;

	mFunction = newFunctionName;
	err = FunctionLib::createUnit(mFunction, (TTObject**)&functionUnit);
	if (err)
		logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
	return err;
}

TTErr RampUnit::getFunctionParameterNames(TTValue& names)
{
	functionUnit->getAttributeNames(names);
	return kTTErrNone;
}

TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, TTValue& newValue)
{
	functionUnit->setAttributeValue(parameterName, newValue);
	return kTTErrNone;
}

TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
	functionUnit->getAttributeValue(parameterName, value);
	return kTTErrNone;
}

void RampUnit::setNumValues(TTUInt32 newNumValues)
{
	if (newNumValues != numValues) {
		if (numValues != 0) {
			delete [] currentValue;
			delete [] targetValue;
			delete [] startValue;
		}

		currentValue = new TTFloat64[newNumValues];
		targetValue = new TTFloat64[newNumValues];
		startValue = new TTFloat64[newNumValues];
		numValues = newNumValues;
	}
	sendMessage(TT("numValuesChanged"));	// Notify sub-classes (if they respond to this message)
}

/***************************************************************************
	RampLib
 ***************************************************************************/

#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"

JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
	if (*unit)
		delete *unit;

	// These should be alphabetized
	if (unitName == TT("async"))
		*unit = (RampUnit*) new AsyncRamp(callback, baton);
	else if (unitName == TT("none"))
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	else if (unitName == TT("queue"))
		*unit = (RampUnit*) new QueueRamp(callback, baton);
	else if (unitName == TT("scheduler"))
		*unit = (RampUnit*) new SchedulerRamp(callback, baton);
	else {
		// Invalid function specified default to linear
//		TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
		error("puke");
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	}
	return JAMOMA_ERR_NONE;
}

void RampLib::getUnitNames(TTValue& unitNames)
{
	unitNames.clear();
	unitNames.append(TT("async"));
	unitNames.append(TT("none"));
	unitNames.append(TT("queue"));
	unitNames.append(TT("scheduler"));
}

<|endoftext|>


<commit_before>/*! \file DegRateNuclide.cpp
    \brief Implements the DegRateNuclide class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>
#include <boost/lexical_cast.hpp>

#include "CycException.h"
#include "Logger.h"
#include "Timer.h"
#include "DegRateNuclide.h"
#include "Material.h"

using namespace std;
using boost::lexical_cast;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::DegRateNuclide():
  deg_rate_(0),
  v_(0),
  tot_deg_(0),
  last_degraded_(0)
{
  wastes_ = deque<mat_rsrc_ptr>();

  set_geom(GeometryPtr(new Geometry()));
  last_updated_=0;

  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::DegRateNuclide(QueryEngine* qe):
  deg_rate_(0),
  v_(0),
  tot_deg_(0),
  last_degraded_(0)
{
  wastes_ = deque<mat_rsrc_ptr>();
  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();

  set_geom(GeometryPtr(new Geometry()));
  last_updated_=0;

  initModuleMembers(qe);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::~DegRateNuclide(){
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::initModuleMembers(QueryEngine* qe){
  set_v(lexical_cast<double>(qe->getElementContent("advective_velocity")));
  set_deg_rate(lexical_cast<double>(qe->getElementContent("degradation")));
  LOG(LEV_DEBUG2,"GRDRNuc") << "The DegRateNuclide Class initModuleMembers(qe) function has been called";;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NuclideModelPtr DegRateNuclide::copy(const NuclideModel& src){
  const DegRateNuclide* src_ptr = dynamic_cast<const DegRateNuclide*>(&src);

  set_v(src_ptr->v());
  set_deg_rate(src_ptr->deg_rate());
  set_tot_deg(0);
  set_last_degraded(TI->time());

  // copy the geometry AND the centroid. It should be reset later.
  set_geom(GeometryPtr(new Geometry()));
  geom_->copy(src_ptr->geom(), src_ptr->geom()->centroid());
  update(TI->time());

  wastes_ = deque<mat_rsrc_ptr>();
  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();

  return shared_from_this();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update(int the_time){
  update_vec_hist(the_time);
  update_conc_hist(the_time);
  set_last_updated(the_time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::print(){
    LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide Model";;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::absorb(mat_rsrc_ptr matToAdd)
{
  // Get the given DegRateNuclide's contaminant material.
  // add the material to it with the material absorb function.
  // each nuclide model should override this function
  LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide is absorbing material: ";
  matToAdd->print();
  wastes_.push_back(matToAdd);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr DegRateNuclide::extract(const CompMapPtr comp_to_rem, double kg_to_rem)
{
  // Get the given DegRateNuclide's contaminant material.
  // add the material to it with the material extract function.
  // each nuclide model should override this function
  LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide" << "is extracting composition: ";
  comp_to_rem->print() ;
  mat_rsrc_ptr to_ret = mat_rsrc_ptr(MatTools::extract(comp_to_rem, kg_to_rem, wastes_));
  update(last_updated());
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::transportNuclides(int the_time){
  // This should transport the nuclides through the component.
  // It will likely rely on the internal flux and will produce an external flux.
  update_degradation(the_time, deg_rate());
  update(the_time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::set_deg_rate(double cur_rate){
  if( cur_rate < 0 || cur_rate > 1 ) {
    stringstream msg_ss;
    msg_ss << "The DegRateNuclide degradation rate range is 0 to 1, inclusive.";
    msg_ss << " The value provided was ";
    msg_ss << cur_rate;
    msg_ss <<  ".";
    LOG(LEV_ERROR,"GRDRNuc") << msg_ss.str();;
    throw CycRangeException(msg_ss.str());
  } else {
    deg_rate_ = cur_rate;
  }
  assert((cur_rate >=0) && (cur_rate <= 1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double DegRateNuclide::contained_mass(){
  return shared_from_this()->contained_mass(last_degraded());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> DegRateNuclide::source_term_bc(){
  return make_pair(contained_vec(last_degraded()),
      tot_deg()*shared_from_this()->contained_mass(last_degraded()));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::dirichlet_bc(){
  IsoConcMap dirichlet, whole_vol;
  whole_vol = conc_hist(last_degraded());
  IsoConcMap::const_iterator it;
  for( it=whole_vol.begin(); it!=whole_vol.end(); ++it){
    dirichlet[(*it).first] = tot_deg()*(*it).second ;
  }
  return dirichlet;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConcGradMap DegRateNuclide::neumann_bc(IsoConcMap c_ext, Radius r_ext){
  ConcGradMap to_ret;

  IsoConcMap c_int = conc_hist(last_degraded());
  Radius r_int = geom_->radial_midpoint();

  int iso;
  IsoConcMap::iterator it;
  for( it=c_int.begin(); it != c_int.end(); ++it){
    iso = (*it).first;
    if( c_ext.count(iso) != 0) {
      // in both
      to_ret[iso] = calc_conc_grad(c_ext[iso], c_int[iso]*tot_deg(), r_ext, r_int);
    } else {
      // in c_int_only
      to_ret[iso] = calc_conc_grad(0, c_int[iso]*tot_deg(), r_ext, r_int);
    }
  }
  for( it=c_ext.begin(); it != c_ext.end(); ++it){
    iso = (*it).first;
    if( c_int.count(iso) == 0) {
      // in c_ext only
      to_ret[iso] = calc_conc_grad(c_ext[iso], 0, r_ext, r_int);
    }
  }

  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoFluxMap DegRateNuclide::cauchy_bc(IsoConcMap c_ext, Radius r_ext){
  // -D dC/dx + v_xC = v_x C
  IsoFluxMap to_ret;
  ConcGradMap neumann = neumann_bc(c_ext, r_ext);
  ConcGradMap::iterator it;
  Iso iso;
  Elem elem;
  for( it = neumann.begin(); it != neumann.end(); ++it){
    iso = (*it).first;
    elem = iso/1000;
    to_ret.insert(make_pair(iso, -mat_table_->D(elem)*(*it).second + v()*shared_from_this()->dirichlet_bc(iso)));
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::update_conc_hist(int the_time){
  return update_conc_hist(the_time, wastes_);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::update_conc_hist(int the_time, deque<mat_rsrc_ptr> mats){
  assert(last_degraded() <= the_time);
  assert(last_updated() <= the_time);

  IsoConcMap to_ret;

  pair<IsoVector, double> sum_pair;
  sum_pair = vec_hist_[the_time];

  int iso;
  double conc;
  if(sum_pair.second != 0 && geom_->volume() != numeric_limits<double>::infinity()) {
    double scale = sum_pair.second/geom_->volume();
    CompMapPtr curr_comp = sum_pair.first.comp();
    CompMap::const_iterator it;
    it=(*curr_comp).begin();
    while(it != (*curr_comp).end() ) {
      iso = (*it).first;
      conc = (*it).second;
      to_ret.insert(make_pair(iso, conc*scale));
      ++it;
    }
  } else {
    to_ret[ 92235 ] = 0;
  }
  conc_hist_[the_time] = to_ret ;
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double DegRateNuclide::update_degradation(int the_time, double cur_rate){
  assert(last_degraded() <= the_time);
  if(cur_rate != deg_rate()){
    set_deg_rate(cur_rate);
  };
  double total = tot_deg() + deg_rate()*(the_time - last_degraded());
  set_tot_deg(min(1.0, total));
  set_last_degraded(the_time);

  return tot_deg_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update_vec_hist(int the_time){
  vec_hist_[ the_time ] = MatTools::sum_mats(wastes_) ;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update_inner_bc(int the_time, std::vector<NuclideModelPtr> daughters){
  std::map<NuclideModelPtr, std::pair<IsoVector,double> > to_ret;
  std::vector<NuclideModelPtr>::iterator daughter;
  std::pair<IsoVector, double> source_term;
  for( daughter = daughters.begin(); daughter!=daughters.end(); ++daughter){
    source_term = (*daughter)->source_term_bc();
    if( source_term.second > 0 ){
      absorb((*daughter)->extract(source_term.first.comp(), source_term.second));
    }
  }
}

<commit_msg>reductio of variable scope<commit_after>/*! \file DegRateNuclide.cpp
    \brief Implements the DegRateNuclide class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>
#include <boost/lexical_cast.hpp>

#include "CycException.h"
#include "Logger.h"
#include "Timer.h"
#include "DegRateNuclide.h"
#include "Material.h"

using namespace std;
using boost::lexical_cast;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::DegRateNuclide():
  deg_rate_(0),
  v_(0),
  tot_deg_(0),
  last_degraded_(0)
{
  wastes_ = deque<mat_rsrc_ptr>();

  set_geom(GeometryPtr(new Geometry()));
  last_updated_=0;

  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::DegRateNuclide(QueryEngine* qe):
  deg_rate_(0),
  v_(0),
  tot_deg_(0),
  last_degraded_(0)
{
  wastes_ = deque<mat_rsrc_ptr>();
  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();

  set_geom(GeometryPtr(new Geometry()));
  last_updated_=0;

  initModuleMembers(qe);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DegRateNuclide::~DegRateNuclide(){
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::initModuleMembers(QueryEngine* qe){
  set_v(lexical_cast<double>(qe->getElementContent("advective_velocity")));
  set_deg_rate(lexical_cast<double>(qe->getElementContent("degradation")));
  LOG(LEV_DEBUG2,"GRDRNuc") << "The DegRateNuclide Class initModuleMembers(qe) function has been called";;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NuclideModelPtr DegRateNuclide::copy(const NuclideModel& src){
  const DegRateNuclide* src_ptr = dynamic_cast<const DegRateNuclide*>(&src);

  set_v(src_ptr->v());
  set_deg_rate(src_ptr->deg_rate());
  set_tot_deg(0);
  set_last_degraded(TI->time());

  // copy the geometry AND the centroid. It should be reset later.
  set_geom(GeometryPtr(new Geometry()));
  geom_->copy(src_ptr->geom(), src_ptr->geom()->centroid());
  update(TI->time());

  wastes_ = deque<mat_rsrc_ptr>();
  vec_hist_ = VecHist();
  conc_hist_ = ConcHist();

  return shared_from_this();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update(int the_time){
  update_vec_hist(the_time);
  update_conc_hist(the_time);
  set_last_updated(the_time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::print(){
    LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide Model";;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::absorb(mat_rsrc_ptr matToAdd)
{
  // Get the given DegRateNuclide's contaminant material.
  // add the material to it with the material absorb function.
  // each nuclide model should override this function
  LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide is absorbing material: ";
  matToAdd->print();
  wastes_.push_back(matToAdd);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr DegRateNuclide::extract(const CompMapPtr comp_to_rem, double kg_to_rem)
{
  // Get the given DegRateNuclide's contaminant material.
  // add the material to it with the material extract function.
  // each nuclide model should override this function
  LOG(LEV_DEBUG2,"GRDRNuc") << "DegRateNuclide" << "is extracting composition: ";
  comp_to_rem->print() ;
  mat_rsrc_ptr to_ret = mat_rsrc_ptr(MatTools::extract(comp_to_rem, kg_to_rem, wastes_));
  update(last_updated());
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::transportNuclides(int the_time){
  // This should transport the nuclides through the component.
  // It will likely rely on the internal flux and will produce an external flux.
  update_degradation(the_time, deg_rate());
  update(the_time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::set_deg_rate(double cur_rate){
  if( cur_rate < 0 || cur_rate > 1 ) {
    stringstream msg_ss;
    msg_ss << "The DegRateNuclide degradation rate range is 0 to 1, inclusive.";
    msg_ss << " The value provided was ";
    msg_ss << cur_rate;
    msg_ss <<  ".";
    LOG(LEV_ERROR,"GRDRNuc") << msg_ss.str();;
    throw CycRangeException(msg_ss.str());
  } else {
    deg_rate_ = cur_rate;
  }
  assert((cur_rate >=0) && (cur_rate <= 1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double DegRateNuclide::contained_mass(){
  return shared_from_this()->contained_mass(last_degraded());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> DegRateNuclide::source_term_bc(){
  return make_pair(contained_vec(last_degraded()),
      tot_deg()*shared_from_this()->contained_mass(last_degraded()));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::dirichlet_bc(){
  IsoConcMap dirichlet, whole_vol;
  whole_vol = conc_hist(last_degraded());
  IsoConcMap::const_iterator it;
  for( it=whole_vol.begin(); it!=whole_vol.end(); ++it){
    dirichlet[(*it).first] = tot_deg()*(*it).second ;
  }
  return dirichlet;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConcGradMap DegRateNuclide::neumann_bc(IsoConcMap c_ext, Radius r_ext){
  ConcGradMap to_ret;

  IsoConcMap c_int = conc_hist(last_degraded());
  Radius r_int = geom_->radial_midpoint();

  int iso;
  IsoConcMap::iterator it;
  for( it=c_int.begin(); it != c_int.end(); ++it){
    iso = (*it).first;
    if( c_ext.count(iso) != 0) {
      // in both
      to_ret[iso] = calc_conc_grad(c_ext[iso], c_int[iso]*tot_deg(), r_ext, r_int);
    } else {
      // in c_int_only
      to_ret[iso] = calc_conc_grad(0, c_int[iso]*tot_deg(), r_ext, r_int);
    }
  }
  for( it=c_ext.begin(); it != c_ext.end(); ++it){
    iso = (*it).first;
    if( c_int.count(iso) == 0) {
      // in c_ext only
      to_ret[iso] = calc_conc_grad(c_ext[iso], 0, r_ext, r_int);
    }
  }

  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoFluxMap DegRateNuclide::cauchy_bc(IsoConcMap c_ext, Radius r_ext){
  // -D dC/dx + v_xC = v_x C
  IsoFluxMap to_ret;
  ConcGradMap neumann = neumann_bc(c_ext, r_ext);
  ConcGradMap::iterator it;
  Iso iso;
  Elem elem;
  for( it = neumann.begin(); it != neumann.end(); ++it){
    iso = (*it).first;
    elem = iso/1000;
    to_ret.insert(make_pair(iso, -mat_table_->D(elem)*(*it).second + v()*shared_from_this()->dirichlet_bc(iso)));
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::update_conc_hist(int the_time){
  return update_conc_hist(the_time, wastes_);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap DegRateNuclide::update_conc_hist(int the_time, deque<mat_rsrc_ptr> mats){
  assert(last_degraded() <= the_time);
  assert(last_updated() <= the_time);

  IsoConcMap to_ret;

  pair<IsoVector, double> sum_pair;
  sum_pair = vec_hist_[the_time];

  if(sum_pair.second != 0 && geom_->volume() != numeric_limits<double>::infinity()) {
    double scale = sum_pair.second/geom_->volume();
    CompMapPtr curr_comp = sum_pair.first.comp();
    CompMap::const_iterator it;
    it=(*curr_comp).begin();
    while(it != (*curr_comp).end() ) {
      int iso((*it).first);
      double conc((*it).second);
      to_ret.insert(make_pair(iso, conc*scale));
      ++it;
    }
  } else {
    to_ret[ 92235 ] = 0;
  }
  conc_hist_[the_time] = to_ret ;
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double DegRateNuclide::update_degradation(int the_time, double cur_rate){
  assert(last_degraded() <= the_time);
  if(cur_rate != deg_rate()){
    set_deg_rate(cur_rate);
  };
  double total = tot_deg() + deg_rate()*(the_time - last_degraded());
  set_tot_deg(min(1.0, total));
  set_last_degraded(the_time);

  return tot_deg_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update_vec_hist(int the_time){
  vec_hist_[ the_time ] = MatTools::sum_mats(wastes_) ;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void DegRateNuclide::update_inner_bc(int the_time, std::vector<NuclideModelPtr> daughters){
  std::map<NuclideModelPtr, std::pair<IsoVector,double> > to_ret;
  std::vector<NuclideModelPtr>::iterator daughter;
  std::pair<IsoVector, double> source_term;
  for( daughter = daughters.begin(); daughter!=daughters.end(); ++daughter){
    source_term = (*daughter)->source_term_bc();
    if( source_term.second > 0 ){
      absorb((*daughter)->extract(source_term.first.comp(), source_term.second));
    }
  }
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/common/planning_gflags.h"
DEFINE_int32(planning_loop_rate, 5, "Loop rate for planning node");

DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
              "Loop rate for planning node");

DEFINE_uint64(backward_trajectory_point_num, 10,
              "The number of points to be included in planning trajectory "
              "before the matched point");

DEFINE_uint64(rtk_trajectory_forward, 800,
              "The number of points to be included in RTK trajectory "
              "after the matched point");

DEFINE_double(trajectory_resolution, 0.01,
              "The time resolution of "
              "output trajectory.");

DEFINE_double(
    look_backward_distance, 10,
    "look backward this distance when creating reference line from routing");

DEFINE_double(
    look_forward_distance, 70,
    "look forward this distance when creating reference line from routing");
DEFINE_bool(enable_smooth_reference_line, true,
            "enable smooth the map reference line");

DEFINE_int32(max_history_frame_num, 5, "The maximum history frame number");

DEFINE_double(max_collision_distance, 0.1,
              "considered as collision if distance (meters) is smaller than or "
              "equal to this (meters)");

DEFINE_double(replan_distance_threshold, 5.0,
              "The distance threshold of replan");

DEFINE_double(default_reference_line_width, 4.0,
              "Default reference line width");

DEFINE_double(planning_upper_speed_limit, 10.0, "Maximum speed in planning.");

DEFINE_double(planning_distance, 100, "Planning distance");

DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
DEFINE_double(trajectory_time_resolution, 0.1,
              "Trajectory time resolution in planning");
DEFINE_double(output_trajectory_time_resolution, 0.05,
              "Trajectory time resolution when publish");

DEFINE_double(speed_lower_bound, 0.0, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");

DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
              "The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
              "The highest longitudinal acceleration allowed.");

DEFINE_double(lateral_acceleration_bound, 4.5,
              "Bound of lateral acceleration; symmetric for left and right");
DEFINE_double(lateral_jerk_bound, 4.0,
              "Bound of lateral jerk; symmetric for left and right");

DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
              "The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
              "The upper bound of longitudinal jerk.");

DEFINE_double(kappa_bound, 0.23, "The bound for vehicle curvature");

// ST Boundary
DEFINE_double(st_max_s, 80, "the maximum s of st boundary");
DEFINE_double(st_max_t, 10, "the maximum t of st boundary");

// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
              "obstacles are considered as static obstacle if its speed is "
              "less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, false, "enable nudge decision");
DEFINE_double(static_decision_ignore_s_range, 3.0,
              "threshold for judging nudge in dp path computing decision");
DEFINE_double(static_decision_nudge_l_buffer, 0.5, "l buffer for nudge");
DEFINE_double(stop_distance_obstacle, 5.0,
              "stop distance from in-lane obstacle (meters)");
DEFINE_double(destination_adjust_distance_buffer, 1.0,
              "distance buffer when adjusting destination stop line");
DEFINE_double(min_driving_width, 2.5,
              "minimum road width(meters) for adc to drive through");
DEFINE_double(nudge_distance_obstacle, 0.3,
              "minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 10,
              "min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(stop_line_min_distance, 0.0,
              "min distance (meters) to stop line for a valid stop");

DEFINE_string(destination_obstacle_id, "DEST",
              "obstacle id for converting destination to an obstacle");
DEFINE_int32(virtual_obstacle_perception_id, -1,
             "virtual obstacle perception id(a negative int)");
DEFINE_double(virtual_stop_wall_length, 0.1,
              "virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_width, 3.7, "virtual stop wall width (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
              "virtual stop wall height (meters)");

// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, true,
            "enable align prediction data based planning time");

// Trajectory
DEFINE_bool(enable_rule_layer, true,
            "enable rule for trajectory before model computation");

// Traffic decision

DEFINE_string(planning_config_file,
              "modules/planning/conf/planning_config.pb.txt",
              "planning config file");

DEFINE_int32(trajectory_point_num_for_debug, 10,
             "number of output trajectory points for debugging");

DEFINE_double(decision_valid_stop_range, 0.5,
              "The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
            "True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
<commit_msg>planning: increase stop distance.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/common/planning_gflags.h"
DEFINE_int32(planning_loop_rate, 5, "Loop rate for planning node");

DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
              "Loop rate for planning node");

DEFINE_uint64(backward_trajectory_point_num, 10,
              "The number of points to be included in planning trajectory "
              "before the matched point");

DEFINE_uint64(rtk_trajectory_forward, 800,
              "The number of points to be included in RTK trajectory "
              "after the matched point");

DEFINE_double(trajectory_resolution, 0.01,
              "The time resolution of "
              "output trajectory.");

DEFINE_double(
    look_backward_distance, 10,
    "look backward this distance when creating reference line from routing");

DEFINE_double(
    look_forward_distance, 70,
    "look forward this distance when creating reference line from routing");
DEFINE_bool(enable_smooth_reference_line, true,
            "enable smooth the map reference line");

DEFINE_int32(max_history_frame_num, 5, "The maximum history frame number");

DEFINE_double(max_collision_distance, 0.1,
              "considered as collision if distance (meters) is smaller than or "
              "equal to this (meters)");

DEFINE_double(replan_distance_threshold, 5.0,
              "The distance threshold of replan");

DEFINE_double(default_reference_line_width, 4.0,
              "Default reference line width");

DEFINE_double(planning_upper_speed_limit, 10.0, "Maximum speed in planning.");

DEFINE_double(planning_distance, 100, "Planning distance");

DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
DEFINE_double(trajectory_time_resolution, 0.1,
              "Trajectory time resolution in planning");
DEFINE_double(output_trajectory_time_resolution, 0.05,
              "Trajectory time resolution when publish");

DEFINE_double(speed_lower_bound, 0.0, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");

DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
              "The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
              "The highest longitudinal acceleration allowed.");

DEFINE_double(lateral_acceleration_bound, 4.5,
              "Bound of lateral acceleration; symmetric for left and right");
DEFINE_double(lateral_jerk_bound, 4.0,
              "Bound of lateral jerk; symmetric for left and right");

DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
              "The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
              "The upper bound of longitudinal jerk.");

DEFINE_double(kappa_bound, 0.23, "The bound for vehicle curvature");

// ST Boundary
DEFINE_double(st_max_s, 80, "the maximum s of st boundary");
DEFINE_double(st_max_t, 10, "the maximum t of st boundary");

// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
              "obstacles are considered as static obstacle if its speed is "
              "less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, false, "enable nudge decision");
DEFINE_double(static_decision_ignore_s_range, 3.0,
              "threshold for judging nudge in dp path computing decision");
DEFINE_double(static_decision_nudge_l_buffer, 0.5, "l buffer for nudge");
DEFINE_double(stop_distance_obstacle, 10.0,
              "stop distance from in-lane obstacle (meters)");
DEFINE_double(destination_adjust_distance_buffer, 1.0,
              "distance buffer when adjusting destination stop line");
DEFINE_double(min_driving_width, 2.5,
              "minimum road width(meters) for adc to drive through");
DEFINE_double(nudge_distance_obstacle, 0.3,
              "minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 10,
              "min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(stop_line_min_distance, 0.0,
              "min distance (meters) to stop line for a valid stop");

DEFINE_string(destination_obstacle_id, "DEST",
              "obstacle id for converting destination to an obstacle");
DEFINE_int32(virtual_obstacle_perception_id, -1,
             "virtual obstacle perception id(a negative int)");
DEFINE_double(virtual_stop_wall_length, 0.1,
              "virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_width, 3.7, "virtual stop wall width (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
              "virtual stop wall height (meters)");

// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, true,
            "enable align prediction data based planning time");

// Trajectory
DEFINE_bool(enable_rule_layer, true,
            "enable rule for trajectory before model computation");

// Traffic decision

DEFINE_string(planning_config_file,
              "modules/planning/conf/planning_config.pb.txt",
              "planning config file");

DEFINE_int32(trajectory_point_num_for_debug, 10,
             "number of output trajectory points for debugging");

DEFINE_double(decision_valid_stop_range, 0.5,
              "The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
            "True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/prediction_component.h"

#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/util/message_util.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"

namespace apollo {
namespace prediction {

using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;

PredictionComponent::~PredictionComponent() { Stop(); }

std::string PredictionComponent::Name() const {
  return FLAGS_prediction_module_name;
}

void PredictionComponent::ProcessOfflineData(const std::string& filename) {
  // TODO(all) implement

  /**
   const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
                                         FLAGS_localization_topic};
   rosbag::Bag bag;
   try {
     bag.open(filename, rosbag::bagmode::Read);
   } catch (const rosbag::BagIOException& e) {
     AERROR << "BagIOException when open bag: " << filename
            << " Exception: " << e.what();
     bag.close();
     return;
   } catch (...) {
     AERROR << "Failed to open bag: " << filename;
     bag.close();
     return;
   }
   rosbag::View view(bag, rosbag::TopicQuery(topics));
   for (auto it = view.begin(); it != view.end(); ++it) {
     if (it->getTopic() == FLAGS_localization_topic) {
       OnLocalization(*(it->instantiate<LocalizationEstimate>()));
     } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
       RunOnce(*(it->instantiate<PerceptionObstacles>()));
     }
   }
   bag.close();
   **/
}

bool PredictionComponent::Init() {
  AINFO << "Loading gflag from file: " << ConfigFilePath();
  google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());

  component_start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    AERROR << "Unable to load prediction conf file: "
           << FLAGS_prediction_conf_file;
    return false;
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    AERROR << "Unable to load adapter conf file: "
           << FLAGS_prediction_adapter_config_filename;
    return false;
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  planning_reader_ = node_->CreateReader<ADCTrajectory>(
      FLAGS_planning_trajectory_topic,
      [this](const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
        ADEBUG << "Received planning data: run planning callback.";
        std::lock_guard<std::mutex> lock(mutex_);
        OnPlanning(*adc_trajectory);
      });

  // Initialization of all managers
  ContainerManager::Instance()->Init(adapter_conf_);
  EvaluatorManager::Instance()->Init(prediction_conf_);
  PredictorManager::Instance()->Init(prediction_conf_);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Map cannot be loaded.";
    return false;
  }

  prediction_writer_ =
      node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      AERROR << "Feature output is not ready.";
      return false;
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return true;  // use listen to ROS topic mode
    }
    std::vector<std::string> inputs;
    apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
    for (const auto& input : inputs) {
      std::vector<std::string> offline_bags;
      GetDataFileNames(boost::filesystem::path(input), &offline_bags);
      std::sort(offline_bags.begin(), offline_bags.end());
      AINFO << "For input " << input << ", found " << offline_bags.size()
            << "  rosbags to process";
      for (std::size_t i = 0; i < offline_bags.size(); ++i) {
        AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
              << " ]: " << offline_bags[i];
        ProcessOfflineData(offline_bags[i]);
      }
    }
    Stop();
  }
  return true;
}

void PredictionComponent::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void PredictionComponent::OnLocalization(
    const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void PredictionComponent::OnPlanning(
    const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

bool PredictionComponent::Proc(
    const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
    const std::shared_ptr<LocalizationEstimate>& localization) {
  if (FLAGS_prediction_test_mode &&
      (Clock::NowInSeconds() - component_start_time_ >
       FLAGS_prediction_test_duration)) {
    ADEBUG << "Prediction finished running in test mode";
  }

  // Update relative map if needed
  // AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return false;
  }

  double start_timestamp = Clock::NowInSeconds();

  OnLocalization(*localization);

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(*perception_obstacles);

  // Scenario analysis
  ScenarioManager::Instance()->Run();

  obstacles_container->BuildLaneGraph();

  ADEBUG << "Received a perception message ["
         << perception_obstacles->ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    adc_container->SetPosition({x, y});
  }

  // Make evaluations
  EvaluatorManager::Instance()->Run(*perception_obstacles);

  // No prediction trajectories for offline mode
  if (FLAGS_prediction_offline_mode) {
    return true;
  }

  // Make predictions
  PredictorManager::Instance()->Run(*perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::Instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
  prediction_obstacles.mutable_header()->set_lidar_timestamp(
      perception_obstacles->header().lidar_timestamp());
  prediction_obstacles.mutable_header()->set_camera_timestamp(
      perception_obstacles->header().camera_timestamp());
  prediction_obstacles.mutable_header()->set_radar_timestamp(
      perception_obstacles->header().radar_timestamp());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return false;
          }
        }
      }
    }
  }

  common::util::FillHeader(node_->Name(), &prediction_obstacles);

  prediction_writer_->Write(
      std::make_shared<PredictionObstacles>(prediction_obstacles));
  return true;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Prediction: turn off scenrio manager tmp<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/prediction_component.h"

#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>

#include "boost/filesystem.hpp"
#include "boost/range/iterator_range.hpp"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/util/message_util.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"

namespace apollo {
namespace prediction {

using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::common::time::Clock;
using apollo::common::util::DirectoryExists;
using apollo::common::util::Glob;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;

PredictionComponent::~PredictionComponent() { Stop(); }

std::string PredictionComponent::Name() const {
  return FLAGS_prediction_module_name;
}

void PredictionComponent::ProcessOfflineData(const std::string& filename) {
  // TODO(all) implement

  /**
   const std::vector<std::string> topics{FLAGS_perception_obstacle_topic,
                                         FLAGS_localization_topic};
   rosbag::Bag bag;
   try {
     bag.open(filename, rosbag::bagmode::Read);
   } catch (const rosbag::BagIOException& e) {
     AERROR << "BagIOException when open bag: " << filename
            << " Exception: " << e.what();
     bag.close();
     return;
   } catch (...) {
     AERROR << "Failed to open bag: " << filename;
     bag.close();
     return;
   }
   rosbag::View view(bag, rosbag::TopicQuery(topics));
   for (auto it = view.begin(); it != view.end(); ++it) {
     if (it->getTopic() == FLAGS_localization_topic) {
       OnLocalization(*(it->instantiate<LocalizationEstimate>()));
     } else if (it->getTopic() == FLAGS_perception_obstacle_topic) {
       RunOnce(*(it->instantiate<PerceptionObstacles>()));
     }
   }
   bag.close();
   **/
}

bool PredictionComponent::Init() {
  AINFO << "Loading gflag from file: " << ConfigFilePath();
  google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());

  component_start_time_ = Clock::NowInSeconds();

  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    AERROR << "Unable to load prediction conf file: "
           << FLAGS_prediction_conf_file;
    return false;
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    AERROR << "Unable to load adapter conf file: "
           << FLAGS_prediction_adapter_config_filename;
    return false;
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  planning_reader_ = node_->CreateReader<ADCTrajectory>(
      FLAGS_planning_trajectory_topic,
      [this](const std::shared_ptr<ADCTrajectory>& adc_trajectory) {
        ADEBUG << "Received planning data: run planning callback.";
        std::lock_guard<std::mutex> lock(mutex_);
        OnPlanning(*adc_trajectory);
      });

  // Initialization of all managers
  ContainerManager::Instance()->Init(adapter_conf_);
  EvaluatorManager::Instance()->Init(prediction_conf_);
  PredictorManager::Instance()->Init(prediction_conf_);

  if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Map cannot be loaded.";
    return false;
  }

  prediction_writer_ =
      node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic);

  if (FLAGS_prediction_offline_mode) {
    if (!FeatureOutput::Ready()) {
      AERROR << "Feature output is not ready.";
      return false;
    }
    if (FLAGS_prediction_offline_bags.empty()) {
      return true;  // use listen to ROS topic mode
    }
    std::vector<std::string> inputs;
    apollo::common::util::split(FLAGS_prediction_offline_bags, ':', &inputs);
    for (const auto& input : inputs) {
      std::vector<std::string> offline_bags;
      GetDataFileNames(boost::filesystem::path(input), &offline_bags);
      std::sort(offline_bags.begin(), offline_bags.end());
      AINFO << "For input " << input << ", found " << offline_bags.size()
            << "  rosbags to process";
      for (std::size_t i = 0; i < offline_bags.size(); ++i) {
        AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
              << " ]: " << offline_bags[i];
        ProcessOfflineData(offline_bags[i]);
      }
    }
    Stop();
  }
  return true;
}

void PredictionComponent::Stop() {
  if (FLAGS_prediction_offline_mode) {
    FeatureOutput::Close();
  }
}

void PredictionComponent::OnLocalization(
    const LocalizationEstimate& localization) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);
  pose_container->Insert(localization);

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void PredictionComponent::OnPlanning(
    const planning::ADCTrajectory& adc_trajectory) {
  ADCTrajectoryContainer* adc_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(adc_trajectory_container);
  adc_trajectory_container->Insert(adc_trajectory);

  ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
         << "].";
}

bool PredictionComponent::Proc(
    const std::shared_ptr<PerceptionObstacles>& perception_obstacles,
    const std::shared_ptr<LocalizationEstimate>& localization) {
  if (FLAGS_prediction_test_mode &&
      (Clock::NowInSeconds() - component_start_time_ >
       FLAGS_prediction_test_duration)) {
    ADEBUG << "Prediction finished running in test mode";
  }

  // Update relative map if needed
  // AdapterManager::Observe();
  if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
    AERROR << "Relative map is empty.";
    return false;
  }

  double start_timestamp = Clock::NowInSeconds();

  OnLocalization(*localization);

  // Insert obstacle
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(*perception_obstacles);

  // Scenario analysis
  // ScenarioManager::Instance()->Run();

  obstacles_container->BuildLaneGraph();

  ADEBUG << "Received a perception message ["
         << perception_obstacles->ShortDebugString() << "].";

  // Update ADC status
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  PerceptionObstacle* adc = pose_container->ToPerceptionObstacle();
  if (adc != nullptr) {
    obstacles_container->InsertPerceptionObstacle(*adc, adc->timestamp());
    double x = adc->position().x();
    double y = adc->position().y();
    ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
           << ", " << std::fixed << std::setprecision(6) << y << "].";
    adc_container->SetPosition({x, y});
  }

  // Make evaluations
  EvaluatorManager::Instance()->Run(*perception_obstacles);

  // No prediction trajectories for offline mode
  if (FLAGS_prediction_offline_mode) {
    return true;
  }

  // Make predictions
  PredictorManager::Instance()->Run(*perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::Instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
  prediction_obstacles.mutable_header()->set_lidar_timestamp(
      perception_obstacles->header().lidar_timestamp());
  prediction_obstacles.mutable_header()->set_camera_timestamp(
      perception_obstacles->header().camera_timestamp());
  prediction_obstacles.mutable_header()->set_radar_timestamp(
      perception_obstacles->header().radar_timestamp());

  if (FLAGS_prediction_test_mode) {
    for (auto const& prediction_obstacle :
         prediction_obstacles.prediction_obstacle()) {
      for (auto const& trajectory : prediction_obstacle.trajectory()) {
        for (auto const& trajectory_point : trajectory.trajectory_point()) {
          if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
            AERROR << "Invalid trajectory point ["
                   << trajectory_point.ShortDebugString() << "]";
            return false;
          }
        }
      }
    }
  }

  common::util::FillHeader(node_->Name(), &prediction_obstacles);

  prediction_writer_->Write(
      std::make_shared<PredictionObstacles>(prediction_obstacles));
  return true;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before><commit_msg>Use the correct signal for the sync type combo box to indicate a change and make the apply button enabled<commit_after><|endoftext|>


<commit_before>/*
 Copyright 2014 Arjan van der Velde, vandervelde.ag [at] gmail

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#include <iostream>
#include <algorithm>

#include "TwoBitSequence.hpp"
#include "TwoBitFile.hpp"
#include "TwoBitUtil.hpp"

namespace TwoBit
{

const uint32_t TwoBitSequence::BUFFER_SIZE;

TwoBitSequence::TwoBitSequence(const std::string& name, const uint32_t offset,
		TwoBitFile& file) :
		name_(name), offset_(offset), filename_(file.filename_), swapped_(
				file.swapped_), dnaSize_(0), dnaBytes_(0), packedpos_(0)
{
	open();
}

TwoBitSequence::~TwoBitSequence()
{
	close();
}

void TwoBitSequence::readRegions(std::vector<Region>& out)
{
	uint32_t count;
	count = nextInt(file_, swapped_);
	std::vector<uint32_t> starts;
	std::vector<uint32_t> lengths;

	for (uint32_t i = 0; i < count; ++i)
	{
		starts.emplace_back(nextInt(file_, swapped_));
	}
	for (uint32_t i = 0; i < count; ++i)
	{
		lengths.emplace_back(nextInt(file_, swapped_));
	}

	out.clear();
	out.reserve(count * 2);
	out.emplace_back(0, 0); // filler, makes logic a little easier
	for (uint32_t i = 0; i < count; ++i)
	{
		out.emplace_back(starts[i], 1);
		out.emplace_back(starts[i] + lengths[i], -1);
	}

	std::sort(out.begin(), out.end(), [](const Region& a, const Region& b)
	{
		return a.pos_ < b.pos_;
	});
}

void TwoBitSequence::open()
{
	// open file, seek to offset and read sequence meta data.
	file_.open(filename_, std::ios::in | std::ios::binary);
	file_.seekg(offset_);
	dnaSize_ = nextInt(file_, swapped_); // length of sequence
	dnaBytes_ = dnaSize_ / 4 + (dnaSize_ % 4 > 0);

	// read nRegions.
	readRegions(nRegions); // N-regions
	readRegions(mRegions); // mask regions

	// check. this number should be zero as per the spec.
	if (0 != nextInt(file_, swapped_))
	{
		throw Exception("Unexpected data. Bad 2-bit file.");
	}

	// store start of packed data
	packedpos_ = file_.tellg();
}

void TwoBitSequence::close()
{
	file_.close();
}

void TwoBitSequence::test()
{
	std::cout << "name_: " << name_ << std::endl;
	std::cout << "offset_: " << offset_ << std::endl;
	std::cout << "swapped_: " << swapped_ << std::endl;
	std::cout << "filename_: " << filename_ << std::endl;
}

void TwoBitSequence::getSequence(std::vector<char>& buffer, uint32_t start, uint32_t end)
{
	// alphabet for masked and unmasked sequence.
	const char upper[5] = {'T', 'C', 'A', 'G', 'N'};
	const char lower[5] = {'t', 'c', 'a', 'g', 'n'};

	// clean start and end (that is: start < end <= dnasize)
	uint32_t startNuc = std::min(dnaSize_ - 1, start);
	uint32_t endNuc = std::max(startNuc + 1, std::min(dnaSize_, end)); // < dnaSize, > startNuc.

	// calculate byte positions in file.
	uint32_t startByte = packedpos_ + (startNuc / 4);
	uint32_t endByte = packedpos_ + (endNuc / 4) + (endNuc % 4 > 0);

	// update start and end nucleotide to the ones we're actually reading (based on byte positions)
	startNuc = (startByte - packedpos_) * 4;
	endNuc = (endByte - packedpos_) * 4;

	buffer.clear();
	buffer.reserve(endNuc - startNuc + 1); // +1?

	// reading starts here.
	uint32_t seqPos = startNuc;
	uint32_t filePos = startByte;

	// counters for N and mask regions
	int m = 0;
	int n = 0;
	uint32_t prevm = 0;
	uint32_t prevn = 0;

	file_.seekg(filePos);
	while (filePos < endByte) {

		file_.read(buffer_, std::min(endByte - filePos, BUFFER_SIZE));
		filePos += BUFFER_SIZE;

		// obtain sequence.
		for (uint32_t i = 0; i < file_.gcount(); ++i)
		{
			for (uint32_t j = 0; j < 8; j += 2)
			{

				// fast-forward N-regions to figure out whether we need to return N's or sequence.
				while (prevn < nRegions.size() && nRegions[prevn].pos_ <= seqPos)
				{
					n += nRegions[prevn++].action_;
				}

				// fast-forward mask-regions to figure out whether or not we need to mask.
				while (prevm < mRegions.size() && mRegions[prevm].pos_ <= seqPos)
				{
					m += mRegions[prevm++].action_;
				}

				// translate 2-bit to sequence.
				if (m == 0 && n == 0)
				{
					// no mask, no N
					buffer.push_back(upper[(buffer_[i] >> (6 - j)) & 0x03]);
				}
				else if (m == 0 && n > 0)
				{
					// no mask, but N
					buffer.push_back(upper[4]);
				}
				else if (m > 0 && n == 0)
				{
					// mask, no N
					buffer.push_back(lower[(buffer_[i] >> (6 - j)) & 0x03]);
				}
				else if (m > 0 && n > 0)
				{
					// masked N (should not happen I guess)
					buffer.push_back(lower[4]);
				} else {
					// negative values for m or n means something's not quite right.
					throw Exception("Error parsing regions.");
				}
				seqPos++;
			}
		}
	}
}

} // namespace TwoBit
<commit_msg>not +1<commit_after>/*
 Copyright 2014 Arjan van der Velde, vandervelde.ag [at] gmail

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#include <iostream>
#include <algorithm>

#include "TwoBitSequence.hpp"
#include "TwoBitFile.hpp"
#include "TwoBitUtil.hpp"

namespace TwoBit
{

const uint32_t TwoBitSequence::BUFFER_SIZE;

TwoBitSequence::TwoBitSequence(const std::string& name, const uint32_t offset,
		TwoBitFile& file) :
		name_(name), offset_(offset), filename_(file.filename_), swapped_(
				file.swapped_), dnaSize_(0), dnaBytes_(0), packedpos_(0)
{
	open();
}

TwoBitSequence::~TwoBitSequence()
{
	close();
}

void TwoBitSequence::readRegions(std::vector<Region>& out)
{
	uint32_t count;
	count = nextInt(file_, swapped_);
	std::vector<uint32_t> starts;
	std::vector<uint32_t> lengths;

	for (uint32_t i = 0; i < count; ++i)
	{
		starts.emplace_back(nextInt(file_, swapped_));
	}
	for (uint32_t i = 0; i < count; ++i)
	{
		lengths.emplace_back(nextInt(file_, swapped_));
	}

	out.clear();
	out.reserve(count * 2);
	out.emplace_back(0, 0); // filler, makes logic a little easier
	for (uint32_t i = 0; i < count; ++i)
	{
		out.emplace_back(starts[i], 1);
		out.emplace_back(starts[i] + lengths[i], -1);
	}

	std::sort(out.begin(), out.end(), [](const Region& a, const Region& b)
	{
		return a.pos_ < b.pos_;
	});
}

void TwoBitSequence::open()
{
	// open file, seek to offset and read sequence meta data.
	file_.open(filename_, std::ios::in | std::ios::binary);
	file_.seekg(offset_);
	dnaSize_ = nextInt(file_, swapped_); // length of sequence
	dnaBytes_ = dnaSize_ / 4 + (dnaSize_ % 4 > 0);

	// read nRegions.
	readRegions(nRegions); // N-regions
	readRegions(mRegions); // mask regions

	// check. this number should be zero as per the spec.
	if (0 != nextInt(file_, swapped_))
	{
		throw Exception("Unexpected data. Bad 2-bit file.");
	}

	// store start of packed data
	packedpos_ = file_.tellg();
}

void TwoBitSequence::close()
{
	file_.close();
}

void TwoBitSequence::test()
{
	std::cout << "name_: " << name_ << std::endl;
	std::cout << "offset_: " << offset_ << std::endl;
	std::cout << "swapped_: " << swapped_ << std::endl;
	std::cout << "filename_: " << filename_ << std::endl;
}

void TwoBitSequence::getSequence(std::vector<char>& buffer, uint32_t start, uint32_t end)
{
	// alphabet for masked and unmasked sequence.
	const char upper[5] = {'T', 'C', 'A', 'G', 'N'};
	const char lower[5] = {'t', 'c', 'a', 'g', 'n'};

	// clean start and end (that is: start < end <= dnasize)
	uint32_t startNuc = std::min(dnaSize_ - 1, start);
	uint32_t endNuc = std::max(startNuc + 1, std::min(dnaSize_, end)); // < dnaSize, > startNuc.

	// calculate byte positions in file.
	uint32_t startByte = packedpos_ + (startNuc / 4);
	uint32_t endByte = packedpos_ + (endNuc / 4) + (endNuc % 4 > 0);

	// update start and end nucleotide to the ones we're actually reading (based on byte positions)
	startNuc = (startByte - packedpos_) * 4;
	endNuc = (endByte - packedpos_) * 4;

	// nuke buffer and resize
	buffer.clear();
	buffer.reserve(endNuc - startNuc);

	// reading starts here.
	uint32_t seqPos = startNuc;
	uint32_t filePos = startByte;

	// counters for N and mask regions
	int m = 0;
	int n = 0;
	uint32_t prevm = 0;
	uint32_t prevn = 0;

	file_.seekg(filePos);
	while (filePos < endByte) {

		file_.read(buffer_, std::min(endByte - filePos, BUFFER_SIZE));
		filePos += BUFFER_SIZE;

		// obtain sequence.
		for (uint32_t i = 0; i < file_.gcount(); ++i)
		{
			for (uint32_t j = 0; j < 8; j += 2)
			{

				// fast-forward N-regions to figure out whether we need to return N's or sequence.
				while (prevn < nRegions.size() && nRegions[prevn].pos_ <= seqPos)
				{
					n += nRegions[prevn++].action_;
				}

				// fast-forward mask-regions to figure out whether or not we need to mask.
				while (prevm < mRegions.size() && mRegions[prevm].pos_ <= seqPos)
				{
					m += mRegions[prevm++].action_;
				}

				// translate 2-bit to sequence.
				if (m == 0 && n == 0)
				{
					// no mask, no N
					buffer.push_back(upper[(buffer_[i] >> (6 - j)) & 0x03]);
				}
				else if (m == 0 && n > 0)
				{
					// no mask, but N
					buffer.push_back(upper[4]);
				}
				else if (m > 0 && n == 0)
				{
					// mask, no N
					buffer.push_back(lower[(buffer_[i] >> (6 - j)) & 0x03]);
				}
				else if (m > 0 && n > 0)
				{
					// masked N (should not happen I guess)
					buffer.push_back(lower[4]);
				} else {
					// negative values for m or n means something's not quite right.
					throw Exception("Error parsing regions.");
				}
				seqPos++;
			}
		}
	}
}

} // namespace TwoBit
<|endoftext|>


<commit_before><commit_msg>first bad version<commit_after><|endoftext|>


<commit_before>#include "CL/cl.h"
#include "ocl.h"
#include "tools.h"
#include "utils.h"
#include "data.h"
#include "control.h"
#include "profiler.h"
#include "enums.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include "windows.h"
#include "shlwapi.h"
#include "parallel.h"
#include "sequential.h"
#include <fstream>

ControlClass::ControlClass()
	: GroupManager("Control")
	, sample_data_(NULL)
	, sample_rate_input_(1000)
	, sample_rate_output_(500)
	, sample_data_input_file_("..\\data\\default.csv")
{
	groups_ = GroupFactory();
}
ControlClass* ControlObject;

std::map<int, ProblemGroup*> ControlClass::GroupFactory()
{
	std::map<int, ProblemGroup*> pgs;

	ProblemGroup* InputControl = GroupManagerInputControlFactory();
	size_t idx = InputControl->problems_.size();
	InputControl->problems_[++idx] = new Problem(&SetInputDataFile, "Set the file path to read sample data from.");
	InputControl->problems_[++idx] = new Problem(&SetSampleRates, "Set the input and output sample rates.");
	InputControl->problems_[++idx] = new Problem(&Test_LoadSampleData, "Read and print sample data.");
	pgs[InputControl->GroupNum()] = InputControl;

	ProblemGroup* projectFuncs = new ProblemGroup(1, "Control");
	projectFuncs->problems_[++idx] = new Problem(&exCL_Resample, "OpenCL: Apply sixth-order polynomial");
	projectFuncs->problems_[++idx] = new Problem(&Test_PolyEval, "Test Polynomial Evaluation Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_QR, "Test QR Decomposition Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_BackSub, "Test Back Substitution Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_SignalGenerator, "Test Signal Generator Function");
	pgs[projectFuncs->GroupNum()] = projectFuncs;
	return pgs;
}

// Attempts to read sample input data from provided data file
// Expects to find one amplitude value per line
// @return the number of data points read
int ControlClass::LoadSampleData(bool printPoints)
{
	// With help from:
	//http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
	std::ifstream f(ControlObject->sample_data_input_file_.c_str());
	if (!f.good())
		return -1;
	int pointCount = 0;
	std::filebuf fb;
	std::vector<float> points;
	if (fb.open(ControlObject->sample_data_input_file_, std::ios::in))
	{
		std::istream is(&fb);
		char point[256];
		while (is.getline(point, 256))
			points.push_back(std::stof(point));
		fb.close();
	}
	if (printPoints)
		std::cout << "Read Points: " << std::endl;
	sample_data_ = (float*)malloc(sizeof(float*)*points.size());
	for (size_t i = 0; i < points.size(); ++i)
	{
		sample_data_[i] = points[i];
		if(printPoints)
			std::cout << i << ": " << points[i] << std::endl;
	}

	return (int)points.size();
}

// Set the Input and Output sample rates
int SetSampleRates(ResultsStruct* results)
{
	std::cout << "Enter INPUT sample rate (currently " << ControlObject->sample_rate_input_ << "): ";
	std::cin >> ControlObject->sample_rate_input_;
	std::cout << "Enter OUTPUT sample rate (currently " << ControlObject->sample_rate_output_ << "): ";
	std::cin >> ControlObject->sample_rate_output_;
	return 0;
}

// Set Input Data File path
int SetInputDataFile(ResultsStruct* results)
{
	std::cout << "Enter path to input sample file to (currently " << ControlObject->sample_data_input_file_ << "): ";
	std::string s(ControlObject->sample_data_input_file_);
	std::cin >> s;
	ControlObject->sample_data_input_file_ = s;
	std::ifstream f(ControlObject->sample_data_input_file_.c_str());
	if (!f.good())
	{
		std::cout << "WARNING: File does not exist: " << ControlObject->sample_data_input_file_ << std::endl;
		return -1;
	}
	return 0;
}

// Reads sample data and prints it to the screen
// Uses LoadSampleData() function with optional print bool set to true
int Test_LoadSampleData(ResultsStruct* results)
{
	// returns number of loaded
	bool printPoints = true; // for test purposes
	size_t loadCount = ControlObject->LoadSampleData(printPoints);
	std::cout << "Points Loaded: " << loadCount << std::endl;
	return (loadCount >= 0 ? 0 : -1);
}

<commit_msg>Fixed counter on problem after changes.<commit_after>#include "CL/cl.h"
#include "ocl.h"
#include "tools.h"
#include "utils.h"
#include "data.h"
#include "control.h"
#include "profiler.h"
#include "enums.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include "windows.h"
#include "shlwapi.h"
#include "parallel.h"
#include "sequential.h"
#include <fstream>

ControlClass::ControlClass()
	: GroupManager("Control")
	, sample_data_(NULL)
	, sample_rate_input_(1000)
	, sample_rate_output_(500)
	, sample_data_input_file_("..\\data\\default.csv")
{
	groups_ = GroupFactory();
}
ControlClass* ControlObject;

std::map<int, ProblemGroup*> ControlClass::GroupFactory()
{
	std::map<int, ProblemGroup*> pgs;

	ProblemGroup* InputControl = GroupManagerInputControlFactory();
	size_t idx = InputControl->problems_.size();
	InputControl->problems_[++idx] = new Problem(&SetInputDataFile, "Set the file path to read sample data from.");
	InputControl->problems_[++idx] = new Problem(&SetSampleRates, "Set the input and output sample rates.");
	InputControl->problems_[++idx] = new Problem(&Test_LoadSampleData, "Read and print sample data.");
	pgs[InputControl->GroupNum()] = InputControl;

	idx = 0; // reset counter
	ProblemGroup* projectFuncs = new ProblemGroup(1, "Control");
	projectFuncs->problems_[++idx] = new Problem(&exCL_Resample, "OpenCL: Apply sixth-order polynomial");
	projectFuncs->problems_[++idx] = new Problem(&Test_PolyEval, "Test Polynomial Evaluation Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_QR, "Test QR Decomposition Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_BackSub, "Test Back Substitution Function");
	projectFuncs->problems_[++idx] = new Problem(&Test_SignalGenerator, "Test Signal Generator Function");
	pgs[projectFuncs->GroupNum()] = projectFuncs;
	return pgs;
}

// Attempts to read sample input data from provided data file
// Expects to find one amplitude value per line
// @return the number of data points read
int ControlClass::LoadSampleData(bool printPoints)
{
	// With help from:
	//http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
	std::ifstream f(ControlObject->sample_data_input_file_.c_str());
	if (!f.good())
		return -1;
	int pointCount = 0;
	std::filebuf fb;
	std::vector<float> points;
	if (fb.open(ControlObject->sample_data_input_file_, std::ios::in))
	{
		std::istream is(&fb);
		char point[256];
		while (is.getline(point, 256))
			points.push_back(std::stof(point));
		fb.close();
	}
	if (printPoints)
		std::cout << "Read Points: " << std::endl;
	sample_data_ = (float*)malloc(sizeof(float*)*points.size());
	for (size_t i = 0; i < points.size(); ++i)
	{
		sample_data_[i] = points[i];
		if(printPoints)
			std::cout << i << ": " << points[i] << std::endl;
	}

	return (int)points.size();
}

// Set the Input and Output sample rates
int SetSampleRates(ResultsStruct* results)
{
	std::cout << "Enter INPUT sample rate (currently " << ControlObject->sample_rate_input_ << "): ";
	std::cin >> ControlObject->sample_rate_input_;
	std::cout << "Enter OUTPUT sample rate (currently " << ControlObject->sample_rate_output_ << "): ";
	std::cin >> ControlObject->sample_rate_output_;
	return 0;
}

// Set Input Data File path
int SetInputDataFile(ResultsStruct* results)
{
	std::cout << "Enter path to input sample file to (currently " << ControlObject->sample_data_input_file_ << "): ";
	std::string s(ControlObject->sample_data_input_file_);
	std::cin >> s;
	ControlObject->sample_data_input_file_ = s;
	std::ifstream f(ControlObject->sample_data_input_file_.c_str());
	if (!f.good())
	{
		std::cout << "WARNING: File does not exist: " << ControlObject->sample_data_input_file_ << std::endl;
		return -1;
	}
	return 0;
}

// Reads sample data and prints it to the screen
// Uses LoadSampleData() function with optional print bool set to true
int Test_LoadSampleData(ResultsStruct* results)
{
	// returns number of loaded
	bool printPoints = true; // for test purposes
	size_t loadCount = ControlObject->LoadSampleData(printPoints);
	std::cout << "Points Loaded: " << loadCount << std::endl;
	return (loadCount >= 0 ? 0 : -1);
}

<|endoftext|>