Repository: akoyamp/geopolrisk-py (language: python)

Issue:
Merge development V2 from Thomas Schraml to Anish



Discussion / hints:

Fix patch:
diff --git a/.gitignore b/.gitignore
index e69de29..c60ed68 100644
--- a/.gitignore
+++ b/.gitignore
@@ -0,0 +1,12 @@
+# Editors
+.vscode/
+.idea/
+.eclipse
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# oert-folder
+geopolrisk/oert
\ No newline at end of file
diff --git a/README.md b/README.md
index e82e5ac..5afd5c7 100644
--- a/README.md
+++ b/README.md
@@ -1,252 +1,12 @@
 # The geopolrisk-py library documentation
 
-
-# Getting started
-## Installing the GeoPolRisk Module
+# The library is licensed by GNU General Public License 3.0
 The geopolrisk-py is a python library that allows the assessment of a geopolitical related supply risk of a resource from the perspective of a country/region/trade bloc/company.
 An assessment would result in two main values; 
 1. GPRS - The probability of supply risk of importing a resource (0 - 1) usefull for comparative risk assessment,
 2. Characterization Factors for GSRP (Geopolitical supply risk potential indicator (Midpoint))
 The library is available to download using pip package manager.
-~~~
-pip install geopolrisk-py
-~~~
 
 ## After installation
-A folder in the Documents directory of the installed user is created after importing the library for the first time named "geopolrisk". Three sub folders are created: *'database'*, *'logs'*, and *'output'*. These are important for the working of the library. The *'database'* folder must contain the library database. Copy the library database to the directory created in the documents folder to use the library (https://github.com/akoyamp/geopolrisk-py/tree/main/geopolrisk-py/lib/library.db). Or you can provide the location of the database in the prompt asked when importing the library for the first time.
-The *'logs'* folder stores the logs of the assessment. The *'output'* folder stores a database containing the results of the assessment and also all the exports of the results.
-
-# Modules and Methods
-The library has following five modules preceded by an init that performs some actions required to smoothly perform an assessment.
-## __init__ module:
---> Reads static databases : resource price data, normalized governance indicator data, commodity hs codes, country iso codes
-
---> Creates a directory in documents folder (only for windows users): Output folder for database to record calculations and exporting results as csv, Log folder for storing logs
-
---> Loads several functions such as logging, sql and some global variables
-
---> The module has a class called instance. Variables in the instance class can be manipulated or used in specific applications. Important variables such as regionslist, price and wgi are manipulated in specific applications.
-    
-## core module
-Contains functions that calculate the components of the geopolrisk method
-1. *settradepath(path):* 
-    Function to declare the path of the trade data as an excel or csv file.
-    To declare the path of the company trade data as an excel file. Must provide path an abosolute trade path. ex. c:/Users/UBx/Documents/tradepath.xlsx
-
-    ### Format for company trade data
-    Follow the format listed below:
-
-    | Reporter | ptCode | ptTitle | TradeQuantity |
-    | -------- | ------ | ------- | ------------- |
-    | Germany  | 76     | Brazil  | 53399700      |
-    | Germany  | 156    | China   | 73139615      |
-
-    ptCode, ptTitle and TradeQuantity are mandatory data that needs to be in the file.
-    | code          | Description                                               |
-    |---------------|---------------------------------------------------------- |
-    | ptCode        | ISO 3 digit code of the country from where a resource is imported.                                                                   |
-    | ptTitle       | The name of the country from where a resource is imported.|
-    | TradeQuantity | Quantity of resource imported in kilograms.               |
-
-2. regions(*args): 
-    
-    Define additional regions of assessment. By default all the countries and EU is included in the database. 
-    To define a new region, a dictionary must be provided with key as the name of the region and values is a list of countries in the region.
-    All the values must be in string and must be exactly as in the ISO.
-    ~~~
-    {"West Europe": ["France", "Germany", "Italy", "Spain", "Portugal", "Belgium"]}
-    ~~~
-
-3. *worldtrade(year = "2010", country = "276", commodity = "2602"):*
-    
-    Function to call the UN COMTRADE api for fetching the trade data.
-    **Mandatory arguments:**
-    - **year** : The year of assessment (integer)
-    - **country**: The area of assessment (integer*: ISO code of the area [annexe])*
-    - **commodity**: The HS code of the commodity under assessment (integer)
-
-4. *specifictrade(sheetname = None):* 
-    
-    Function to calculate the trade data using specific company data.
-    Function settradepath must be called to define the path of the company data.
-
-5. *weightedtrade(period, TradeData = None, PIData = None, scenario = 0, recyclingrate = 0.00):* 
-    
-    Function to calculate the second component of the GeoPolRisk method.
-    The trade data from either the COMTRADE function or InputTrade function is required as an argument. PIData is the world governance indicator that is stored in a variable by the init module.
-    However, the argument is provided in case of use of other indicators.
-
-    Note: The scenario does not affect the assessment if the value for recyclingrate is '0'.
-
-6. *ProductionData(Resource, EconomicUnit):* 
-    
-    Function to calculate the HHI (first component of the GeoPolRisk Method) and local production quantity. 
-    Arguments required are the name of the resource (not HS code) and the economic unit (country/existing or defined regions/defined economic blocs)
-
-7. *GeoPolRisk(ProductionData, WTAData, Year, AVGPrice):* 
-   
-    Function to calculate the values of the GeoPolRisk method. The ProductionData is a list of HHi and local production quantity (result from the *ProductionData* function).
-    The WTAData is a list of the calculation involving trade. AVGPrice is the yearly average price of the resource. It provides a list of four values.
-    [HHI, WTA, GPRS, CF]
-
-### Example to use the core module
-~~~
-from geopolrisk.assessment.core import *
-from geopolrisk.assessment.__init__ import instance #Optional
-_price = instance.price
-_wgi = instance.wgi
-Resource = "Nickel"
-HS = 2604
-Country = "Germany"
-ISO = 276
-Year = "2016"
-
-regions()
-TradeData = worldtrade(year = "2016", country = "276", commodity = "2604")
-ProductionData = ProductionData(Resource, Country)
-WTAData = weightedtrade(Year, TradeData = TradeData, PIData = _wgi, scenario = 0, recyclingrate = 0.00)
-
-
-YearlyAveragePrice = 10203.98
-YearlyAveragePrice =  _price[Year].tolist()[_price.HS.to_list().index(HS)] #Optional - A database already exists that can be used to fetch the price data.
-
-result = GeoPolRisk(ProductionData, WTAData, Year, YearlyAveragePrice)
-
-~~~
-
-## main module:
-Contains aggregate functions to simplify assessment.
-
-1. *main_complete (resourcelist, yearlist, countrylist, recyclingrate=0.0, scenario=0,sheetname=None,PIindicator=None):*
-
-    An aggregate function for a complete geopolitical related supply risk assessment. Instead of using the functions from the core module, a list of all the data is provided to get an output file with the results. This function records all the assessment into a database in the documents directory. This is to prevent repeated API calls to the COMTRADE as there is a limit to use the free API. 
-    Its a complete function that acknowledges, regional and company level assessment. Two functions from the core module must be called before this function is called. If a custom region is considered for the assessment such as example below, the regions function must be called and the new custom region must be declared.
-    ~~~
-    CustomRegion = {"West Europe": ["France", "Germany", "Italy", "Spain", "Portugal", "Belgium"]}
-    from geopolrisk.assessment.core import regions
-    regions(CustomRegion)
-    ~~~
-    In case the data for the custom region is provided using an excel or csv file, the path to the file should be declared using settradepath function from the core module. (Must use the template provided in the tests folder: https://github.com/akoyamp/geopolrisk-py/tree/main/geopolrisk-py/tests). The sheetname should be provided in the sheetname argument in the function.
-    ~~~
-    {"West Europe": ["France", "Germany", "Italy", "Spain", "Portugal", "Belgium"]}
-    from geopolrisk.assessment.core import regions
-    regions(CustomRegion)
-    locationtotheexcelfile = "user/documents/folder/tradedata.xlsx"
-    settradepath(locationtotheexcelfile)
-    ~~~
-
-    **Arguments:**
-    1. **resourcelist**: A list of all the resources for the assessment as HS commodity codes.
-    2. **countrylist**: A list of all the countries under assessment as 3 digit ISO codes.
-    3. **yearlist**: A list of all the years in integers.
-    4. **recyclingrate**: The ratio of domestic recycling of the resource (typically 0 to 1) also can provide from 0 to 100.
-    5. **scenario**: Refer to https://doi.org/10.1016/j.resconrec.2020.105108 for more data. In this function, three scenarios are considered: 0 for no scenario, 1 for best case scenario, 2 for worst case scenario
-    6. **sheetname**: In case data is provided through excel sheet, provide the sheetname (mandatory argument)
-    7. **PIindicator**: In case of using other political instability indicator, provide the json or dataframe containing normalized values.  
-
-    ### Example to demonstrate the use of main_complete function.
-    ~~~
-    ListofMetals = [2602, 2601, 2603, 2846, 2614,]
-    ListofCountries = [36, 124, 97, 251, 276, 392, 826, 842,] 
-    ListofYear = [2017, 2018, 2019, 2020]
-
-    from geopolrisk.assessment.main import main_complete
-
-    main_complete(ListofMetals, ListofYear, ListofCountries, 0, 0, sheetname= None, PIindicator = None)
-    ~~~
-
-    ### Example to demonstrate the use of main_complete function using custom region and specific trade data.
-    ~~~
-    ListofMetals = [2602, 2601, 2603, 2846, 2614,]
-    ListofYear = [2017, 2018, 2019, 2020]
-    CustomRegion = {"West Europe": ["France", "Germany", "Italy", "Spain", "Portugal", "Belgium"]}
-    locationtotheexcelfile = "user/documents/folder/tradedata.xlsx" #Avoid if using COMTRADE
-    ListofCountries = ["West Europe"] 
-
-    from geopolrisk.assessment.main import main_complete
-    from geopolrisk.assessment.core import regions
-
-    regions(CustomRegion)
-
-    settradepath(locationtotheexcelfile) #Do not use if using COMTRADE
-
-    main_complete(ListofMetals, ListofYear, ListofCountries, 0, 0, sheetname= "test", PIindicator = None)
-    ~~~
-2. *startmain (resourcelist, yearlist, countrylist, recyclingrate=0.0, scenario=0,sheetname=None,PIindicator=None):* 
-    
-    Function to calculate the GeoPolRisk but doesnt have the ability to aggregate data for regional calculation. In case of company level assessment, declare the path to the trade data as above before calling this function.
-
-3. *endmain():*
-
-    Exports the results of the assessment from the *startmain* function to the output folder.
-    ### Example to demonstrate the use of main_complete function using custom region and specific trade data.
-    ~~~
-    ListofMetals = [2602, 2601, 2603, 2846, 2614,]
-    ListofCountries = [36, 124, 97, 251, 276, 392, 826, 842,] 
-    ListofYear = [2017, 2018, 2019, 2020]
-    locationtotheexcelfile = "user/documents/folder/tradedata.xlsx" #Avoid if using COMTRADE
-
-
-    from geopolrisk.assessment.main import main_complete
-    from geopolrisk.assessment.core import regions
-
-    regions()
-    settradepath(locationtotheexcelfile) #Do not use if using COMTRADE
-
-    startmain(ListofMetals, ListofYear, ListofCountries, 0, 0, sheetname= "test", PIindicator = None)
-    endmain()
-    ~~~
-
-
-4. udpate_cf, updateprice are functions to automatically update null data stored as a result of a failed API request and changes in price data (or updates).
-
-
-# Other Modules
-1. utils module has some functions that are useful for the working of library. It has functions that record data, convert data and exports data.
-   1. *generateCF(exportType="csv", orient=""):*
-    Usefull function to export all calculated data from the database to one of three formats: csv, excel, json.
-2. The console module has one method guided for a console input based assessment.
-3. The functions in gprsplots module read the output file. An assessment must be done before using this module. There are three ways of plotting the results.
-trendplot for plotting the evolution of supply risk. Must have more than three years assessed.
-indplot for comparing each resource or country for ONE particular year.
-compareplot for stacked graphs for comparison for one year.
-   
-# ANNEXE
- 
-
-| **id**      | **hs** |
-| ----------- | ------ |
-| Aluminium   | 2606   |
-| Antimony    | 261710 |
-| Asbestos    | 2524   |
-| Barytes     | 2511   |
-| Bismuth     | 8106   |
-| Cadmium     | 8107   |
-| Chromium    | 2610   |
-| Coal        | 2701   |
-| Cobalt      | 810520 |
-| Copper      | 2603   |
-| Gold        | 7108   |
-| Graphite    | 2504   |
-| Iron        | 2601   |
-| Lead        | 2607   |
-| Lithium     | 283691 |
-| Magnesite   | 251910 |
-| Magnesium   | 251910 |
-| Manganese   | 2602   |
-| Mercury     | 280540 |
-| Molybdenum  | 2613   |
-| Natural gas | 271111 |
-| Nickel      | 2604   |
-| Petroleum   | 2709   |
-| Rare earth  | 2846   |
-| Silver      | 261610 |
-| Tin         | 2609   |
-| Titanium    | 2614   |
-| Tungsten    | 2611   |
-| Uranium     | 261210 |
-| Zinc        | 2608   |
-| Zirconium   | 261510 |
-
-## Country ISO codes
-ISO CODES: https://www.iso.org/standard/63546.html
+A folder in the Documents directory of the installed user is created after importing the library for the first time named "geopolrisk". Three sub folders are created: *'database'*, *'logs'*, and *'output'*. These are important for the working of the library. The *'database'* folder must contain the library database. Copy the [library databases](https://github.com/akoyamp/geopolrisk-py/tree/main/geopolrisk-py/lib/) to the directory *'geopolrisk/database/'* created in the documents folder to use the library. 
+The *'logs'* folder stores the logs of the assessment. The *'output'* folder stores a database containing the results of the assessment and also the exports of the results.
diff --git a/Test.ipynb b/Test.ipynb
new file mode 100644
index 0000000..fe04c6a
--- /dev/null
+++ b/Test.ipynb
@@ -0,0 +1,1018 @@
+{
+ "cells": [
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "# Import main calculation function"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stderr",
+     "output_type": "stream",
+     "text": [
+      "Reading table/s ['Aluminium', 'Antimony', 'Arsenic', 'Asbestos', 'Baryte', 'Bauxite', 'Bentonite', 'Beryllium (conc.)',\n",
+      "Reading table/s ['Normalized'] from the library database C:\\Users\\anish\\Documents/geopolrisk/databases/wgi.db.: 100%|█|\n",
+      "Reading table/s ['baci_trade'] from the library database C:\\Users\\anish\\Documents/geopolrisk/databases/baci.db.: 100%|█\n"
+     ]
+    }
+   ],
+   "source": [
+    "from geopolrisk.assessment.main import gprs_calc"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "\n",
+    "## Prepare the lists"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "ListofMetals = [\n",
+    "    260400,\n",
+    "    261000,\n",
+    "    260300,\n",
+    "    283691,\n",
+    "    282200,\n",
+    "]\n",
+    "ListofCountries = [\n",
+    "    36,\n",
+    "    124,\n",
+    "    251,\n",
+    "    276,\n",
+    "    392,\n",
+    "    826,\n",
+    "    842,\n",
+    "]\n",
+    "ListofYear = [2018, 2019, 2020]"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 3,
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stderr",
+     "output_type": "stream",
+     "text": [
+      "Calculating the GeoPolRisk: 100%|████████████████████████████████████████████████████| 105/105 [00:19<00:00,  5.50it/s]\n"
+     ]
+    },
+    {
+     "data": {
+      "text/html": [
+       "<div>\n",
+       "<style scoped>\n",
+       "    .dataframe tbody tr th:only-of-type {\n",
+       "        vertical-align: middle;\n",
+       "    }\n",
+       "\n",
+       "    .dataframe tbody tr th {\n",
+       "        vertical-align: top;\n",
+       "    }\n",
+       "\n",
+       "    .dataframe thead th {\n",
+       "        text-align: right;\n",
+       "    }\n",
+       "</style>\n",
+       "<table border=\"1\" class=\"dataframe\">\n",
+       "  <thead>\n",
+       "    <tr style=\"text-align: right;\">\n",
+       "      <th></th>\n",
+       "      <th>DBID</th>\n",
+       "      <th>Country [Economic Entity]</th>\n",
+       "      <th>Raw Material</th>\n",
+       "      <th>Year</th>\n",
+       "      <th>GeoPolRisk Score</th>\n",
+       "      <th>GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]</th>\n",
+       "      <th>HHI</th>\n",
+       "      <th>Import Risk</th>\n",
+       "      <th>Price</th>\n",
+       "    </tr>\n",
+       "  </thead>\n",
+       "  <tbody>\n",
+       "    <tr>\n",
+       "      <th>0</th>\n",
+       "      <td>260400362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Nickel</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.004924</td>\n",
+       "      <td>0.004810</td>\n",
+       "      <td>0.129735</td>\n",
+       "      <td>0.037953</td>\n",
+       "      <td>0.976947</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>1</th>\n",
+       "      <td>261000362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Chromium</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.166175</td>\n",
+       "      <td>0.071648</td>\n",
+       "      <td>0.293783</td>\n",
+       "      <td>0.565641</td>\n",
+       "      <td>0.431162</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>2</th>\n",
+       "      <td>260300362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Copper</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.000455</td>\n",
+       "      <td>0.001007</td>\n",
+       "      <td>0.117225</td>\n",
+       "      <td>0.003881</td>\n",
+       "      <td>2.212434</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>3</th>\n",
+       "      <td>283691362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Lithium</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.000289</td>\n",
+       "      <td>0.005080</td>\n",
+       "      <td>0.386376</td>\n",
+       "      <td>0.000749</td>\n",
+       "      <td>17.547412</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>4</th>\n",
+       "      <td>282200362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Cobalt</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.004286</td>\n",
+       "      <td>0.069885</td>\n",
+       "      <td>0.506365</td>\n",
+       "      <td>0.008463</td>\n",
+       "      <td>16.306945</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>...</th>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>100</th>\n",
+       "      <td>2604008422020</td>\n",
+       "      <td>USA</td>\n",
+       "      <td>Nickel</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.085713</td>\n",
+       "      <td>0.417177</td>\n",
+       "      <td>0.154270</td>\n",
+       "      <td>0.555601</td>\n",
+       "      <td>4.867145</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>101</th>\n",
+       "      <td>2610008422020</td>\n",
+       "      <td>USA</td>\n",
+       "      <td>Chromium</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.143870</td>\n",
+       "      <td>0.025402</td>\n",
+       "      <td>0.261554</td>\n",
+       "      <td>0.550059</td>\n",
+       "      <td>0.176561</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>102</th>\n",
+       "      <td>2603008422020</td>\n",
+       "      <td>USA</td>\n",
+       "      <td>Copper</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.044010</td>\n",
+       "      <td>0.111505</td>\n",
+       "      <td>0.113133</td>\n",
+       "      <td>0.389012</td>\n",
+       "      <td>2.533609</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>103</th>\n",
+       "      <td>2836918422020</td>\n",
+       "      <td>USA</td>\n",
+       "      <td>Lithium</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.165915</td>\n",
+       "      <td>1.029701</td>\n",
+       "      <td>0.327579</td>\n",
+       "      <td>0.506488</td>\n",
+       "      <td>6.206202</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>104</th>\n",
+       "      <td>2822008422020</td>\n",
+       "      <td>USA</td>\n",
+       "      <td>Cobalt</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.172901</td>\n",
+       "      <td>4.747532</td>\n",
+       "      <td>0.458017</td>\n",
+       "      <td>0.377498</td>\n",
+       "      <td>27.458120</td>\n",
+       "    </tr>\n",
+       "  </tbody>\n",
+       "</table>\n",
+       "<p>105 rows × 9 columns</p>\n",
+       "</div>"
+      ],
+      "text/plain": [
+       "              DBID Country [Economic Entity] Raw Material  Year  \\\n",
+       "0     260400362018                 Australia       Nickel  2018   \n",
+       "1     261000362018                 Australia     Chromium  2018   \n",
+       "2     260300362018                 Australia       Copper  2018   \n",
+       "3     283691362018                 Australia      Lithium  2018   \n",
+       "4     282200362018                 Australia       Cobalt  2018   \n",
+       "..             ...                       ...          ...   ...   \n",
+       "100  2604008422020                       USA       Nickel  2020   \n",
+       "101  2610008422020                       USA     Chromium  2020   \n",
+       "102  2603008422020                       USA       Copper  2020   \n",
+       "103  2836918422020                       USA      Lithium  2020   \n",
+       "104  2822008422020                       USA       Cobalt  2020   \n",
+       "\n",
+       "     GeoPolRisk Score  GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]  \\\n",
+       "0            0.004924                                           0.004810   \n",
+       "1            0.166175                                           0.071648   \n",
+       "2            0.000455                                           0.001007   \n",
+       "3            0.000289                                           0.005080   \n",
+       "4            0.004286                                           0.069885   \n",
+       "..                ...                                                ...   \n",
+       "100          0.085713                                           0.417177   \n",
+       "101          0.143870                                           0.025402   \n",
+       "102          0.044010                                           0.111505   \n",
+       "103          0.165915                                           1.029701   \n",
+       "104          0.172901                                           4.747532   \n",
+       "\n",
+       "          HHI  Import Risk      Price  \n",
+       "0    0.129735     0.037953   0.976947  \n",
+       "1    0.293783     0.565641   0.431162  \n",
+       "2    0.117225     0.003881   2.212434  \n",
+       "3    0.386376     0.000749  17.547412  \n",
+       "4    0.506365     0.008463  16.306945  \n",
+       "..        ...          ...        ...  \n",
+       "100  0.154270     0.555601   4.867145  \n",
+       "101  0.261554     0.550059   0.176561  \n",
+       "102  0.113133     0.389012   2.533609  \n",
+       "103  0.327579     0.506488   6.206202  \n",
+       "104  0.458017     0.377498  27.458120  \n",
+       "\n",
+       "[105 rows x 9 columns]"
+      ]
+     },
+     "execution_count": 3,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "gprs_calc(ListofYear, ListofCountries, ListofMetals)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "# Testing individual functions for the same list"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 4,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "FirstMetal = ListofMetals[0]\n",
+    "FirstCountry = ListofCountries[0]\n",
+    "FirstYear = ListofYear[0]"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from geopolrisk.assessment.core import HHI\n",
+    "\n",
+    "ProductionQuantity, hhi = HHI(FirstMetal, FirstYear, FirstCountry)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from geopolrisk.assessment.core import importrisk\n",
+    "\n",
+    "Numerator, TotalTrade, Price = importrisk(\n",
+    "    FirstMetal, FirstYear, [FirstCountry]\n",
+    ")  # Country has to be in a list"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 7,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from geopolrisk.assessment.core import GeoPolRisk\n",
+    "Values = GeoPolRisk(Numerator, TotalTrade, Price, ProductionQuantity, hhi)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "# Testing company level functions using same data as above"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 8,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from geopolrisk.assessment.core import importrisk_company\n",
+    "\n",
+    "Numerator_C, TotalTrade_C, Price_C = importrisk_company(FirstMetal, FirstYear)\n",
+    "Values_c = GeoPolRisk(Numerator_C, TotalTrade_C, Price_C, ProductionQuantity*1000, hhi)"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "# Testing Regional Data"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 9,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "NewRegions = {\n",
+    "    \"EFTA\" : [\"Iceland\", \"Norway\", \"Switzerland\"],\n",
+    "    \"NAFTA\" : [\"Canada\", \"Mexico\", \"USA\"]\n",
+    "}#Liechtenstein has a customs union with Switzerland whose trade is not reported by UN Comtrade"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 10,
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from geopolrisk.assessment.utils import regions\n",
+    "regions(NewRegions)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 11,
+   "metadata": {
+    "scrolled": true
+   },
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "{'EU': ['Austria',\n",
+       "  'Belgium',\n",
+       "  'Belgium-Luxembourg',\n",
+       "  'Bulgaria',\n",
+       "  'Croatia',\n",
+       "  'Czechia',\n",
+       "  'Czechoslovakia',\n",
+       "  'Denmark',\n",
+       "  'Estonia',\n",
+       "  'Finland',\n",
+       "  'France',\n",
+       "  'Fmr Dem. Rep. of Germany',\n",
+       "  'Fmr Fed. Rep. of Germany',\n",
+       "  'Germany',\n",
+       "  'Greece',\n",
+       "  'Hungary',\n",
+       "  'Ireland',\n",
+       "  'Italy',\n",
+       "  'Latvia',\n",
+       "  'Lithuania',\n",
+       "  'Luxembourg',\n",
+       "  'Malta',\n",
+       "  'Netherlands',\n",
+       "  'Poland',\n",
+       "  'Portugal',\n",
+       "  'Romania',\n",
+       "  'Slovakia',\n",
+       "  'Slovenia',\n",
+       "  'Spain',\n",
+       "  'Sweden'],\n",
+       " 'Afghanistan': ['Afghanistan'],\n",
+       " 'Albania': ['Albania'],\n",
+       " 'Algeria': ['Algeria'],\n",
+       " 'Andorra': ['Andorra'],\n",
+       " 'Angola': ['Angola'],\n",
+       " 'Anguilla': ['Anguilla'],\n",
+       " 'Antigua and Barbuda': ['Antigua and Barbuda'],\n",
+       " 'Argentina': ['Argentina'],\n",
+       " 'Armenia': ['Armenia'],\n",
+       " 'Aruba': ['Aruba'],\n",
+       " 'Australia': ['Australia'],\n",
+       " 'Austria': ['Austria'],\n",
+       " 'Azerbaijan': ['Azerbaijan'],\n",
+       " 'Bahamas': ['Bahamas'],\n",
+       " 'Bahrain': ['Bahrain'],\n",
+       " 'Bangladesh': ['Bangladesh'],\n",
+       " 'Barbados': ['Barbados'],\n",
+       " 'Belarus': ['Belarus'],\n",
+       " 'Belgium': ['Belgium'],\n",
+       " 'Belgium-Luxembourg': ['Belgium-Luxembourg'],\n",
+       " 'Belize': ['Belize'],\n",
+       " 'Benin': ['Benin'],\n",
+       " 'Bermuda': ['Bermuda'],\n",
+       " 'Bhutan': ['Bhutan'],\n",
+       " 'Bolivia (Plurinational State of)': ['Bolivia (Plurinational State of)'],\n",
+       " 'Bonaire': ['Bonaire'],\n",
+       " 'Bosnia Herzegovina': ['Bosnia Herzegovina'],\n",
+       " 'Botswana': ['Botswana'],\n",
+       " 'Br. Virgin Isds': ['Br. Virgin Isds'],\n",
+       " 'Brazil': ['Brazil'],\n",
+       " 'Brunei Darussalam': ['Brunei Darussalam'],\n",
+       " 'Bulgaria': ['Bulgaria'],\n",
+       " 'Burkina Faso': ['Burkina Faso'],\n",
+       " 'Burundi': ['Burundi'],\n",
+       " 'Cabo Verde': ['Cabo Verde'],\n",
+       " 'Cambodia': ['Cambodia'],\n",
+       " 'Cameroon': ['Cameroon'],\n",
+       " 'Canada': ['Canada'],\n",
+       " 'Cayman Isds': ['Cayman Isds'],\n",
+       " 'Central African Rep.': ['Central African Rep.'],\n",
+       " 'Chad': ['Chad'],\n",
+       " 'Chile': ['Chile'],\n",
+       " 'China': ['China'],\n",
+       " 'China, Hong Kong SAR': ['China, Hong Kong SAR'],\n",
+       " 'China, Macao SAR': ['China, Macao SAR'],\n",
+       " 'Colombia': ['Colombia'],\n",
+       " 'Comoros': ['Comoros'],\n",
+       " 'Congo': ['Congo'],\n",
+       " 'Cook Isds': ['Cook Isds'],\n",
+       " 'Costa Rica': ['Costa Rica'],\n",
+       " \"Côte d'Ivoire\": [\"Côte d'Ivoire\"],\n",
+       " 'Croatia': ['Croatia'],\n",
+       " 'Cuba': ['Cuba'],\n",
+       " 'Curaçao': ['Curaçao'],\n",
+       " 'Cyprus': ['Cyprus'],\n",
+       " 'Czechia': ['Czechia'],\n",
+       " 'Czechoslovakia': ['Czechoslovakia'],\n",
+       " \"Dem. People's Rep. of Korea\": [\"Dem. People's Rep. of Korea\"],\n",
+       " 'Dem. Rep. of the Congo': ['Dem. Rep. of the Congo'],\n",
+       " 'Denmark': ['Denmark'],\n",
+       " 'Djibouti': ['Djibouti'],\n",
+       " 'Dominica': ['Dominica'],\n",
+       " 'Dominican Rep.': ['Dominican Rep.'],\n",
+       " 'East and West Pakistan': ['East and West Pakistan'],\n",
+       " 'Ecuador': ['Ecuador'],\n",
+       " 'Egypt': ['Egypt'],\n",
+       " 'El Salvador': ['El Salvador'],\n",
+       " 'Equatorial Guinea': ['Equatorial Guinea'],\n",
+       " 'Eritrea': ['Eritrea'],\n",
+       " 'Estonia': ['Estonia'],\n",
+       " 'Ethiopia': ['Ethiopia'],\n",
+       " 'European Union': ['European Union'],\n",
+       " 'Faeroe Isds': ['Faeroe Isds'],\n",
+       " 'Falkland Isds (Malvinas)': ['Falkland Isds (Malvinas)'],\n",
+       " 'Fiji': ['Fiji'],\n",
+       " 'Finland': ['Finland'],\n",
+       " 'Fmr Arab Rep. of Yemen': ['Fmr Arab Rep. of Yemen'],\n",
+       " 'Fmr Dem. Rep. of Germany': ['Fmr Dem. Rep. of Germany'],\n",
+       " 'Fmr Dem. Rep. of Vietnam': ['Fmr Dem. Rep. of Vietnam'],\n",
+       " 'Fmr Dem. Yemen': ['Fmr Dem. Yemen'],\n",
+       " 'Fmr Ethiopia': ['Fmr Ethiopia'],\n",
+       " 'Fmr Fed. Rep. of Germany': ['Fmr Fed. Rep. of Germany'],\n",
+       " 'Fmr Pacific Isds': ['Fmr Pacific Isds'],\n",
+       " 'Fmr Panama, excl.Canal Zone': ['Fmr Panama, excl.Canal Zone'],\n",
+       " 'Fmr Panama-Canal-Zone': ['Fmr Panama-Canal-Zone'],\n",
+       " 'Fmr Rep. of Vietnam': ['Fmr Rep. of Vietnam'],\n",
+       " 'Fmr Rhodesia Nyas': ['Fmr Rhodesia Nyas'],\n",
+       " 'Fmr Sudan': ['Fmr Sudan'],\n",
+       " 'Fmr Tanganyika': ['Fmr Tanganyika'],\n",
+       " 'Fmr USSR': ['Fmr USSR'],\n",
+       " 'Fmr Yugoslavia': ['Fmr Yugoslavia'],\n",
+       " 'Fmr Zanzibar and Pemba Isd': ['Fmr Zanzibar and Pemba Isd'],\n",
+       " 'France': ['France'],\n",
+       " 'French Guiana': ['French Guiana'],\n",
+       " 'French Polynesia': ['French Polynesia'],\n",
+       " 'FS Micronesia': ['FS Micronesia'],\n",
+       " 'Gabon': ['Gabon'],\n",
+       " 'Gambia': ['Gambia'],\n",
+       " 'Georgia': ['Georgia'],\n",
+       " 'Germany': ['Germany'],\n",
+       " 'Ghana': ['Ghana'],\n",
+       " 'Gibraltar': ['Gibraltar'],\n",
+       " 'Greece': ['Greece'],\n",
+       " 'Greenland': ['Greenland'],\n",
+       " 'Grenada': ['Grenada'],\n",
+       " 'Guadeloupe': ['Guadeloupe'],\n",
+       " 'Guatemala': ['Guatemala'],\n",
+       " 'Guinea': ['Guinea'],\n",
+       " 'Guinea-Bissau': ['Guinea-Bissau'],\n",
+       " 'Guyana': ['Guyana'],\n",
+       " 'Haiti': ['Haiti'],\n",
+       " 'Holy See (Vatican City State)': ['Holy See (Vatican City State)'],\n",
+       " 'Honduras': ['Honduras'],\n",
+       " 'Hungary': ['Hungary'],\n",
+       " 'Iceland': ['Iceland'],\n",
+       " 'India': ['India'],\n",
+       " 'India, excl. Sikkim': ['India, excl. Sikkim'],\n",
+       " 'Indonesia': ['Indonesia'],\n",
+       " 'Iran': ['Iran'],\n",
+       " 'Iraq': ['Iraq'],\n",
+       " 'Ireland': ['Ireland'],\n",
+       " 'Israel': ['Israel'],\n",
+       " 'Italy': ['Italy'],\n",
+       " 'Jamaica': ['Jamaica'],\n",
+       " 'Japan': ['Japan'],\n",
+       " 'Jordan': ['Jordan'],\n",
+       " 'Kazakhstan': ['Kazakhstan'],\n",
+       " 'Kenya': ['Kenya'],\n",
+       " 'Kiribati': ['Kiribati'],\n",
+       " 'Kuwait': ['Kuwait'],\n",
+       " 'Kyrgyzstan': ['Kyrgyzstan'],\n",
+       " \"Lao People's Dem. Rep.\": [\"Lao People's Dem. Rep.\"],\n",
+       " 'Latvia': ['Latvia'],\n",
+       " 'Lebanon': ['Lebanon'],\n",
+       " 'Lesotho': ['Lesotho'],\n",
+       " 'Liberia': ['Liberia'],\n",
+       " 'Libya': ['Libya'],\n",
+       " 'Lithuania': ['Lithuania'],\n",
+       " 'Luxembourg': ['Luxembourg'],\n",
+       " 'Madagascar': ['Madagascar'],\n",
+       " 'Malawi': ['Malawi'],\n",
+       " 'Malaysia': ['Malaysia'],\n",
+       " 'Maldives': ['Maldives'],\n",
+       " 'Mali': ['Mali'],\n",
+       " 'Malta': ['Malta'],\n",
+       " 'Marshall Isds': ['Marshall Isds'],\n",
+       " 'Martinique': ['Martinique'],\n",
+       " 'Mauritania': ['Mauritania'],\n",
+       " 'Mauritius': ['Mauritius'],\n",
+       " 'Mayotte': ['Mayotte'],\n",
+       " 'Mexico': ['Mexico'],\n",
+       " 'Mongolia': ['Mongolia'],\n",
+       " 'Montenegro': ['Montenegro'],\n",
+       " 'Montserrat': ['Montserrat'],\n",
+       " 'Morocco': ['Morocco'],\n",
+       " 'Mozambique': ['Mozambique'],\n",
+       " 'Myanmar': ['Myanmar'],\n",
+       " 'N. Mariana Isds': ['N. Mariana Isds'],\n",
+       " 'Namibia': ['Namibia'],\n",
+       " 'Nepal': ['Nepal'],\n",
+       " 'Neth. Antilles': ['Neth. Antilles'],\n",
+       " 'Neth. Antilles and Aruba': ['Neth. Antilles and Aruba'],\n",
+       " 'Netherlands': ['Netherlands'],\n",
+       " 'New Caledonia': ['New Caledonia'],\n",
+       " 'New Zealand': ['New Zealand'],\n",
+       " 'Nicaragua': ['Nicaragua'],\n",
+       " 'Niger': ['Niger'],\n",
+       " 'Nigeria': ['Nigeria'],\n",
+       " 'Norway': ['Norway'],\n",
+       " 'Oman': ['Oman'],\n",
+       " 'Other Asia, nes': ['Other Asia, nes'],\n",
+       " 'Pakistan': ['Pakistan'],\n",
+       " 'Palau': ['Palau'],\n",
+       " 'Panama': ['Panama'],\n",
+       " 'Papua New Guinea': ['Papua New Guinea'],\n",
+       " 'Paraguay': ['Paraguay'],\n",
+       " 'Peninsula Malaysia': ['Peninsula Malaysia'],\n",
+       " 'Peru': ['Peru'],\n",
+       " 'Philippines': ['Philippines'],\n",
+       " 'Poland': ['Poland'],\n",
+       " 'Portugal': ['Portugal'],\n",
+       " 'Qatar': ['Qatar'],\n",
+       " 'Rep. of Korea': ['Rep. of Korea'],\n",
+       " 'Rep. of Moldova': ['Rep. of Moldova'],\n",
+       " 'Réunion': ['Réunion'],\n",
+       " 'Romania': ['Romania'],\n",
+       " 'Russian Federation': ['Russian Federation'],\n",
+       " 'Rwanda': ['Rwanda'],\n",
+       " 'Ryukyu Isd': ['Ryukyu Isd'],\n",
+       " 'Sabah': ['Sabah'],\n",
+       " 'Saint Barthelemy': ['Saint Barthelemy'],\n",
+       " 'Saint Helena': ['Saint Helena'],\n",
+       " 'Saint Kitts and Nevis': ['Saint Kitts and Nevis'],\n",
+       " 'Saint Kitts, Nevis and Anguilla': ['Saint Kitts, Nevis and Anguilla'],\n",
+       " 'Saint Lucia': ['Saint Lucia'],\n",
+       " 'Saint Maarten': ['Saint Maarten'],\n",
+       " 'Saint Pierre and Miquelon': ['Saint Pierre and Miquelon'],\n",
+       " 'Saint Vincent and the Grenadines': ['Saint Vincent and the Grenadines'],\n",
+       " 'Samoa': ['Samoa'],\n",
+       " 'San Marino': ['San Marino'],\n",
+       " 'Sao Tome and Principe': ['Sao Tome and Principe'],\n",
+       " 'Sarawak': ['Sarawak'],\n",
+       " 'Saudi Arabia': ['Saudi Arabia'],\n",
+       " 'Senegal': ['Senegal'],\n",
+       " 'Serbia': ['Serbia'],\n",
+       " 'Serbia and Montenegro': ['Serbia and Montenegro'],\n",
+       " 'Seychelles': ['Seychelles'],\n",
+       " 'Sierra Leone': ['Sierra Leone'],\n",
+       " 'Singapore': ['Singapore'],\n",
+       " 'Slovakia': ['Slovakia'],\n",
+       " 'Slovenia': ['Slovenia'],\n",
+       " 'So. African Customs Union': ['So. African Customs Union'],\n",
+       " 'Solomon Isds': ['Solomon Isds'],\n",
+       " 'Somalia': ['Somalia'],\n",
+       " 'South Africa': ['South Africa'],\n",
+       " 'South Sudan': ['South Sudan'],\n",
+       " 'Spain': ['Spain'],\n",
+       " 'Sri Lanka': ['Sri Lanka'],\n",
+       " 'State of Palestine': ['State of Palestine'],\n",
+       " 'Sudan': ['Sudan'],\n",
+       " 'Suriname': ['Suriname'],\n",
+       " 'Eswatini': ['Eswatini'],\n",
+       " 'Sweden': ['Sweden'],\n",
+       " 'Switzerland': ['Switzerland'],\n",
+       " 'Syria': ['Syria'],\n",
+       " 'Tajikistan': ['Tajikistan'],\n",
+       " 'North Macedonia': ['North Macedonia'],\n",
+       " 'Thailand': ['Thailand'],\n",
+       " 'Timor-Leste': ['Timor-Leste'],\n",
+       " 'Togo': ['Togo'],\n",
+       " 'Tokelau': ['Tokelau'],\n",
+       " 'Tonga': ['Tonga'],\n",
+       " 'Trinidad and Tobago': ['Trinidad and Tobago'],\n",
+       " 'Tunisia': ['Tunisia'],\n",
+       " 'Turkey': ['Turkey'],\n",
+       " 'Turkmenistan': ['Turkmenistan'],\n",
+       " 'Turks and Caicos Isds': ['Turks and Caicos Isds'],\n",
+       " 'Tuvalu': ['Tuvalu'],\n",
+       " 'Uganda': ['Uganda'],\n",
+       " 'Ukraine': ['Ukraine'],\n",
+       " 'United Arab Emirates': ['United Arab Emirates'],\n",
+       " 'United Kingdom': ['United Kingdom'],\n",
+       " 'United Rep. of Tanzania': ['United Rep. of Tanzania'],\n",
+       " 'Uruguay': ['Uruguay'],\n",
+       " 'US Virgin Isds': ['US Virgin Isds'],\n",
+       " 'USA': ['USA'],\n",
+       " 'USA (before 1981)': ['USA (before 1981)'],\n",
+       " 'Uzbekistan': ['Uzbekistan'],\n",
+       " 'Vanuatu': ['Vanuatu'],\n",
+       " 'Venezuela': ['Venezuela'],\n",
+       " 'Viet Nam': ['Viet Nam'],\n",
+       " 'Wallis and Futuna Isds': ['Wallis and Futuna Isds'],\n",
+       " 'Yemen': ['Yemen'],\n",
+       " 'Zambia': ['Zambia'],\n",
+       " 'Zimbabwe': ['Zimbabwe'],\n",
+       " 'ASEAN': ['ASEAN'],\n",
+       " 'EFTA': ['Iceland', 'Norway', 'Switzerland'],\n",
+       " 'NAFTA': ['Canada', 'Mexico', 'USA']}"
+      ]
+     },
+     "execution_count": 11,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "from geopolrisk.assessment.database import databases\n",
+    "databases.regionslist"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 12,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "True"
+      ]
+     },
+     "execution_count": 12,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "databases.regional"
+   ]
+  },
+  {
+   "cell_type": "markdown",
+   "metadata": {},
+   "source": [
+    "## Main Function to run for the regional assessment"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 13,
+   "metadata": {
+    "scrolled": false
+   },
+   "outputs": [
+    {
+     "name": "stderr",
+     "output_type": "stream",
+     "text": [
+      "Calculating the GeoPolRisk: 100%|████████████████████████████████████████████████████| 150/150 [01:53<00:00,  1.32it/s]\n"
+     ]
+    },
+    {
+     "data": {
+      "text/html": [
+       "<div>\n",
+       "<style scoped>\n",
+       "    .dataframe tbody tr th:only-of-type {\n",
+       "        vertical-align: middle;\n",
+       "    }\n",
+       "\n",
+       "    .dataframe tbody tr th {\n",
+       "        vertical-align: top;\n",
+       "    }\n",
+       "\n",
+       "    .dataframe thead th {\n",
+       "        text-align: right;\n",
+       "    }\n",
+       "</style>\n",
+       "<table border=\"1\" class=\"dataframe\">\n",
+       "  <thead>\n",
+       "    <tr style=\"text-align: right;\">\n",
+       "      <th></th>\n",
+       "      <th>DBID</th>\n",
+       "      <th>Country [Economic Entity]</th>\n",
+       "      <th>Raw Material</th>\n",
+       "      <th>Year</th>\n",
+       "      <th>GeoPolRisk Score</th>\n",
+       "      <th>GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]</th>\n",
+       "      <th>HHI</th>\n",
+       "      <th>Import Risk</th>\n",
+       "      <th>Price</th>\n",
+       "    </tr>\n",
+       "  </thead>\n",
+       "  <tbody>\n",
+       "    <tr>\n",
+       "      <th>0</th>\n",
+       "      <td>260400362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Nickel</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.004924</td>\n",
+       "      <td>0.004810</td>\n",
+       "      <td>0.129735</td>\n",
+       "      <td>0.037953</td>\n",
+       "      <td>0.976947</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>1</th>\n",
+       "      <td>261000362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Chromium</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.166175</td>\n",
+       "      <td>0.071648</td>\n",
+       "      <td>0.293783</td>\n",
+       "      <td>0.565641</td>\n",
+       "      <td>0.431162</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>2</th>\n",
+       "      <td>260300362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Copper</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.000455</td>\n",
+       "      <td>0.001007</td>\n",
+       "      <td>0.117225</td>\n",
+       "      <td>0.003881</td>\n",
+       "      <td>2.212434</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>3</th>\n",
+       "      <td>283691362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Lithium</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.000289</td>\n",
+       "      <td>0.005080</td>\n",
+       "      <td>0.386376</td>\n",
+       "      <td>0.000749</td>\n",
+       "      <td>17.547412</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>4</th>\n",
+       "      <td>282200362018</td>\n",
+       "      <td>Australia</td>\n",
+       "      <td>Cobalt</td>\n",
+       "      <td>2018</td>\n",
+       "      <td>0.004286</td>\n",
+       "      <td>0.069885</td>\n",
+       "      <td>0.506365</td>\n",
+       "      <td>0.008463</td>\n",
+       "      <td>16.306945</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>...</th>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "      <td>...</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>145</th>\n",
+       "      <td>260400NAFTA2020</td>\n",
+       "      <td>NAFTA</td>\n",
+       "      <td>Nickel</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.011225</td>\n",
+       "      <td>0.098518</td>\n",
+       "      <td>0.154270</td>\n",
+       "      <td>0.072761</td>\n",
+       "      <td>8.776762</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>146</th>\n",
+       "      <td>261000NAFTA2020</td>\n",
+       "      <td>NAFTA</td>\n",
+       "      <td>Chromium</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.143038</td>\n",
+       "      <td>0.029895</td>\n",
+       "      <td>0.261554</td>\n",
+       "      <td>0.546878</td>\n",
+       "      <td>0.208998</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>147</th>\n",
+       "      <td>260300NAFTA2020</td>\n",
+       "      <td>NAFTA</td>\n",
+       "      <td>Copper</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.021160</td>\n",
+       "      <td>0.052529</td>\n",
+       "      <td>0.113133</td>\n",
+       "      <td>0.187032</td>\n",
+       "      <td>2.482504</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>148</th>\n",
+       "      <td>283691NAFTA2020</td>\n",
+       "      <td>NAFTA</td>\n",
+       "      <td>Lithium</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.165154</td>\n",
+       "      <td>1.023609</td>\n",
+       "      <td>0.327579</td>\n",
+       "      <td>0.504167</td>\n",
+       "      <td>6.197892</td>\n",
+       "    </tr>\n",
+       "    <tr>\n",
+       "      <th>149</th>\n",
+       "      <td>282200NAFTA2020</td>\n",
+       "      <td>NAFTA</td>\n",
+       "      <td>Cobalt</td>\n",
+       "      <td>2020</td>\n",
+       "      <td>0.078282</td>\n",
+       "      <td>1.537623</td>\n",
+       "      <td>0.458017</td>\n",
+       "      <td>0.170916</td>\n",
+       "      <td>19.642007</td>\n",
+       "    </tr>\n",
+       "  </tbody>\n",
+       "</table>\n",
+       "<p>150 rows × 9 columns</p>\n",
+       "</div>"
+      ],
+      "text/plain": [
+       "                DBID Country [Economic Entity] Raw Material  Year  \\\n",
+       "0       260400362018                 Australia       Nickel  2018   \n",
+       "1       261000362018                 Australia     Chromium  2018   \n",
+       "2       260300362018                 Australia       Copper  2018   \n",
+       "3       283691362018                 Australia      Lithium  2018   \n",
+       "4       282200362018                 Australia       Cobalt  2018   \n",
+       "..               ...                       ...          ...   ...   \n",
+       "145  260400NAFTA2020                     NAFTA       Nickel  2020   \n",
+       "146  261000NAFTA2020                     NAFTA     Chromium  2020   \n",
+       "147  260300NAFTA2020                     NAFTA       Copper  2020   \n",
+       "148  283691NAFTA2020                     NAFTA      Lithium  2020   \n",
+       "149  282200NAFTA2020                     NAFTA       Cobalt  2020   \n",
+       "\n",
+       "     GeoPolRisk Score  GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]  \\\n",
+       "0            0.004924                                           0.004810   \n",
+       "1            0.166175                                           0.071648   \n",
+       "2            0.000455                                           0.001007   \n",
+       "3            0.000289                                           0.005080   \n",
+       "4            0.004286                                           0.069885   \n",
+       "..                ...                                                ...   \n",
+       "145          0.011225                                           0.098518   \n",
+       "146          0.143038                                           0.029895   \n",
+       "147          0.021160                                           0.052529   \n",
+       "148          0.165154                                           1.023609   \n",
+       "149          0.078282                                           1.537623   \n",
+       "\n",
+       "          HHI  Import Risk      Price  \n",
+       "0    0.129735     0.037953   0.976947  \n",
+       "1    0.293783     0.565641   0.431162  \n",
+       "2    0.117225     0.003881   2.212434  \n",
+       "3    0.386376     0.000749  17.547412  \n",
+       "4    0.506365     0.008463  16.306945  \n",
+       "..        ...          ...        ...  \n",
+       "145  0.154270     0.072761   8.776762  \n",
+       "146  0.261554     0.546878   0.208998  \n",
+       "147  0.113133     0.187032   2.482504  \n",
+       "148  0.327579     0.504167   6.197892  \n",
+       "149  0.458017     0.170916  19.642007  \n",
+       "\n",
+       "[150 rows x 9 columns]"
+      ]
+     },
+     "execution_count": 13,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "ListofMetals = [\n",
+    "    260400,\n",
+    "    261000,\n",
+    "    260300,\n",
+    "    283691,\n",
+    "    282200,\n",
+    "]\n",
+    "ListofCountries = [\n",
+    "    36,\n",
+    "    124,\n",
+    "    251,\n",
+    "    276,\n",
+    "    392,\n",
+    "    826,\n",
+    "    842,\n",
+    "    \"EU\",\n",
+    "    \"EFTA\",\n",
+    "    \"NAFTA\"\n",
+    "]#EU is already defined in the library\n",
+    "ListofYear = [2018, 2019, 2020]\n",
+    "gprs_calc(ListofYear, ListofCountries, ListofMetals)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3 (ipykernel)",
+   "language": "python",
+   "name": "python3"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 3
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython3",
+   "version": "3.11.4"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/geopolrisk/assessment/__init__.py b/geopolrisk/assessment/__init__.py
index ad2284c..183e1ce 100644
--- a/geopolrisk/assessment/__init__.py
+++ b/geopolrisk/assessment/__init__.py
@@ -1,301 +1,19 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
+# Copyright (C) 2024 University of Bordeaux, CyVi Group & University of Bayreuth,
+# Ecological Resource Technology & Anish Koyamparambath, Christoph Helbig, Thomas Schraml
 # This file is part of geopolrisk-py library.
-#
 # geopolrisk-py is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
-#
 # geopolrisk-py is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
-#
 # You should have received a copy of the GNU General Public License
 # along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
 
-import sqlite3, pandas as pd, getpass, logging, os
-from datetime import datetime
-from pathlib import Path
-
-# from .Exceptions.warningsgprs import *
-
-logging = logging
-__all__ = ["core", "operations", "console", "gprsplots", "utils", "tests", "main"]
-__author__ = "Anish Koyamparambath <CyVi- University of Bordeaux>"
-__status__ = "release"
-__version__ = "1"
-__data__ = "10 March 2023"
-
-hard_dependencies = ("pandas", "scipy", "matplotlib")
-missing_dependencies = []
-for dependency in hard_dependencies:
-    try:
-        __import__(dependency)
-    except ImportError as e:
-        missing_dependencies.append(f"{dependency}: {e}")
-
-if missing_dependencies:
-    raise ImportError(
-        "Unable to import required dependencies:\n" + "\n".join(missing_dependencies)
-    )
-del hard_dependencies, dependency, missing_dependencies
-
-
-# Function to use sqlite3
-def execute_query(query, db_path=""):
-    # Connect to the database
-    conn = sqlite3.connect(db_path)
-    cursor = conn.cursor()
-
-    # Determine if the query is a SELECT or INSERT query
-    is_select_query = query.strip().lower().startswith("select")
-
-    # Execute the query and fetch the results (if it is a SELECT query)
-    if is_select_query:
-        cursor.execute(query)
-        results = cursor.fetchall()
-    else:
-        cursor.execute(query)
-        results = None
-
-    # Commit the query to the database
-    conn.commit()
-
-    # Close the database connection
-    conn.close()
-
-    # Return the results (if it is a SELECT query)
-    if is_select_query:
-        return results
-
-
-class database:
-    # Global Variables
-    Output = "Datarecords.db"
-    Database = "library.db"
-    OutputFolder = "Documents/geopolrisk"
-    LogFolder = OutputFolder + "/logs"
-    CFDatabase = OutputFolder + "/output"
-    DBFolder = OutputFolder + "/databases"
-
-    # Create directories
-    try:
-        directory = getpass.getuser()
-        if not os.path.exists(os.path.join(Path.home(), OutputFolder)):
-            os.makedirs(os.path.join(Path.home(), OutputFolder))
-
-        logfile = os.path.join(Path.home(), LogFolder)
-        if not os.path.exists(logfile):
-            os.makedirs(logfile)
-
-        dbFolder = os.path.join(Path.home(), DBFolder)
-        if not os.path.exists(dbFolder):
-            os.makedirs(dbFolder)
-
-        exportfile = os.path.join(Path.home(), CFDatabase)
-        if not os.path.exists(exportfile):
-            os.makedirs(exportfile)
-    except Exception as e:
-        print(f"Unable to create directories {e}")
-        raise FileNotFoundError
-
-    # Verify that the file exists else input the correct file path
-    if not os.path.isfile(os.path.join(dbFolder, Database)):
-        folder_path = input("The file doesn't exist. Please enter a folder path: ")
-
-    # Verify if the database contains the required tables
-    Tables = [
-        "commodityHS",
-        "Country_ISO",
-        "Aluminium",
-        "Antimony",
-        "Asbestos",
-        "Barytes",
-        "Bismuth",
-        "Cadmium",
-        "Chromium",
-        "Coal",
-        "Cobalt",
-        "Copper",
-        "Gold",
-        "Graphite",
-        "Iron",
-        "Lead",
-        "Lithium",
-        "Magnesite",
-        "Magnesium",
-        "Manganese",
-        "Mercury",
-        "Molybdenum",
-        "Nickel",
-        "Crude_Oil",
-        "REE",
-        "Silver",
-        "Tin",
-        "Titanium",
-        "Tungsten",
-        "Uranium",
-        "Zinc",
-        "Zirconium",
-        "NG",
-        "WGI",
-        "Price",
-    ]
-
-    db = dbFolder + "/" + Database
-    # Check if the database exists and fetch the required tables
-    try:
-        result = execute_query(
-            "SELECT name FROM sqlite_master WHERE type='table';", db_path=db
-        )
-        table_names = [row[0] for row in result]
-    except Exception as e:
-        print(f"Unable to verify if the database contains the required tables {e}")
-        raise FileNotFoundError
-
-    # check if all the tables in the list are present in the database
-    missingTables = []
-    for table_name in Tables:
-        if table_name not in table_names:
-            missingTables.append(table_name)
-        else:
-            pass
-
-    # If there are missing tables, raise an error
-    if len(missingTables) > 0:
-        print(f"The following tables are missing from the database: {missingTables}")
-    else:
-        pass
-
-    # Function to extract the tables into a dictionary
-    def extract_tables_to_df(db_path, table_names):
-        # Create a dictionary to store the extracted tables
-        tables = {}
-
-        # Connect to the database
-        conn = sqlite3.connect(db_path)
-
-        # Loop through the table names and extract each table as a DataFrame
-        for table_name in table_names:
-            query = f"SELECT * FROM {table_name}"
-            table_df = pd.read_sql_query(query, conn)
-
-            # Add the table DataFrame to the tables dictionary with the table name as the key
-            tables[table_name] = table_df
-
-        # Close the database connection
-        conn.close()
-
-        # Return the tables dictionary
-        return tables
-
-    # verify if output database exists else create it
-    try:
-        sqlstatement = """CREATE TABLE IF NOT EXISTS "recordData" (
-        	"index"	INTEGER,
-            "id" TEXT NOT NULL,
-        	"country"	TEXT,
-        	"resource"	TEXT,
-        	"year"	INTEGER,
-        	"recycling_rate"	REAL,
-        	"scenario"	REAL,
-        	"geopolrisk"	REAL,
-        	"hhi"	REAL,
-        	"wta"	REAL,
-        	"geopol_cf"	REAL,
-        	"resource_hscode"	INTEGER,
-        	"iso"	INTEGER,
-            "log_ref" TEXT,
-        	PRIMARY KEY("index")
-        );"""
-        execute_query(sqlstatement, db_path=exportfile + "/" + Output)
-    except Exception as e:
-        print(f"Could not create the output database {e}")
-
-    # Extract the tables into a dictionary
-    try:
-        tables = extract_tables_to_df(db, Tables)
-    except Exception as e:
-        print(f"Could not extract the tables {e}")
-
-    production = tables
-    reporter = tables["Country_ISO"]
-    price = tables["Price"]
-    commodity = tables["commodityHS"]
-    wgi = tables["WGI"]
-    regionslist = {}
-    regionslist["EU"] = [
-        "Austria",
-        "Belgium",
-        "Belgium-Luxembourg",
-        "Bulgaria",
-        "Croatia",
-        "Czechia",
-        "Czechoslovakia",
-        "Denmark",
-        "Estonia",
-        "Finland",
-        "France",
-        "Fmr Dem. Rep. of Germany",
-        "Fmr Fed. Rep. of Germany",
-        "Germany",
-        "Greece",
-        "Hungary",
-        "Ireland",
-        "Italy",
-        "Latvia",
-        "Lithuania",
-        "Luxembourg",
-        "Malta",
-        "Netherlands",
-        "Poland",
-        "Portugal",
-        "Romania",
-        "Slovakia",
-        "Slovenia",
-        "Spain",
-        "Sweden",
-    ]
-
-
-instance = database()
-
-
-class outputDF:
-    columns = [
-        "Year",
-        "Resource",
-        "Country",
-        "Recycling Rate",
-        "Recycling Scenario",
-        "Risk",
-        "GeoPolRisk Characterization Factor",
-        "HHI",
-        "Weighted Trade AVerage",
-    ]
-    outputList = []
-
-
-outputdf = outputDF()
-# Test fail variables
-LOGFAIL, DBIMPORTFAIL = False, False
-
-# Create a log file for init function
-
-Filename = "Log_File_{:%Y-%m-%d(%H-%M-%S)}.log".format(datetime.now())
-
-log_level = logging.DEBUG
-try:
-    logging.basicConfig(
-        level=log_level,
-        format="""%(asctime)s | %(levelname)s | %(threadName)-10s |
-          %(filename)s:%(lineno)s - %(funcName)20s() |
-            %(message)s""",
-        filename=instance.logfile + "/" + Filename,
-        filemode="w",
-    )
-except:
-    # it is imperative that the log file work before running the main code.
-    LOGFAIL = True
-    print("Cannot create log file!")
+__all__ = ["core", "main", "utils", "database"]
+__author__ = "Anish Koyamparambath <CyVi- University of Bordeaux>; Thomas Schraml <ERT - Univeristy of Bayreuth>"
+__status__ = "alpha"
+__version__ = "2"
+__data__ = "20 October 2024"
\ No newline at end of file
diff --git a/geopolrisk/assessment/__pycache__/__init__.cpython-311.pyc b/geopolrisk/assessment/__pycache__/__init__.cpython-311.pyc
deleted file mode 100644
index 59773b3..0000000
Binary files a/geopolrisk/assessment/__pycache__/__init__.cpython-311.pyc and /dev/null differ
diff --git a/geopolrisk/assessment/console.py b/geopolrisk/assessment/console.py
deleted file mode 100644
index 8b9ede2..0000000
--- a/geopolrisk/assessment/console.py
+++ /dev/null
@@ -1,208 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-import pandas as pd, json, sqlite3
-import comtradeapicall as ctac
-from urllib.request import Request, urlopen
-from .__init__ import instance, logging, execute_query
-from .main import main_complete as gprs_comtrade
-from .utils import convertCodes
-
-
-# Define Paths
-tradepath = None
-_production, _reporter = instance.production, instance.reporter
-regionslist, _outputfile = instance.regionslist, instance.exportfile
-_price = instance.price
-db = _outputfile + "/" + instance.Output
-# Extract list of all data
-HS = _price.HS.to_list()
-HS = [int(float(x)) for x in HS]
-Resource = _price.Resource.to_list()
-Country = _reporter.Country.to_list()
-ISO = _reporter.ISO.to_list()
-ISO = [int(x) for x in ISO]
-
-
-# from .Exceptions.warningsgprs import *
-import itertools, sqlite3, pandas as pd, sys
-from difflib import get_close_matches
-
-
-"""
-A simple guided step by step method for new users. This method can be called 
-to any console based application if needed.
-"""
-
-
-def matchwords(word, List):
-    word = word.lower()
-    List = [x.lower() for x in List]
-    if word in List:
-        index = List.index(word)
-        return index
-    else:
-        return -1
-
-
-def getthequestions(compareList, *args):
-    A = args[0]
-    B = args[1]
-    print(A)
-    _exit = True
-    finalvalue = False
-    while _exit:
-        inputvalue = input("Enter the value: ")
-        comparelist = list(map(lambda x: x.lower(), compareList))
-        closevalues = get_close_matches(inputvalue.lower(), comparelist)
-        cl_index = matchwords(inputvalue, comparelist)
-        if cl_index > -1:
-            finalvalue = compareList[cl_index]
-            _exit = False
-        elif inputvalue.lower() == "exit":
-            sys.exit(1)
-        elif len(closevalues) == 1:
-            cl_index = matchwords(closevalues[0], comparelist)
-            if cl_index > -1:
-                finalvalue = compareList[cl_index]
-                _exit = False
-            else:
-                print("Please try again.")
-        elif len(closevalues) > 1:
-            print("Input did not match exactly a value in our list.")
-            print("Is the value you intented in the list below?")
-            print(closevalues)
-            print("If yes, input the position of the value as 1 ,2 ,3,...")
-            print("If not, type 'no'.")
-            ni_value = input("Inpute the position : ")
-            try:
-                ni_value = int(ni_value) - 1
-                _exit = False
-            except:
-                _exit = True
-                break
-
-            cl_index = matchwords(closevalues[ni_value], comparelist)
-            if cl_index > -1:
-                finalvalue = compareList[cl_index]
-                _exit = False
-            else:
-                print("")
-                _exit = True
-                break
-        else:
-            print(B)
-
-    return finalvalue
-
-
-def guided():
-    start = True
-    intro = """
-    Welcome to the geopolrisk-py guided assessment. Using this function, a user can
-    assess the supply risk of importing a resource to a country. Questions are asked
-    at each step of the assessment to which the user must type the response. At any 
-    given point, the user can exit the assessment by typing 'exit'. The results of 
-    the assessment are downloaded to the output folder.
-    """
-    print(intro)
-    logging.info("Assessment type: Guided")
-    while start:
-        A = "Enter the name of the resource : "
-        B = "The entered resource is not found! Please try again."
-        resource = [
-            getthequestions(Resource, A, B),
-        ]
-        logging.debug("Guided Assessment| Input Resource: {}".format(resource))
-        A = "Enter the name of the country of asssessment : "
-        B = "The entered country is not found! Please try again."
-        country = [
-            getthequestions(Country, A, B),
-        ]
-        logging.debug("Guided Assessment| Input Country: {}".format(country))
-        _exit = True
-        while _exit:
-            period = input("Enter the year of assessment :")
-            try:
-                if int(period) in range(2000, 2020):
-                    period = int(period)
-                    logging.debug("Guided Assessment| Input Year: {}".format(period))
-                    _exit = False
-                else:
-                    print("Provide enter an year between 2000 and 2020")
-                    _exit = True
-            except Exception as e:
-                logging.debug(e)
-                if period.lower() == "exit":
-                    sys.exit()
-                break
-
-        _exit = True
-        while _exit:
-            print(
-                "Enter the rate of domestic recycling input of the raw material (in fractions) or type exit to exit"
-            )
-            recyclingrate = input("Enter the recycling input rate: ")
-            try:
-                if float(recyclingrate) in range(0, 101):
-                    recyclingrate = float(recyclingrate) / 100
-                    logging.debug(
-                        "Guided Assessment| Input Recycling Rate: {}".format(
-                            recyclingrate
-                        )
-                    )
-                    _exit = False
-                else:
-                    print("Provide enter a value between 0 to 100.")
-                    _exit = True
-            except Exception as e:
-                logging.debug(e)
-                if recyclingrate.lower() == "exit":
-                    sys.exit()
-                break
-
-        _exit = True
-        while _exit:
-            print("Select 0 for no recycling scenario (recyclingrate is set to zero)")
-            print(
-                "Select 0 for assuming a best case scenario where the imports from a riskier country is reduced"
-            )
-            print(
-                "Select 1 for assuming a worst case scenario where the imports from a stable country is reduced"
-            )
-            scenario = input("Select 1 or 0: ")
-            try:
-                if int(scenario) in [0, 1]:
-                    scenario = int(scenario)
-                    logging.debug(
-                        "Guided Assessment| Input Scenario: {}".format(scenario)
-                    )
-                    _exit = False
-                else:
-                    print("Provide enter either 0 or 1.")
-                    _exit = True
-            except Exception as e:
-                logging.debug(e)
-                if scenario.lower() == "exit":
-                    sys.exit()
-                break
-        _ignore, _ignore2, resource, country = convertCodes(resource, country)
-        regions()
-        gprs_comtrade(resource, [period], country, recyclingrate, scenario)
-        endmain()
-
-        print("Assessment completed! The results are downloaded to the output folder")
-        print("In case of error in the output file, refer to logs.")
diff --git a/geopolrisk/assessment/core.py b/geopolrisk/assessment/core.py
index ed41246..2ff33eb 100644
--- a/geopolrisk/assessment/core.py
+++ b/geopolrisk/assessment/core.py
@@ -1,442 +1,158 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
+# Copyright (C) 2024 University of Bordeaux, CyVi Group & University of Bayreuth,
+# Ecological Resource Technology & Anish Koyamparambath, Christoph Helbig, Thomas Schraml
 # This file is part of geopolrisk-py library.
-#
 # geopolrisk-py is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
-#
 # geopolrisk-py is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
-#
 # You should have received a copy of the GNU General Public License
 # along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
 
-import pandas as pd, json
-from urllib.request import Request, urlopen
-from pathlib import Path
-from .__init__ import instance, logging, execute_query
-from .utils import *
-
-
-# Define class for storing the path information for trade data
-class classPath:
-    tradepath = None
-
 
-classpath = classPath()
-
-# Create instances of data required for calculation of the GeoPolRisk
-try:
-    # All instances are extracted from the library database
-    _production, _reporter = instance.production, instance.reporter
-    regionslist, _outputfile = instance.regionslist, instance.exportfile
-    db = _outputfile + "/" + instance.Output
-except Exception as e:
-    logging.debug(f"Error with database files or init file {e}")
-
-
-# Function to set the path of the trade data file for specific trade data calculation
-# Provide the absolute path of the trade data file or relative to the current working directory
-def settradepath(path):
-    tradepath = path
-    try:
-        df = pd.read_excel(tradepath)
-        classpath.tradepath = path
-    except FileNotFoundError:
-        logging.debug(f"File {tradepath} not found")
-        tradepath = None
-    except Exception as e:
-        logging.debug(e)
-        tradepath = None
-    return tradepath
-
-
-# Function to define new regions
-# Provide a dictionary of the new regions
-# The key should be the name of the negion
-# The value should be the list of countries in the new region
-# In case of using aggregate function from the main module,
-# use the key as the country
-def regions(*args):
-    if len(args) != 0:
-        for key, value in args[0].items():
-            if type(key) is not str and type(value) is not list:
-                logging.debug(
-                    "Dictionary input to regions does not match required type."
-                )
-                return None
-            Print_Error = [
-                x
-                for x in value
-                if str(x) not in _reporter.Country.to_list()
-                and str(x) not in _reporter["ISO"].astype(str).tolist()
-            ]
-            if len(Print_Error) != 0:
-                logging.debug(
-                    "Error in creating a region! "
-                    "Following list of countries not"
-                    " found in the ISO list {}. "
-                    "Please conform with the ISO list or use"
-                    " 3 digit ISO country codes.".format(Print_Error)
-                )
-                return None
-            else:
-                regionslist[key] = value
-    # The function must be called before calling any other functions in the core
-    # module. The following lines populate the region list with all the countries
-    # in the world including EU defined in the init file.
-    for i in _reporter.Country.to_list():
-        if i in regionslist.keys():
-            logging.debug("Country or region already exists cannot overwrite.")
-        regionslist[i] = [i]
-    return regionslist
+from typing import Union
+from .database import databases, logging
+from .utils import *
 
 
-# Extrade the trade data using the COMTRADE API
-def worldtrade(
-    year="2010",
-    country="276",
-    commodity="2602",
-):
+def HHI(resource: Union[str, int], year: int, country: str):
+    """
+    Calculates the Herfindahl-Hirschman index of production of resources
+    which is normalized to the scale of 0 - 1.
+    The dataframe is fetched from a utlity function.
+    """
+    proddf = getProd(resource)
+    proddf = proddf[proddf["Country_Code"] != "DELETE"]
+    prod_year = proddf[str(year)].tolist()
+    HHI_Num = sumproduct(prod_year, prod_year)
     try:
-        # pricecif is the cif price of traded commodity
-        # it is included in case of change of methodology or
-        # unavailability of price data from USGS or LME
-        data = oldapirequest(year, country, commodity)
-    except Exception as e:
-        logging.debug(f"Error with the comtrade API request: {e}")
-
-    if data is None or data.shape[0] == 0:
-        data, pricecif = callapirequest(year, country, commodity)
-        if data is None or data.shape[0] == 0:
-            logging.debug("API returned empty dataframe")
-            TradeData = [None, None, None], None
-        else:
-            if 0 in data.partnerCode.astype(int).to_list():
-                err = data.partnerCode.to_list().index(0)
-                data = data.drop(data.index[[err]])
-                logging.info(
-                    "Partner code 0 is found in the trade file. "
-                    "Please check the trade file."
-                )
-            try:
-                code = data.partnerCode.to_list()
-                countries = data.partnerDesc.to_list()
-                quantity = data.Qty.to_list()
-                cifvalue = data.Cifvalue.to_list()
-                pricecif = sum(cifvalue)/sum(quantity)
-                TradeData = [code, countries, quantity]
-            except Exception as e:
-                logging.debug(
-                    f"The fetched dataframe from "
-                    "the API does not have the required columns. {e}"
-                )
-                TradeData = [None, None, None], None
-    elif data is not None and data.shape[0] != 0:
-        if data is not None and data.shape[0] != 0:
-            Worldindex = data.ptCode.to_list().index(0)
-            data = data.drop(data.index[[Worldindex]])
-            code = data.ptCode.to_list()
-            countries = data.ptTitle.to_list()
-            quantity = data.TradeQuantity.to_list()
-            TradeData = [code, countries, quantity]
-        else:
-            logging.debug("API returned empty dataframe")
-            TradeData = [None, None, None], None
-    else:
-
-        logging.info("API returned empty dataframe")
-        TradeData = [None, None, None], None
-    return TradeData, pricecif
-
-
-# Extract trade data from the specific trade data file whose path is defined in
-# the method earlier.
-def specifictrade(sheetname=None):
-    trade_path = classpath.tradepath
-
-    # This function reads the trade file specific to an organization/company.
-    # It is possible to read excel or csv file. Section 1 validates if the
-    # path to the file is set using method 1 and reads the file into a dataframe.
-
-    # 4.1 Section to validate the path to trade file
-    if trade_path == None:
-        logging.debug("Trade file path is not set.")
-        return None
-    else:
-
-        # The file must be either in excel or csv file, failing which raises an
-        # InputError from the warningsgprs module
-
-        if Path(trade_path).suffix == ".xlsx" or Path(trade_path).suffix == ".xls":
-            try:
-                data = pd.read_excel(trade_path, sheet_name=sheetname)
-            except Exception as e:
-                logging.debug(f"Error while accessing the trade file {e}")
-                return None
-        elif Path(trade_path).suffix == ".csv":
-            try:
-                data = pd.read_csv(trade_path)
-            except Exception as e:
-                logging.debug(f"Error while accessing the trade file {e}")
-                return None
-        else:
-            logging.debug(Path(trade_path).suffix)
-            return None
-
-        # The comtrade API results are categorized by imports to a region/country
-        # per country and it includes the total imports to the region/country. The
-        # code removes such imports to avoid erronous calculation.
+        hhi = HHI_Num / (sum(prod_year) * sum(prod_year))
+    except:
+        logging.debug(f"Error while calculating the HHI. Resource : {resource}, year : {year}")
+        raise ValueError
+    if cvtcountry(country, type="Name") in proddf["Country"].tolist():
         try:
-            if data.shape[0] != 0:
-                if 0 in data.ptCode.astype(int).to_list():
-                    err = data.ptCode.to_list().index(0)
-                    data = data.drop(data.index[[err]])
-                    logging.info(
-                        "Partner code 0 is found in the trade file. "
-                        "Please check the trade file."
-                    )
-                try:
-                    code = data.ptCode.to_list()
-                    countries = data.ptTitle.to_list()
-                    quantity = data.TradeQuantity.to_list()
-                    TradeData = [code, countries, quantity]
-                except Exception as e:
-                    logging.debug(
-                        f"The fetched dataframe from "
-                        f"the API does not have the required columns. {e}"
-                    )
-                    TradeData = None
-            else:
-                logging.info("API returned empty dataframe")
-                TradeData = None
-            return TradeData
-        except Exception as e:
-            logging.debug(f"Error in the trade file {e}")
-            return None
-
-
-# Fetch the mineral resource ore production data from the library
-def ProductionData(Resource, EconomicUnit):
-
-    EconomicUnit = "EU" if EconomicUnit == "European Union" else EconomicUnit
-    EconomicUnit = regionslist[EconomicUnit]
-    try:
-        prod = _production[Resource].fillna(0)
-        Countries = prod.Country.to_list()
-    except Exception as e:
-        logging.debug(
-            f"There was an error while acessing"
-            f" the production data file with an exception as {e}"
-        )
-        return None
-
-    # P2. Fetching the production quantity from 'prod' dataframe.
-    try:
-        Prod_Year = prod.columns.to_list()[1:-1]
-        Prod_Year = [int(i) for i in Prod_Year]
-        temp = [0] * len(Prod_Year)
-        for i in EconomicUnit:
-            if i in Countries:
-                Prod_Qty = (
-                    prod.loc[prod["Country"] == i]
-                    .reset_index()
-                    .loc[0, :]
-                    .values.flatten()
-                    .tolist()[2:-1]
-                )
-                Prod_Qty = replace_values(Prod_Qty, "^", 0)
-                Prod_Qty = [float(i) for i in Prod_Qty]
-                Prod_Qty = [sum(j) for j in zip(temp, Prod_Qty)]
-                temp = Prod_Qty
-            else:
-                Prod_Qty = temp
-    except Exception as e:
-        logging.debug(f"Error while processing production data {e}")
-        return None
-
-    # P3. Calculating the HHI.
-    HHI = []
-    try:
-        for i in Prod_Year:
-            temp = prod[str(i)].values.tolist()
-            temp = replace_values(temp, "^", 0)
-            temp = [float(i) for i in temp]
-            DeNom = sum(temp)
-            Nom = sum([j[0] * j[1] for j in zip(temp, temp)])
-            try:
-                HHI.append(round(Nom / (DeNom * DeNom), 3))
-            except Exception as e:
-                HHI.append(0)
-    except Exception as e:
-        logging.debug(f"Error while calculating the HHI {e}")
-        return None
-    length = len(Prod_Year)
-    if all(len(lst) == length for lst in [Prod_Qty, HHI]):
-        return [HHI, Prod_Qty, Prod_Year]
+            ProdQty = float(proddf.loc[proddf["Country"] == cvtcountry(country, type="Name"), str(year)].iloc[0])
+        except:
+            logging.debug(f"Error while extracting the production quantity, Resource : {resource}, Year: {year}, Country: {country} ")
+            raise ValueError
     else:
-        return None
-
-
-# Weight the extracted trade data with the political instability indicator data.
-# WGI is used as the default PI indicator that can be replaced with any other
-# normalized indicator data.
-def weightedtrade(year, TradeData=None, PIData=None, scenario=0, recyclingrate=0.00):
-    if TradeData is None or PIData is None:
-        logging.debug("Trade data or Indicator data returned empty!")
-        return None
-    elif TradeData is not None:
-        code, quantity = TradeData[0], TradeData[2]
-        reducedmass, totalreduce = 0, 0
-
-        # 1.2 Section to calculate the numerator and trade total
-        try:
-            PIData = PIData.fillna(0)
-            PIData.columns = PIData.columns.astype(str)
-            PI_year = [str(i) for i in PIData.Year.to_list()]
-        except Exception as e:
-            logging.debug(f"Error while working with Indicator Data {e}")
-            return None
-        try:
-            index = PI_year.index(year)
-            PI_score = []
-            for i in code:
-                if str(i) in PIData.columns.to_list():
-                    PI_score.append(PIData[str(i)].tolist()[index])
-                else:
-                    # The political instability score from the WGI is not provided for few countries
-                    # We assign them a score of 0.5 as most of these countries fall in this range
-                    PI_score.append(0.5)
-        except Exception as e:
-            logging.debug(f"Error while working with Indicator Data {e}")
-            return None
-
-        # Version 0.2: Domestic recycling mitigates the supply risk of a raw material. However domestic recycling
-        # can be attributed to decrease of imports from a country with low WGI score or high WGI score.
-        # In other words, there can be two scenarios where imports are reduced from
-        # a riskier country (best case scenario) or imports are reduced from
-        # much stable country (worst case scenario). Both the cases are determined by the
-        # WGI score, a higher WGI score is for a riskier country while lower for a stable
-        # country. The following code intends to manipulate the trade data to incorporate
-        # the domestic recycling.
-
-        # Recyclability factor of GeoPolRisk
-
-        # Usually users are supposed to provide an input between 0 and 1
-        if recyclingrate >= 1.00001 and recyclingrate < 100:
-            recyclingrate = recyclingrate / 100
-        elif recyclingrate >= 0 and recyclingrate < 1.00001:
-            recyclingrate = recyclingrate
+        ProdQty = 0
+    
+    if proddf["unit"].tolist()[0] == "kg":
+        ProdQty = ProdQty / 1000
+    elif proddf["unit"].tolist()[0] != "metr. t" and proddf["unit"].tolist()[0] != "kg":
+        raise ValueError
+    elif proddf["unit"].tolist()[0] == "Mio m3":
+        """
+        1 m³ = 0.8 kg = 0.0008 metr. t
+        """
+        ProdQty = ProdQty * 0.0008
+    """
+    The output includes the production quantity of a resource for a country in a given year and the Herfindahl-Hirschman Indexfor that year.
+    'ProdQty' : float
+    'hhi': float
+    """
+    return ProdQty, hhi
+
+
+def importrisk(resource: int, year: int, country: list):
+    """
+    The second part of the equation of the GeoPolRisk method is referred to as 'import risk'.
+    This involves weighting the import quantity with the political stability score.
+    The political stability score is derived from the 
+    Political Stability and Absence of Violence indicator of the Worldwide Governance Indicators.
+    For more information, see Koyamparambath et al. (2024).
+    """
+    def wgi_func(x):
+        """
+        For a country whose political stability score is missing, a score of 0.5 is assigned.
+        """
+        if isinstance(x, float):
+            return x
         else:
-            logging.debug(
-                f"Recycling Rate out of bounds| Recycling Rate : {recyclingrate}"
-            )
-            recyclingrate = 0
-
-        # The mitigation due to recycling has a redistribution and reduction effect
-        # The reduction effect is symbolical because the reduced trade is included in the domestic production
-        # Two cases are assumed for the redistribution
-        # The function takes in the trade quantity, political instability indicator and sum of the trade quantity
-        # This function sorts and reduces the trade quantity based on the scenario and returns the reduced quantity
-        def redistribution(quantity, indicator, totQ, reverse):
-            try:
-                totQ = totQ * recyclingrate
-                temp = [(v, i) for i, v in enumerate(indicator)]
-                temp.sort(reverse=reverse)
-                sortedVal, sortedInd = zip(*temp)
-                dump = 0
-                for i, n in enumerate(sortedInd):
-                    dump += quantity[n]
-                    if (totQ - dump) < quantity[sortedInd[i + 1]]:
-                        quantity[sortedInd[i + 1]] = quantity[sortedInd[i + 1]] - (
-                            totQ - dump
-                        )
-                        quantity[n] = 0
-                        break
-                    else:
-                        quantity[n] = 0
-            except Exception as e:
-                logging.debug(f"Error while redistributing the trade {e}")
-                quantity = None
-            return quantity
-
-        totQ = sum(quantity)
-        if scenario == 1:  # Best case scenario
-            newquantity = redistribution(quantity, PI_score, totQ, True)
-            if newquantity is not None:
-                try:
-                    zipped_list = zip(newquantity, PI_score)
-                    wgiavg = [x * y for (x, y) in zipped_list]
-                except Exception as e:
-                    logging.debug(f"Error while weighting the trade data {e}")
-                    return None
+            if x is None or isinstance(x, type(None)) or x.strip() == "NA":
+                return 0.5
             else:
-                logging.debug("Error while redistributing the trade")
-                return None
-        elif scenario == 2:  # Worst case scenario
-            newquantity = redistribution(quantity, PI_score, totQ, False)
-            if newquantity is not None:
-                try:
-                    zipped_list = zip(newquantity, PI_score)
-                    wgiavg = [x * y for (x, y) in zipped_list]
-                except Exception as e:
-                    logging.debug(f"Error while weighting the trade data {e}")
-                    return None
-            else:
-                logging.debug("Error while redistributing the trade")
-                return None
-        elif scenario == 0:  # No scenario
-            try:
-                zipped_list = zip(quantity, PI_score)
-                wgiavg = [x * y for (x, y) in zipped_list]
-            except Exception as e:
-                logging.debug(f"Error while weighting the trade data {e}")
-                return None
-
-        # After manipulation of the trade data it is multiplied with the WGI
-        # score forming the numerator of the second factor of GeoPolRisk (WTA)
-
+                return x
+                  
+    if databases.regional != True:
+        ctry = cvtcountry(country[0], type="ISO")
+        tradedf = getbacidata(year, ctry, resource, data=databases.baci_trade) #Dataframe from the utility function
+        QTY = tradedf["qty"].astype(float).tolist()
+        WGI = tradedf["partnerWGI"].apply(wgi_func).astype(float).tolist()
+        VAL = tradedf["cifvalue"].astype(float).tolist()
         try:
-            numerator = sum(wgiavg)
-            tradetotal = totQ
-        except Exception as e:
-            logging.debug(f"Error while summing the weighted trade data{e}")
-        return numerator, tradetotal
+            Price = sum(VAL) / sum(QTY)
+            TotalTrade = sum(QTY)
+            Numerator = sumproduct(QTY, WGI)
+        except:
+            logging.debug(f"Error while making calculations. Resource: {resource}, Country: {country}, Year: {year}")
+            raise ValueError
     else:
-        return 0, 0
-
-
-# The first component of the GeoPolRisk method involved calculating the herfindahl-hirschmann
-# index (HHI) and total domestic production required for calculating the second factor (WTA).
-def GeoPolRisk(ProductionData, WTAData, Year, AVGPrice):
-    newdf = pd.DataFrame(columns=["production"])
-    Index = ProductionData[2].index(int(Year))
-    HHI = ProductionData[0][Index]
-    PQT = ProductionData[1][Index] * 1000  # Converting from Mtonnes to kilograms
-    if isinstance(AVGPrice, (int, float)) and WTAData[1] != 0:
         try:
-            WTA = WTAData[0] / (WTAData[1] + PQT)
-            GeoPolRisk = HHI * WTA
-            GeoPolCF = GeoPolRisk * AVGPrice
-        except Exception as e:
-            logging.debug(f"Error while calculating GeoPolRisk {e}")
-            return None
-    elif WTAData[1] != 0:
-        try:
-            WTA = WTAData[0] / (WTAData[1] + PQT)
-            GeoPolRisk = HHI * WTA
-            GeoPolCF = "NA"
-        except Exception as e:
-            logging.debug(f"Error while calculating GeoPolRisk {e}")
-            return None
-    else:
-        WTA = 0
-        GeoPolRisk = 0
-        GeoPolCF = 0
-        logging.info("WTA has returned 0")
-        return None
-    results = [HHI, WTA, GeoPolRisk, GeoPolCF]
-    return results
+            Numerator, TotalTrade, Price = aggregateTrade(
+                year, country, resource, data=databases.baci_trade
+            )
+        except:
+            logging.debug(f"The inputs for calculating the 'import risk' dont match, Country: {country}")
+
+    """
+    'Numerator' : float
+    'TotalTrade' : float
+    'Price' : float
+    """
+    return Numerator, TotalTrade, Price
+
+
+def importrisk_company(resource: int, year: int):
+    """
+    The 'import risk' for a company differs from that of the country's.
+    This data is provided in a template in the output folder.
+    The utility function transforms the data into a 
+    usable format similar to that of the country-level data.
+    """
+    tradedf = transformdata()
+    df_query = f"(period == {year})  & (cmdCode == {resource})"
+    data = tradedf.query(df_query)
+    QTY = data["qty"].tolist()
+    WGI = data["partnerWGI"].tolist()
+    VAL = data["cifvalue"].tolist()
+    try:
+        Price = sum(VAL) / sum(QTY)
+        TotalTrade = sum(QTY)
+        Numerator = sumproduct(QTY, WGI)
+    except:
+        logging.debug(f"Error while making calculations. Resource: {resource}, Country: Company, Year: {year}")
+        raise ValueError
+    """
+    'Numerator' : float
+    'TotalTrade' : float
+    'Price' : float
+    """
+    return Numerator, TotalTrade, Price
+
+
+def GeoPolRisk(Numerator, TotalTrade, Price, ProdQty, hhi):
+    """
+    The GeoPolRisk method has two value outputs: the GeoPolRisk Score,
+    a non-dimensional score useful for comparative risk assessment,
+    and the characterization factor, which is used for evaluating
+    the GeoPolitical Supply Risk in Life Cycle Assessment with units of eq. kg-Cu/kg.
+    """
+    Denominator = TotalTrade + ProdQty
+    try:
+        WTA = Numerator / Denominator
+    except:
+        logging.debug(f"Check the Numerator and Denominator. Numerator: {Numerator}, Denominator: {Denominator}")
+    Score = hhi * WTA
+    CF = Score * Price
+    """
+    'Score' : GeoPolRisk Score : float
+    'CF' : GeoPolitical Supply Risk Potential : float
+    'WTA': Import Risk : float
+    """
+    return Score, CF, WTA
diff --git a/geopolrisk/assessment/database.py b/geopolrisk/assessment/database.py
new file mode 100644
index 0000000..510591e
--- /dev/null
+++ b/geopolrisk/assessment/database.py
@@ -0,0 +1,336 @@
+# Copyright (C) 2024 University of Bordeaux, CyVi Group & University of Bayreuth,
+# Ecological Resource Technology & Anish Koyamparambath, Christoph Helbig, Thomas Schraml
+# This file is part of geopolrisk-py library.
+# geopolrisk-py is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+# geopolrisk-py is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# You should have received a copy of the GNU General Public License
+# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
+
+
+import sqlite3, pandas as pd, logging, os
+from tqdm import tqdm
+from datetime import datetime
+from pathlib import Path
+
+logging = logging
+
+databases = None
+
+# Generic SQL function (multi use)
+def execute_query(query, db_path="", params=None):
+    conn = sqlite3.connect(db_path)
+    cursor = conn.cursor()
+    is_select_query = query.strip().lower().startswith("select")
+    if is_select_query:
+        cursor.execute(query, params or [])
+        results = cursor.fetchall()
+    else:
+        cursor.execute(query, params or [])
+        results = None
+    conn.commit()
+    conn.close()
+    if is_select_query:
+        return results
+
+
+class database:
+    Output = "Datarecords.db"  # Database file to store the GeoPolRisk values
+    _dwmd = "world_mining_data.db"  # World Mining Data Database
+    _dwgi = "wgi.db"  # World Governance Indicator Database
+    _dbaci = "baci.db"  # Trade data from BACI HS92
+    def __init__(self):
+        pass
+    """
+    The first iteration runs the init files that creates a folder 
+    "geopolrisk" in the documents folder of the operating system 
+    and all the required subfolders. The user must then copy all 
+    the required database files into the "databases" folder in 
+    the newly created "geopolrisk".
+    """
+    try:
+        directory = os.path.join(Path.home(), "Documents/geopolrisk")
+        if not os.path.exists(os.path.join(Path.home(), "Documents/geopolrisk")):
+            os.makedirs(os.path.join(Path.home(), "Documents/geopolrisk"))
+
+        if not os.path.exists(os.path.join(Path.home(), "Documents/geopolrisk/logs")):
+            os.makedirs(os.path.join(Path.home(), "Documents/geopolrisk/logs"))
+
+        directory_databases = os.path.join(Path.home(), "Documents/geopolrisk/databases")
+        if not os.path.exists(
+            os.path.join(Path.home(), "Documents/geopolrisk/databases")
+        ):
+            os.makedirs(os.path.join(Path.home(), "Documents/geopolrisk/databases"))
+
+        if not os.path.exists(os.path.join(Path.home(), "Documents/geopolrisk/output")):
+            os.makedirs(os.path.join(Path.home(), "Documents/geopolrisk/output"))
+    except Exception as e:
+        print(f"Unable to create directories {e}")
+        raise FileNotFoundError
+
+    if not os.path.isfile(os.path.join(directory + "/databases/", _dwmd)):
+        print(
+            f"Database file {_dwmd} not found! Copy the required database files into the folder {directory_databases}."
+        )
+    if not os.path.isfile(os.path.join(directory + "/databases/", _dwgi)):
+        print(
+            f"Database file {_dwgi} not found! Copy the required database files into the folder {directory_databases}."
+        )
+    if not os.path.isfile(os.path.join(directory + "/databases/", _dbaci)):
+        print(
+            f"Database file {_dbaci} not found! Copy the required database files into the folder {directory_databases}."
+        )
+
+    ##############################################
+    ##   READING TABLES FROM THE DATABASE FILES ##
+    ##############################################
+
+    Tables_world_mining_data = [
+        "Aluminium",
+        "Antimony",
+        "Arsenic",
+        "Asbestos",
+        "Baryte",
+        "Bauxite",
+        "Bentonite",
+        "Beryllium (conc.)",
+        "Bismuth",
+        "Boron Minerals",
+        "Cadmium",
+        "Chromium (Cr2O3)",
+        "Cobalt",
+        "Coking Coal",
+        "Copper",
+        "Diamonds (Gem)",
+        "Diamonds (Ind)",
+        "Diatomite",
+        "Feldspar",
+        "Fluorspar",
+        "Gallium",
+        "Germanium",
+        "Gold",
+        "Graphite",
+        "Gypsum and Anhydrite",
+        "Indium",
+        "Iron (Fe)",
+        "Kaolin (China-Clay)",
+        "Lead",
+        "Lignite",
+        "Lithium (Li2O)",
+        "logging",
+        "Magnesite",
+        "Manganese",
+        "Mercury",
+        "Molybdenum",
+        "Natural Gas",
+        "Nickel",
+        "Niobium (Nb2O5)",
+        "Oil Sands (part of Petroleum)",
+        "Oil Shales",
+        "Palladium",
+        "Perlite",
+        "Petroleum",
+        "Phosphate Rock (P2O5)",
+        "Platinum",
+        "Potash (K2O)",
+        "Rare Earths (REO)",
+        "Rhenium",
+        "Rhodium",
+        "Salt (rock, brines, marine)",
+        "Selenium",
+        "Silver",
+        "Steam Coal ",
+        "Sulfur (elementar & industrial)",
+        "Talc, Steatite & Pyrophyllite",
+        "Tantalum (Ta2O5)",
+        "Tellurium",
+        "Tin",
+        "Titanium (TiO2)",
+        "Tungsten (W)",
+        "Uranium (U3O8)",
+        "Vanadium (V)",
+        "Vermiculite",
+        "Zinc",
+        "Zircon",
+        "Country_ISO",
+        "HS Code Map",
+    ]
+    Tables_wgi = [
+        "Normalized",
+    ]
+    Tables_baci = [
+        "baci_trade",
+    ]
+
+    # Function to check if database exists and fetch the required tables
+    def check_db_tables(db, table_names):
+        try:
+            conn = sqlite3.connect(db)
+            cursor = conn.cursor()
+            query = "SELECT name FROM sqlite_master WHERE type='table';"
+            cursor.execute(query)
+            result = cursor.fetchall()
+            table_names = [row[0] for row in result]
+        except Exception as e:
+            print(f"Unable to verify if the database contains the required tables {e}")
+            raise FileNotFoundError
+
+        # check if all the tables in the list are present in the database
+        missingTables = []
+        for table_name in table_names:
+            if table_name not in table_names:
+                missingTables.append(table_name)
+            else:
+                pass
+
+        # If there are missing tables, raise an error
+        if len(missingTables) > 0:
+            print(
+                f"The following tables are missing from the database: {missingTables}"
+            )
+            return False
+        else:
+            return True
+
+    ###############################################
+    ## Extracting TABLES FROM THE DATABASE FILES ##
+    ###############################################
+
+    def extract_tables_to_df(db_path, table_names):
+        try:
+            tables = {}
+            conn = sqlite3.connect(db_path)
+            for table_name in tqdm(
+                table_names,
+                desc=f"Reading table/s {table_names} from the library database {db_path}.",
+            ):
+                if table_name == "baci_trade":
+                    query = f"""
+                            select 
+                                bacitab.t as period,
+                                bacitab.j as reporterCode,
+                                (SELECT cc.country_name FROM country_codes_V202401b cc WHERE bacitab.j = cc.country_code) AS reporterDesc,
+                                (SELECT cc.country_iso3 FROM country_codes_V202401b cc WHERE bacitab.j = cc.country_code) AS reporterISO,
+                                bacitab.i as partnerCode,
+                                (SELECT cc.country_name FROM country_codes_V202401b cc WHERE bacitab.i = cc.country_code) AS partnerDesc,
+                                (SELECT cc.country_iso3 FROM country_codes_V202401b cc WHERE bacitab.i = cc.country_code) AS partnerISO,
+                                bacitab.k as cmdCode,
+                                REPLACE(TRIM(bacitab.q), 'NA', 0) as qty,
+	                            REPLACE(TRIM(bacitab.v),'NA', 0) as cifvalue,
+                                (SELECT vwyc.wgi FROM v_wgi_year_country vwyc WHERE bacitab.t = vwyc.Year and bacitab.i = vwyc.country_code) AS partnerWGI
+                            from baci_trade bacitab
+                              --where bacitab.k = '260400'
+                            """
+                    # Test-Query - read the vieww
+                    # query = f"""
+                    #         select 
+                    #         *
+                    #         from v_baci_trade_with_wgi bacitab
+                    #         --where cmdCode = '260400'
+                    #         """
+                else:
+                    query = f"SELECT * FROM '{table_name}'"
+                table_df = pd.read_sql_query(query, conn)
+                tables[table_name] = table_df
+            conn.close()
+        except Exception as e:
+            print(f"Error to read tables {table_names} from database {db_path} - {e}")
+            conn.close()
+        return tables
+
+    # Check if the world_mining_data.db database exists and fetch the required tables
+    Database_wmd_path = directory + "/databases/" + _dwmd
+    if check_db_tables(Database_wmd_path, Tables_world_mining_data):
+        tables_world_mining_data = extract_tables_to_df(
+            Database_wmd_path, Tables_world_mining_data
+        )
+    else:
+        print("Error while reading the World Mining Data db")
+        raise (FileNotFoundError)
+
+    # Check if the wgi.db database exists and fetch the required tables
+    Database_wgi_path = directory + "/databases/" + _dwgi
+    if check_db_tables(Database_wgi_path, Tables_wgi):
+        tables_wgi = extract_tables_to_df(Database_wgi_path, Tables_wgi)
+    else:
+        print("Error while reading the WGI db")
+        raise (FileNotFoundError)
+
+    # Check if the baci.db exists and fetch the required tables
+    Database_baci_path = directory + "/databases/" + _dbaci
+    if check_db_tables(Database_baci_path, Tables_baci):
+        tables_baci = extract_tables_to_df(Database_baci_path, Tables_baci)
+    else:
+        print("Error while reading the BACI db")
+        raise (FileNotFoundError)
+
+    #############################################################
+    ## Extracting the dataframes into the individual variables ##
+    #############################################################
+
+    production = tables_world_mining_data
+    baci_trade = tables_baci["baci_trade"]
+    wgi = tables_wgi["Normalized"]
+
+    regionslist = {}
+    regional = False
+    regionslist["EU"] = [
+        "Austria",
+        "Belgium",
+        "Belgium-Luxembourg",
+        "Bulgaria",
+        "Croatia",
+        "Czechia",
+        "Czechoslovakia",
+        "Denmark",
+        "Estonia",
+        "Finland",
+        "France",
+        "Fmr Dem. Rep. of Germany",
+        "Fmr Fed. Rep. of Germany",
+        "Germany",
+        "Greece",
+        "Hungary",
+        "Ireland",
+        "Italy",
+        "Latvia",
+        "Lithuania",
+        "Luxembourg",
+        "Malta",
+        "Netherlands",
+        "Poland",
+        "Portugal",
+        "Romania",
+        "Slovakia",
+        "Slovenia",
+        "Spain",
+        "Sweden",
+    ]
+
+if databases == None:
+    databases = (
+        database()
+    )
+
+###########################################################
+## Creating a log object and file for logging the errors ##
+###########################################################
+
+Filename = "Log_File_{:%Y-%m-%d(%H-%M-%S)}.log".format(datetime.now())
+log_level = logging.DEBUG
+try:
+    logging.basicConfig(
+        level=log_level,
+        format="""%(asctime)s | %(levelname)s | %(threadName)-10s |
+          %(filename)s:%(lineno)s - %(funcName)20s() |
+            %(message)s""",
+        filename=databases.directory + "/logs/" + Filename,
+        filemode="w",
+    )
+except:
+    print("Cannot create log file!")
diff --git a/geopolrisk/assessment/gprsplots.py b/geopolrisk/assessment/gprsplots.py
deleted file mode 100644
index fba398b..0000000
--- a/geopolrisk/assessment/gprsplots.py
+++ /dev/null
@@ -1,370 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-from matplotlib import rcParams
-
-rcParams["font.family"] = "sans-serif"
-rcParams["font.sans-serif"] = ["Tahoma"]
-import pandas as pd, numpy as np, matplotlib.pyplot as plt
-from scipy.interpolate import make_interp_spline, BSpline
-from matplotlib.ticker import MaxNLocator
-from textwrap import wrap
-from .__init__ import (
-    instance,
-    logging,
-)
-_outputfile = instance.exportfile
-logging.info("Accessed gprsplots module.")
-
-# Read output file
-global csvfile
-csvfile = "/export.csv"
-try:
-    data = pd.read_csv(_outputfile + csvfile)
-except Exception as e:
-    logging.debug(e)
-
-try:
-    data.columns = [
-        "Year",
-        "Resource",
-        "Country",
-        "RR",
-        "RRScenario",
-        "GeoPolRisk",
-        "CF",
-        "HHI",
-        "WTA",
-    ]
-except Exception as e:
-    logging.debug(e)
-
-
-# Splining function
-def splining(x, y, degree):
-    try:
-        x = np.array(x)
-        y = np.array(y)
-        xnew = np.linspace(x.min(), x.max(), 1000)
-        spl = make_interp_spline(x, y, k=degree)  # type: BSpline
-        smooth = spl(xnew)
-    except Exception as e:
-        logging.debug(e)
-    return xnew, smooth
-
-
-def trendplot(country, period, resources):
-    fig = plt.figure(figsize=(7, 5), dpi=200, facecolor="#f4f6fa", edgecolor="k")
-    gs = fig.add_gridspec(1, 1)
-    fig.suptitle("Evolution of the supply risk of selected resources", fontsize=14)
-    ax = fig.add_subplot(gs[0, 0])
-    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
-    plt.yticks(np.arange(0, 1, 0.1))
-
-    for i in resources:
-        GPRS, year = [], []
-        rm_temp = 0
-        for j in period:
-            try:
-                year.append(int(j))
-            except Exception as e:
-                logging.debug(e)
-            try:
-                GPRS.append(
-                    data.loc[
-                        (data["Resource"] == i)
-                        & (data["Country"] == country[0])
-                        & (data["Year"] == j)
-                        & (data["RRScenario"] == 0),
-                        "GeoPolRisk",
-                    ].values[0]
-                )
-            except Exception as e:
-                logging.debug(e)
-        rm = max(GPRS)
-        rm_temp = rm if rm > rm_temp else rm_temp
-        try:
-            x, y = splining(year, GPRS, 2)
-            plt.plot(x, y, label=i)
-        except Exception as e:
-            logging.debug(e)
-
-    plt.xlabel("Year")
-    plt.ylabel("GPRS")
-    ax.set_ylim([0, rm_temp + 0.1])
-    handles, labels = ax.get_legend_handles_labels()
-    fig.legend(handles, labels, loc="center right")
-    fig.tight_layout()
-    fig.subplots_adjust(top=0.90, right=0.80, left=0.15)
-    return fig
-
-
-def indplot(Country, Year, resource, scenario):
-    Year = int(Year[0])
-    switch_dict = {"Resource": resource, "Country": Country}
-    if len(resource) > 1 and len(Country) == 1:
-        switch = switch_dict["Resource"]
-        catch = switch_dict["Country"]
-    else:
-        switch = switch_dict["Country"]
-        catch = switch_dict["Resource"]
-
-    fig = plt.figure(figsize=(7, 5), dpi=200, facecolor="#f4f6fa", edgecolor="k")
-    gs = fig.add_gridspec(1, 1)
-    fig.suptitle("Comparison of supply risk of resources", fontsize=14)
-    ax = fig.add_subplot(gs[0, 0])
-    plt.yticks(np.arange(0, 1, 0.1))
-    for i in switch:
-        try:
-            if scenario == 0:
-                _Year = (
-                    data.loc[
-                        (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(switch)
-                                ]
-                            ]
-                            == i
-                        )
-                        & (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ]
-                            == switch_dict[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ][0]
-                        ),
-                        "Year",
-                    ]
-                    .values.tolist()
-                    .index(Year)
-                )
-                trend = data.loc[
-                    (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(switch)
-                            ]
-                        ]
-                        == i
-                    )
-                    & (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ]
-                        == switch_dict[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ][0]
-                    ),
-                    "GeoPolRisk",
-                ].values[_Year]
-                plt.bar([i], trend, label=catch[0])
-
-            else:
-                # Best Case Scenario
-                _Year = (
-                    data.loc[
-                        (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(switch)
-                                ]
-                            ]
-                            == i
-                        )
-                        & (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ]
-                            == switch_dict[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ][0]
-                        )
-                        & (data["RRScenario"] == 2),
-                        "Year",
-                    ]
-                    .values.tolist()
-                    .index(Year)
-                )
-                trend = data.loc[
-                    (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(switch)
-                            ]
-                        ]
-                        == i
-                    )
-                    & (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ]
-                        == switch_dict[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ][0]
-                    )
-                    & (data["RRScenario"] == 2),
-                    "GeoPolRisk",
-                ].values[_Year]
-                plt.bar([i], trend, label=catch[0])
-                # Worst Case Scenario
-                _Year = (
-                    data.loc[
-                        (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(switch)
-                                ]
-                            ]
-                            == i
-                        )
-                        & (
-                            data[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ]
-                            == switch_dict[
-                                list(switch_dict.keys())[
-                                    list(switch_dict.values()).index(catch)
-                                ]
-                            ][0]
-                        )
-                        & (data["RRScenario"] == 1),
-                        "Year",
-                    ]
-                    .values.tolist()
-                    .index(Year)
-                )
-                trend = data.loc[
-                    (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(switch)
-                            ]
-                        ]
-                        == i
-                    )
-                    & (
-                        data[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ]
-                        == switch_dict[
-                            list(switch_dict.keys())[
-                                list(switch_dict.values()).index(catch)
-                            ]
-                        ][0]
-                    )
-                    & (data["RRScenario"] == 1),
-                    "GeoPolRisk",
-                ].values[_Year]
-                plt.bar([i], trend, label=catch[0])
-        except Exception as e:
-            logging.debug(e)
-
-    plt.ylabel("GPRS")
-    ax.set_ylim([0.00, 0.10])
-    handles, labels = ax.get_legend_handles_labels()
-    labels = ["\n".join(wrap(l, 10)) for l in labels]
-    fig.legend(
-        handles,
-        labels,
-        loc="center right",
-    )
-    fig.tight_layout()
-    fig.subplots_adjust(top=0.90, right=0.75, left=0.15)
-    return fig
-
-
-def compareplot(Country, Year, resource, scenario):
-    if len(Year) == 1 and scenario == 0:
-        Year = int(Year[0])
-        fig = plt.figure(figsize=(7, 5), dpi=200, facecolor="#f4f6fa", edgecolor="k")
-        gs = fig.add_gridspec(1, 1)
-        fig.suptitle("Comparison of supply risk of resources", fontsize=14)
-        ax = fig.add_subplot(gs[0, 0])
-        plt.yticks(np.arange(0, 1, 0.1))
-        columns = ["Country"]
-        columns.extend(resource)
-        allrows = []
-        for i in Country:
-            GPRS, HHI, WTA = [], [], []
-            dfrow = [i]
-            for j in resource:
-                GPRS.append(
-                    data.loc[
-                        (data["Resource"] == j)
-                        & (data["Country"] == i)
-                        & (data["Year"] == Year)
-                        & (data["RRScenario"] == 0),
-                        "GeoPolRisk",
-                    ].values[0]
-                )
-                HHI.append(
-                    data.loc[
-                        (data["Resource"] == j)
-                        & (data["Country"] == i)
-                        & (data["Year"] == Year)
-                        & (data["RRScenario"] == 0),
-                        "HHI",
-                    ].values[0]
-                )
-                WTA.append(
-                    data.loc[
-                        (data["Resource"] == j)
-                        & (data["Country"] == i)
-                        & (data["Year"] == Year)
-                        & (data["RRScenario"] == 0),
-                        "WTA",
-                    ].values[0]
-                )
-            total = sum(GPRS)
-            GPRS = [(i / total) * 100 for i in GPRS]
-            dfrow.extend(GPRS)
-            allrows.append(dfrow)
-        newpd = pd.DataFrame(allrows, columns=columns)
-        newpd.plot(
-            x="Country",
-            kind="bar",
-            stacked=True,
-            title="Percentage Stacked Bar Graph",
-            mark_right=True,
-        )
-        plt.ylabel("GPRS")
-        plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
-        ax.set_ylim([0.00, 100])
-        fig.tight_layout()
-        fig.subplots_adjust(top=0.90, right=0.75, left=0.15)
-        return fig
diff --git a/geopolrisk/assessment/main.py b/geopolrisk/assessment/main.py
index 9103c51..41a93a2 100644
--- a/geopolrisk/assessment/main.py
+++ b/geopolrisk/assessment/main.py
@@ -1,483 +1,135 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
+# Copyright (C) 2024 University of Bordeaux, CyVi Group & University of Bayreuth,
+# Ecological Resource Technology & Anish Koyamparambath, Christoph Helbig, Thomas Schraml
 # This file is part of geopolrisk-py library.
-#
 # geopolrisk-py is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
-#
 # geopolrisk-py is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
-#
 # You should have received a copy of the GNU General Public License
 # along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
 
-from .__init__ import (
-    instance,
-    logging,
-    Filename,
-    outputdf,
-    execute_query,
-)
-import numpy as np
+import itertools
+from tqdm import tqdm
+from .database import databases, logging
 from .core import *
-import itertools, pandas as pd, time
 from .utils import *
-import sys
 
-"""
-The module implements the functions of the core module for ease of use.
-Provide the list of mineral resources, countries and year to the main function.
-Call the regions function to define any custom regions. Call the settradepath
-function to define the trade data for specific trade calculation. 
-The main function verifies if the above said functions are called or not to 
-automatically detect the type of calculation required.
-"""
 
-
-try:
-    regionslist, _outputfile = instance.regionslist, instance.exportfile
-    _reporter = instance.reporter
-    Country = _reporter.Country.to_list()
-    _price = instance.price
-    _wgi = instance.wgi
-    db = _outputfile + "/" + instance.Output
-    OutputList = outputdf.outputList
-    counter, totalcounter, emptycounter = 0, 0, 0
-except Exception as e:
-    logging.debug(f"Error with database files or init file {e}")
-
-
-def tradeagg(resource, year, listofcountries, sheetname=None):
+def gprs_calc(period: list, country: list, resource: list, region_dict = {}):
     """
-    This function is used to aggregate the trade data from COMTRADE API.
-    The trade data is aggregated (summed) which is then
-    processed for further calculation.
+    A single aggregate function performs all calculations and exports the results as an Excel file.
+    The inputs include a list of years, a list of countries, 
+    and a list of resources, with an optional dictionary for defining new regions.
+    The lists can contain resource names such as 'Cobalt' and 'Lithium',
+    and country names like 'Japan' and 'Canada', or alternatively, HS codes and ISO digit codes.
+    
+    For regional assessments, regions must be defined in the dictionary with country names,
+    not ISO digit codes.
+    For example, the 'West Europe' region can be defined as 
+    { 
+        'West Europe': ['France', 'Germany', 'Italy', 'Spain', 'Portugal', 'Belgium', 'Netherlands', 'Luxembourg']
+        }.
     """
-    # resources is hs code of the commodity
-    # New variables to aggregate trade data from COMTRADE API
-    newcodelist = []
-    newcountrylist = []
-    newquantitylist = []
-    # TradeData (from core module) fetchs the ISO country code,
-    # country names and trade quantity in KG from COMTRADE
-    newtradelist = [
-        newcodelist,
-        newcountrylist,
-        newquantitylist,
-    ]
-    pricecifAGG = []
-    # Variable to fetch production data
-    TotalDomesticProduction, TDP = 0, []
-    # If the aggregation is not from the specific trade data source,
-    # then its not necessary to call the settradepath function and
-    # input sheetname as None.
-    if sheetname is None:
-        for k in listofcountries:
+    Score_list, CF_list = [], []
+    hhi_list, ir_list, price_list = [], [], []
+    dbid = []
+    ctry_db, rm_db, period_db = [], [], []
+    regions(region_dict) #Function to define region
+    for year, ctry, rm in tqdm(
+        list(itertools.product(period, country, resource)),
+        desc="Calculating the GeoPolRisk: "
+        ):
+        if len(databases.regionslist[cvtcountry(ctry, type="Name")]) > 1:
+            logging.debug("Logged - Multiregional Assessment")
             try:
-                TradeData, pricecif = worldtrade(
-                    year=year,
-                    country=k,
-                    commodity=resource,
+                Numerator, TotalTrade, Price = aggregateTrade(
+                    year, databases.regionslist[ctry], cvtresource(rm, type="HS")
                 )
+            except ValueError:
+                logging.debug("Couldnt calculate the Import Risk - Regional. Check functional error!")
+                break
             except Exception as e:
-                logging.debug(
-                    f"""Failed COMTRADE attempt!: resource - {resource}
-                            country - {k}, year - {year}, : {e}"""
-                )
-            # Logging null return of the trade data from the world trade.
-            if (
-                isinstance(TradeData[0], type(None))
-                or len(TradeData) == 0
-                or any(v is None for v in TradeData[0])
-            ):
-                logging.debug(f"Trade of {resource} to {k} returned None for {year}")
-                newcodelist.append(0)
-                newcountrylist.append(0)
-                newquantitylist.append(0)
-                pricecifAGG.append(0)
-            else:
-                # code to aggregate the data
-                TradeData[2] = [0 if v is None else v for v in TradeData[2]]
-                for ind, n in enumerate(TradeData[0]):
-                    # Aggregation of the trade data
-                    # EX: for a region of two countries (A, B) that import from similar set of countries
-                    # The aggregation is the sum of the trade quantities for the two countries (A, B)
-                    if n not in newcodelist:
-                        newcodelist.append(n)
-                        newquantitylist.append(TradeData[2][ind])
-                        newcountrylist.append(TradeData[1][ind])
-                    else:
-                        index = newcodelist.index(n)
-                        newquantitylist[index] = (
-                            newquantitylist[index] + TradeData[2][ind]
-                        )
-                pricecifAGG.append(pricecif)
-                
-                logging.debug(f"The aggregated trade quantity {newtradelist}")
-            avgpricecif = sum(pricecif)/len(pricecif)
-            # Aggregation of the production of mineral resource data
-            xresource, country, _ignore, _ignore2 = convertCodes(resource, k)
-            X = ProductionData(xresource, country)
-            index = X[2].index(year)
-            TotalDomesticProduction += X[1][index]
-            logging.info(f"The aggegated production quantity {TotalDomesticProduction}")
-    else:
-        TradeData = specifictrade(sheetname)
-        for k in listofcountries:
-            xresource, country, _ignore, _ignore2 = convertCodes(resource, k)
-            X = ProductionData(xresource, country)
-            index = X[2].index(year)
-            TotalDomesticProduction += X[1][index]
-        newtradelist = TradeData
-        pricecif = None
-    # Calculation of the components of the GeoPolRisk method
-    TDP = [0] * len(X[1])
-    TDP[X[2].index(year)] = TotalDomesticProduction
-    productiondata = [X[0], TDP, X[2]]
-
-    return newtradelist, productiondata, avgpricecif
-
-
-def main_complete(
-    resourcelist,
-    yearlist,
-    countrylist,
-    recyclingrate=0.0,
-    scenario=0,
-    sheetname=None,
-    PIindicator=None,
-):
-
-    if PIindicator is None:
-        PIindicator = _wgi
-    # Instantiate counters for logging
-    logging.info("Running")
-    newregion = []
-    if len(regionslist) > 1:
-        logging.info("Regional calculation started!")
-        newregionlist = []
-        # Compare if the region already exists withing the library.
-        newregion = [
-            i
-            for i, x in enumerate(countrylist)
-            if str(x) not in Country or str(x) not in [str(i) for i in ISO]
-        ]
-        logging.info(f"List of new regions {newregion}")
-
-        # Extract new regions from the provided countrylist parameter (argument).
-        if len(newregion) > 0:
-            for i in newregion:
-                newregionlist.append(countrylist[i])
-                del countrylist[i]
-        if len(newregionlist) > 0:  # Calculate the values for the new region(s)
-            for l in newregionlist:
-                # New regions can be defined as ISO nomenclature or ISO numeric.
-                #  The values must be converted to numeric.newcountrylist
-                ncountrylist = regionslist[l]
-                logging.info(
-                    f"The new region defined {l} and the countries in it are {ncountrylist}"
-                )
-                _ignore1, _ignore2, _ignore3, Xcountrylist = convertCodes(
-                    ["Cobalt"], ncountrylist
-                )
-
-                # Iterate the resources, year for COMTRADE query
-                for I in itertools.product(resourcelist, yearlist):
-                    # LOGIC
-                    DBID = create_id(I[0], l, I[1])
-                    try:
-                        verify = sqlverify(DBID)
-                    except Exception as e:
-                        logging.debug(f"SQL Verification failed! {e}")
-                    if verify is False:
-                        time.sleep(2)
-                        TradeData, productiondata, avgpricecif = tradeagg(I[0], I[1], Xcountrylist)
-                        if avgpricecif in [np.nan, 0, "nan"]:
-                            AVGPrice = _price[str(I[1])].tolist()[
-                            _price.HS.to_list().index(I[0])
-                        ]
-                        else:
-                            AVGPrice = avgpricecif
-                        Y = weightedtrade(
-                            str(I[1]),
-                            TradeData=TradeData,
-                            PIData=PIindicator,
-                            scenario=scenario,
-                            recyclingrate=recyclingrate,
-                        )
-                        if Y is not None and productiondata is not None:
-                            result = GeoPolRisk(productiondata, Y, str(I[1]), AVGPrice)
-                            if result is not None:
-                                HHI, WTA, Risk, CF = (
-                                    result[0],
-                                    result[1],
-                                    result[2],
-                                    result[3],
-                                )
-                            else:
-                                HHI, WTA, Risk, CF = 0, 0, 0, 0
-                        else:
-                            HHI, WTA, Risk, CF = 0, 0, 0, 0
-                        # Final outputs from the GeoPolRisk calculation
-                        logging.info(
-                            f"""
-                        GeoPolRisk calculation completed successfully! The following
-                        values are calculated: {HHI}, {WTA}, {Risk}, {CF} for resource {I[0]}
-                        , year {I[1]} to region {l} with recyclingrate {recyclingrate} and 
-                        scenario {scenario}
-                        """
-                        )
-                        resource, _ignore1, _ignore2, _ignore3 = convertCodes(I[0], 174)
-                        # Record or update data
-                        recordData(
-                            resource,
-                            l,
-                            I[1],
-                            recyclingrate,
-                            scenario,
-                            Risk,
-                            CF,
-                            HHI,
-                            WTA,
-                            Filename,
-                            OutputList,
-                        )
-                    else:
-                        try:
-                            sqlstatement = f""" SELECT  geopolrisk, hhi, wta, geopol_cf FROM
-                            recordData WHERE id = '{DBID}'
-                            """
-                            row = execute_query(sqlstatement, db_path=db)
-                            OutputList.append(
-                                [
-                                    str(I[1]),
-                                    str(resource),
-                                    str(l),
-                                    str(recyclingrate),
-                                    str(scenario),
-                                    str(row[0][0]),
-                                    str(row[0][3]),
-                                    str(row[0][1]),
-                                    str(row[0][2]),
-                                ]
-                            )
-                        except Exception as e:
-                            logging.debug(f"Cannot append into list of records {e}")
-                        logging.debug(
-                            "No transaction has been made. "
-                            "Preexisting data has been inserted in output file."
-                        )
-        else:
-            startmain(
-                resourcelist,
-                yearlist,
-                countrylist,
-                recyclingrate=0.0,
-                scenario=0,
-                sheetname=None,
-                PIindicator=None,
-            )
-    else:
-        regions()
-        startmain(
-            resourcelist,
-            yearlist,
-            countrylist,
-            recyclingrate=0.0,
-            scenario=0,
-            sheetname=None,
-            PIindicator=None,
-        )
-
-    endmain()
-
-
-def startmain(
-    resourcelist,
-    yearlist,
-    countrylist,
-    recyclingrate=0.0,
-    scenario=0,
-    sheetname=None,
-    PIindicator=None,
-):
-    if PIindicator is None:
-        PIindicator = _wgi
-    for I in itertools.product(resourcelist, countrylist, yearlist):
-        # LOGIC
-        # Need to verify if the data preexists to avoid limited API calls
-        resource, country, _ignore, _ignore1 = convertCodes(I[0], I[1])
-        DBID = create_id(I[0], I[1], I[2])
-        try:
-            verify = sqlverify(DBID)
-        except Exception as e:
-            logging.debug(f"Error with sqlverify or DBID {e}")
-        if verify is False:
-            # The program has to sleep inorder to avoid conflict in multiple API requests
-            time.sleep(2)
-            if sheetname is None:
-                try:
-                    TradeData, pricecif = worldtrade(
-                        year=I[2],
-                        country=I[1],
-                        commodity=I[0],
-                    )
-                except Exception as e:
-                    logging.debug(f"Error accessing world trade data {e}")
-                    counter -= 1
-                    break
-            else:
-                try:
-                    TradeData = specifictrade(
-                        year=I[2],
-                        country=I[1],
-                        commodity=I[0],
-                    )
-                except Exception as e:
-                    logging.debug(f"Error accessing specific trade data {e}")
-                    break
-
+                logging.debug("Unknwon exception at ", e)
+                break
             try:
-                if pricecif in [np.nan, 0, "nan"]:
-                    AVGPrice = _price[str(I[2])].tolist()[_price.HS.to_list().index(I[0])]
-                else:
-                    AVGPrice = pricecif
-                X = ProductionData(resource, country)
-                Y = weightedtrade(
-                    str(I[2]),
-                    TradeData=TradeData,
-                    PIData=PIindicator,
-                    scenario=scenario,
-                    recyclingrate=recyclingrate,
-                )
-                if Y is not None and X is not None:
-                    result = GeoPolRisk(X, Y, str(I[2]), AVGPrice)
-                    if result is not None:
-                        HHI, WTA, Risk, CF = (
-                            result[0],
-                            result[1],
-                            result[2],
-                            result[3],
-                        )
-                    else:
-                        HHI, WTA, Risk, CF = 0, 0, 0, 0
-                else:
-                    HHI, WTA, Risk, CF = 0, 0, 0, 0
+                sum_ProdQty = []
+                for j in databases.regionslist[ctry]:
+                    ProdQty, hhi = HHI(rm, int(year),  cvtcountry(j, type="Name"))
+                    sum_ProdQty.append(ProdQty)
+            except ValueError:
+                logging.debug("Couldnt calculate the HHI and Production Quantity - Regional. Check functional error!")
+                break
             except Exception as e:
-                logging.debug(
-                    f"Error unpacking the production data/weighted trade data/price data {e}"
-                )
-                continue
-
-            recordData(
-                resource,
-                country,
-                I[2],
-                recyclingrate,
-                scenario,
-                Risk,
-                CF,
-                HHI,
-                WTA,
-                Filename,
-                OutputList,
-            )
+                logging.debug("Unknwon exception at ", e)
+                break
+            try:
+                Score, CF, IR = GeoPolRisk(Numerator, TotalTrade, Price, sum(sum_ProdQty), hhi)
+            except ValueError:
+                logging.debug("Couldnt calculate the GeoPolRisk - Regional. Check functional error!")
+                break
+            except Exception as e:
+                logging.debug("Unknwon exception at ", e)
+                break
         else:
             try:
-                sqlstatement = f""" SELECT  geopolrisk, hhi, wta, geopol_cf FROM
-                recordData WHERE id = '{DBID}'
-                """
-                row = execute_query(sqlstatement, db_path=db)
-                OutputList.append(
-                    [
-                        str(I[1]),
-                        str(resource),
-                        str(country),
-                        str(recyclingrate),
-                        str(scenario),
-                        str(row[0][0]),
-                        str(row[0][3]),
-                        str(row[0][1]),
-                        str(row[0][2]),
-                    ]
+                ProdQty, hhi = HHI(rm, int(year), ctry)
+            except ValueError:
+                logging.debug("Couldnt calculate the HHI. Check functional error!")
+                break
+            except Exception as e:
+                logging.debug("Unknwon exception at ", e)
+                break
+            try:
+                Numerator, TotalTrade, Price = importrisk(
+                    cvtresource(rm, type="HS"), year, databases.regionslist[cvtcountry(ctry, type="Name")]
                 )
+            except ValueError:
+                logging.debug("Couldnt calculate the Import Risk. Check functional error!")
+                break
             except Exception as e:
-                logging.debug(f"Cannot append into list of records {e}")
-            logging.debug(
-                "No transaction has been made. "
-                "Preexisting data has been inserted in output file."
-            )
-
-
-def endmain():
-    outputDF = pd.DataFrame(OutputList, columns=outputdf.columns)
-    outputDF.to_csv(_outputfile + "/export.csv", index=False, encoding="utf-8")
-    logging.info("GeoPolRisk calculation completed successfully!")
-
-
-def update_cf():
-    # Fetch Missing Data
-    sqlstatement = (
-        "SELECT resource_hscode, year, iso, geopol_cf FROM recordData WHERE "
-        " wta = '0';"
-    )
-    row = execute_query(sqlstatement, db_path=db)
-    df = pd.DataFrame(
-        row, columns=["HS Code", "Year", "Country Alpha", "Characterziation Factors"]
-    )
-    logging.debug("Update of database! The shape of df is " + str(df.shape[0]))
-    if df.shape[0] > 0:
-        Year = [int(i) for i in df.Year.to_list()]
-        ISO = [int(i) for i in df["Country Alpha"].tolist()]
-        HS = [int(i) for i in df["HS Code"].tolist()]
-    else:
-        logging.debug("No updates required!")
-        return None
+                logging.debug("Unknwon exception at ", e)
+                break
+            try:
+                Score, CF, IR = GeoPolRisk(Numerator, TotalTrade, Price, ProdQty, hhi)
+            except ValueError:
+                logging.debug("Couldnt calculate the GeoPolRisk. Check functional error!")
+                break
+            except Exception as e:
+                logging.debug("Unknwon exception at ", e)
+                break
+        try:
+            Score_list.append(Score)
+            CF_list.append(CF)
+            hhi_list.append(hhi)
+            ir_list.append(IR)
+            price_list.append(Price)
+            ctry_db.append(cvtcountry(ctry, type="Name"))
+            rm_db.append(cvtresource(rm, type="Name"))
+            period_db.append(year)
+            dbid.append(create_id(cvtresource(rm, type="HS"), cvtcountry(ctry, type="ISO"), year))
+        except Exception as e:
+            logging.debug("Error while recording data for non regional assessment!", e)
+    result = createresultsdf()
     try:
-        startmain(HS, Year, ISO, 0, 0)
-        endmain()
+        result["DBID"] = dbid
+        result["Country [Economic Entity]"] = ctry_db
+        result["Raw Material"] = rm_db
+        result["Year"] = period_db
+        result["GeoPolRisk Score"] = Score_list
+        result["GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]"] = CF_list
+        result["HHI"] = hhi_list
+        result["Import Risk"] = ir_list
+        result["Price"] = price_list
+
+        excel_path = databases.directory + "/output/results.xlsx"
+        result.to_excel(excel_path, index=False)
+        writetodb(result)
+        # add return result for test-cases
+        # return result
     except Exception as e:
-        logging.debug(f"Error while updating CF! {e}")
-
-
-# Run this function if there is an update in the missing price data in the average yearly price json.
-def updateprice():
-    logging.info("Updating the characterization prices | price")
-    sqlstatement = (
-        "SELECT resource_hscode, year, iso, geopolrisk FROM recordData WHERE "
-        " geopol_cf = 'NA' AND recycling_rate ='0' AND scenario ='0';"
-    )
-    row = execute_query(sqlstatement)
-    df = pd.DataFrame(row, columns=["HS Code", "Year", "Country Alpha", "GeoPolRisk"])
-    logging.debug("Update of database! The shape of df is " + str(df.shape[0]))
-    if df.shape[0] > 0:
-        Year = [int(i) for i in df.Year.to_list()]
-        ISO = [int(i) for i in df["Country Alpha"].tolist()]
-        _HS = [int(i) for i in df["HS Code"].tolist()]
-        GPRS = [float(i) for i in df["GeoPolRisk"].tolist()]
-    else:
-        logging.debug("No updates required!")
-        return None
-    for i, n in enumerate(_HS):
-        AVGPrice = _price[str(Year[i])].tolist()[_price.HS.to_list().index(n)]
-        if isinstance(AVGPrice, (int, float)):
-            index = ISO.index(ISO[i])
-            CF = float(GPRS[index]) * AVGPrice
-            sqlstatement = (
-                "UPDATE recordData SET geopol_cf= '"
-                + str(CF)
-                + "', log_ref='"
-                + str(Filename)
-                + "' WHERE iso = '"
-                + str(ISO[i])
-                + "' AND resource_hscode= '"
-                + str(n)
-                + "' AND year = '"
-                + str(Year[i])
-                + "' AND recycling_rate = '0' AND scenario = '0';"
-            )
-            norow = execute_query(sqlstatement, db_path=db)
-            logging.debug(f"Database update sucessfully! for {n} for {Year[i]}")
+        logging.debug("Error while recording data into dataframe for regional assessment!", e)
+        
\ No newline at end of file
diff --git a/geopolrisk/assessment/utils.py b/geopolrisk/assessment/utils.py
index f7ae520..95f0cf1 100644
--- a/geopolrisk/assessment/utils.py
+++ b/geopolrisk/assessment/utils.py
@@ -1,352 +1,481 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
+# Copyright (C) 2024 University of Bordeaux, CyVi Group & University of Bayreuth,
+# Ecological Resource Technology & Anish Koyamparambath, Christoph Helbig, Thomas Schraml
 # This file is part of geopolrisk-py library.
-#
 # geopolrisk-py is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
-#
 # geopolrisk-py is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
-#
 # You should have received a copy of the GNU General Public License
 # along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
 
-import pandas as pd, json, sqlite3
-import comtradeapicall as ctac
-from urllib.request import Request, urlopen
-from .__init__ import instance, logging, execute_query
+import pandas as pd, os, glob
+from .database import databases, logging, execute_query
 
-# Define Paths
 tradepath = None
-_production, _reporter = instance.production, instance.reporter
-regionslist, _outputfile = instance.regionslist, instance.exportfile
-_price = instance.price
-db = _outputfile + "/" + instance.Output
-# Extract list of all data
-HS = _price.HS.to_list()
-HS = [int(float(x)) for x in HS]
-Resource = _price.Resource.to_list()
-Country = _reporter.Country.to_list()
-ISO = _reporter.ISO.to_list()
-ISO = [int(x) for x in ISO]
-
-
-def convertCodes(resource, country):
-    # Verify direction
-    def check_variables(A, B):
-        if isinstance(A, list) and isinstance(B, list):
-            if all(isinstance(element, str) for element in A) and all(
-                isinstance(element, str) for element in B
-            ):
-                return "numeric"
-            elif all(isinstance(element, int) for element in A) and all(
-                isinstance(element, int) for element in B
-            ):
-                return "text"
-            else:
-                return None
-        elif isinstance(A, str) and isinstance(B, str):
-            return "numeric"
-        elif isinstance(A, int) and isinstance(B, int):
-            return "text"
+db = databases.directory + "/output"
+
+########################################
+##   Utility functions --  GeoPolRisk ##
+########################################
+
+
+def replace_func(x):
+    if isinstance(x, float):
+        return x
+    else:
+        if x is None or isinstance(x, type(None)) or x.strip() == "NA" or x == " ":
+            return 0
         else:
-            return None
-
-    def return_variables(X, A, B):
-        if isinstance(X, list):
-            X_transform = []
-            for i, n in enumerate(X):
-                try:
-                    idx = A.index(n)
-                    X_transform.append(B[idx])
-                except Exception as e:
-                    if n in regionslist.keys():
-                        logging.debug(f"Region transformation cannot be applied!")
-                        X_transform.append(n)
-                    else:
-                        logging.debug(f"Failed to transform! {e}")
-                        logging.debug(f"Transformation failed for {n}")
-                        X_transform = None
-            return X_transform
+            return x
+
+def cvtresource(resource, type="HS"):
+    # Function to convert resource inputs, HS to name or name to HS
+    """
+    Type can be either 'HS' or 'Name'
+    """
+    MapHSdf = databases.production["HS Code Map"]
+    if type == "HS":
+        if resource in MapHSdf["ID"].tolist():
+            return int(MapHSdf.loc[MapHSdf["ID"] == resource, "HS Code"].iloc[0])
         else:
             try:
-                idx = A.index(X)
-                X_transform = B[idx]
+                resource = int(resource)
             except Exception as e:
-                if X in regionslist.keys():
-                    logging.debug(f"Region transformation cannot be applied!")
-                    X_transform = X
-                else:
-                    logging.debug(f"Failed to transform! {e}")
-                    logging.debug(f"Transformation failed for {X}")
-                    X_transform = None
-            return X_transform
-
-    direction = check_variables(resource, country)
-
-    commodity, countryname, HSCode, ISOCode = None, None, None, None
-    if direction.lower() == "numeric":
-        ResourceCX = return_variables(resource, Resource, HS)
-        CountryCX = return_variables(country, Country, ISO)
-        commodity = resource
-        countryname = country
-        HSCode = ResourceCX
-        ISOCode = CountryCX
-    elif direction.lower() == "text":
-        ResourceCX = return_variables(resource, HS, Resource)
-        CountryCX = return_variables(country, ISO, Country)
-        commodity = ResourceCX
-        countryname = CountryCX
-        HSCode = resource
-        ISOCode = country
-    else:
-        logging.debug("Failed to transform!")
-        logging.debug(direction)
-        ResourceCX, CountryCX = resource, country
-    return commodity, countryname, HSCode, ISOCode
-
+                print(f"To HS: Entered raw material {resource} does not exist in our database!")
+                logging.debug(f"To HS: Entered raw material {resource} does not exist in our database!, {e}")
+                raise ValueError
+            if str(resource) in MapHSdf["HS Code"].tolist():
+                return int(resource)
+    elif type == "Name":
+        try:
+            resource = int(resource)
+        except:
+            #print(f"Entered raw material '{resource}' does not exist in our database! Please enter numerical inputs")
+            logging.debug(f"Entered raw material '{resource}' does not exist in our database! Please enter numerical inputs")
+            resource = str(resource)
+        if str(resource) in MapHSdf["HS Code"].astype(str).tolist():
+            return MapHSdf.loc[MapHSdf["HS Code"] == str(resource), "ID"].iloc[0]
+        elif resource in MapHSdf["ID"].tolist():
+            return resource
+        else:
+            print(f"To Name: Entered raw material '{resource}' does not exist in our database!")
+            logging.debug(f"To Name: Entered raw material '{resource}' does not exist in our database!")
+            raise ValueError
 
-def callapirequest(period, country, commoditycode):
-    period = str(period)
-    country = str(country)
-    commoditycode = str(commoditycode)
-    try:
-        get = ctac.previewTarifflineData(
-            typeCode="C",
-            freqCode="A",
-            clCode="HS",
-            period=period,
-            reporterCode=country,
-            cmdCode=commoditycode,
-            flowCode="M",
-            partnerCode=None,
-            partner2Code=None,
-            customsCode=None,
-            motCode=None,
-            maxRecords=500,
-            format_output="JSON",
-            countOnly=None,
-            includeDesc=True,
-        )
-    except Exception as e:
-        logging.debug(f"Error while calling API! {e}")
-        return None, None
-    try:
-        if get is not None or not isinstance(get, type(None)) or len(get) == 0:
-            get["Qty"] = get.groupby(["partnerCode"])["qty"].transform(sum)
-            get["CifValue"] = get.groupby(["partnerCode"])["cifvalue"].transform(sum)
-            get = get.drop_duplicates(subset="partnerCode", keep="first")
+def cvtcountry(country, type="ISO"):
+    # Function to convert country inputs, ISO to name or name to ISO
+    """
+    Type can be either 'ISO' or 'Name'
+    """
+    MapISOdf = databases.production["Country_ISO"]
+    if type == "ISO":
+        if country in MapISOdf["Country"].tolist():
+            return MapISOdf.loc[MapISOdf["Country"] == country, "ISO"].iloc[0]
+        elif databases.regional == True and country in databases.regionslist:
+            return country
+        else:
             try:
-                cifvalueToT = sum(get["CifValue"].to_list())
-                totalQ = sum(get["Qty"].to_list())
-                if totalQ == 0:
-                    pricecif = 0
-                else:
-                    pricecif = cifvalueToT / totalQ
+                country = int(country)
             except Exception as e:
-                logging.debug(f"Error while extracting cifvalue! {e}")
-                get, pricecif = None, None
+                print(f"To ISO: Entered country '{country}' does not exist in our database!")
+                logging.debug(f"To ISO: Entered country '{country}' does not exist in our database!, {e}")
+                raise ValueError
+            if country in MapISOdf["ISO"].astype(int).tolist():
+                return country
+    elif type == "Name":
+        try:
+            country = int(country)
+        except:
+            #print(f"Entered country '{country}' does not exist in our database! Please enter numerical inputs")
+            logging.debug(f"Entered country '{country}' does not exist in our database! Please enter numerical inputs")
+            country = str(country)
+        if country in MapISOdf["ISO"].astype(int).tolist():
+            return MapISOdf.loc[MapISOdf["ISO"] == country, "Country"].iloc[0]
+        elif country in MapISOdf["Country"].tolist():
+            return country
+        elif databases.regional == True and country in databases.regionslist:
+            return country
         else:
-            logging.debug(f"Problem with the new API call! {get}")
-            get, pricecif = None, None
-    except Exception as e:
-        logging.debug(f"Error while extracting and combining data! {e}")
-        get, pricecif = None, None
-    return get, pricecif
+            print(f"To Name: Entered country '{country}' does not exist in our database!")
+            logging.debug(f"To Name: Entered country '{country}' does not exist in our database!")
+            raise ValueError
+        
 
+def sumproduct(A: list, B: list):
+    return sum(i * j for i, j in zip(A, B))
 
-def oldapirequest(period, country, commoditycode):
-    period = str(period)
-    country = str(country)
-    commoditycode = str(commoditycode)
-    url = f"""https://comtrade.un.org/api/get?max=50000&type=C&freq=A&px=HS&ps={period}&r={country}&p=all&cc={commoditycode}&rg=1&fmt=json"""
-    logging.info(url)
-    try:
-        request = Request(url)
-        response = urlopen(request)
-        elevations = response.read()
-    except Exception as e:
-        logging.debug(url)
-        logging.debug(f"Error while calling native API! {e}")
-        return None
 
-    try:
-        data = json.loads(elevations)
-        data = pd.json_normalize(data["dataset"])
-    except Exception as e:
-        logging.debug("Error while parsing JSON!")
-        return None
+def create_id(HS, ISO, Year):
+    return str(HS) + str(ISO) + str(Year)
 
-    return data
+# 2024-08-23 - this function is not being used - deleted
+# Verify if the calculation is already stored in the database to avoid recalculation
+# def sqlverify(DBID):
+#     try:
+#         sql = f"SELECT * FROM recordData WHERE id = '{DBID}';"
+#         row = execute_query(
+#             f"SELECT * FROM recordData WHERE id = '{DBID}';",
+#             db_path=db,
+#         )
+#     except Exception as e:
+#         logging.debug(f"Database error in sqlverify - {e}, {sql}")
+#         row = None
+#     if not row:
+#         return False
+#     else:
+#         return True
 
+def createresultsdf():
+    dbpath = databases.directory + "/output/" + databases.Output
 
-def replace_values(list_to_replace, item_to_replace, item_to_replace_with):
-    return [
-        item_to_replace_with if item == item_to_replace else item
-        for item in list_to_replace
+    # Columns for the dataframe
+    Columns = [
+        "DBID",
+        "Country [Economic Entity]",
+        "Raw Material",
+        "Year",
+        "GeoPolRisk Score",
+        "GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]",
+        "HHI",
+        "Import Risk",
+        "Price",
     ]
+    df = pd.DataFrame(columns=Columns)
+    SQLQuery = """CREATE TABLE IF NOT EXISTS "recordData" (
+            "DBID"	TEXT,
+        	"Country [Economic Entity]"	TEXT,
+        	"Raw Material"	TEXT,
+        	"Year"	INTEGER,
+        	"GeoPolRisk Score"	REAL,
+        	"GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]"	REAL,
+        	"HHI"	REAL,
+        	"Import Risk" REAL,
+        	"Price"	INTEGER,
+        	PRIMARY KEY("DBID")
+        );"""
+    row = execute_query(
+        SQLQuery,
+        db_path=dbpath,
+    )
+    return df
 
+def writetodb(dataframe):
+    dbpath = databases.directory + "/output/" + databases.Output
+    for index, row in dataframe.iterrows():
+        check_query = "SELECT 1 FROM recordData WHERE DBID = ?;"
+        exists = execute_query(check_query, db_path=dbpath, params=(row['DBID'],))
 
-def create_id(HS, ISO, Year):
-    HS, ISO, Year = str(HS), str(ISO), str(Year)
-    if len(HS) == 4:
-        HSID = "xx" + HS
-    elif len(HS) == 5:
-        HSID = "x" + HS
-    else:
-        HSID = HS
-    if len(ISO) == 2:
-        ISOID = "x" + ISO
-    elif len(ISO) == 1:
-        ISOID = "xx" + ISO
-    else:
-        ISOID = ISO
-    DBID = HSID + ISOID + Year
-    return DBID
+        if exists:
+            update_query = '''
+                UPDATE recordData
+                SET 
+                    "Country [Economic Entity]" = ?,
+                    "Raw Material" = ?,
+                    Year = ?,
+                    "GeoPolRisk Score" = ?,
+                    "GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]" = ?,
+                    HHI = ?,
+                    "Import Risk" = ?,
+                    Price = ?
+                WHERE DBID = ?;
+            '''
+            params = (
+                row['Country [Economic Entity]'],
+                row['Raw Material'],
+                row['Year'],
+                row['GeoPolRisk Score'],
+                row['GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]'],
+                row['HHI'],
+                row['Import Risk'],
+                row['Price'],
+                row['DBID']
+            )
+            try:
+                execute_query(update_query, db_path=dbpath, params=params)
+            except Exception as e:
+                print("Failed to write to output database, Check logs!")
+                logging.debug(f"Failed to write to output database - Update Query - Dataframe index = {index} | Error = {e}")
+        else:
+            insert_query = '''
+                INSERT INTO recordData (
+                    DBID,
+                    "Country [Economic Entity]",
+                    "Raw Material",
+                    Year,
+                    "GeoPolRisk Score",
+                    "GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]",
+                    HHI,
+                    "Import Risk",
+                    Price
+                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
+            '''
+            params = (
+                row['DBID'],
+                row['Country [Economic Entity]'],
+                row['Raw Material'],
+                row['Year'],
+                row['GeoPolRisk Score'],
+                row['GeoPolRisk Characterization Factor [eq. Kg-Cu/Kg]'],
+                row['HHI'],
+                row['Import Risk'],
+                row['Price']
+            )
+            try:
+                execute_query(insert_query, db_path=dbpath, params=params)
+            except Exception as e:
+                print("Failed to write to output database, Check logs!")
+                logging.debug(f"Failed to write to output database - Insert Query - Dataframe index = {index} | Error = {e}")
 
 
-# Verify if the calculation is already stored in the database to avoid recalculation
-def sqlverify(DBID):
-    try:
-        sql = f"SELECT * FROM recordData WHERE id = '{DBID}';"
-        row = execute_query(
-            f"SELECT * FROM recordData WHERE id = '{DBID}';",
-            db_path=db,
-        )
 
-    except Exception as e:
-        logging.debug(f"Database error in sqlverify - {e}, {sql}")
-        row = None
-    if not row:
-        return False
-    else:
-        return True
+###################################################
+##   Extrade trade data functions --  GeoPolRisk ##
+###################################################
 
 
-# This function doesnt override the calculaiton
-def recordData(
-    Resource, Country, Year, RR, Scenario, GPRS, CF, HHI, WTA, LogFile, OuputList
+def getbacidata(
+    period: float, country: float, commoditycode: float, data=databases.baci_trade
 ):
-    resource, country, HSCODE, ISO = convertCodes(Resource, Country)
-    DBID = create_id(HSCODE, ISO, Year)
-    if sqlverify(DBID) is True:
-        sqlstatement = f"""SELECT 'recycling_rate' ,'scenario', 'geopolrisk'
-        FROM recordData WHERE id = '{DBID}';
-        """
-        try:
-            row = execute_query(sqlstatement, db_path=db)
-        except Exception as e:
-            logging.debug(f"Failed to execute statement {e} with {sqlstatement}")
-        if str(row[0][0]) == str(RR) and str(row[0][1]) == str(Scenario):
-            if str(row[0][2]) != str(GPRS):
-                sqlstatement = f"""UPDATE recordData SET hhi =
-                '{HHI}', wta = '{WTA}', geopolrisk = '{GPRS}', geopol_cf = '{CF}',
-                log_ref = '{LogFile}'
-                """
-                try:
-                    row = execute_query(sqlstatement, db_path=db)
-                except Exception as e:
-                    logging.debug(
-                        f"Failed to execute statement {e} with {sqlstatement}"
-                    )
-                OuputList.append(
-                    str(Year),
-                    str(resource),
-                    str(country),
-                    str(RR),
-                    str(Scenario),
-                    str(GPRS),
-                    str(CF),
-                    str(HHI),
-                    str(WTA),
-                )
+    """
+    get the baci-trade-data from the baci_trade dataframe
+    """
+    period = str(period)
+    country = str(country)
+    commoditycode = str(commoditycode)
+    df_query = f"(period == '{period}') & (reporterCode == '{country}') & (cmdCode == '{commoditycode}')"
+    baci_data = data.query(df_query)
+    """
+    The dataframe is structured as follows:
+    'period' -> The year of the trade recorded
+    'reporterCode' -> The ISO 3 digit code of the reporting country
+    'reporterISO' -> The ISO code of the reporting country
+    'reporterDesc' -> The name of the reporting country
+    'partnerCode' -> The ISO 3 digit code of the partner country
+    'partnerISO' -> The ISO code of the partner country
+    'partnerDesc' -> The name of the partner country
+    'cmdCode' -> The 6 digit commodity code (HS92)
+    'qty' -> The trade quantity in 1000 kilograms
+    'cifvalue' -> The value of the traded quantity in 1000 USD
+    'partnerWGI' -> The WGI political stability and absence of violence indicator (Normalized) for the partner country
+    """
+    baci_data.loc[:, "qty"] = baci_data["qty"].apply(replace_func).astype(float)
+    baci_data.loc[:, "cifvalue"] = baci_data["cifvalue"].apply(replace_func).astype(float)
+    if baci_data is None or isinstance(baci_data, type(None)) or len(baci_data) == 0:
+        logging.debug(
+            f"Problem with get the baci-data - {baci_data} - period == '{period}') - reporterCode == '{country}' - cmdCode == '{commoditycode}'"
+        )
+        baci_data = None
+    return baci_data
+
+
+def aggregateTrade(
+    period: float, country: list, commoditycode: float, data=databases.baci_trade
+):
+    """
+    The function is only to aggregate the trade for each partner country in the region.
+    """
+    def wgi_func(x):
+        if isinstance(x, float):
+            return x
+        else:
+            if x is None or isinstance(x, type(None)) or x.strip() == "NA":
+                return 0.5
             else:
-                logging.info("The database already exists with the data")
+                return x
+    SUMQTY, SUMVAL, SUMNUM = [], [], []
+    for i, n in enumerate(country):
+        baci_data = getbacidata(
+            period, cvtcountry(n, type="ISO"), commoditycode, data=data
+        )
+        if baci_data is None:
+            QTY, WGI, VAL = [0], [0], [0]
         else:
-            sqlstatement = f""" INSERT INTO recordData (id, country, resource, year,
-            recycling_rate, scenario, geopolrisk, hhi, wta, geopol_cf, resource_hscode, 
-            iso, log_ref) VALUES ('{DBID}','{country}', '{resource}', '{Year}',
-            '{RR}', '{Scenario}', '{GPRS}', '{HHI}', '{WTA}', '{CF}', '{HSCODE}',
-            '{ISO}', '{LogFile}');
-            """
-            try:
-                row = execute_query(sqlstatement, db_path=db)
-            except Exception as e:
-                logging.debug(f"Failed to execute statement {e} with {sqlstatement}")
-            OuputList.append(
-                [
-                    str(Year),
-                    str(resource),
-                    str(country),
-                    str(RR),
-                    str(Scenario),
-                    str(GPRS),
-                    str(CF),
-                    str(HHI),
-                    str(WTA),
-                ]
-            )
-    else:
-        sqlstatement = f""" INSERT INTO recordData (id, country, resource, year,
-            recycling_rate, scenario, geopolrisk, hhi, wta, geopol_cf, resource_hscode, 
-            iso, log_ref) VALUES ('{DBID}','{country}', '{resource}', '{Year}',
-            '{RR}', '{Scenario}', '{GPRS}', '{HHI}', '{WTA}', '{CF}', '{HSCODE}',
-            '{ISO}', '{LogFile}');
-            """
+            QTY = baci_data["qty"].tolist()
+            WGI = baci_data["partnerWGI"].apply(wgi_func).astype(float).tolist()
+            VAL = baci_data["cifvalue"].tolist()
+        SUMQTY.append(sum(QTY))
+        SUMVAL.append(sum(VAL))
+        SUMNUM.append(sumproduct(QTY, WGI))
+
+    Price = sum(SUMVAL) / sum(SUMQTY)
+    """
+    The function returns the numerator of the import risk, 
+    The total trade for the region,
+    The price calculated with the total value for all the countries in the region &
+    the total quantity traded with the countries in the region.
+    """
+    return sum(SUMNUM), sum(SUMQTY), Price
+
+
+###########################################################
+## Converting company trade data into a usable dataframe ##
+###########################################################
+
+
+def transformdata(mode="prod"):
+    folder_path = databases.directory + "/databases"
+    file_name = "Company data.xlsx"
+    excel_sheet_name = "Template"
+    # file_path = glob.glob(os.path.join(folder_path, file_name))[0]
+    file_path = os.path.join(folder_path, file_name)
+    # in test-mode - use the excel-file from the test-folder
+    if "test" in mode:
+        test_dir = os.path.abspath("./geopolrisk/tests/")
+        file_path = f"{test_dir}/{file_name}"
+        excel_sheet_name = "Test"
+    """
+    The template excel file has the following headers
+    'Metal': Specify the type of metal.
+    'Country of Origin': Indicate the country where the metal was sourced.
+    'Quantity (kg)': Enter the quantity of metal imported from each country.
+    'Value (USD)': Value of the metal of the quantity imported.
+    'Year': The year of the trade
+    'Additional Notes': Include any additional relevant information.
+    """
+    Data = pd.read_excel(file_path, sheet_name=excel_sheet_name)
+    HS_Code = []
+    for resource in Data["Metal"].tolist():
+        HS_Code.append(cvtresource(resource, type="HS"))
+    ISO = []
+    for country in Data["Country of Origin"].tolist():
+        ISO.append(cvtcountry(country, type="ISO"))
+    MapWGIdf = databases.wgi
+    wgi = []
+    for i, iso in enumerate(ISO):
         try:
-            row = execute_query(sqlstatement, db_path=db)
-        except Exception as e:
-            logging.debug(f"Failed to execute statement {e} with {sqlstatement}")
-        OuputList.append(
-            [
-                str(Year),
-                str(resource),
-                str(country),
-                str(RR),
-                str(Scenario),
-                str(GPRS),
-                str(CF),
-                str(HHI),
-                str(WTA),
-            ]
+            wgi.append(
+                # MapWGIdf.loc[MapWGIdf["country_code"] == iso, Data["Year"].tolist()[i]]
+                float(MapWGIdf.query(f'country_code == "{iso}"')[str(Data["Year"].tolist()[i])].iloc[0])
+            )
+        except:
+            print("The entered year is not available in our database!")
+            logging.debug(f"Error while fetching the wgi, the ISO is {iso}")
+    try:
+        Data["Quantity (kg)"] = [
+            float(x) * 1000 for x in Data["Quantity (kg)"].tolist()
+        ]
+    except:
+        print(
+            "Error in converting values to float, check the formatting in the Template"
         )
+        logging.debug("Excel file not formatted correctly! numerical must be numbers")
+        raise ValueError
+    try:
+        Data["Value (USD)"] = [float(x) * 1000 for x in Data["Value (USD)"].to_list()]
+    except:
+        print(
+            "Error in converting values to float, check the formatting in the Template"
+        )
+        logging.debug("Excel file not formatted correctly! numerical must be numbers")
+        raise ValueError
+    Data["partnerISO"] = ISO
+    Data["partnerWGI"] = wgi
+    Data["cmdCode"] = HS_Code
+    Data["reporterDesc"] = ["Company"] * len(ISO)
+    Data["reporterISO"] = [999] * len(ISO)
+
+    Data.columns = [
+        "Commodity",
+        "partnerDesc",
+        "qty",
+        "cifvalue",
+        "period",
+        "Notes",
+        "partnerISO",
+        "partnerWGI",
+        "cmdCode",
+        "reporterDesc",
+        "reporterISO",
+    ]
+    return Data
+
 
+########################################################
+##   Extrade production data functions --  GeoPolRisk ##
+########################################################
 
-"""Convert entire database to required format
-**CHARACTERIZATION FACTORS
-Refer to python json documentation for more information on types of
-orientation required for the output.
-"""
 
-# Extract CFs
-def generateCF(exportType="csv", orient=""):
-    exportF = ["csv", "excel", "json"]
-    if exportType in exportF:
-        logging.debug("Exporting database in the format {}".format(exportType))
-        CFType = exportType
+def getProd(resource):
+    """
+    The dictionary have a unique identifier that is accessed through a table called 'HS Code Map'
+    The mapping table has the following structure
+    'Sheet_name' -> The name of the table corresponding to the raw material
+    'Category - WMD' -> The world mining data categorization of the raw material
+    'ID' -> The name of the raw material (metals and minerals)
+    'HS Code' -> The HS Code mapping of raw material
+    'Description' -> The description of the HS code
+    'Symbol' -> Element equivalent to the raw material
+    """
+    Mapdf = databases.production["HS Code Map"]
+    if resource in Mapdf["ID"].tolist():
+        MappedTableName = Mapdf.loc[Mapdf["ID"] == resource, "Sheet_name"]
+    elif str(resource) in Mapdf["HS Code"].tolist() and resource != "Not Available":
+        MappedTableName = Mapdf.loc[Mapdf["HS Code"] == str(resource), "Sheet_name"]
     else:
+        print("Entered raw material does not exist in our database!")
         logging.debug(
-            "Exporting format not supported {}. "
-            "Using default format [csv]".format(exportType)
+            f"Error while fetching raw material. Entered raw material = {resource}"
         )
-        CFType = "csv"
-    try:
-        conn = sqlite3.connect(
-            db,
-            isolation_level=None,
-            detect_types=sqlite3.PARSE_COLNAMES,
-        )
-        db_df = pd.read_sql_query("SELECT * FROM recorddata", conn)
-        if CFType == "csv":
-            db_df.to_csv(_outputfile + "/database.csv", index=False, encoding="utf-8")
-        elif CFType == "excel":
-            db_df.to_excel(
-                _outputfile + "/database.xlsx", index=False, encoding="utf-8"
-            )
-        elif CFType == "json":
-            db_df.to_json(_outputfile + "/database.json", orient=orient, index=False)
-    except Exception as e:
-        logging.debug(f"Error while exporting database! {e}")
+        raise ValueError
+    
+    """
+    The returned dataframe is mapped based on the input resource.
+    The output dataframe has the following structure.
+    'Country' -> The country name, according to the BACI
+    'Country_Code' -> The numeric ISO country code
+    'Country_ISO' -> The ISO code of the country
+    '2018', '2019', '2020', '2021', '2022' -> The production quantity of each raw material
+    'unit' -> The units of the value
+    'data_source' -> The data source of each value point
+    """
+ 
+    result = databases.production[MappedTableName.iloc[0]]
+    return result
+
+
+########################################################
+##   Define multiple regions --  GeoPolRisk ##
+########################################################
+
+
+def regions(*args):
+    trackregion = 0
+    if len(args) != 0:
+        for key, value in args[0].items():
+            if type(key) is not str and type(value) is not list:
+                logging.debug(
+                    "Dictionary input to regions does not match required type."
+                )
+                return None
+            Print_Error = [
+                x
+                for x in value
+                if str(x) not in databases.production["Country_ISO"]["Country"].tolist()
+                and str(x)
+                not in databases.production["Country_ISO"]["ISO"].astype(str).tolist()
+            ]
+            if len(Print_Error) != 0:
+                logging.debug(
+                    "Error in creating a region! "
+                    "Following list of countries not"
+                    " found in the ISO list {}. "
+                    "Please conform with the ISO list or use"
+                    " 3 digit ISO country codes.".format(Print_Error)
+                )
+                return None
+            else:
+                trackregion += 1
+                databases.regionslist[key] = value
+    if trackregion > 0:
+        databases.regional = True
+    # The function must be called before calling any other functions in the core
+    # module. The following lines populate the region list with all the countries
+    # in the world including EU defined in the init file.
+    for i in databases.production["Country_ISO"]["Country"].tolist():
+        if i in databases.regionslist.keys():
+            logging.debug("Country or region already exists cannot overwrite.")
+        databases.regionslist[i] = [i]
diff --git a/geopolrisk/lib/Library.db b/geopolrisk/lib/Library.db
deleted file mode 100644
index 9ff8b3c..0000000
Binary files a/geopolrisk/lib/Library.db and /dev/null differ
diff --git a/geopolrisk/lib/baci.db b/geopolrisk/lib/baci.db
new file mode 100644
index 0000000..97f5cce
Binary files /dev/null and b/geopolrisk/lib/baci.db differ
diff --git a/geopolrisk/lib/wgi.db b/geopolrisk/lib/wgi.db
new file mode 100644
index 0000000..4582c73
Binary files /dev/null and b/geopolrisk/lib/wgi.db differ
diff --git a/geopolrisk/lib/world_mining_data.db b/geopolrisk/lib/world_mining_data.db
new file mode 100644
index 0000000..7bb4491
Binary files /dev/null and b/geopolrisk/lib/world_mining_data.db differ
diff --git a/gpl-3.0.md b/gpl-3.0.md
new file mode 100644
index 0000000..496acdb
--- /dev/null
+++ b/gpl-3.0.md
@@ -0,0 +1,675 @@
+# GNU GENERAL PUBLIC LICENSE
+
+Version 3, 29 June 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc.
+<https://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+## Preamble
+
+The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom
+to share and change all versions of a program--to make sure it remains
+free software for all its users. We, the Free Software Foundation, use
+the GNU General Public License for most of our software; it applies
+also to any other work released this way by its authors. You can apply
+it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you
+have certain responsibilities if you distribute copies of the
+software, or if you modify it: responsibilities to respect the freedom
+of others.
+
+For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the
+manufacturer can do so. This is fundamentally incompatible with the
+aim of protecting users' freedom to change the software. The
+systematic pattern of such abuse occurs in the area of products for
+individuals to use, which is precisely where it is most unacceptable.
+Therefore, we have designed this version of the GPL to prohibit the
+practice for those products. If such problems arise substantially in
+other domains, we stand ready to extend this provision to those
+domains in future versions of the GPL, as needed to protect the
+freedom of users.
+
+Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish
+to avoid the special danger that patents applied to a free program
+could make it effectively proprietary. To prevent this, the GPL
+assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+## TERMS AND CONDITIONS
+
+### 0. Definitions.
+
+"This License" refers to version 3 of the GNU General Public License.
+
+"Copyright" also means copyright-like laws that apply to other kinds
+of works, such as semiconductor masks.
+
+"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of
+an exact copy. The resulting work is called a "modified version" of
+the earlier work or a work "based on" the earlier work.
+
+A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user
+through a computer network, with no transfer of a copy, is not
+conveying.
+
+An interactive user interface displays "Appropriate Legal Notices" to
+the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+### 1. Source Code.
+
+The "source code" for a work means the preferred form of the work for
+making modifications to it. "Object code" means any non-source form of
+a work.
+
+A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can
+regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same
+work.
+
+### 2. Basic Permissions.
+
+All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey,
+without conditions so long as your license otherwise remains in force.
+You may convey covered works to others for the sole purpose of having
+them make modifications exclusively for you, or provide you with
+facilities for running those works, provided that you comply with the
+terms of this License in conveying all material for which you do not
+control copyright. Those thus making or running the covered works for
+you must do so exclusively on your behalf, under your direction and
+control, on terms that prohibit them from making any copies of your
+copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the
+conditions stated below. Sublicensing is not allowed; section 10 makes
+it unnecessary.
+
+### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such
+circumvention is effected by exercising rights under this License with
+respect to the covered work, and you disclaim any intention to limit
+operation or modification of the work as a means of enforcing, against
+the work's users, your or third parties' legal rights to forbid
+circumvention of technological measures.
+
+### 4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+### 5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these
+conditions:
+
+-   a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+-   b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under
+    section 7. This requirement modifies the requirement in section 4
+    to "keep intact all notices".
+-   c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy. This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged. This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+-   d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+### 6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms of
+sections 4 and 5, provided that you also convey the machine-readable
+Corresponding Source under the terms of this License, in one of these
+ways:
+
+-   a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+-   b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the Corresponding
+    Source from a network server at no charge.
+-   c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source. This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+-   d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge. You need not require recipients to copy the
+    Corresponding Source along with the object code. If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source. Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+-   e) Convey the object code using peer-to-peer transmission,
+    provided you inform other peers where the object code and
+    Corresponding Source of the work are being offered to the general
+    public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal,
+family, or household purposes, or (2) anything designed or sold for
+incorporation into a dwelling. In determining whether a product is a
+consumer product, doubtful cases shall be resolved in favor of
+coverage. For a particular product received by a particular user,
+"normally used" refers to a typical or common use of that class of
+product, regardless of the status of the particular user or of the way
+in which the particular user actually uses, or expects or is expected
+to use, the product. A product is a consumer product regardless of
+whether the product has substantial commercial, industrial or
+non-consumer uses, unless such uses represent the only significant
+mode of use of the product.
+
+"Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to
+install and execute modified versions of a covered work in that User
+Product from a modified version of its Corresponding Source. The
+information must suffice to ensure that the continued functioning of
+the modified object code is in no case prevented or interfered with
+solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or
+updates for a work that has been modified or installed by the
+recipient, or for the User Product in which it has been modified or
+installed. Access to a network may be denied when the modification
+itself materially and adversely affects the operation of the network
+or violates the rules and protocols for communication across the
+network.
+
+Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+### 7. Additional Terms.
+
+"Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders
+of that material) supplement the terms of this License with terms:
+
+-   a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+-   b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+-   c) Prohibiting misrepresentation of the origin of that material,
+    or requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+-   d) Limiting the use for publicity purposes of names of licensors
+    or authors of the material; or
+-   e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+-   f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions
+    of it) with contractual assumptions of liability to the recipient,
+    for any liability that these contractual assumptions directly
+    impose on those licensors and authors.
+
+All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions; the
+above requirements apply either way.
+
+### 8. Termination.
+
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+However, if you cease all violation of this License, then your license
+from a particular copyright holder is reinstated (a) provisionally,
+unless and until the copyright holder explicitly and finally
+terminates your license, and (b) permanently, if the copyright holder
+fails to notify you of the violation by some reasonable means prior to
+60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+### 9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or run
+a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+### 10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+### 11. Patents.
+
+A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+A contributor's "essential patent claims" are all patent claims owned
+or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+A patent license is "discriminatory" if it does not include within the
+scope of its coverage, prohibits the exercise of, or is conditioned on
+the non-exercise of one or more of the rights that are specifically
+granted under this License. You may not convey a covered work if you
+are a party to an arrangement with a third party that is in the
+business of distributing software, under which you make payment to the
+third party based on the extent of your activity of conveying the
+work, and under which the third party grants, to any of the parties
+who would receive the covered work from you, a discriminatory patent
+license (a) in connection with copies of the covered work conveyed by
+you (or copies made from those copies), or (b) primarily for and in
+connection with specific products or compilations that contain the
+covered work, unless you entered into that arrangement, or that patent
+license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+### 12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under
+this License and any other pertinent obligations, then as a
+consequence you may not convey it at all. For example, if you agree to
+terms that obligate you to collect a royalty for further conveying
+from those to whom you convey the Program, the only way you could
+satisfy both those terms and this License would be to refrain entirely
+from conveying the Program.
+
+### 13. Use with the GNU Affero General Public License.
+
+Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+### 14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions
+of the GNU General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in
+detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies that a certain numbered version of the GNU General Public
+License "or any later version" applies to it, you have the option of
+following the terms and conditions either of that numbered version or
+of any later version published by the Free Software Foundation. If the
+Program does not specify a version number of the GNU General Public
+License, you may choose any version ever published by the Free
+Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions
+of the GNU General Public License can be used, that proxy's public
+statement of acceptance of a version permanently authorizes you to
+choose that version for the Program.
+
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+### 15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
+WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
+PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
+DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
+CORRECTION.
+
+### 16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
+CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
+NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
+LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
+TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
+PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+### 17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+## How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these
+terms.
+
+To do so, attach the following notices to the program. It is safest to
+attach them to the start of each source file to most effectively state
+the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+        <one line to give the program's name and a brief idea of what it does.>
+        Copyright (C) <year>  <name of author>
+
+        This program is free software: you can redistribute it and/or modify
+        it under the terms of the GNU General Public License as published by
+        the Free Software Foundation, either version 3 of the License, or
+        (at your option) any later version.
+
+        This program is distributed in the hope that it will be useful,
+        but WITHOUT ANY WARRANTY; without even the implied warranty of
+        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+        GNU General Public License for more details.
+
+        You should have received a copy of the GNU General Public License
+        along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper
+mail.
+
+If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+        <program>  Copyright (C) <year>  <name of author>
+        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+        This is free software, and you are welcome to redistribute it
+        under certain conditions; type `show c' for details.
+
+The hypothetical commands \`show w' and \`show c' should show the
+appropriate parts of the General Public License. Of course, your
+program's commands might be different; for a GUI interface, you would
+use an "about box".
+
+You should also get your employer (if you work as a programmer) or
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. For more information on this, and how to apply and follow
+the GNU GPL, see <https://www.gnu.org/licenses/>.
+
+The GNU General Public License does not permit incorporating your
+program into proprietary programs. If your program is a subroutine
+library, you may consider it more useful to permit linking proprietary
+applications with the library. If this is what you want to do, use the
+GNU Lesser General Public License instead of this License. But first,
+please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/paper.bib b/paper.bib
new file mode 100644
index 0000000..c1d3e2e
--- /dev/null
+++ b/paper.bib
@@ -0,0 +1,215 @@
+@article{Ciroth2016,
+author = {Ciroth, Andreas and Muller, St{\'{e}}phanie and Weidema, Bo and Lesage, Pascal},
+doi = {10.1007/s11367-013-0670-5},
+journal = {International Journal of Life Cycle Assessment},
+title = {{Empirically based uncertainty factors for the pedigree matrix in ecoinvent}},
+year = {2016}
+}
+@article{Rhoades1993TheHI,
+author = {Rhoades, Stephen A},
+journal = {Federal Reserve Bulletin},
+pages = {188--189},
+title = {{The Herfindahl-Hirschman index}},
+url = {https://api.semanticscholar.org/CorpusID:153018440},
+year = {1993}
+}
+@misc{cepii_baci_2024,
+annote = {BACI is distributed under the Etalab Open Licence 2.0, which means that any use is authorized, provided the source is mentioned. Mentioning BACI and the CEPII is an appropriate reference, ideally with a link to the webpage.},
+author = {CEPII},
+institution = {CEPII},
+title = {{BACI: International Trade Database at the Product-Level}},
+url = {https://www.cepii.fr/cepii/en/bdd_modele/bdd_modele_item.asp?id=37},
+urldate = {2024-09-20},
+year = {2024}
+}
+@article{Cimprich2019,
+author = {Cimprich, Alexander and Bach, Vanessa and Helbig, Christoph and Thorenz, Andrea and Schrijvers, Dieuwertje and Sonnemann, Guido and Young, Steven B. and Sonderegger, Thomas and Berger, Markus},
+doi = {10.1111/jiec.12865},
+journal = {Journal of Industrial Ecology},
+keywords = {critical raw materials,industrial ecology,life cycle assessment,life cycle sustainability assessment,raw material criticality assessment,supply risk},
+number = {5},
+pages = {1226--1236},
+title = {{Raw material criticality assessment as a complement to environmental life cycle assessment: Examining methods for product-level supply risk assessment}},
+volume = {23},
+year = {2019}
+}
+@article{Hackenhaar2022,
+author = {Hackenhaar, Isadora and Alvarenga, Rodrigo A.F. and Bachmann, Till M. and Riva, Federico and Horn, Rafael and Graf, Roberta and Dewulf, Jo},
+doi = {10.1016/j.procir.2022.02.071},
+issn = {22128271},
+journal = {Procedia CIRP},
+keywords = {"Criticality assessment","Life Cycle Sustainability Assessment","raw materials","supply risk",Criticality assessment,Life Cycle Sustainability Assessment,criticality,raw materials,supply risk},
+number = {March},
+pages = {428--433},
+publisher = {Elsevier B.V.},
+title = {{A critical review of criticality methods for a European Life Cycle Sustainability Assessment}},
+url = {https://doi.org/10.1016/j.procir.2022.02.071},
+volume = {105},
+year = {2022}
+}
+@article{Santillan-Saldivar2022,
+author = {Santill{\'{a}}n-Saldivar, Jair and Gemechu, Eskinder and Muller, St{\'{e}}phanie and Villeneuve, Jacques and Young, Steven B. and Sonnemann, Guido},
+doi = {10.1007/s11367-022-02027-y},
+isbn = {1136702202},
+issn = {0948-3349},
+journal = {The International Journal of Life Cycle Assessment},
+keywords = {Geopolitical supply risk,Life cycle impact assessment,Lithium-ion batteries,Raw material criticality,geopolitical supply risk,life cycle impact assessment,lithium-ion batteries,matthias finkbeiner,raw material criticality,responsible editor},
+number = {3},
+pages = {457--468},
+publisher = {Springer Berlin Heidelberg},
+title = {{An improved resource midpoint characterization method for supply risk of resources: integrated assessment of Li-ion batteries}},
+url = {https://doi.org/10.1007/s11367-022-02027-y},
+volume = {27},
+year = {2022}
+}
+@article{Mutel2017,
+author = {Mutel, Chris},
+doi = {10.21105/joss.00236},
+number = {12},
+pages = {236},
+title = {{Brightway: An open source framework for Life Cycle Assessment}},
+volume = {2},
+year = {2017}
+}
+@misc{FMRA2023,
+author = {FMRA},
+title = {{Federal ministry republic of Austria}},
+url = {https://www.bmf.gv.at/en.html},
+urldate = {2023-05-05},
+year = {2023}
+}
+@article{Siddhantakar2023,
+author = {Siddhantakar, Ankesh and Santill{\'{a}}n‐Saldivar, Jair and Kippes, Thomas and Sonnemann, Guido and Reller, Armin and Young, Steven B},
+doi = {10.1016/j.resconrec.2023.106935},
+journal = {Resources, Conservation & Recycling},
+number = {September 2022},
+title = {{Helium resource global supply and demand : Geopolitical supply risk analysis}},
+volume = {193},
+year = {2023}
+}
+@article{Koyamparambath2021,
+author = {Koyamparambath, Anish and Santillan-Saldivar, Jair and Mclellan, Benjamin and Sonnemann, Guido},
+doi = {10.1016/j.resourpol.2021.102465},
+journal = {Resources Policy},
+keywords = {Critical raw materials,Energy security,Energy storage,Geopolitical supply risk,Timelines},
+title = {{Supply risk evolution of raw materials for batteries and fossil fuels for selected OECD countries ( 2000 – 2018 )}},
+volume = {75},
+year = {2021}
+}
+@article{Sonnemann2015,
+author = {Sonnemann, Guido and Gemechu, Eskinder Demisse and Adibi, Naeem and {De Bruille}, Vincent and Bulle, C{\'{e}}cile},
+doi = {10.1016/j.jclepro.2015.01.082},
+issn = {09596526},
+journal = {Journal of Cleaner Production},
+keywords = {Areas of Protection,Criticality,Life Cycle Assessment,Natural resources,Sustainability},
+pages = {20--34},
+title = {{From a critical review to a conceptual framework for integrating the criticality of resources into Life Cycle Sustainability Assessment}},
+volume = {94},
+year = {2015}
+}
+@article{Schrijvers2020,
+author = {Schrijvers, Dieuwertje and Hool, Alessandra and Blengini, Gian Andrea and Chen, Wei Qiang and Dewulf, Jo and Eggert, Roderick and van Ellen, Layla and Gauss, Roland and Goddin, James and Habib, Komal and Hagel{\"{u}}ken, Christian and Hirohata, Atsufumi and Hofmann-Amtenbrink, Margarethe and Kosmol, Jan and {Le Gleuher}, Ma{\"{i}}t{\'{e}} and Grohol, Milan and Ku, Anthony and Lee, Min Ha and Liu, Gang and Nansai, Keisuke and Nuss, Philip and Peck, David and Reller, Armin and Sonnemann, Guido and Tercero, Luis and Thorenz, Andrea and W{\"{a}}ger, Patrick A.},
+doi = {10.1016/j.resconrec.2019.104617},
+issn = {18790658},
+journal = {Resources, Conservation and Recycling},
+keywords = {Critical raw materials,Critical resources,Criticality assessment,Material criticality,Strategic raw materials},
+number = {October 2019},
+pages = {104617},
+publisher = {Elsevier},
+title = {{A review of methods and data to determine raw material criticality}},
+url = {https://doi.org/10.1016/j.resconrec.2019.104617},
+volume = {155},
+year = {2020}
+}
+@misc{WorldBank2024,
+author = {{World Bank}},
+booktitle = {World Bank},
+title = {{Worldwide Governance Indicators}},
+url = {https://info.worldbank.org/governance/wgi/},
+urldate = {2024-09-02},
+year = {2024}
+}
+@article{Gemechu2015,
+author = {Gemechu, Eskinder D. and Helbig, Christoph and Sonnemann, Guido and Thorenz, Andrea and Tuma, Axel},
+doi = {10.1111/jiec.12279},
+issn = {15309290},
+journal = {Journal of Industrial Ecology},
+keywords = {Criticality assessment,Geopolitical supply risk,Industrial ecology,Life cycle assessment,Life cycle sustainability assessment,Resources},
+number = {1},
+pages = {154--165},
+title = {{Import-based Indicator for the Geopolitical Supply Risk of Raw Materials in Life Cycle Sustainability Assessments}},
+volume = {20},
+year = {2015}
+}
+@article{Helbig2016,
+author = {Helbig, Christoph and Gemechu, Eskinder D. and Pillain, Baptiste and Young, Steven B. and Thorenz, Andrea and Tuma, Axel and Sonnemann, Guido},
+doi = {10.1016/j.jclepro.2016.07.214},
+issn = {09596526},
+journal = {Journal of Cleaner Production},
+keywords = {Carbon fiber,Criticality assessment,Life cycle sustainability assessment,Political stability,Supply risk},
+pages = {1170--1178},
+publisher = {Elsevier Ltd},
+title = {{Extending the geopolitical supply risk indicator: Application of life cycle sustainability assessment to the petrochemical supply chain of polyacrylonitrile-based carbon fibers}},
+url = {http://dx.doi.org/10.1016/j.jclepro.2016.07.214},
+volume = {137},
+year = {2016}
+}
+@article{Mancini2016,
+author = {Mancini, Lucia and Benini, Lorenzo and Sala, Serenella},
+doi = {10.1007/s11367-016-1137-2},
+issn = {16147502},
+journal = {International Journal of Life Cycle Assessment},
+keywords = {Characterization factors,Critical raw materials,Life cycle assessment,Resource impact assessment,Supply risk},
+number = {3},
+pages = {726--738},
+publisher = {The International Journal of Life Cycle Assessment},
+title = {{Characterization of raw materials based on supply risk indicators for Europe}},
+volume = {23},
+year = {2016}
+}
+@article{Bachmann2021,
+author = {Bachmann, Till M and Hackenhaar, Isadora C. and Horn, Rafael and Charter, Martin and Gehring, Florian and Graf, Roberta and Huysveld, Sophie and Alvarenga, Rodrigo A. F.},
+keywords = {LCSA,circular economy,circularity,criticality,review,supply risk},
+number = {958231},
+pages = {130},
+title = {{Critical evaluation of material criticality and product-related circularity approaches}},
+year = {2021}
+}
+@article{Koyamparambath2024,
+author = {Koyamparambath, Anish and Loubet, Philippe and Young, Steven B and Sonnemann, Guido},
+doi = {10.1016/j.resconrec.2024.107801},
+issn = {0921-3449},
+journal = {Resources, Conservation & Recycling},
+number = {May},
+pages = {107801},
+publisher = {Elsevier B.V.},
+title = {{Spatially and temporally differentiated characterization factors for supply risk of abiotic resources in life cycle assessment}},
+url = {https://doi.org/10.1016/j.resconrec.2024.107801},
+volume = {209},
+year = {2024}
+}
+@article{Santillan-Saldivar2021,
+author = {Santill{\'{a}}n-Saldivar, Jair and Cimprich, Alexander and Shaikh, Noor and Laratte, Bertrand and Young, Steven B. and Sonnemann, Guido},
+doi = {10.1016/j.resconrec.2020.105108},
+issn = {18790658},
+journal = {Resources, Conservation and Recycling},
+keywords = {Circular economy,Critical raw materials,Criticality assessment,Domestic recycling,Life cycle assessment,Life cycle sustainability assessment},
+number = {August 2020},
+pages = {105108},
+publisher = {Elsevier},
+title = {{How recycling mitigates supply risks of critical raw materials: Extension of the geopolitical supply risk methodology applied to information and communication technologies in the European Union}},
+url = {https://doi.org/10.1016/j.resconrec.2020.105108},
+volume = {164},
+year = {2021}
+}
+@article{Berger2020,
+author = {Berger, Markus and Sonderegger, Thomas and Alvarenga, Rodrigo and Bach, Vanessa and Cimprich, Alexander and Dewulf, Jo and Frischknecht, Rolf and Guin{\'{e}}e, Jeroen and Helbig, Christoph and Huppertz, Tom and Jolliet, Olivier and Motoshita, Masaharu and Northey, Stephen and Pe{\~{n}}a, Claudia A. and Rugani, Benedetto and Sahnoune, Abdelhadi and Schrijvers, Dieuwertje and Schulze, Rita and Sonnemann, Guido and Valero, Alicia and Weidema, Bo P. and Young, Steven B.},
+doi = {10.1007/s11367-020-01737-5},
+isbn = {1136702001737},
+issn = {16147502},
+journal = {International Journal of Life Cycle Assessment},
+keywords = {Life Cycle Initiative,Life cycle assessment,Life cycle impact assessment,Mineral resources,Raw materials,Resource depletion,Resource dissipation,Task force mineral resources},
+publisher = {The International Journal of Life Cycle Assessment},
+title = {{Mineral resources in life cycle impact assessment: part II – recommendations on application-dependent use of existing methods and on future method development needs}},
+year = {2020}
+}
diff --git a/paper.md b/paper.md
new file mode 100644
index 0000000..50f6735
--- /dev/null
+++ b/paper.md
@@ -0,0 +1,85 @@
+---
+title: "geopolrisk-py: A Python-Based Library to Operationalize the Geopolitical Supply Risk Method for use in Life Cycle Assessment and Comparative Risk Assessment"
+tags:
+  - Criticality
+  - LCA
+  - Import
+  - Raw material
+  - Market concentration
+  - Abiotic Resources
+authors:
+  - name: Anish Koyamparambath
+    orcid: 0000-0003-0839-0552
+    corresponding: true
+    affiliation: 1
+  - name: Thomas Schraml
+    affiliation: 2
+  - name: Christoph Helbig
+    orcid: 0000-0001-6709-373X
+    affiliation: 2
+  - name: Guido Sonnemann
+    orcid: 0000-0003-2581-1910
+    affiliation: 1
+
+affiliations:
+  - name: Université de Bordeaux, CNRS, Bordeaux INP, ISM, UMR 5255, 33400 Talence, France
+    index: 1
+  - name: Ecological Resource Technology, University of Bayreuth, Universitaetsstr. 30, 95447 Bayreuth, Germany
+    index: 2
+date: 21 October 2024
+bibliography: paper.bib
+aas-doi: 10.3847/xxxxx <- update this with the DOI from AAS once you know it.
+aas-journal: The Journal of Open Source Software.
+---
+
+# Summary
+
+The Geopolitical Supply Risk (GeoPolRisk) method assesses raw material criticality in Life Cycle Assessment, complementing traditional resource and environmental impact indicators. It is also applied for comparative risk assessment. However, calculating values for the GeoPolRisk method, such as characterization factors for the Geopolitical Supply Risk indicator and the supply risk score for comparative assessment, can be complex. To address this, the `geopolrisk-py` library has been developed to operationalize the method, simplifying the calculation process. This library processes data inputs like raw material names, countries, and years, making it more accessible. A notable feature is its ability to serve as a company-specific supply risk assessment tool. Future development will include integrating an uncertainty model and additional modules for complete compatibility with Brightway 2.5, further enhancing functionality and usability.
+
+# The GeoPolRisk Method
+
+The GeoPolRisk method is an import-based indicator [@Gemechu2015] to integrate the criticality of raw materials into the Area of Protection ‘natural resources’, as proposed by [@Sonnemann2015]. It is designed to evaluate the supply risk of importing raw material from a trade (country, trade block, region, group of countries, or company/organization) perspective during a specific period. Since its inception, the method has evolved, incorporating several components of resource criticality [@Cimprich2019]. HHIA is the Herfindahl-Hirschman index for raw material “A” calculated as the sum of the squared production shares of all the countries producing raw material “A”. The GeoPolRisk method weights the import (“$f_Aic$”) of raw material A to economic unit “c” from “i” with the political (in-)stability indicator of the exporting country (“$g_i$”). “$F_Ac$” is the total imports to the entity in assessment, and _pAc_ is the domestic production of raw material A in entity c. $p ̅$ represents the yearly average market price of the raw material in US dollars per kilogram of raw material. The _GeoPolRisk MidpointAc,_ as presented in **Equation 1**_,_ has units as US dollars per kilogram of raw material “A” consumed (USD/kgA) [@Santillan-Saldivar2022]. The values for the Geopolitical Supply Risk Potential (GSP) are obtained by dividing $GeoPolRisk midpoint_Ac$ with the average GeoPolRisk midpoint of copper for the countries over 5 years (2017 to 2020) as shown in **Equation 2**. where ‘A’ represents the raw material, ‘c’ represents an economic unit, ‘t’ refers to the time period (year) [@Koyamparambath2024]. The _Geopolitical Supply Risk Potential_ has units of kg_Cu-eq per $kg_A$.
+(1) $GeoPolRisk Midpoint CF_Ac= HHI_A*∑_i((g_i*f_Aic)/( p_Ac+F_Ac )) * p ̅$ 
+
+(2) $Geopolitical Supply Risk Potential (GSP)=  GeoPolRisk midpoint_Act/GeoPolRisk midpoint _copper $
+
+# Statement of Need
+
+The method consists of three main components: (1) the evaluation of the concentration of global mine production using the normalized Herfindahl-Hirschman index [@Rhoades1993TheHI], (2) the weighting of a raw material’s import share to an economic unit by the political stability score of its origin, and (3) the yearly average traded price of the raw material. The first two components provide a supply risk score, which can be used for comparative risk assessment, while the third component combined with the other two, introduces a characterization factor, GSP, for Life Cycle Assessment to evaluate the supply risk of abiotic resources from an “outside-in” perspective [@Koyamparambath2024] [@Santillan-Saldivar2022]. The GeoPolRisk method is suggested by initiatives such as Global Guidance for Life Cycle Impact Assessment Indicators and Methods, a task force hosted by the United Nations Environmental Program [@Berger2020] and is recommended by the ORIENTING project [@Hackenhaar2022]. It is also recognized by the International Round Table on Materials Criticality [@Schrijvers2020].
+
+Despite its benefits, broader applications of the GeoPolRisk method, especially for multiple raw materials or in generating characterization factors, are limited due to the complexity of its calculation [@Santillan-Saldivar2021]. The ORIENTING project has highlighted this complexity in its reports [@Bachmann2021] [@Hackenhaar2022], and Santillán-Saldivar et al. noted that an automated calculation tool could significantly enhance the method's practical applicability [@Santillan-Saldivar2021]. By using this library, the characterization factors for 46 raw materials in 38 OECD countries have been generated [@Koyamparambath2024]. Integrating this library into LCA tools like Brightway [@Mutel2017], a widely used open-source Python-based LCA software, could further streamline the implementation of the GeoPolRisk method into LCA. Such integration could address current limitations by aligning the methodology with intermediate flows [@Bachmann2021] [@Mancini2016] and enabling the calculation of supply risk CFs along the supply chain [@Helbig2016] [@Koyamparambath2024] [@Siddhantakar2023].
+
+Beyond LCA applications, the GeoPolRisk method can be used as a comparative risk assessment tool for companies and organizations [@Koyamparambath2022]. With an automated calculation tool, users can input their specific supply mix to calculate tailored supply risk scores. This feature can benefit companies seeking to analyze different supply risk scenarios based on their unique supply chains and compare their risk with national averages.
+
+# Features of the `geopolrisk-py` Library
+
+The *geopolrisk-py* library is organized into four modules: `database.py`, `core.py`, `main.py`, and `utils.py`, each with specific roles to facilitate the calculation of the GeoPolRisk method.
+
+1. **database.py**: This module is responsible for loading all the essential background data required for the library’s operations. The necessary data includes mining production data (from world mining data) [@FMRA2023], trade data (from BACI for past years) [@cepii_baci_2024], and governance indicators (from the World Bank) [@WorldBank2024]. These datasets are stored in a SQLite3 database, which is updated annually and available in the repository. Upon installation, the library sets up a folder in the Document folder in the user's home directory with three subfolders: 
+   - **databases**: Users should place the downloaded background database here.
+   - **output**: This folder stores the SQLite3 database and Excel output files generated after calculations.
+   - **logs**: For debugging errors encountered during the process.
+
+2. **core.py**: This module contains functions that compute each component of the GeoPolRisk method, following the structure of the formula (**Equation 1**). The functions accept specific inputs like raw material names, countries, and years. To simplify input, the library matches raw materials to their Harmonized System (HS) codes, which are commonly used in trade. Similarly, it maps country names to their three-digit ISO codes, both stored in the background database. This helps standardize inputs, making it easier for users to perform calculations. Additionally, the `utils.py` functions assist in transforming names into the required HS and ISO codes for internal processing.
+
+3. **utils.py**: This module supports data transformation, ensuring compatibility between user input and database requirements. It handles the conversion between names (strings) and codes (HS and ISO), aligning user inputs with the functions in `core.py`. For example, if a user defines a new region or group of countries, `utils.py` functions can aggregate trade and production data accordingly. The module also provides the `transformdata` function, allowing users to load company-specific trade data in an Excel format. This function extracts HS codes and ISO codes from the background database and reformats the trade data to the structure required for calculations.
+
+4. **main.py**: The central module of the library, `main.py`, simplifies the use of the GeoPolRisk method through the `gprs_calc` function. Users can input a `list` of raw materials, countries, and years to compute GeoPolRisk values. The `gprs_calc` function calls relevant functions from `core.py` to calculate the supply risk score (using the first two components of the GeoPolRisk formula) and the characterization factors for Life Cycle Assessment (using all three components). Results are stored in an Excel file and a SQLite3 database, which are then exported to the "outputs" folder for easy access.
+
+### Unique Features of the *geopolrisk-py* Library
+
+The *`geopolrisk-py`* library offers several features to enhance its functionality:
+- **Custom Region Creation**: Users can define regions or groups of countries not available in the background database. This allows for trade aggregation and region-specific supply risk analysis, a capability supported by `utils.py` and `core.py` functions.
+- **Company-Specific Risk Assessment**: A standout feature is the ability to calculate supply risk based on company-specific trade data. Using a predefined Excel template available in the repository, users can input their trade data, which the library then processes using `transformdata` and other relevant functions. For example, `importrisk_company` in `core.py` calculates the second component of the GeoPolRisk method (weighted import risk), tailored to the company's unique trade mix. This feature enables companies to model different supply risk scenarios based on their specific supply chains and compare them to national averages.
+
+#  Future Work
+Uncertainties in the GeoPolRisk method stem from various sources, such as the quality of the data used and the methodology of calculation. The library will be further enhanced by incorporating a module for calculating the uncertainty of the GeoPolRisk values , consistent with best practices in LCA [@Ciroth2016]. Another area of ongoing development is the integration of the library with LCA tools like Brightway [@Mutel2017]. A new module is being designed to leverage Brightway's features and create a two-way interface. This interface will enable users to calculate specific supply risks along the value chain using the GeoPolRisk method, based on their LCA models in Brightway.
+
+# Acknowledgments
+This library was developed in collaboration with the Ecological Resource Technology group at the University of Bayreuth. The PhD thesis of the first author at the University of Bordeaux provided the opportunity to develop the initial version of the library under the TripleLink project, funded by EIT Raw Materials and supported by the EIT, a body of the European Union. The library’s development was inspired by the work of Noor-ur-Rahman Shaikh during his master's thesis at the University of Waterloo. We gratefully acknowledge his significant contributions, as well as those of Jair Santillán-Saldivar and Steven B. Young, who played key roles in its development.
+
+# Author contributions
+Anish Koyamparambath: Writing -original draft, writing - review & editing, methodology, data curation, software, validation  
+Thomas Schraml: Software, validation  
+Christoph Helbig: Methodology, writing - review & editing  
+Guido Sonnemann: Conceptualization, writing – review & editing, supervision


Test patch:
diff --git a/Company data test case.xlsx b/Company data test case.xlsx
new file mode 100644
index 0000000..184e371
Binary files /dev/null and b/Company data test case.xlsx differ
diff --git a/geopolrisk/test.py b/geopolrisk/test.py
deleted file mode 100644
index b199012..0000000
--- a/geopolrisk/test.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-import unittest, os
-from geopolrisk.tests.test_case_1 import Testutilsfunctions
-from geopolrisk.tests.test_case_2 import TestCoreFunctions
-from geopolrisk.tests.test_case_3 import Testmainfunctions
-
-
-def main():
-
-    # Test Suite
-    suite = unittest.TestSuite()
-
-    # Add all test cases to the test suite
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(Testutilsfunctions))
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestCoreFunctions))
-    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(Testmainfunctions))
-
-    # Run the test suite
-    unittest.TextTestRunner(verbosity=3).run(suite)
-
-
-if __name__ == '__main__':
-    main()
\ No newline at end of file
diff --git a/geopolrisk/tests/__init__.py b/geopolrisk/tests/__init__.py
deleted file mode 100644
index 7d5ca44..0000000
--- a/geopolrisk/tests/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-__all__ = ["test_case_1","test_case_2", "test_case_3", "defaults"] 
-__author__ = "Anish Koyamparambath <CyVi- University of Bordeaux>"
-__status__ = "beta"
-__version__ = "2.5"
-__data__ = "10 March 2023"
diff --git a/geopolrisk/tests/defaults.py b/geopolrisk/tests/defaults.py
deleted file mode 100644
index 5638041..0000000
--- a/geopolrisk/tests/defaults.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-ListofMetals = [
-    2606,
-    261710,
-    2524,
-    2511,
-    8106,
-    8107,
-    2610,
-    2701,
-    810520,
-    2603,
-    7108,
-    2504,
-    2601,
-    2607,
-    283691,
-    251910,
-    2602,
-    280540,
-    2613,
-    271111,
-    2604,
-    2709,
-    2846,
-    261610,
-    2609,
-    2611,
-    2608,
-    261510,
-]
-
-ListofYears = [
-    2002,
-    2003,
-    2004,
-    2005,
-    2006,
-    2007,
-    2008,
-    2009,
-    2010,
-    2011,
-    2012,
-    2013,
-    2014,
-    2015,
-    2016,
-    2017,
-    2018,
-    2019,
-    2020,
-]
-
-ListofCountries = [
-    36,
-    124,
-    97,
-    251,
-    276,
-    392,
-    826,
-    842,
-    32,
-    40,
-    50,
-    56,
-    191,
-    203,
-    208,
-    246,
-    300,
-    381,
-    348,
-    372,
-    442,
-    528,
-    579,
-    616,
-    724,
-    642,
-    620,
-    703,
-    705,
-    752,
-    757,
-    76,
-    64,
-]
-
-ListofMetalName = [
-    "Aluminium",
-    "Antimony",
-    "Asbestos",
-    "Barytes",
-    "Bismuth",
-    "Cadmium",
-    "Chromium",
-    "Coal",
-    "Cobalt",
-    "Copper",
-    "Gold",
-    "Graphite",
-    "Iron",
-    "Lead",
-    "Lithium",
-    "Magnesite",
-    "Manganese",
-    "Mercury",
-    "Molybdenum",
-    "NG",
-    "Nickel",
-    "Crude_Oil",
-    "REE",
-    "Silver",
-    "Tin",
-    "Tungsten",
-    "Zinc",
-    "Zirconium",
-]
-ListofCountryName = [
-    "Australia",
-    "Canada",
-    "European Union",
-    "France",
-    "Germany",
-    "Japan",
-    "United Kingdom",
-    "USA",
-    "Argentina",
-    "Austria",
-    "Bangladesh",
-    "Belgium",
-    "Croatia",
-    "Czechia",
-    "Denmark",
-    "Finland",
-    "Greece",
-    "Italy",
-    "Hungary",
-    "Ireland",
-    "Luxembourg",
-    "Netherlands",
-    "Norway",
-    "Poland",
-    "Spain",
-    "Romania",
-    "Portugal",
-    "Slovakia",
-    "Slovenia",
-    "Sweden",
-    "Switzerland",
-    "Brazil",
-    "Bhutan",
-]
-
-
-import random
-
-
-def random_sampler(A, n):
-    return random.sample(A, n)
diff --git a/geopolrisk/tests/sample trade data.xlsx b/geopolrisk/tests/sample trade data.xlsx
deleted file mode 100644
index 22e01d3..0000000
Binary files a/geopolrisk/tests/sample trade data.xlsx and /dev/null differ
diff --git a/geopolrisk/tests/test_case_1.py b/geopolrisk/tests/test_case_1.py
deleted file mode 100644
index aaafdf3..0000000
--- a/geopolrisk/tests/test_case_1.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-import unittest
-from .defaults import *
-from geopolrisk.assessment.utils import *
-from geopolrisk.assessment.core import *
-
-# testcase to test the gprs_comtrade function
-
-#Extracting samples data from a list of resources, countries and years
-Resources = random_sampler(ListofMetals, 5)
-Countries = random_sampler(ListofCountries, 5)
-Year = random_sampler(ListofYears, 5)
-listofcountryname, listofresourcename = [], []
-for i, n in enumerate(Resources):
-    listofcountryname.append(ListofCountryName[ListofCountries.index(Countries[i])])
-    listofresourcename.append(
-        ListofMetalName[ListofMetals.index(n)]
-    )
-
-
-#Test class to test the functions in utils module
-#Please note functions such as record data, extract data are excluded
-class Testutilsfunctions(unittest.TestCase):
-     
-    #Test to verify the functionality of id creation 
-    def test_verifyidcreation(self):
-        Resources = [2606, 261710, 2524]
-        Countries = [4, 36, 124]
-        Year = [2016]
-        result = [
-            "xx2606xx42016",
-            "xx2606x362016",
-            "xx26061242016",
-            "261710xx42016",
-            "261710x362016",
-            "2617101242016",
-            "xx2524xx42016",
-            "xx2524x362016",
-            "xx25241242016",
-        ]
-        for i, n in enumerate(Resources):
-            get = create_id(Resources[i], Countries[i], Year[0])
-            self.assertIn(get, result, msg="Id creation failed!")
-
-    #Test to verify the conversion of the codes
-    def test_conversiontonumericcodes(self):
-        __ignore, __ignore, hscode, iso = convertCodes(
-            listofresourcename, listofcountryname
-        )
-        self.assertEqual(
-            [hscode, iso],
-            [Resources, Countries],
-            msg="Code conversion failed!",
-        )
-
-    #Test to verify the reverse conversion of the codes
-    def test_conversiontonames(self):
-        resourcename, countryname, __ignore, __ignore = convertCodes(
-            listofresourcename, listofcountryname
-        )
-        self.assertEqual(
-            [resourcename, countryname],
-            [listofresourcename, listofcountryname],
-            msg="Code conversion failed!",
-        )
-
-    #Test to verify the functionality of the new Comtrade API
-    def test_pythoncomtradeapi(self):
-        randomresource = random.choice(Resources)
-        randomcountry = random.choice(Countries)
-        randomyear = random.choice(Year)
-        TradeData, cifprice = callapirequest(randomyear, randomcountry, randomresource)
-        self.assertIsNotNone(TradeData, msg="API call failed!")
-        self.assertIsNotNone(cifprice, msg="API call failed!")
-
-    #Test to verify the functionality of the old Comtrade API
-    def test_oldcomtradeapi(self):
-        randomresource = random.choice(Resources)
-        randomcountry = random.choice(Countries)
-        randomyear = random.choice(Year)
-        TradeData = oldapirequest(randomyear, randomcountry, randomresource)
-        self.assertIsNotNone(TradeData, msg="API call failed!")
-
-    #Test to verify the sql verify function to check for existing data
-    def test_verifydatabase(self):
-        DBID = ["xx81061912014", "xx81077052003", "xx2846x562012", "2615102032017"]
-        for i in DBID:
-            result =  sqlverify(i)
-            self.assertTrue(result, msg="SQL verification failed!")
diff --git a/geopolrisk/tests/test_case_2.py b/geopolrisk/tests/test_case_2.py
deleted file mode 100644
index 722e23c..0000000
--- a/geopolrisk/tests/test_case_2.py
+++ /dev/null
@@ -1,187 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-import unittest, os
-from .defaults import *
-from geopolrisk.assessment.utils import *
-from geopolrisk.assessment.core import *
-from geopolrisk.assessment.__init__ import instance
-
-_wgi = instance.wgi
-# testcase to test the gprs_comtrade function
-Resources = random_sampler(ListofMetals, 5)
-Countries = random_sampler(ListofCountries, 5)
-Year = random_sampler(ListofYears, 5)
-listofcountryname, listofresourcename = [], []
-for i, n in enumerate(Resources):
-    listofcountryname.append(ListofCountryName[ListofCountries.index(Countries[i])])
-    listofresourcename.append(ListofMetalName[ListofMetals.index(n)])
-
-
-class TestCoreFunctions(unittest.TestCase):
-    def test_regioninsertion(self):
-        NewRegion = {
-            "West Europe": [
-                "France",
-                "Germany",
-                "Italy",
-                "Spain",
-                "Portugal",
-                "Belgium",
-            ]
-        }
-        result = regions(NewRegion)
-        from geopolrisk.assessment.__init__ import instance
-
-        regionslist = instance.regionslist
-        self.assertEqual(
-            regionslist["West Europe"],
-            NewRegion["West Europe"],
-            msg="Region insertion failed",
-        )
-        self.assertIsNotNone(result, msg="Error in region creation!")
-
-    def test_tradepathinsertion(self):
-        result = settradepath("geopolrisk/tests/sample trade data.xlsx")
-        self.assertIsNotNone(result, msg="Error in tradepath creation!")
-
-    def test_worldtrade(self):
-        regions()
-        randomresource = random.choice(Resources)
-        randomcountry = random.choice(Countries)
-        randomyear = random.choice(Year)
-        result = worldtrade(randomyear, randomcountry, randomresource)
-        self.assertIsNotNone(result, msg="Error in worldtrade calculation!")
-
-    def test_specifictrade(self):
-        xxx = settradepath("geopolrisk/tests/sample trade data.xlsx")
-        result = specifictrade(sheetname="test")
-        self.assertIsNotNone(result, msg="Error in specific trade calculation!")
-
-    def test_productiondata(self):
-        regions()
-        randomresource = random.choice(listofresourcename)
-        randomcountry = random.choice(listofcountryname)
-        result = ProductionData(randomresource, randomcountry)
-        self.assertIsNotNone(result, msg="Error in production data calculation!")
-
-    def test_weightedaverage(self):
-        TradeData = [
-            [
-                40,
-                56,
-                76,
-            ],
-            [
-                "Austria",
-                "Belgium",
-                "Brazil",
-            ],
-            [
-                1723782,
-                2155207,
-                53399700,
-            ],
-        ]
-        PIData = _wgi
-        Year = "2015"
-        recyclingrate = 0
-        scenario = 0
-        numerator, tradetotal = weightedtrade(
-            Year,
-            TradeData=TradeData,
-            PIData=PIData,
-            scenario=scenario,
-            recyclingrate=recyclingrate,
-        )
-        res_num, res_total = [31532151.035755564, 57278689]
-        self.assertEqual(
-            [numerator, tradetotal],
-            [res_num, res_total],
-            msg="Weighted average calculation failed!",
-        )
-        self.assertIsNotNone(numerator, msg="Weighted average calculation failed!")
-
-    def test_GeoPolRisk(self):
-        ProductionData = [
-            [   0.289,
-                0.304,
-                0.287,
-                0.258,
-                0.213,
-                0.222,
-                0.218,
-            ],
-            [   23659.0,
-                25000.0,
-                25000.0,
-                21000.0,
-                20000.0,
-                20000.0,
-                20000.0,
-            ],
-            [   2014,
-                2015,
-                2016,
-                2017,
-                2018,
-                2019,
-                2020,
-            ],
-        ]
-        WTAData = [31532151.035755564, 57278689]
-        Year = "2015"
-        AVGPrice = 2010.22
-        result = GeoPolRisk(ProductionData, WTAData, Year, AVGPrice)
-        theresult = [0.304, 0.3832359438269072, 0.11650372692337978, 234.1981219359165]
-        self.assertEqual(result, theresult, msg = "The GeoPolRisk calculation failed!")
-
-    def test_redistribution(self):
-        TradeData = [
-            [
-                40,
-                56,
-                76,
-            ],
-            [
-                "Austria",
-                "Belgium",
-                "Brazil",
-            ],
-            [
-                1723782,
-                2155207,
-                53399700,
-            ],
-        ]
-        PIData = _wgi
-        Year = "2015"
-        recyclingrate = 10
-        scenario = 1
-        numerator, tradetotal = weightedtrade(
-            Year,
-            TradeData=TradeData,
-            PIData=PIData,
-            scenario=scenario,
-            recyclingrate=recyclingrate,
-        )
-        res_num, res_total = [31532151.035755564, 57278689]
-        self.assertLessEqual(
-            numerator,
-            res_num,
-            msg="Weighted average calculation failed!"
-        )
-        self.assertIsNotNone(numerator, msg="Weighted average calculation failed!")
diff --git a/geopolrisk/tests/test_case_3.py b/geopolrisk/tests/test_case_3.py
deleted file mode 100644
index 60f0a0b..0000000
--- a/geopolrisk/tests/test_case_3.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (C) 2023 University of Bordeaux, CyVi Group & Anish Koyamparambath
-# This file is part of geopolrisk-py library.
-#
-# geopolrisk-py is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# geopolrisk-py is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with geopolrisk-py.  If not, see <https://www.gnu.org/licenses/>.
-
-import unittest
-from .defaults import *
-from geopolrisk.assessment.core import regions
-from geopolrisk.assessment.main import startmain, endmain, main_complete
-from geopolrisk.assessment.__init__ import instance
-
-_wgi = instance.wgi
-# testcase to test the gprs_comtrade function
-Resources = random_sampler(ListofMetals, 2)
-Countries = random_sampler(ListofCountries, 2)
-Year = random_sampler(ListofYears, 2)
-listofcountryname, listofresourcename = [], []
-for i, n in enumerate(Resources):
-    listofcountryname.append(ListofCountryName[ListofCountries.index(Countries[i])])
-    listofresourcename.append(ListofMetalName[ListofMetals.index(n)])
-
-class Testmainfunctions(unittest.TestCase):
-    def test_aggregion(self):
-        NewRegion = {"Custom Region" : listofcountryname }
-        xx = regions(NewRegion)
-        try:
-            main_complete(Resources,Year,["Custom Region"],0,0,None,_wgi)
-            assert True
-        except Exception as e:
-            print(e)
-            assert False
-
-    def test_mainfunction(self):
-        try:
-            startmain(
-            Resources,
-            Year,
-            Countries,
-            recyclingrate=0.0,
-            scenario=0,
-            sheetname=None,
-            PIindicator=None,
-            )
-            endmain()
-        except Exception as e:
-            print(e)
-            assert False