source: observatorio/simulacion/SimEscenariosEconomicos/indicatorGenerator.C

simulacion
Last change on this file was ac8ea81, checked in by Alejandro <amujica@…>, 9 years ago

Agregado el paramatro de conexion a la base de datos a la documentacion

  • Property mode set to 100644
File size: 21.8 KB
Line 
1/*
2  Copyright (C) 2012
3  Alejandro Mujica (amujica@cenditel.gob.ve)
4  Erwin Paredes (eparedes@cenditel.gob.ve)
5  José Ruiz (jruiz@cenditel.gob.ve)
6  Rodolfo Rangel (rrangel@cenditel.gob.ve)
7  Julie Vera (jvera@cenditel.gob.ve)
8 
9  CENDITEL Fundación Centro Nacional de Desarrollo e Investigación en
10  Tecnologías Libres
11 
12  Este programa es software libre; Usted puede usarlo bajo los términos de la
13  licencia de software GPL versión 2.0 de la Free Software Foundation.
14 
15  Este programa se distribuye con la esperanza de que sea útil, pero SIN
16  NINGUNA GARANTÍA; tampoco las implícitas garantías de MERCANTILIDAD o
17  ADECUACIÓN A UN PROPÓSITO PARTICULAR.
18  Consulte la licencia GPL para más detalles. Usted debe recibir una copia
19  de la GPL junto con este programa; si no, escriba a la Free Software
20  Foundation Inc. 51 Franklin Street,5 Piso, Boston, MA 02110-1301, USA.
21*/
22
23/*
24  Autor:             Alejandro J. Mujica
25  Fecha de creación: 25/11/2013
26  Este archivo contiene las implementaciones de las clases para la generación de
27  indicadores.
28*/
29
30# include <indicatorGenerator.H>
31
32std::unique_ptr <IndicatorGeneratorFactory>
33IndicatorGeneratorFactory::instance;
34
35const std::string ProductionIndicatorGenerator::PRODUCT_INPUT_FILE_NAME =
36    "indicadores-producto-insumo.csv";
37
38const std::string ProductionIndicatorGenerator::PRODUCT_FILE_NAME =
39    "indicadores-producto.csv";
40
41
42void ProductionIndicatorGenerator::writeProductLine(AutoConnection & conn,
43    Graph::Node * node, std::ofstream & file,
44    Map <long, PlantLocation> & mapPlantLocation,
45    Map <std::string, std::string> & mapCompanyCiiu) {
46   
47    Good * good = node->get_info().get();
48
49    std::string rel = "";
50
51    switch(node->type) {
52
53        case ROOT:
54            rel = "Inicial";
55            break;
56
57        case SUGGESTED:
58            rel = "Propuesta";
59            break;
60
61        case IMPORT:
62            rel = "Importación";
63            break;
64
65        default:
66            rel = "Existente";
67    }
68
69    const std::string & rif = COMPANY(good)->getRif();
70
71    std::string * ptrCiiu = mapCompanyCiiu.search(rif);
72
73    if (ptrCiiu == NULL) {
74
75        std::string ciiu = getCiiu(conn, rif);
76
77        ptrCiiu = mapCompanyCiiu.insert(rif, ciiu);
78    }
79
80    PlantLocation plantLocation;
81
82    if (good->getType() == PRODUCT_GOOD) {
83
84        Product * product = static_cast <Product *>(good);
85
86        const long & plantId = product->getProducerPlant()->getId();
87
88        PlantLocation * ptrPlantLocation = mapPlantLocation.search(plantId);
89
90        if (ptrPlantLocation == NULL) {
91
92            plantLocation = getPlantLocation(conn, plantId);
93
94            mapPlantLocation.insert(plantId, plantLocation);
95               
96        } else
97            plantLocation = *ptrPlantLocation;
98
99    }
100
101    std::string levels;
102
103    node->levels.for_each(WriteLevels(levels));
104
105    levels = levels.substr(0, levels.size() - 2);
106
107    file << doubleQuote(rel) << ","
108         << doubleQuote(*ptrCiiu) << ","
109         << doubleQuote(rif) << ","
110         << doubleQuote(COMPANY(good)->getName()) << ","
111         << doubleQuote(plantLocation.state) << ","
112         << doubleQuote(plantLocation.town) << ","
113         << doubleQuote(plantLocation.parish) << ","
114         << doubleQuote(good->getTariffCode()) << ","
115         << doubleQuote(good->getName()) << ","
116         << doubleQuote(good->getTechnicalSpecifications()) << ","
117         << doubleQuote(good->getTrademark()) << ","
118         << doubleQuote(good->getMeasurementUnit()) << ","
119         << doubleQuote(levels) << ",";
120}
121
122real computeGeneratedEmployment(AutoConnection & conn, Graph::Node * node,
123                                const std::string & rif,
124                                const std::string & year,
125                                const real & amountDiff) {
126
127    real generatedEmployment = 0;
128
129    Good * good = node->get_info().get();
130
131    if ((node->type == UPSTREAM or node->type == DOWNSTREAM or
132         node->type == ROOT) and good->getType() == PRODUCT_GOOD) {
133
134        real staffNumber = getOperatingStaffNumber(conn, rif, year);
135
136        real totalAmount = getTotalAmount(conn, rif, year);
137
138        generatedEmployment = staffNumber * amountDiff / totalAmount;
139    }
140
141    return generatedEmployment;
142}
143
144
145void ProductionIndicatorGenerator::writeInputLine(AutoConnection & conn,
146    Graph & graph, Graph::Arc * arc, std::ofstream & file,
147    Map <long, PlantLocation> & mapPlantLocation,
148    Map <std::string, std::string> & mapCompanyCiiu,
149    const std::string & year) {
150   
151    Graph::Node * node = graph.get_src_node(arc);
152
153    Good * good = node->get_info().get();
154
155    std::string rel = "";
156
157    switch(node->type) {
158
159        case ROOT:
160            rel = "Inicial";
161            break;
162
163        case SUGGESTED:
164            rel = "Propuesta";
165            break;
166
167        case IMPORT:
168            rel = "Importación";
169            break;
170
171        default:
172            rel = "Existente";
173    }
174
175    const std::string & rif = COMPANY(good)->getRif();
176
177    std::string * ptrCiiu = mapCompanyCiiu.search(rif);
178
179    if (ptrCiiu == NULL) {
180
181        std::string ciiu = getCiiu(conn, rif);
182
183        ptrCiiu = mapCompanyCiiu.insert(rif, ciiu);
184    }
185
186    PlantLocation plantLocation;
187
188    if (good->getType() == PRODUCT_GOOD) {
189
190        Product * product = static_cast <Product *>(good);
191
192        const long & plantId = product->getProducerPlant()->getId();
193
194        PlantLocation * ptrPlantLocation = mapPlantLocation.search(plantId);
195
196        if (ptrPlantLocation == NULL) {
197
198            plantLocation = getPlantLocation(conn, plantId);
199
200            mapPlantLocation.insert(plantId, plantLocation);
201               
202        } else
203            plantLocation = *ptrPlantLocation;
204
205    }
206
207    Company * ptrCompany = COMPANY(good);
208
209    std::string nat = ptrCompany->getNationality() == "E" ?
210                      "Importado" : "Nacional";
211
212    const real & quantity = arc->get_info().newValue1 -
213                            arc->get_info().totalQuantity;
214
215    const real amount = quantity * arc->get_info().price;
216
217    real employment = computeGeneratedEmployment(conn, node, rif, year, amount);
218
219    char sep = 0;
220
221    file << doubleQuote(rel) << ","
222         << doubleQuote(nat) << ","
223         << doubleQuote(ptrCompany->getOrigCountry()) << ","
224         << doubleQuote(ptrCompany->getProcCountry()) << ","
225         << doubleQuote(*ptrCiiu) << ","
226         << doubleQuote(rif) << ","
227         << doubleQuote(COMPANY(good)->getName()) << ","
228         << doubleQuote(plantLocation.state) << ","
229         << doubleQuote(plantLocation.town) << ","
230         << doubleQuote(plantLocation.parish) << ","
231         << doubleQuote(good->getTariffCode()) << ","
232         << doubleQuote(good->getName()) << ","
233         << doubleQuote(good->getTechnicalSpecifications()) << ","
234         << doubleQuote(good->getTrademark()) << ","
235         << doubleQuote(good->getMeasurementUnit()) << ","
236         << doubleQuote(numtostr(quantity, 6, sep)) << ","
237         << doubleQuote(numtostr(amount, 6, sep)) << ","
238         << doubleQuote(numtostr(employment, 6, sep)) << "\n";
239}
240
241void ProductionIndicatorGenerator::writeEmptyInput(std::ofstream & file) {
242
243    file << doubleQuote("") << ","
244         << doubleQuote("") << ","
245         << doubleQuote("") << ","
246         << doubleQuote("") << ","
247         << doubleQuote("") << ","
248         << doubleQuote("") << ","
249         << doubleQuote("") << ","
250         << doubleQuote("") << ","
251         << doubleQuote("") << ","
252         << doubleQuote("") << ","
253         << doubleQuote("") << ","
254         << doubleQuote("") << ","
255         << doubleQuote("") << ","
256         << doubleQuote("") << ","
257         << doubleQuote("") << ","
258         << doubleQuote("") << ","
259         << doubleQuote("") << ","
260         << doubleQuote("") << "\n";
261}
262
263bool ProductionIndicatorGenerator::writeProductInputsIndicators(
264    AutoConnection & conn,
265    Graph & graph, const std::string & path, const std::string & year) {
266
267    std::string fileName = path;
268
269    if (fileName[fileName.size() - 1] != '/')
270        fileName.append("/");
271
272    fileName.append(PRODUCT_INPUT_FILE_NAME);
273
274    std::ofstream file(fileName.c_str());
275
276    if (not file)
277        return false;
278
279    file << doubleQuote("Relación") << ","
280         << doubleQuote("CIIU") << ","
281         << doubleQuote("RIF") << ","
282         << doubleQuote("Razón Social Unidad Económica") << ","
283         << doubleQuote("Planta") << ","
284         << doubleQuote("Planta") << ","
285         << doubleQuote("Planta") << ","
286         << doubleQuote("Producto") << ","
287         << doubleQuote("Producto") << ","
288         << doubleQuote("Producto") << ","
289         << doubleQuote("Producto") << ","
290         << doubleQuote("Producto") << ","
291         << doubleQuote("Niveles de la cadena") << ","
292         << doubleQuote("Relacion") << ","
293         << doubleQuote("Nacional o Importado") << ","
294         << doubleQuote("Nombre país de Origen") << ","
295         << doubleQuote("Nombre país de Procedencia") << ","
296         << doubleQuote("CIIU") << ","
297         << doubleQuote("RIF") << ","
298         << doubleQuote("Razón Social Unidad Económica") << ","
299         << doubleQuote("Planta") << ","
300         << doubleQuote("Planta") << ","
301         << doubleQuote("Planta") << ","
302         << doubleQuote("Insumo") << ","
303         << doubleQuote("Insumo") << ","
304         << doubleQuote("Insumo") << ","
305         << doubleQuote("Insumo") << ","
306         << doubleQuote("Insumo") << ","
307         << doubleQuote("Insumo") << ","
308         << doubleQuote("Insumo") << ","
309         << doubleQuote("Empleo generado") << "\n";
310
311    file << doubleQuote("") << ","
312         << doubleQuote("") << ","
313         << doubleQuote("") << ","
314         << doubleQuote("") << ","
315         << doubleQuote("Estado") << ","
316         << doubleQuote("Municipio") << ","
317         << doubleQuote("Parroquia") << ","
318         << doubleQuote("Código Arancelario") << ","
319         << doubleQuote("Nombre Producto") << ","
320         << doubleQuote("Especificaciones Técnicas") << ","
321         << doubleQuote("Marca") << ","
322         << doubleQuote("Unidad") << ","
323         << doubleQuote("") << ","
324         << doubleQuote("") << ","
325         << doubleQuote("") << ","
326         << doubleQuote("") << ","
327         << doubleQuote("") << ","
328         << doubleQuote("") << ","
329         << doubleQuote("") << ","
330         << doubleQuote("") << ","
331         << doubleQuote("Estado") << ","
332         << doubleQuote("Municipio") << ","
333         << doubleQuote("Parroquia") << ","
334         << doubleQuote("Código Arancelario") << ","
335         << doubleQuote("Nombre Producto") << ","
336         << doubleQuote("Especificaciones Técnicas") << ","
337         << doubleQuote("Marca") << ","
338         << doubleQuote("Unidad") << ","
339         << doubleQuote("Cantidad") << ","
340         << doubleQuote("Monto") << ","
341         << doubleQuote("Cantidad") << "\n";
342
343    Map <long, PlantLocation> mapPlantLocation;
344
345    Map <std::string, std::string> mapCompanyCiiu;
346
347    for (Graph::Node_Iterator nit(graph); nit.has_current();
348         nit.next()) {
349
350        Graph::Node * node = nit.get_current();
351
352        if (node->newValue2 == node->get_info()->getQuantity())
353            continue;
354
355        if (node->type == SUGGESTED or node->type == IMPORT or
356            node->get_info()->getType() == INPUT_GOOD) {
357
358            writeProductLine(conn, node, file, mapPlantLocation,
359                             mapCompanyCiiu);
360
361            writeEmptyInput(file);
362
363            continue;
364        }
365
366        for (Graph::Node_Arc_Iterator nait(node); nait.has_current();
367             nait.next()) {
368
369            Graph::Arc * arc = nait.get_current();
370
371            Graph::Node * src = graph.get_src_node(arc);
372
373            if (src == node)
374                continue;
375
376            writeProductLine(conn, node, file, mapPlantLocation,
377                             mapCompanyCiiu);
378
379            writeInputLine(conn, graph, arc, file, mapPlantLocation,
380                           mapCompanyCiiu, year);
381        }
382
383    }
384
385    file.close();
386
387    return true;
388}
389
390void ProductionIndicatorGenerator::writeProductionInfo(AutoConnection & conn,
391                                                       Graph & graph,
392                                                       Graph::Node * node,
393                                                       const std::string & year,
394                                                       std::ofstream & file) {
395
396    Good * good = node->get_info().get();
397
398    const real & oldProduction = good->getTotalQuantity();
399
400    const real oldAmount = oldProduction * good->getUnitarianPrice();
401
402    const real & newProduction = node->newValue1;
403
404    const real newAmount = newProduction * good->getUnitarianPrice();
405
406    real amountDiff = newAmount - oldAmount;
407
408    const real productionChange = ((newProduction / oldProduction) - 1) * 100;
409
410    const real amountChange = ((newAmount / oldAmount) - 1) * 100;
411
412    char sep = 0;
413
414    file << doubleQuote(numtostr(oldProduction, 6, sep)) << ","
415         << doubleQuote(numtostr(oldAmount, 6, sep)) << ","
416         << doubleQuote(numtostr(newProduction, 6, sep)) << ","
417         << doubleQuote(numtostr(newAmount, 6, sep)) << ","
418         << doubleQuote(numtostr(productionChange, 6, sep)) << ","
419         << doubleQuote(numtostr(amountChange, 6, sep)) << ",";
420
421    real directInputsAmount = 0.0;
422
423    real suggestedInputsAmount = 0.0;
424
425    real nationalInputsAmount = 0.0;
426
427    real importedInputsAmount = 0.0;
428
429    real totalInputsAmount = 0.0;
430
431    for (Graph::Node_Arc_Iterator it(node); it.has_current(); it.next()) {
432
433        Graph::Arc * a = it.get_current();
434
435        Graph::Node * p = graph.get_src_node(a);
436
437        if (p == node)
438            continue;
439
440        Good * input = p->get_info().get();
441
442        real amount = 0.0;
443
444        if (input->getType() == INPUT_GOOD)
445            amount = a->get_info().quantity * a->get_info().price;
446        else
447            amount = a->get_info().newValue2 * input->getUnitarianPrice();
448
449        totalInputsAmount += amount;
450
451        switch(p->type) {
452
453            case UPSTREAM:
454            case ROOT:
455            case DOWNSTREAM:
456
457                if (input->getType() == INPUT_GOOD and
458                    COMPANY(input)->getNationality() == "E")
459                    importedInputsAmount += amount;
460                else {
461                    nationalInputsAmount += amount;
462                    directInputsAmount += amount;
463                }
464
465                break;
466
467            case SUGGESTED:
468                nationalInputsAmount += amount;
469                suggestedInputsAmount += amount;
470
471                break;
472
473            case IMPORT:
474                importedInputsAmount += amount;
475
476                break;
477
478            default: throw std::domain_error("Invalid node type");
479        }
480    }
481
482    real directInputsVsNationalInputs = nationalInputsAmount == 0 ? 0 :
483      (directInputsAmount / nationalInputsAmount) * 100;
484
485    real suggestedInputsVsNationalInputs = nationalInputsAmount == 0 ? 0 :
486      (suggestedInputsAmount / nationalInputsAmount) * 100;
487
488    real nationalInputsVsTotalInputs = totalInputsAmount == 0 ? 0 :
489      (nationalInputsAmount / totalInputsAmount) * 100;
490
491    real importedInputsVsTotalInputs = totalInputsAmount == 0 ? 0 :
492      (importedInputsAmount / totalInputsAmount) * 100;
493
494    real diff = newAmount - totalInputsAmount;
495
496    real generatedEmployment =
497        computeGeneratedEmployment(conn, node, COMPANY(good)->getRif(), year,
498                                   amountDiff);
499
500    const real & currentCap = good->getUsedCapacity();
501
502    const real & alterCap = node->newValue3;
503
504    file << doubleQuote(numtostr(directInputsAmount, 6, sep)) << ","
505         << doubleQuote(numtostr(directInputsVsNationalInputs, 6, sep)) << ","
506         << doubleQuote(numtostr(suggestedInputsAmount, 6, sep)) << ","
507         << doubleQuote(numtostr(suggestedInputsVsNationalInputs, 6, sep)) << ","
508         << doubleQuote(numtostr(nationalInputsAmount, 6, sep)) << ","
509         << doubleQuote(numtostr(nationalInputsVsTotalInputs, 6, sep)) << ","
510         << doubleQuote(numtostr(importedInputsAmount, 6, sep)) << ","
511         << doubleQuote(numtostr(importedInputsVsTotalInputs, 6, sep)) << ","
512         << doubleQuote(numtostr(totalInputsAmount, 6, sep)) << ","
513         << doubleQuote(numtostr(diff, 6, sep)) << ","
514         << doubleQuote(numtostr(generatedEmployment, 6, sep)) << ","
515         << doubleQuote(numtostr(currentCap, 6, sep)) << ","
516         << doubleQuote(numtostr(alterCap, 6, sep)) << "\n";
517
518}
519
520bool ProductionIndicatorGenerator::writeProductIndicators(AutoConnection & conn,
521    Graph & graph, const std::string & path, const std::string & year) {
522
523    std::string fileName = path;
524
525    if (fileName[fileName.size() - 1] != '/')
526        fileName.append("/");
527
528    fileName.append(PRODUCT_FILE_NAME);
529
530    std::ofstream file(fileName.c_str());
531
532    if (not file)
533        return false;
534
535    file << doubleQuote("Relación") << ","
536         << doubleQuote("CIIU") << ","
537         << doubleQuote("RIF") << ","
538         << doubleQuote("Razón Social Unidad Económica") << ","
539         << doubleQuote("Planta") << ","
540         << doubleQuote("Planta") << ","
541         << doubleQuote("Planta") << ","
542         << doubleQuote("Producto") << ","
543         << doubleQuote("Producto") << ","
544         << doubleQuote("Producto") << ","
545         << doubleQuote("Producto") << ","
546         << doubleQuote("Producto") << ","
547         << doubleQuote("Niveles de la cadena") << ","
548         << doubleQuote("Producción sin Variación") << ","
549         << doubleQuote("Producción sin Variación") << ","
550         << doubleQuote("Nivel de Producción") << ","
551         << doubleQuote("Nivel de Producción") << ","
552         << doubleQuote("% de Variación de la Producción") << ","
553         << doubleQuote("% de Variación de la Producción") << ","
554         << doubleQuote("Insumos Relacionados Directamente") << ","
555         << doubleQuote("Con Referencia al Total Nacional") << ","
556         << doubleQuote("Insumos con Relación Propuesta") << ","
557         << doubleQuote("Con Referencia al Total Nacional") << ","
558         << doubleQuote("Total Insumos Nacionales") << ","
559         << doubleQuote("Con Referencia al Total de Insumos") << ","
560         << doubleQuote("Total Insumos Importados") << ","
561         << doubleQuote("Con Referencia al Total de Insumos") << ","
562         << doubleQuote("Total de Insumos") << ","
563         << doubleQuote("Ventas - Gastos en Compras de Insumos") << ","
564         << doubleQuote("Estimación Empleo Generado Directo") << ","
565         << doubleQuote("Capacidad Utilizada") << ","
566         << doubleQuote("Capacidad Utilizada") << "\n";
567
568    file << doubleQuote("") << ","
569         << doubleQuote("") << ","
570         << doubleQuote("") << ","
571         << doubleQuote("") << ","
572         << doubleQuote("Estado") << ","
573         << doubleQuote("Municipio") << ","
574         << doubleQuote("Parroquia") << ","
575         << doubleQuote("Código Arancelario") << ","
576         << doubleQuote("Nombre Producto") << ","
577         << doubleQuote("Especificaciones Técnicas") << ","
578         << doubleQuote("Marca") << ","
579         << doubleQuote("Unidad") << ","
580         << doubleQuote("") << ","
581         << doubleQuote("Cantidad") << ","
582         << doubleQuote("Monto") << ","
583         << doubleQuote("Cantidad") << ","
584         << doubleQuote("Monto") << ","
585         << doubleQuote("Cantidad") << ","
586         << doubleQuote("Monto") << ","
587         << doubleQuote("Monto") << ","
588         << doubleQuote("%") << ","
589         << doubleQuote("Monto") << ","
590         << doubleQuote("%") << ","
591         << doubleQuote("Monto") << ","
592         << doubleQuote("%") << ","
593         << doubleQuote("Monto") << ","
594         << doubleQuote("%") << ","
595         << doubleQuote("Monto") << ","
596         << doubleQuote("Monto") << ","
597         << doubleQuote("Cantidad") << ","
598         << doubleQuote("Actual") << ","
599         << doubleQuote("Variada") << "\n";
600
601
602    Map <long, PlantLocation> mapPlantLocation;
603
604    Map <std::string, std::string> mapCompanyCiiu;
605
606    for (Graph::Node_Iterator nit(graph); nit.has_current();
607         nit.next()) {
608
609        Graph::Node * node = nit.get_current();
610
611        if (node->get_info()->getType() != PRODUCT_GOOD)
612            continue;
613
614        if (node->newValue2 == node->get_info()->getQuantity())
615            continue;
616
617        writeProductLine(conn, node, file, mapPlantLocation, mapCompanyCiiu);
618
619        writeProductionInfo(conn, graph, node, year, file);
620    }
621
622    file.close();
623
624    return true;
625}
626
627std::string ProductionIndicatorGenerator::generate(Graph & graph,
628                                                   const std::string & path,
629                                                   const std::string & year) {
630
631    AutoConnection conn;
632
633    bool res = writeProductInputsIndicators(conn, graph, path, year);
634
635    res = res and writeProductIndicators(conn, graph, path, year);
636
637    if (not res)
638        return "Los indicadores no se escribieron correctamente";
639
640    return std::string("Se escribieron los archivos ") + PRODUCT_INPUT_FILE_NAME
641            + std::string(" y ") + PRODUCT_FILE_NAME;
642}
643
644std::string CostIndicatorGenerator::generate(Graph & /*g*/,
645                                             const std::string & /*path*/,
646                                             const std::string & /*year*/) {
647    return ""; //TODO: Implementar.
648}
649
650IndicatorGeneratorFactory::IndicatorGeneratorFactory() {
651    // Empty
652}
653
654IndicatorGeneratorFactory & IndicatorGeneratorFactory::getInstance() {
655
656    if (instance.get() == NULL)
657        instance =
658            std::unique_ptr <IndicatorGeneratorFactory> (
659                new IndicatorGeneratorFactory);
660
661    return *instance;
662}
663
664std::unique_ptr <IndicatorGenerator>
665IndicatorGeneratorFactory::getIndicatorGenerator(const StudyType & type) {
666    switch (type) {
667
668        case PRODUCTION_CHANGE:
669            return std::unique_ptr <IndicatorGenerator> (
670                new ProductionIndicatorGenerator);
671
672        case COST_CHANGE:
673            return std::unique_ptr <IndicatorGenerator> (
674                new CostIndicatorGenerator);
675
676        default: throw std::domain_error("Invalid study type");
677
678    }
679}
Note: See TracBrowser for help on using the repository browser.