diff --git a/README-pt.md b/README-pt.md index cc0e136960e1264fd9090978f6658aba3e253db5..d5f944bb1e493f1cb7526d75e89325b904a40dcc 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,108 +1,267 @@ -# Administrador de base de dados SimCAQ/SMPPIR # +# HOTMapper # -Esse repositório implementa a classe DatabaseTable e funções para verificar pareamento entre -diferentes anos inseridos no banco de dados. A ferramenta é desenvolvida em Python 3, e usa -como base arquivos de mapeamento em formato CSV. +Este repositório contem a ferramenta HOTMapper, o qual permite o usuário gerenciar seus dados históricos usando protocolos de mapeamento. -Para a utilização a partir da linha de comando, a CLI manage.py pode ser utilizada sem -que se invoque manualmente as funções a partir da linha de comando Python. +## Dados ## + +Os dados abertos extraÃdos e processados pela ferramenta podem ser encontrados no link [INEP](http://portal.inep.gov.br/web/guest/microdados) na seção "Censo Escolar" e " Censo da Educação Superior". + +Para facilitar a execução da ferramente, nós baixamos todos os dados de "Local Oferta" no diretório `open_data`. Desta forma não é necessário procurar os dados originais. + +**NOTA**: É importante verificar se existem uma coluna identificando o ano do conjunto de dados ## Requisitos ## -O utilitário foi desenvolvido em Python 3 usando a biblioteca SQLAlchemy com vistas ao banco -de dados MonetDB. Versões futuras podem ter modificações visando a compatibilidade com outros -bancos de dados, aproveitando as capacidades da biblioteca base. +* Python 3 (É recomendado o uso de um ambiente virtual, como o virtualenv) +* MonetDB (Nós temos planos de expandir o suporte de bancos de dados que o HOTMapper suporta no futuro) + +## Installação ## + +---- +**IMPORTANTE:** +Nós assumimos queo Python 3.X está instalado na máquina que executará o HOTMapper e que todos os comandos a seguir que utilizam Python serão executados com o Python 3.x. +---- + + +1) Instale o virtualenv + +1a) No Linux/macOS + +```bash +$ sudo -H pip install virtualenv +``` + +1b) No Windows (with administrator privilleges) + +```cmd +$ pip install virtualenv +``` -Para a instalação dos requisitos conforme usados durante o desenvolvimento, o arquivo -requirements.txt pode ser usado como base (Recomenda-se o uso de um ambiente virtual). +2) Clone este repositório ```bash -(env) $ pip install -r requirements.txt +$ git clone git@gitlab.c3sl.ufpr.br:tools/hotmapper.git ``` -A CLI depende do módulo manage.py. Demais dependências serão listadas a seguir. +ou + +```bash +$ git clone https://github.com/C3SL/hotmapper.git +``` + +3) Acesse o repositório + +```bash +$ cd hotmapper +``` + +4) Crie um ambiente virtual + +```bash +$ virtualenv env +``` + +5) Inicie o ambiente virtual + +5a) No Linux/macOS + +```bash +$ source env/bin/activate +``` -### Requisitos para a interface com a base de dados ### +5b) No Windows (com privilégios de administrador) -* pymonetdb -* SQLAlchemy -* sqlalchemy-monetdb +```cmd +$ .\env\Scripts/activate +``` -### Requisitos para geração de pareamentos ### +6) Instale as dependências + +```bash +$ pip install -r requirements.txt +``` -* numpy -* pandas -* xlrd -* XlsxWriter +## Interface de Linha de Comando (CLI) ## -## Interface de linha de comando ## -A invocação da CLI utiliza o padrão do pacote manage.py, que é: +A interface de linha de comando (CLI) permite a ações fornecidas pelo manage.py. Para utilizar a CLI utiliza o seguinte formato padrão: ```bash -$ python manage.py [commando] [argumentos posicionais] [argumentos opcionais com valor] +$ python manage.py [COMANDO] [ARGUMENTOS POSICIONAIS] [ARGUMENTOS OPCIONAIS] ``` -Os comandos já implementados são: +Onde comando pode ser: -* create: Cria a tabela conforme definido no protocolo de mapeamento. +* create: Cria uma tabela usando o protocolo de mapeamento. ```bash -$ python manage.py create <nome da tabela> +$ python manage.py create <nome_da_tabela> ``` -O único argumento usado é o nome da tabela. O script procurará por um protocolo de -mapeamento com o mesmo nome para a busca do esquema das colunas. +**IMPORTANTE:** O HOTMapper usará o nome do protocolo como o nome da tabela + -* insert: insere um arquivo de dados em formato CSV ou similar em uma tabela existente. +* insert: Insere um arquivo CSV em uma tabela existente. ```bash -$ python manage.py insert <caminho para o arquivo> <nome da tabela> <ano> [--sep separador] [--null valor_nulo] +$ python manage.py insert <caminho/completo/para/o/arquivo> <nome_da_tabela> <ano> [--sep separador] [--null valor_null] +``` + ``` +<caminho/completo/para/o/arquivo> : O caminho absoluto para o arquivo + +<nome_da_tabela>: O nome da tabela onde o arquivo será inserido -O caminho para o arquivo deve ser absoluto. A tabela utilizada deve existir e estar -sincronizada com o protocolo de mapeamento correspondente. O separador padrão utilizado -é ponto e vÃrgula (';'); caso outros separadores sejam utilizados pelo arquivo fonte, -devem ser especificados com --sep (por exemplo --sep \\| para pipe). O valor nulo padrão -é string vazia. Caso outro valor seja usado, deve ser especificado com --null. +<ano>: A coluna do protocolo de mapeamento que o HOTMapper deve usar para inserir os dados -* drop: derruba uma tabela do banco de dados. +[--sep separador]: O separador personalizado do CSV. Para mudar, você deve substituir 'separador' com o separador que seu arquivo usa. + +[--null valor_null]: Define o que substituirá o valor nulo. Substitua 'valor_nulo' com o que quiser que seja o valor nulo + +``` + +* drop: Apaga uma tabela do banco de dados ```bash -$ python manage.py drop <nome da tabela> +$ python manage.py drop <nome_da_tabela> ``` -O comando não contorna chaves estrangeiras que apontem para a tabela, e o banco de dados -pode retornar um erro caso exista alguma. +**IMPORTANTE:** O comando não gerencia chaves estrangeiras que apontam para a tabela que está sendo excluÃda. -* remap: sincroniza uma tabela com o protocolo de mapeamento. +* remap: sincroniza a tabela com os mapeamentos ```bash -$ python manage.py remap <nome da tabela> +$ python manage.py remap <nome_da_tabela> ``` +Este comando deve ser executado toda vez que a definição dos mapeamentos são atualizadas. -Esse comando deve ser utilizado sempre que um protocolo de mapeamento for atualizado. +O rema permite a criação de novas colunas, a exclusão de colunas existentes, a renomeação de columnas e a modificação de tipo das colunas. Preste atenção que quanto maior a tabela sendo atualizada, maior o uso de memória RAM. -O remapeamento permite a criação de novas colunas, derrubada de colunas existentes, -renomeamento de colunas e mudança de tipo. Dependendo do tamanho da tabela, o uso de -memória primária pode ser intenso. +* update_from_file: Atualiza os dados em um tabela -* generate_pairing_report: gera relatórios de pareamento para comparação de dados ano -a ano. +```bash +$ python manage.py update_from_file <arquivo_csv> <nome_da_tabela> <ano> [--columns="column_name1","column_name2"] [--sep=separador] +``` + +* generate_pairing_report: gera relatórios para comparar os dados de diferentes anos. ```bash $ python manage.py generate_pairing_report [--output xlsx|csv] ``` -Os relatórios são criados na pasta pairing. Caso o formato não seja especificado, -csv será utilizado (um arquivo será criado para cada tabela). Caso xlsx seja o formato -utilizado, um arquivo será criado com todas as tabelas separadas em diferentes planilhas. +Os relatórios serão criados no diretório "pairing" -* generate_backup: Cria/Atualiza o arquivo monitorado para o backup. + +* generate_backup: Cria/Atualiza um arquivo de backup da base de dados. ```bash $ python manage.py generate_backup ``` -O arquivo é criado ou atualizado na máquina onde o banco de dados da produção está, -o procedimento de backup da equipe de infraestrutura o monitora para realizar o procedimento. \ No newline at end of file +## Cenários demonstrativos ## + +Nesta Seção nós explicaremos como executar os cenários demonstrativos que foram enviados para a conferência EDBT 2019. No cenário 1 será utilizado o conjunto de dados de "local oferta", o qual está incluÃdo no diretório `open_data`. O cenário 2 utiliza o conjunto de dados "matrÃcula", o qual pode ser baixado do [Link do INEP](http://portal.inep.gov.br/web/guest/microdados) na seção "Censo Escolar". + +Em ambos os cenários nós assumimos que você iniciou o ambiente virtual como explicado na Seção `Instalação - 5`; + +### Cenário 1 ### + +Esta Seção contem os comandos usados no cenário 1, os quais criam uma tabela e adicionam os dados correspondentes. + + +1) Primeiro nós precisamos criar a tabela no banco de dados. Para fazer isso execute o seguinte comando: +```bash +$ ./manage.py create localoferta_ens_superior +``` + +2) Agora, que nós já temos o protocolo de mapeamento, nós precisamos inserir os dados abertos no banco de dados. Para fazer isso nós precisamos executar os seguintes comandos: + +**IMPORTANTE:** CAMINHO_DO_ARQUIVO é o **_caminho completo_** para o diretório que o dado aberto está localizado, por exemplo (em um ambiente Linux): `/home/c3sl/HOTMapper/open_data/DM_LOCAL_OFERTA_2010.CSV` + + +a) Para inserir 2010: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2010.CSV localoferta_ens_superior 2010 --sep="|" +``` + +b) Para inserir 2011: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2011.CSV localoferta_ens_superior 2011 --sep="|" +``` + +c) Para inserir 2012: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2012.CSV localoferta_ens_superior 2012 --sep="|" +``` + +d) Para inserir 2013: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2013.CSV localoferta_ens_superior 2013 --sep="|" +``` + +e) Para inserir 2014: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2014.CSV localoferta_ens_superior 2014 --sep="|" +``` + +f) Para inserir 2015: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2015.CSV localoferta_ens_superior 2015 --sep="|" +``` + +g) Para inserir 2016: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/DM_LOCAL_OFERTA_2016.CSV localoferta_ens_superior 2016 --sep="|" +``` + +### Cenário 2 ### + +Esta Seção contem os comandos usados no cenário 2, os quais são uma atualização de uma tabela. + + +1) Primeiro nós precisamos criar a tabela no banco de dados. Para fazer isso execute o seguinte comando: +```bash +$ ./manage.py create matricula +``` + +2) Agora, que nós já temos o protocolo de mapeamento, nós precisamos inserir os dados abertos no banco de dados. Para fazer isso nós precisamos executar os seguintes comandos: + +**IMPORTANTE:** CAMINHO_DO_ARQUIVO é o **_caminho completo_** para o diretório que o dado aberto está localizado, por exemplo (em um ambiente Linux): `/home/c3sl/HOTMapper/open_data/MATRICULA_2013.CSV` + +a) Para inserir 2013: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/MATRICULA_2013.CSV matricula 2013 --sep="|" +``` + +b) Para inserir 2014: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/MATRICULA_2014.CSV matricula 2014 --sep="|" +``` + +c) Para inserir 2015: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/MATRICULA_2015.CSV matricula 2015 --sep="|" +``` + +d) Para inserir 2016: +```bash +$ ./manage.py insert CAMINHO_DO_ARQUIVO/MATRICULA_2016.CSV matricula 2016 --sep="|" +``` + +3) Mude o protocolo de mapeamento de matrÃcula. Você pode usar o protocolo `matricula_remap.csv` ( Para fazer isso, renomeie o atual `matricula.csv` para qualquer outra coisa e o `matricula_remap.csv` para `matricula.csv`). Neste caso, a única coluna que mudará é a "profissionalizante", porque agora, ao invés de `ELSE returns 0` ela retorna `9`. + +4) Rode o comando remap + +```bash +$ ./manage.py remap matricula +``` + +O comando acima atualizará a tabela `Fonte` e o esquema da tabela `matricula` + +5) Atualize a tabela + +```bash +$ ./manage.py update_from_file CAMINHO_DO_ARQUIVO/MATRICULA_2013.CSV matricula 2013 --columns="profissionalizante" --sep="|" +``` + +O comando acima atualizará os dados na tabela `matricula`. \ No newline at end of file diff --git a/README.md b/README.md index 55bfa51a8ebc643170e5cc4f1b8a5bc5f74c31c1..c17fbb891f63e80f5d014b4effa625c5bf51d8d2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # HOTMapper # -This respository contains the HOTMapper tool, a tool that allows the user to manage his historical data using a mapping protocol. This specific version is freezed for demonstration purposes for the EDBT 2019 conference. +This respository contains the HOTMapper tool, a tool that allows the user to manage his historical data using a mapping protocol. ## Table of content ## @@ -17,9 +17,9 @@ This respository contains the HOTMapper tool, a tool that allows the user to man The Open Data sources extracted and processed by the tool can be found at the link: [INEP](http://portal.inep.gov.br/web/guest/microdados) in the section "Censo Escolar" and "Censo da Educação Superior". -To make it easier to execute the tool, we have dowloaded all data from "Local Oferta" is in the directory open_data. This way it is not necessary to search for the original sources. +To make it easier to execute the tool, we have dowloaded all data from "Local Oferta" is in the directory `open_data`. This way it is not necessary to search for the original sources. -**NOTE**: It's important to verify if there is a column identifying the year of the dataset; +**NOTE**: It's important to verify if there is a column identifying the year of the dataset ## Requirements ## @@ -30,7 +30,7 @@ To make it easier to execute the tool, we have dowloaded all data from "Local Of ---- **NOTICE:** -We assume thatPython 3.x is installed in the local computer and that all the following commands that use Python will use Python 3.x. +We assume that Python 3.x is installed in the local computer and that all the following commands that use Python will use Python 3.x. -- 1) Install virtualenv @@ -52,6 +52,11 @@ $ pip install virtualenv ```bash $ git clone git@gitlab.c3sl.ufpr.br:tools/hotmapper.git ``` +or + +```bash +$ git clone https://github.com/C3SL/hotmapper.git +``` 3) Go to the repository @@ -85,7 +90,7 @@ $ .\env\Scripts/activate $ pip install -r requirements.txt ``` -## Command Line Interface ## +## Command Line Interface (CLI) ## The CLI (Command Line Interface) uses the standard actions provided by manage.py, which means that to invoke a command it follows the following patterns: @@ -101,7 +106,7 @@ Where COMMAND can be: $ python manage.py create <table_name> ``` -**Notice** that the HOTMapper will use the name of the protocol as the name of the table. +**NOTICE** that the HOTMapper will use the name of the protocol as the name of the table. * insert: Inserts a CSV file in an existing table. @@ -164,23 +169,23 @@ $ python manage.py generate_backup ``` ## Demo scenarios ## -In this Section we will explain how to execute the demo scenarios that were submitted to EDBT 2019. Demo scenario 1 uses the dataset "local oferta", which is included in the directory open_data. Demo scenario 2 uses the dataset "matricula" which can be downloaded from the [INEP's Link ](http://portal.inep.gov.br/web/guest/microdados) in the section "Censo Escolar". +In this Section we will explain how to execute the demo scenarios that were submitted to EDBT 2019. Demo scenario 1 uses the dataset "local oferta", which is included in the directory `open_data`. Demo scenario 2 uses the dataset "matricula" which can be downloaded from the [INEP's Link ](http://portal.inep.gov.br/web/guest/microdados) in the section "Censo Escolar". -In both scnearios, we assume that you started the virtual environment as explained in Section `Installation - 5` +In both scenarios, we assume that you started the virtual environment as explained in Section `Installation - 5` ### Demo scenario 1 ### -This section contains the commands used in the scenario 1, which is the creation of a new data source and the inclusion of the corresponding data. +This Section contains the commands used in the scenario 1, which is the creation of a new table and the inclusion of the corresponding data. -1) First we need to create the database, to do so we execute the following command: +1) First we need to create the table in the database, to do so we execute the following command: ```bash $ ./manage.py create localoferta_ens_superior ``` -2) Now, as we already have the mapping definition, we need to insert the open data in the data base. To do it we must execute the following commands: +2) Now, as we already have the mapping definition, we need to insert the open data in the database. To do it we must execute the following commands: -**NOTE:** FILEPATH is the **_full path_** for the directory where the open data table is, for example (in a Linux environment): `/home/c3sl/HOTMapper/open_data/DM_LOCAL_OFERTA_2010` +**NOTE:** FILEPATH is the **_full path_** for the directory where the open data table is, for example (in a Linux environment): `/home/c3sl/HOTMapper/open_data/DM_LOCAL_OFERTA_2010.CSV` a) To insert 2010: @@ -220,10 +225,10 @@ $ ./manage.py insert FILEPATH/DM_LOCAL_OFERTA_2016.CSV localoferta_ens_superior ### Demo scenario 2 ### -This section contains the commands used in the scenario 2, which is an update of an existing data source. +This Section contains the commands used in the scenario 2, which is an update of an existing table. -1) First we need to create the database, to do so execute the following command: +1) First we need to create the table in the database, to do so we execute the following command: ```bash $ ./manage.py create matricula ``` @@ -252,19 +257,19 @@ d) To insert 2016: $ ./manage.py insert FILEPATH/MATRICULA_2016.CSV matricula 2016 --sep="|" ``` -3) Change the matricula's mapping protocol. You can use the `matricula_remap.csv` (To do so, rename the current `matricula.csv` to something else and the `matricula_remap.csv` to `matricula.csv`). In that case, the only column that will change is the "profissionalizante", because now, instead of the ELSE returns 0 it returns 9. +3) Change the matricula's mapping protocol. You can use the `matricula_remap.csv` (To do so, rename the current `matricula.csv` to something else and the `matricula_remap.csv` to `matricula.csv`). In that case, the only column that will change is the "profissionalizante", because now, instead of the `ELSE returns 0` it returns `9`. 4) Run the remap command ```bash $ ./manage.py remap matricula ``` -The above command will update the table `Fonte` and the schema from the table matricula +The above command will update the table `Fonte` and the schema from the table `matricula` 5) Update the table ```bash -$ ./manage.py update_from_file /FILEPATH/MATRICULA_2013.CSV matricula 2013 --columns="profissionalizante" --sep="|" +$ ./manage.py update_from_file FILEPATH/MATRICULA_2013.CSV matricula 2013 --columns="profissionalizante" --sep="|" ``` -The above command will update the data in the table matricula. +The above command will update the data in the table `matricula`.