from flask import Blueprint, jsonify, abort, request
from ..healthtrace_models import Clinics, db
bp = Blueprint('clinics', __name__, url_prefix='/clinics')

@bp.route('', methods=['GET'])
def get_all_clinics():
    clinics = Clinics.query.all()
    result = []
    for c in clinics:
        result.append(c.serialize())
    return jsonify(result)

@bp.route('', methods=['POST'])
def create_clinic():
    if 'name' not in request.json:
        return abort(400)

    clinic = Clinics(
        id = request.json['id'],
        name = request.json['name'],
        address  = request.json['address'],
        phone = request.json['phone'],
        email = request.json['email'],
        created_at = request.json['created_at'],
    )
    try:
        db.session.add(clinic)
        db.session.commit()
        return jsonify(clinic.serialize())
    except:
        return jsonify(message="something went wrong :(")

@bp.route('/<int:id>', methods=['GET'])
def get_clinic_by_id(id: int):
    clinic = Clinics.query.get_or_404(id)
    return jsonify(clinic.serialize())

@bp.route('/<int:id>', methods=['DELETE'])
def delete_clinic(id: int):
    clinic = Clinics.query.get_or_404(id)
    try:
        db.session.delete(clinic)
        db.session.commit()
        return jsonify(message="Clinic deleted successfully")
    except:
        return jsonify(message="something went wrong :(")

@bp.route('/clinics/<int:clinic_id>', methods=['PUT', 'PATCH'])
def modify_clinic(clinic_id):
    clinic = Clinics.query.get_or_404(clinic_id)
    req_data = request.get_json()
    if 'name' not in request.json:
        return abort(400)

    clinic.id = req_data['id']
    clinic.name = req_data['name']
    clinic.address = req_data['address']
    clinic.phone = req_data['phone']
    clinic.email = req_data['email']
    clinic.created_at = req_data['created_at']

    try:
        db.session.commit()
        return jsonify(clinic.serialize(), message="clinic modified successfully")
    except:
        return jsonify(message = "something went wrong :(")


import streamlit as st
from model.banco import Banco
from time import sleep
banco = Banco()
data_hospital = ()
st.title("Hospital")

def inputs_hospital(layout, key='include_hospital'):

  with layout.form(key=f"{key}", clear_on_submit = False):
    input_hospital_code = st.number_input(label="Código do Hospital", step=1)
    input_hospital_name = st.text_input(label="Nome do Hospital")
    input_service_area = st.text_input(label="Area de Serviço")
    input_county = st.text_input(label="Condado")
    input_button_submit = st.form_submit_button("Enviar")

    if input_button_submit:
      flag = [
        input_county=='',
        input_service_area=='',
        input_hospital_name=='',
      ]
      if(flag.count(True) == 0):
        hospital = (
          input_hospital_code,
          input_hospital_name,
          input_service_area,
          input_county
        )
        if(banco.insert('hospital', hospital) == 200):
          layout.title(':green[Hospital cadastrado com sucesso]')
        else:
          layout.title(':orange[já está cadastrado]')
      else:
        layout.title(':red[Deixou campos em banco]')

def read_hospital(layout, at):
  container = layout.container()
  layout.title('Consultar Dados')

  colunas = layout.columns((1,2,2,2,1.5))
  campos = ['Facility ID','Facility Name','Heal Service Area','Hospital County','Excluir']
  for coluna, campo in zip(colunas,campos):
    coluna.write(campo)
  items = banco.get_all('hospital')
  for i, item in enumerate(items):
    layout.write('<hr>', unsafe_allow_html=True)
    c1,c2,c3,c4,c6 = layout.columns((1,2,2,2,1.5))
    c1.write(item[0])
    c2.write(item[1])
    c3.write(item[2])
    c4.write(item[3])
    delete = c6.button('Excluir', key=str(item[0]))

    if delete:
      banco.delete('hospital', item[0])
      st.experimental_rerun()

def update_hospital(at):
  with at.form(key="update_hospital", clear_on_submit = False):
    c1, c2 = st.columns((1, 1))
    last_code = c1.number_input(label="Código do Hospital", step=1, )
    new_code = c2.number_input(label="Novo código para o Hospital", step=1, )
    update_name = st.text_input(label="Nome do Hospital")
    update_service = st.text_input(label="Area de Serviço")
    update_county = st.text_input(label="Condado")
    update_button = st.form_submit_button("Atualizar")

    #('id INT PRIMARY KEY, hospital_name TEXT NOT NULL, service_area TEXT NOT NULL, county TEXT NOT NULL')
    if update_button:
      update_txt= ''
      if(update_name != ''):
        update_txt += f'hospital_name="{update_name}"'
      if(update_county != ''):
        update_txt += f' county="{update_county}"'
      if(update_service != ''):
        update_txt += f' service_area="{update_service}"'
      if(new_code != last_code):
        update_txt += f' id="{new_code}"'
      #print(update_txt.replace('" ', '", '))
      if(banco.update('hospital', update_txt.replace('" ', '", '), last_code) == 200):
        at.title(':green[Hospital atualizado com sucesso]')
      else:
        at.title(':orange[Hospital não cadastrado]')
      sleep(.5)
      st.experimental_rerun()

insert, read, at = st.tabs(["Inserir Hospital", "Procurar Hospital", 'Atualizar'])
inputs_hospital(insert)
read_hospital(read, at)
update_hospital(at)


from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def home(request):
    return render(request, 'home.html')

def String(request):
    return render(request, 'String.html')

def s1(request):
    return render(request, 's1.html')

def tests1(request):
    sentence = request.GET['scr']
    ls = sentence.split()
    sen_new = ""
    ls1 = ls[::-1]
    for word in ls1:
        sen_new = sen_new + " " + word
    sen_new = sen_new.strip()
    res = "The reversed sentence is : " + sen_new
    print(sentence)
    return render(request, 's1.html', {'result': res})

def s2(request):
    return render(request, 's2.html')

def tests2(request):
    sen = request.GET['scr']
    counter = 0
    for i in sen:
        counter += 1
    res = ("Total chars. : " + str(counter))
    return render(request, 's2.html', {'result': res})

def s3(request):
    return render(request, 's3.html')

def tests3(request):
    sen = request.GET['scr']
    counter = 0
    vowel = ['a', 'e', 'i', 'o', 'u']
    for char in sen:
        for vow in vowel:
            if char.lower() == vow:
                counter += 1
    res = (counter)
    return render(request, 's3.html', {'result': res})

def s4(request):
    return render(request, 's4.html')

def tests4(request):
    sen = request.GET['scr']
    sen1 = ""
    counter = 0
    for i in sen:
        sen1 += i
        counter += 1
    res = "The number of characters copied are : " + str(counter)
    return render(request, 's4.html', {'result': res})

def Simple(request):
    return render(request, 'Simple.html')

def n1(request):
    return render(request, 'n1.html')

def testn1(request):
    n = request.GET['scr']
    d = int(n)
    if d % 365 == 0:
        years = int(d / 365)
        days = 0
    else:
        years = int(d / 365)
        days = d % 365
    if days % 30 == 0:
        months = days / 30
        days1 = 0
    else:
        months = int(days / 30)
        days1 = days % 30
    res = ("The value converted to {:} years , {:} months , {:} days".format(years, months, days1))
    return render(request, 'n1.html', {'result': res})

def n2(request):
    return render(request, 'n2.html')

def testn2(request):
    ID = request.GET['scr1']
    hrs = request.GET['scr2']
    amt = request.GET['scr3']
    salary = int(hrs) * int(amt)
    res = ("Salary of Employee with id {:} is Rs{:}".format(ID, salary))
    return render(request, 'n2.html', {'result': res})

def n3(request):
    return render(request, 'n3.html')

def testn3(request):
    nu1 = int(request.GET['scr1'])
    nu2 = int(request.GET['scr2'])
    nu3 = int(request.GET['scr3'])
    if nu1 > nu2 and nu1 > nu3:
        res = "number1 is the greatest if the three"
    elif nu2 > nu1 and nu2 > nu3:
        res = "number2 is the greatest of the three"
    else:
        res = "number3 is the greatest of the three"
    return render(request, 'n3.html', {'result': res})

def n4(request):
    return render(request, 'n4.html')

def testn4(request):
    # Taking 2000,500,100,20,10 Notes

    amt1 = request.GET['scr']
    res1000 = 0
    res500 = 0
    res100 = 0
    res20 = 0
    res10 = 0
    amt = int(amt1)
    if amt % 2000 == 0:
        two1000 = int(amt / 2000)
        res1000 = "Rs 2000 notes :" + str(two1000)

    else:
        two1000 = int(amt / 2000)
        amt = amt % 2000
        res1000 = "Rs 2000 notes :" + str(two1000)

        if amt % 500 == 0:
            five100 = int(amt / 500)
            res500 = "Rs 500 notes :" + str(five100)

        else:
            five100 = int(amt / 500)
            amt = amt % 500
            res500 = "Rs 500 notes :" + str(five100)
            if amt % 100 == 0:
                one100 = int(amt / 100)
                res100 = "Rs 100 notes :" + str(one100)
            else:
                one100 = int(amt / 100)
                amt = amt % 100
                res100 = "Rs 100 notes :" + str(one100)
                if amt % 20 == 0:
                    two10 = int(amt / 20)
                    res20 = "Rs 20 notes :" + str(two10)
                else:
                    two10 = int(amt / 20)
                    amt = amt % 20
                    res20 = "Rs 20 notes :" + str(two10)
                    if amt % 10 == 0:
                        one10 = int(amt / 10)
                        res10 = "Rs 10 notes :" + str(one10)
                    else:
                        one10 = int(amt / 10)
                        amt = amt % 10
                        res10 = "Rs 10 notes :" + str(one10)
    return render(request, 'n4.html',
                  {'result2000': res1000, 'result500': res500, 'result100': res100, 'result20': res20,
                   'result10': res10})

def n5(request):
    return render(request, 'n5.html')

def testn5(request):
    sec1 = request.GET['scr']
    sec = int(sec1)
    if sec % 3600 == 0:
        hours = int(sec / 3600)
        sec = 0
    else:
        hours = int(sec / 3600)
        sec = sec % 3600
    if sec % 60 == 0:
        minutes = sec / 60
        sec = 0
    else:
        minutes = int(sec / 60)
        sec = sec % 60
    res = ("The value converted to {:} hours , {:} minutes , {:} seconds".format(hours, minutes, sec))
    return render(request, 'n5.html', {'result': res})

def n6(request):
    return render(request, 'n6.html')

def testn6(request):
    num_list = list()
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    sum1 = 0
    for n in num_list:
        if not int(n) % 2 == 0:
            sum1 = sum1 + int(n)
        else:
            continue
    res = ("Sum of Odd values is :" + str(sum1))
    return render(request, 'n6.html', {'result': res})

def n7(request):
    return render(request, 'n7.html')

def testn7(request):
    n1 = request.GET['scr']
    n = int(n1)
    months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
              'November', 'December']
    res = ("The month resembling the value entered is :", months[n - 1])
    return render(request, 'n7.html', {'result': res})

def n8(request):
    return render(request, 'n8.html')

def testn8(request):
    n = []
    for i in range(2):
        n.append(input(request.GET['scr']))
    if not int(n[1]) == 0:
        res = ("The result of division is :", (float(n[0]) / float(n[1])))
    else:
        res = "Division not possible"
    return render(request, 'n8.html', {'result': res})

def n9(request):
    return render(request, 'n9.html')

def testn9(request):
    cm1 = request.GET['scr']
    cm = float(cm1)
    inches = cm / 2.54
    res = ("The length in inches is :", inches)
    return render(request, 'n9.html', {'result': res})

def n10(request):
    return render(request, 'n10.html')

def testn10(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    n3 = 0
    n3 = n1
    n1 = n2
    n2 = n3
    res = ("The swapped values :" + n1 + "," + n2)
    return render(request, 'n10.html', {'result': res})

def n11(request):
    return render(request, 'n11.html')

def testn11(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    n1 = n1 + n2
    n2 = n1 - n2
    n1 = n1 - n2
    res = ("The number of n1 : {:} & n2 : {:} after swapping ".format(n1, n2))
    return render(request, 'n11.html', {'result': res})

def Array(request):
    return render(request, 'Array.html')

def a1(request):
    return render(request, 'a1.html')

def testa1(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    n7 = request.GET['scr7']
    for i in [n1, n2, n3, n4, n5, n6, n7]:
        num_list.append(int(i))
    res1 = ("The value at element number : 1 is {:}".format(n1))
    res2 = ("The value at element number : 2 is {:}".format(n2))
    res3 = ("The value at element number : 3 is {:}".format(n3))
    res4 = ("The value at element number : 4 is {:}".format(n4))
    res5 = ("The value at element number : 5 is {:}".format(n5))
    res6 = ("The value at element number : 6 is {:}".format(n6))
    res7 = ("The value at element number : 7 is {:}".format(n7))
    return render(request, 'a1.html',
                  {'result1': res1, 'result2': res2, 'result3': res3, 'result4': res4, 'result5': res5, 'result6': res6,
                   'result7': res7})

def a2(request):
    return render(request, 'a2.html')

def testa2(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    num_list1 = []
    for n in num_list:
        counter = 0
        n = int(n)
        for i in range(1, n + 1):
            if n % i == 0:
                counter += 1
        if counter == 2:
            num_list1.append(n)
    res = "List of prime numbers in the entered array is :" + str(num_list1)
    return render(request, 'a2.html', {'result': res})

def a3(request):
    return render(request, 'a3.html')

def testa3(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    res = []
    i = 1
    for n in num_list:
        n = int(n)
        if n < 5:
            res.append("The element at position {:} whose value is {:} less than 5.".format(i, n))
        i += 1
    return render(request, 'a3.html', {'result': res})

def a4(request):
    return render(request, 'a4.html')

def testa4(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    for i in [n1, n2, n3, n4, n5, n6]:
        num_list.append(i)
    reverse = []
    res1 = "Original list is :" + str(num_list)
    num_list.reverse()
    for n in num_list:
        reverse.append(n)
    res2 = "Reversed list is :" + str(reverse)
    return render(request, 'a4.html', {'result1': res1, 'result2': res2})

def a5(request):
    return render(request, 'a5.html')

def testa5(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    for i in [n1, n2, n3, n4, n5, n6]:
        num_list.append(i)
    small_num = None
    small_pos = None
    i = 1
    for n in num_list:
        n = int(n)
        if small_num is None:
            small_num = n
            small_pos = i
        elif n < small_num:
            small_num = n
            small_pos = i
        i += 1
    res = ("The smallest number is {:} at the position : {:}.".format(small_num, small_pos))
    return render(request, 'a5.html', {'result': res})

def Loop(request):
    return render(request, 'Loop.html')

def l1(request):
    return render(request, 'l1.html')

def testl1(request):
    num = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    n7 = request.GET['scr7']
    n8 = request.GET['scr8']
    n9 = request.GET['scr9']
    n10 = request.GET['scr10']
    for i in [n1, n2, n3, n4, n5, n6, n7, n8, n9, n10]:
        num.append(i)
    sum = 0
    for n in num:
        sum += int(n)
    avg = sum / 10
    res = ("Sum : {:}  &  Average : {:.1f}".format(sum, avg))
    return render(request, 'l1.html', {'result': res})

def l2(request):
    return render(request, 'l2.html')

def testl2(request):
    n1 = int(request.GET['scr1'])
    product = 1
    for i in range(3):
        product = product * n1
    res = "The product is : " + str(product)
    return render(request, 'l2.html', {'result': res})

def l3(request):
    return render(request, 'l3.html')

def testl3(request):
    n = int(request.GET['scr'])
    num_list = []
    for i in range(10):
        product = 1
        product = n * (i + 1)
        num_list.append("{:>2} * {:<2} = {:>1}  ".format(n, (i + 1), product))

    return render(request, 'l3.html', {'result': num_list})

def l4(request):
    return render(request, 'l4.html')

def testl4(request):
    n = int(request.GET['scr'])
    sum = 0
    for i in range(1, (n)):
        if n % i == 0:
            sum = sum + i
    if sum == n:
        res = "Perfect number"
    else:
        res = "Not a Perfect number"
    return render(request, 'l4.html', {'result': res})

def l5(request):
    return render(request, 'l5.html')

def testl5(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    num_list = []
    for n in range(n1, n2 + 1):
        sum = 0

        for i in range(1, n):
            if n % i == 0:
                sum = sum + i
        if sum == n:
            num_list.append(" {:} is a perfect number.".format(sum))
        else:
            num_list.append(" {:} is not a perfect number.".format(n))

    return render(request, 'l5.html', {'result': num_list})

def l6(request):
    return render(request, 'l6.html')

def testl6(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    sum = 0
    for n in range(n1, n2 + 1):
        if not n % 17 == 0:
            sum += n
    res = ("The sum of numbers in the range not divisible by 17 is {:} .".format(sum))
    return render(request, 'l6.html', {'result': res})

def l7(request):
    return render(request, 'l7.html')

def testl7(request):
    num = int(request.GET['scr'])
    counter = 0
    for i in range(1, num + 1):
        if num % i == 0:
            counter += 1
    if counter == 2:
        res = "The entered number is prime."
    else:
        res = "The entered number is not prime."
    return render(request, 'l7.html', {'result': res})

def l8(request):
    return render(request, 'l8.html')

def testl8(request):
    num = int(request.GET['scr'])
    product = 1
    for i in range(1, num + 1):
        product *= i
    res = ("The factorial of the entered number is : " + str(product))
    return render(request, 'l8.html', {'result': res})

def l9(request):
    return render(request, 'l9.html')

def testl9(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    num_list = []
    for num in range(n1, n2 + 1):
        counter = 0
        for i in range(1, num + 1):
            if num % i == 0:
                counter += 1

        if counter == 2:
            num_list.append("The number {:} is prime.  ".format(num))
        else:
            num_list.append("The number {:} is not prime.  ".format(num))
    return render(request, 'l9.html', {'result': num_list})

def l10(request):
    return render(request, 'l10.html')

def testl10(request):
    num = int(request.GET['scr'])
    num1 = num
    sum = 0
    while num1 > 0:
        m = num1 % 10
        sum = sum + m ** 3
        num1 = num1 // 10
    if sum == num:
        res = "The entered number is armstrong."
    else:
        res = "The entered number is not armstrong."
    return render(request, 'l10.html', {'result': res})

def l11(request):
    return render(request, 'l11.html')

def testl11(request):
    num_list = []
    for n in range(1, 1001):
        sum1 = 0
        m = n
        while m > 0:
            a = m % 10
            sum1 += a ** 3
            m = m // 10
        if sum1 == n:
            num_list.append("The number {:} is armstrong.  ".format(n))
        else:
            num_list.append("The number {:} is not armstrong.  ".format(n))
    return render(request, 'l11.html', {'result': num_list})

def l12(request):
    return render(request, 'l12.html')

def testl12(request):
    num_list = []
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    for n in range(n1, n2 + 1):
        if n < 7:
            continue
        if not n % 7 == 0:
            if n % 7 == 2 or n % 7 == 3:
                m = n % 7
                num_list.append("{:} being divided by 7 leaves remainder {:}.  ".format(n, m))
    return render(request, 'l12.html', {'result': num_list})

def l13(request):
    return render(request, 'l13.html')

def testl13(request):
    n = int(request.GET['scr'])
    num_list = []
    for i in range(1, n + 1):
        if n % i == 0:
            num_list.append("{:} is a divisor for the entered number.  ".format(i))
    return render(request, 'l13.html', {'result': num_list})

def l14(request):
    return render(request, 'l14.html')

def testl14(request):
    n = int(request.GET['scr'])
    sum1 = 0
    m = n
    while m > 0:
        a = m % 10
        sum1 = sum1 * 10 + a
        m = m // 10
    res = ("The reverse of the entered number is : " + str(sum1))
    return render(request, 'l14.html', {'result': res})


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import rospy
from visualization_msgs.msg import Marker
from std_msgs.msg import ColorRGBA
from geometry_msgs.msg import Point
from tf.transformations import quaternion_from_euler
from geometry_msgs.msg import Vector3

rospy.init_node("rviz_marker")
marker_pub = rospy.Publisher("marker", Marker, queue_size=1)
text_pub = rospy.Publisher("text", Marker, queue_size=1)

while not rospy.is_shutdown():
    rviz_points = Marker()

    rviz_points.header.frame_id = "/world"
    rviz_points.ns = "points"
    rviz_points.id = 1

    rviz_points.type = Marker.POINTS
    rviz_points.action = Marker.ADD

    rviz_points.color = ColorRGBA(1, 1, 0, 1)
    rviz_points.scale = Vector3(0.2, 0.2, 0)

    # rviz_points.points.append(Point(1, 1, 0))     # 점 하나만 넣기
    rviz_points.points.append(Point(0, 0, 0))
    rviz_points.points.append(Point(1, 5, 0))
    rviz_points.points.append(Point(1, 7, 0))

    rviz_lineslist = Marker()

    rviz_lineslist.header.frame_id = "/world"
    rviz_lineslist.ns = "linelist"
    rviz_lineslist.id = 2

    rviz_lineslist.type = Marker.LINE_LIST
    rviz_lineslist.action = Marker.ADD

    rviz_lineslist.color = ColorRGBA(1, 0, 0, 1)
    rviz_lineslist.scale.x = 0.2

    x_list = [0,1,1,3,3,5,5,0]
    y_list = [0,2,2,4,4,5,5,0]

    for i in range(len(x_list)):
        rviz_lineslist.points.append(Point(x_list[i],y_list[i],0))

#    for i in range(1,3):
#        rviz_points.points.append(Point(i, i, 0))

    marker_pub.publish(rviz_points)
    marker_pub.publish(rviz_lineslist)
#________________________________________________________________


import random

class Employee:
    next_id = 1

    def __init__(self, first_name, last_name):
        self.id = Employee.next_id
        Employee.next_id += 1
        self.first_name = first_name
        self.last_name = last_name
        self._salary = None
        self.__prawdziwe_imie = 'czesław'

    def set_salary(self, amount):
        if not (isinstance(amount, (int, float)) and amount > 0):
            raise ValueError("nie Poprawna wartość pensji")
        self._salary = amount

class Employee2:
    next_id = 1

    @classmethod
    def get_next_id(cls):
        id = cls.next_id
        cls.next_id += 1
        return id

    def __init__(self, first_name, last_name):
        self.id = self.get_next_id()
        self.first_name = first_name
        self.last_name = last_name
        self._salary = None
        self.__prawdziwe_imie = 'czesław'

    def set_salary(self, amount):
        if not (isinstance(amount, (int, float)) and amount > 0):
            raise ValueError("nie Poprawna wartość pensji")
        self._salary = amount

class SuperEmployee(Employee2):
    next_id = 1

for x in range(20):
    if random.randint(0, 1):
        a = Employee2(1, 1)
        a.get_next_id()
        print(a.id, 'Employee')
    else:
        b = SuperEmployee(1, 1)
        b.get_next_id()
        print(b.id, 'SuperEmployee')


import pyogmaneo
import gym
import numpy as np

# Squashing function
def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))

# Create the environment
env = gym.make('CartPole-v1')

# Get observation size
numObs = env.observation_space.shape[0] # 4 values for Cart-Pole
numActions = env.action_space.n # N actions (1 discrete value)

# Squashing scale multiplier for observation
obsSquashScale = 1.0

# Define binning resolution
obsColumnSize = 32

# Set the number of threads
pyogmaneo.ComputeSystem.setNumThreads(4)

# Create the compute system
cs = pyogmaneo.ComputeSystem()

# Define layer descriptors: Parameters of each layer upon creation
lds = []

for i in range(2): # Layers with exponential memory. Not much memory is needed for Cart-Pole, so we only use 2 layers
    ld = pyogmaneo.LayerDesc()

    # Set the hidden (encoder) layer size: width x height x columnSize
    ld.hiddenSize = pyogmaneo.Int3(4, 4, 16)

    ld.ffRadius = 4 # Sparse coder radius onto visible layers
    ld.pRadius = 4 # Predictor radius onto sparse coder hidden layer (and feed back)
    ld.aRadius = 4 # Actor radius onto sparse coder hidden layer (and feed back)

    ld.ticksPerUpdate = 2 # How many ticks before a layer updates (compared to previous layer) - clock speed for exponential memory
    ld.temporalHorizon = 4 # Memory horizon of the layer. Must be greater or equal to ticksPerUpdate

    lds.append(ld)

# Create the hierarchy: Provided with input layer sizes (a single column in this case), and input types (a single predicted layer)
h = pyogmaneo.Hierarchy(cs, [ pyogmaneo.Int3(1, numObs, obsColumnSize), pyogmaneo.Int3(1, 1, numActions) ], [ pyogmaneo.inputTypeNone, pyogmaneo.inputTypeAction ], lds)

reward = 0.0

for episode in range(1000):
    obs = env.reset()

    # Timesteps
    for t in range(500):
        # Bin the 4 observations. Since we don't know the limits of the observation, we just squash it
        binnedObs = (sigmoid(obs * obsSquashScale) * (obsColumnSize - 1) + 0.5).astype(np.int).ravel().tolist()

        h.step(cs, [ binnedObs, h.getPredictionCs(1) ], True, reward)

        # Retrieve the action, the hierarchy already automatically applied exploration
        action = h.getPredictionCs(1)[0] # First and only column

        obs, reward, done, info = env.step(action)

        # Re-define reward so that it is 0 normally and then -1 if done
        if done:
            reward = -1.0

            print("Episode {} finished after {} timesteps".format(episode + 1, t + 1))

            break
        else:
            reward = 0.0


import matplotlib
from matplotlib import pyplot as plt
import glob
import numpy as np
import sys

filename = sys.argv[1]

r = np.genfromtxt(filename,usecols=0)
rho = np.genfromtxt(filename,usecols=1)
P = np.genfromtxt(filename,usecols=2)
vp = np.genfromtxt(filename,usecols=6)
vr = np.genfromtxt(filename,usecols=3)

alpha = 0.1
r0 = 5.
d = 4
PoRho_r1 = 0.01
rho_init = np.power(r,-3./5.)*np.exp(-np.power(r/r0,-d))
rho_ss = np.power(r,-3./5.)
P_init = PoRho_r1*np.power(r,-3./2.)*np.exp(-np.power(r/r0,-d))
P_ss = PoRho_r1*np.power(r,-3./2.)
vp_ss = -0.75*PoRho_r1*np.power(r,-2./5.)
r_drP_o_P = -1.5 + d*np.power(r/r0,-d);
P_o_rho_init = PoRho_r1*np.divide(np.power(r,-1.5),np.power(r,-3./5.))
vp_init = np.zeros(r.size)
vr_init = np.zeros(r.size)
vr_ss = -1.5*alpha*PoRho_r1*np.power(r,-2./5.)

fig,ax = plt.subplots(4,1,figsize=(4,6))
ax[0].plot(r,rho_init,linewidth=2.)
ax[0].plot(r,rho_ss,linewidth=2.)
ax[0].plot(r,rho,linewidth=2.)
ax[1].plot(r,P_init,linewidth=2.)
ax[1].plot(r,P_ss,linewidth=2.)
ax[1].plot(r,P,linewidth=2.)
ax[2].plot(r,vp_init,linewidth=2.)
ax[2].plot(r,vp_ss,linewidth=2.)
ax[2].plot(r,vp,linewidth=2.)
ax[3].plot(r,vr_init,linewidth=2.)
ax[3].plot(r,vr,linewidth=2.)
ax[3].plot(r,vr_ss,linewidth=2.)
ax[0].set_xlim(1,20)
ax[0].set_ylim(0.0,.99)
ax[1].set_xlim(1,20)
ax[1].set_ylim(0.00001,.0019)
ax[2].set_xlim(1,20)
ax[2].set_ylim(-.009,0.0019)
ax[3].set_xlim(1,20)
ax[3].set_ylim(-.0029,0.0004)
ax[3].set_xlabel(r'$r/a$',size='x-large')
ax[0].set_ylabel(r'$\rho$',labelpad=20.,size='x-large',rotation='horizontal')
ax[1].set_ylabel(r'$P$',labelpad=20.,size='x-large',rotation='horizontal')
ax[2].set_ylabel(r'$\delta v_{\phi}$',labelpad=20.,size='x-large',rotation='horizontal')
ax[3].set_ylabel(r'$v_r$',labelpad=20.,size='x-large',rotation='horizontal')
ax[0].get_xaxis().set_visible(False)
ax[1].get_xaxis().set_visible(False)
ax[2].get_xaxis().set_visible(False)
y_formatter = matplotlib.ticker.FormatStrFormatter('%2.0e')
ax[1].yaxis.set_major_formatter(y_formatter)
ax[2].yaxis.set_major_formatter(y_formatter)
ax[3].yaxis.set_major_formatter(y_formatter)
plt.tight_layout()
plt.subplots_adjust(hspace = 0.0)
plt.savefig("SS1D.pdf")


# -*- coding: cp1252 -*-
########################################################################################################
########################################################################################################
"""
                                        Code_2_Downscaling_and_Bias_Correcting_CMIP6_climate_projections
"""
########################################################################################################
########################################################################################################

"""

Title: Code_2_Downscaling_and_Bias_Correcting_CMIP6_climate_projections
Author: Richard Fewster (gy15ref@leeds.ac.uk)
Reference: Fewster, R.E., Morris, P.J., Ivanovic, R.F., Swindles, G.T., Peregon, A., and Smith, C. Imminent loss of climate space for permafrost peatlands in Europe and Western Siberia. (in review).
Description: This program reads in CMIP6 climate netcdf files, slices them to time periods of interest, calculates monthly means, and then
extrapolates, downscales and bias-corrects the outputs following the method of Morris et al. (2018). Functions are included for the export
of this data to csv and netcdf format. This script includes example pathfiles for the processing of ACCESS-CM2 projections.
References:
* Morris, P.J., Swindles, G.T., Valdes, P.J., Ivanovic, R.F., Gregoire, L.J., Smith, M.W., Tarasov, L., Haywood, A.M. and Bacon, K.L., 2018. Global peatland initiation driven by regionally asynchronous warming. Proceedings of the National Academy of Sciences, 115(19), pp.4851-4856.
* Dawson, A. 2018. gridfill. [Online]. [Accessed June 2020]. Available from: https://github.com/ajdawson/gridfill
Most recent update: 29/01/2021

"""

########################################################################################################
"""
STEP 1: IMPORT LIBRARIES AND DATA FILES
"""
########################################################################################################

"""
(1.1) Import required libraries.
"""
print('(1.1) Importing libraries...')

import xarray as xr
import datetime as dt
import numpy as np
import pandas as pd
import re
from netCDF4 import Dataset, date2index, num2date, date2num
import scipy
import gridfill
import iris

print('Import complete')

"""
(1.2) Import CMIP netCDF files
"""
print('(1.2) Importing CMIP data files...')

# Import CMIP land-sea mask file
mask_file = r"...\ACCESS-CM2\land\sftlf_fx_ACCESS-CM2_historical_r1i1p1f1_gn.nc"

# Import temperature files (e.g. for ACCESS-CM2...)
tas_file_hist = r"...\ACCESS-CM2\tmp\historical\*.nc"
tas_file_hist = xr.open_mfdataset(tas_file_hist, combine='by_coords')
tas_file_ssp1 = r"...\ACCESS-CM2\tmp\ssp1_26\*.nc"
tas_file_ssp1 = xr.open_mfdataset(tas_file_ssp1, combine='by_coords')
tas_file_ssp2 = r"...\ACCESS-CM2\tmp\ssp2_45\*.nc"
tas_file_ssp2 = xr.open_mfdataset(tas_file_ssp2, combine='by_coords')
tas_file_ssp3 = r"...\ACCESS-CM2\tmp\ssp3_70\*.nc"
tas_file_ssp3 = xr.open_mfdataset(tas_file_ssp3, combine='by_coords')
tas_file_ssp5 = r"...\ACCESS-CM2\tmp\ssp5_85\*.nc"
tas_file_ssp5 = xr.open_mfdataset(tas_file_ssp5, combine='by_coords')

# Import precipitation files (e.g. for ACCESS-CM2...)
pre_file_hist = r"...\ACCESS-CM2\pre\historical\*.nc"
pre_file_hist = xr.open_mfdataset(pre_file_hist, combine='by_coords')
pre_file_ssp1 = r"...\ACCESS-CM2\pre\ssp1_26\*.nc"
pre_file_ssp1 = xr.open_mfdataset(pre_file_ssp1, combine='by_coords')
pre_file_ssp2 = r"...\ACCESS-CM2\pre\ssp2_45\*.nc"
pre_file_ssp2 = xr.open_mfdataset(pre_file_ssp2, combine='by_coords')
pre_file_ssp3 = r"...\ACCESS-CM2\pre\ssp3_70\*.nc"
pre_file_ssp3 = xr.open_mfdataset(pre_file_ssp3, combine='by_coords')
pre_file_ssp5 = r"...\ACCESS-CM2\pre\ssp5_85\*.nc"
pre_file_ssp5 = xr.open_mfdataset(pre_file_ssp5, combine='by_coords')

"""
(1.3) Import observational netCDF files
"""
print('(1.3) Importing observational data files...')

# Import observational temperature dataset (e.g. for CRU TS 4.02...)
CRU_tmp_file = r"...\cru_ts4.04.1901.2019.tmp.dat.nc"
CRU_tmp_dset = xr.open_mfdataset(CRU_tmp_file, combine='by_coords')

# Import observational precipitation dataset (e.g. for CRU TS 4.02...)
CRU_pre_file =r"...\cru_ts4.04.1901.2019.pre.dat.nc"
CRU_pre_dset = xr.open_mfdataset(CRU_pre_file, combine='by_coords')

"""
(1.4) Setup export directory.
"""
print('(1.4) Setting up export directory...')

# Export path for temperature files (e.g. for ACCESS-CM2...)
tmp_DIR = r'...\ACCESS-CM2_1x_downscaled_monthly_tmp_'

# Export path for precipitation files (e.g. for ACCESS-CM2...)
pre_DIR = r'...\ACCESS-CM2_1x_downscaled_monthly_pre_'

print('Step 1: Import and Setup complete')

########################################################################################################
"""
STEP 2: PROCESS CLIMATE DATA AND CALCULATE AVERAGES
"""
########################################################################################################

"""
(2.1) Slice CMIP data to desired time period and study area.
"""
print('(2.1) Slicing data files to chosen time period...')

# Temperature files sliced to desired time period
tas_hist_slice = tas_file_hist.sel(time=slice("1961-01-16", "1990-12-16"))
tas_ssp1_slice = tas_file_ssp1.sel(time=slice("2090-01-16", "2099-12-16"))
tas_ssp2_slice = tas_file_ssp2.sel(time=slice("2090-01-16", "2099-12-16"))
tas_ssp3_slice = tas_file_ssp3.sel(time=slice("2090-01-16", "2099-12-16"))
tas_ssp5_slice = tas_file_ssp5.sel(time=slice("2090-01-16", "2099-12-16"))

# Precipitation files sliced to desired time period
pre_hist_slice = pre_file_hist.sel(time=slice("1961-01-16", "1990-12-16"))
pre_ssp1_slice = pre_file_ssp1.sel(time=slice("2090-01-16", "2099-12-16"))
pre_ssp2_slice = pre_file_ssp2.sel(time=slice("2090-01-16", "2099-12-16"))
pre_ssp3_slice = pre_file_ssp3.sel(time=slice("2090-01-16", "2099-12-16"))
pre_ssp5_slice = pre_file_ssp5.sel(time=slice("2090-01-16", "2099-12-16"))

"""
(2.2) Convert climate data into desired units and average climate values for study time period
"""
print('(2.2) Calculating monthly temperature and precipitation values...')

# Temperature files
# GroupBy subdivides dataset into months before averaging. This code produces mean monthly temperatures.
tas_hist_mean_monthly_K = tas_hist_slice['tas'].groupby("time.month").mean('time',keep_attrs=True)
tas_ssp1_mean_monthly_K = tas_ssp1_slice['tas'].groupby("time.month").mean('time',keep_attrs=True)
tas_ssp2_mean_monthly_K = tas_ssp2_slice['tas'].groupby("time.month").mean('time',keep_attrs=True)
tas_ssp3_mean_monthly_K = tas_ssp3_slice['tas'].groupby("time.month").mean('time',keep_attrs=True)
tas_ssp5_mean_monthly_K = tas_ssp5_slice['tas'].groupby("time.month").mean('time',keep_attrs=True)

# Convert from Kelvin to Celsius
tas_hist_mean_monthly_C = tas_hist_mean_monthly_K-273.15
tas_ssp1_mean_monthly_C = tas_ssp1_mean_monthly_K-273.15
tas_ssp2_mean_monthly_C = tas_ssp2_mean_monthly_K-273.15
tas_ssp3_mean_monthly_C = tas_ssp3_mean_monthly_K-273.15
tas_ssp5_mean_monthly_C = tas_ssp5_mean_monthly_K-273.15

# Precipitation files
# Convert from precipitation flux (mm per second) to daily totals (mm per 24 hours)
# 60 seconds x 60 minutes x 24 hours = 86,400 seconds in one day
pre_hist_day = pre_hist_slice['pr'] * 86400.
pre_ssp1_day = pre_ssp1_slice['pr'] * 86400.
pre_ssp2_day = pre_ssp2_slice['pr'] * 86400.
pre_ssp3_day = pre_ssp3_slice['pr'] * 86400.
pre_ssp5_day = pre_ssp5_slice['pr'] * 86400.

# Assign the number of days in each month
# adapted from http://xarray.pydata.org/en/stable/examples/monthly-means.html
# Build a dictionary of calendars
dpm = {'noleap': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '365_day': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'standard': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'proleptic_gregorian': [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       'all_leap': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '366_day': [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
       '360_day': [0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]}

# Define new function get_dpm to retrieve the length of each month
def get_dpm(time, calendar='standard'):
    #return an array of days per month corresponding to the months provided in `months`
    month_length = np.zeros(len(time), dtype=np.int)
    cal_days = dpm[calendar]
    for i, (month, year) in enumerate(zip(time.month, time.year)):
        month_length[i] = cal_days[month]
    return month_length

# Use get_dpm to assign the number of days in each month to the sliced dataset
pre_hist_month_length = xr.DataArray(get_dpm(pre_hist_day.time.to_index(), calendar='noleap'), coords=[pre_hist_day.time], name='month_length')
pre_ssp1_month_length = xr.DataArray(get_dpm(pre_ssp1_day.time.to_index(), calendar='noleap'), coords=[pre_ssp1_day.time], name='month_length')
pre_ssp2_month_length = xr.DataArray(get_dpm(pre_ssp2_day.time.to_index(), calendar='noleap'), coords=[pre_ssp2_day.time], name='month_length')
pre_ssp3_month_length = xr.DataArray(get_dpm(pre_ssp3_day.time.to_index(), calendar='noleap'), coords=[pre_ssp3_day.time], name='month_length')
pre_ssp5_month_length = xr.DataArray(get_dpm(pre_ssp5_day.time.to_index(), calendar='noleap'), coords=[pre_ssp5_day.time], name='month_length')

# Multiply the number of days in each month by the mean daily precipitation values (mm per day)
pre_hist_mth= pre_hist_month_length * pre_hist_day
pre_ssp1_mth= pre_ssp1_month_length * pre_ssp1_day
pre_ssp2_mth= pre_ssp2_month_length * pre_ssp2_day
pre_ssp3_mth= pre_ssp3_month_length * pre_ssp3_day
pre_ssp5_mth= pre_ssp5_month_length * pre_ssp5_day

# Calculate mean precipitation values for each month
# GroupBy subdivides dataset into months before averaging. This code produces mean monthly precipitation totals.
pre_hist_mean_mth = pre_hist_mth.groupby("time.month").mean('time',keep_attrs=True)
pre_ssp1_mean_mth = pre_ssp1_mth.groupby("time.month").mean('time',keep_attrs=True)
pre_ssp2_mean_mth = pre_ssp2_mth.groupby("time.month").mean('time',keep_attrs=True)
pre_ssp3_mean_mth = pre_ssp3_mth.groupby("time.month").mean('time',keep_attrs=True)
pre_ssp5_mean_mth = pre_ssp5_mth.groupby("time.month").mean('time',keep_attrs=True)

print('Step 2: Calculate Monthly Averages Complete')

########################################################################################################
"""
STEP 3: MASK CMIP OCEANIC CELLS
"""
########################################################################################################

"""
(3.1) Use xarray to assign the land cover percentage data for the CMIP model to a new object.
"""
print('(3.1) Checking CMIP land-sea mask...')

#Use xarray to open the mask dataset
mask_dset = xr.open_dataset(mask_file)
# Assign the land percentage variable ['sftlf'] to a new object
land_perc = mask_dset['sftlf']
# check that max land area is 100 % (if values range from 0 - 1 adjust code in section below)
print('Max land area (CMIP mask):', land_perc.data.max(), '%')
# check that min land area is 0 %
print('Min land area (CMIP mask):', land_perc.data.min(), '%')

"""
(3.2) Mask out ocean in CMIP datasets (i.e. selecting only grid cells with > 50 % land)
"""
print('(3.2) Applying land-sea mask...')
#numpy includes a np.where function that allows us to simply use a logical command to mask out temperature data for oceanic grid cells (e.g. where land % is less than 50 %)
# if values range from 0 - 1 adjust conditional function
tas_hist_land_C = tas_hist_mean_monthly_C.where(land_perc.data > 50.)
tas_ssp1_land_C = tas_ssp1_mean_monthly_C.where(land_perc.data > 50.)
tas_ssp2_land_C = tas_ssp2_mean_monthly_C.where(land_perc.data > 50.)
tas_ssp3_land_C = tas_ssp3_mean_monthly_C.where(land_perc.data > 50.)
tas_ssp5_land_C = tas_ssp5_mean_monthly_C.where(land_perc.data > 50.)

# Mask out preciptiation data
pre_hist_land = pre_hist_mean_mth.where(land_perc.data > 50.)
pre_ssp1_land = pre_ssp1_mean_mth.where(land_perc.data > 50.)
pre_ssp2_land = pre_ssp2_mean_mth.where(land_perc.data > 50.)
pre_ssp3_land = pre_ssp3_mean_mth.where(land_perc.data > 50.)
pre_ssp5_land = pre_ssp5_mean_mth.where(land_perc.data > 50.)

print('Step 3: Mask Out Ocean complete')

########################################################################################################
"""
STEP 4: EXTRAPOLATION
Use Poisson Equation solver with overrelaxation to extrapolate terrestrial data over ocean.
"""
########################################################################################################
"""
(4.1) Convert xarray to iris cubes
"""
print ('(4.1) Converting data to iris cubes...')
# Temperature files
# Convert to iris from xarray:
tas_hist_land_Ciris = tas_hist_land_C.to_iris()
tas_ssp1_land_Ciris = tas_ssp1_land_C.to_iris()
tas_ssp2_land_Ciris = tas_ssp2_land_C.to_iris()
tas_ssp3_land_Ciris = tas_ssp3_land_C.to_iris()
tas_ssp5_land_Ciris = tas_ssp5_land_C.to_iris()
# Add the cyclic attribute to the iris cube to ensure data covers full 360 degrees of longitude
tas_hist_land_Ciris.coord('longitude').circular = True
tas_ssp1_land_Ciris.coord('longitude').circular = True
tas_ssp2_land_Ciris.coord('longitude').circular = True
tas_ssp3_land_Ciris.coord('longitude').circular = True
tas_ssp5_land_Ciris.coord('longitude').circular = True

# Precipitation files
# Convert to iris from xarray:
pre_hist_land_iris = pre_hist_land.to_iris()
pre_ssp1_land_iris = pre_ssp1_land.to_iris()
pre_ssp2_land_iris = pre_ssp2_land.to_iris()
pre_ssp3_land_iris = pre_ssp3_land.to_iris()
pre_ssp5_land_iris = pre_ssp5_land.to_iris()
# Add the cyclic attribute to the iris cube to ensure data covers full 360 degrees of longitude
pre_hist_land_iris.coord('longitude').circular = True
pre_ssp1_land_iris.coord('longitude').circular = True
pre_ssp2_land_iris.coord('longitude').circular = True
pre_ssp3_land_iris.coord('longitude').circular = True
pre_ssp5_land_iris.coord('longitude').circular = True

"""
(4.2) Conduct extrapolation procedure
"""
print ('(4.2) Extrapolating terrestrial climate over ocean...')
# Next step is to backfill (extrapolate) terrestrial climate over the ocean using gridfill.fill function
# Users can install gridfill manually from https://github.com/ajdawson/gridfill

## Definitions of terms used in Poisson gridfilling [and default values used in Morris et al. 2018]:
# eps = Tolerance for determining the solution complete. [1e-3]
# relax = Relaxation constant. Usually 0.45 <= *relax* <= 0.6. Defaults to 0.6. [0.6]
# itermax = Maximum number of iterations of the relaxation scheme. Defaults to 100 iterations. [2000] [here we specify a higher threshold e.g. 12000]
# initzonal = If *False* missing values will be initialized to zero, if *True* missing values will be initialized to the zonal mean. Defaultsto *False*. [True]
# cyclic = Set to *False* if the x-coordinate of the grid is not cyclic, set to *True* if it is cyclic. Defaults to *False*. [Not used]
# verbose = If *True* information about algorithm performance will be printed to stdout, if *False* nothing is printed. Defaults to *False*. [True]

# Temperature files
tas_hist_land_Ciris_backfilled = gridfill.fill_cube(tas_hist_land_Ciris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
tas_ssp1_land_Ciris_backfilled = gridfill.fill_cube(tas_ssp1_land_Ciris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
tas_ssp2_land_Ciris_backfilled = gridfill.fill_cube(tas_ssp2_land_Ciris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
tas_ssp3_land_Ciris_backfilled = gridfill.fill_cube(tas_ssp3_land_Ciris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
tas_ssp5_land_Ciris_backfilled = gridfill.fill_cube(tas_ssp5_land_Ciris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)

# Precipitation files
pre_hist_land_iris_backfilled = gridfill.fill_cube(pre_hist_land_iris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
pre_ssp1_land_iris_backfilled = gridfill.fill_cube(pre_ssp1_land_iris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
pre_ssp2_land_iris_backfilled = gridfill.fill_cube(pre_ssp2_land_iris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
pre_ssp3_land_iris_backfilled = gridfill.fill_cube(pre_ssp3_land_iris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)
pre_ssp5_land_iris_backfilled = gridfill.fill_cube(pre_ssp5_land_iris, 1e-3, 0.6, 12000, initzonal=True, verbose=True)

print('Step 4: Extrapolation complete')

########################################################################################################
"""
STEP 5: REGRIDDING TO HIGHER RESOLUTION
Regrid (interpolate) to the same resolution as the CRU grid (0.5 x 0.5 deg).
"""
########################################################################################################
"""
(5.1) Convert observational dataset to iris and reshape
"""
print('(5.1) Converting observational data to iris cube...')

# Temporarily convert CRU data to iris. Select only the 'tmp' variable (not stn). Use of either the tmp or pre grid is equivalent.
CRU_tmp_array = iris.load(CRU_tmp_file)[1] # only tmp not stn

# OPTIONAL] Select desired dates
import datetime
date1 = datetime.datetime.strptime('19610116T0000Z','%Y%m%dT%H%MZ')
date2 = datetime.datetime.strptime('19901216T0000Z','%Y%m%dT%H%MZ')
date_range = iris.Constraint(time=lambda cell: date1 <= cell.point <= date2 )
CRU_tmp_array_slice = CRU_tmp_array.extract(date_range)

"""
(5.2) Perform bilinear interpolation
"""
print("(5) Performing linear interpolation with Iris...")
# Here, we prefer the use of bilinear interpolation to regrid the CMIP climate data onto the CRU grid.
# Temperature files
tas_hist_land_Ciris_backfilled_high = tas_hist_land_Ciris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
tas_ssp1_land_Ciris_backfilled_high = tas_ssp1_land_Ciris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
tas_ssp2_land_Ciris_backfilled_high = tas_ssp2_land_Ciris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
tas_ssp3_land_Ciris_backfilled_high = tas_ssp3_land_Ciris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
tas_ssp5_land_Ciris_backfilled_high = tas_ssp5_land_Ciris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())

# Precipitation files
pre_hist_land_iris_backfilled_high = pre_hist_land_iris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
pre_ssp1_land_iris_backfilled_high = pre_ssp1_land_iris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
pre_ssp2_land_iris_backfilled_high = pre_ssp2_land_iris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
pre_ssp3_land_iris_backfilled_high = pre_ssp3_land_iris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())
pre_ssp5_land_iris_backfilled_high = pre_ssp5_land_iris_backfilled.regrid(CRU_tmp_array_slice, iris.analysis.Linear())

"""
(5.3)  Convert back to xarray
"""
print('(5.3) Converting interpolated data back to xarray...')

## Convert back to xarray:
# Temperature
tas_hist_land_C_backfilled_high = xr.DataArray.from_iris(tas_hist_land_Ciris_backfilled_high)
tas_ssp1_land_C_backfilled_high = xr.DataArray.from_iris(tas_ssp1_land_Ciris_backfilled_high)
tas_ssp2_land_C_backfilled_high = xr.DataArray.from_iris(tas_ssp2_land_Ciris_backfilled_high)
tas_ssp3_land_C_backfilled_high = xr.DataArray.from_iris(tas_ssp3_land_Ciris_backfilled_high)
tas_ssp5_land_C_backfilled_high = xr.DataArray.from_iris(tas_ssp5_land_Ciris_backfilled_high)

# Precipitation
pre_hist_land_backfilled_high = xr.DataArray.from_iris(pre_hist_land_iris_backfilled_high)
pre_ssp1_land_backfilled_high = xr.DataArray.from_iris(pre_ssp1_land_iris_backfilled_high)
pre_ssp2_land_backfilled_high = xr.DataArray.from_iris(pre_ssp2_land_iris_backfilled_high)
pre_ssp3_land_backfilled_high = xr.DataArray.from_iris(pre_ssp3_land_iris_backfilled_high)
pre_ssp5_land_backfilled_high = xr.DataArray.from_iris(pre_ssp5_land_iris_backfilled_high)

print("Step 5: Interpolation complete")

########################################################################################################
"""
STEP 6: APPLY OBSERVATIONAL LAND-SEA MASK
"""
########################################################################################################
"""
(6.1) Create CRU land sea mask
"""
print("(6.1) Creating CRU land-sea mask...")

## Reload CRU data as an xarray, select climate variable, and reshape to match shape of CMIP array.
# Temperature files
CRU_tmp_slice_xr = CRU_tmp_dset.sel(time=slice("1961-01-16", "1990-12-16"))
CRU_tmp_xr = CRU_tmp_slice_xr['tmp'].groupby("time.month").mean('time',keep_attrs=True)

# Precipitation files
CRU_pre_slice_xr = CRU_pre_dset.sel(time=slice("1961-01-16", "1990-12-16"))
CRU_pre_xr = CRU_pre_slice_xr['pre'].groupby("time.month").mean('time',keep_attrs=True)

"""
(6.2) Apply CRU land sea mask to downscaled CMIP data
"""
print("(6) Applying Observational Mask")

# The fill value for missing values (i.e. oceanic cells) in the CRU data is -999. This line selects only those which are greater than that value (i.e. terrestrial cells).
# Temperature files
tas_hist_land_C_backfilled_high_masked = tas_hist_land_C_backfilled_high.where(CRU_tmp_xr.data >-998)
tas_ssp1_land_C_backfilled_high_masked = tas_ssp1_land_C_backfilled_high.where(CRU_tmp_xr.data >-998)
tas_ssp2_land_C_backfilled_high_masked = tas_ssp2_land_C_backfilled_high.where(CRU_tmp_xr.data >-998)
tas_ssp3_land_C_backfilled_high_masked = tas_ssp3_land_C_backfilled_high.where(CRU_tmp_xr.data >-998)
tas_ssp5_land_C_backfilled_high_masked = tas_ssp5_land_C_backfilled_high.where(CRU_tmp_xr.data >-998)

# Precipitation files
pre_hist_land_backfilled_high_masked = pre_hist_land_backfilled_high.where(CRU_tmp_xr.data >-998)
pre_ssp1_land_backfilled_high_masked = pre_ssp1_land_backfilled_high.where(CRU_tmp_xr.data >-998)
pre_ssp2_land_backfilled_high_masked = pre_ssp2_land_backfilled_high.where(CRU_tmp_xr.data >-998)
pre_ssp3_land_backfilled_high_masked = pre_ssp3_land_backfilled_high.where(CRU_tmp_xr.data >-998)
pre_ssp5_land_backfilled_high_masked = pre_ssp5_land_backfilled_high.where(CRU_tmp_xr.data >-998)

print("Step 6: Apply Observational Land-Sea Mask complete")

########################################################################################################
"""
STEP 7: BIAS CORRECTION
"""
########################################################################################################
"""
(7.1) Variable formatting
"""
print('(7.1) Preparing data for bias-correction...')

# Temperature
CRU_tmp = CRU_tmp_xr
CMIP_hist_tmp = tas_hist_land_C_backfilled_high_masked
SSP1_tmp = tas_ssp1_land_C_backfilled_high_masked
SSP2_tmp = tas_ssp2_land_C_backfilled_high_masked
SSP3_tmp = tas_ssp3_land_C_backfilled_high_masked
SSP5_tmp = tas_ssp5_land_C_backfilled_high_masked

# Precipitation
CRU_pre = CRU_pre_xr
CMIP_hist_pre = pre_hist_land_backfilled_high_masked
SSP1_pre = pre_ssp1_land_backfilled_high_masked
SSP2_pre = pre_ssp2_land_backfilled_high_masked
SSP3_pre = pre_ssp3_land_backfilled_high_masked
SSP5_pre = pre_ssp5_land_backfilled_high_masked

"""
(7.2) Temperature Bias correction

BCor_Temp = (CMIP_fut_tmp - CMIP_hist_tmp) + CRU_tmp
"""
print('(7.2) Performing temperature bias-correction...')

# Temperature correction calculation is followed by a function that renames each variable:
SSP1_BCor_tmp = (SSP1_tmp - CMIP_hist_tmp) + CRU_tmp
SSP1_BCor_tmp = SSP1_BCor_tmp.rename('mean monthly near-surface temperature (degrees Celsius)')
SSP2_BCor_tmp = (SSP2_tmp - CMIP_hist_tmp) + CRU_tmp
SSP2_BCor_tmp = SSP2_BCor_tmp.rename('mean monthly near-surface temperature (degrees Celsius)')
SSP3_BCor_tmp = (SSP3_tmp - CMIP_hist_tmp) + CRU_tmp
SSP3_BCor_tmp = SSP3_BCor_tmp.rename('mean monthly near-surface temperature (degrees Celsius)')
SSP5_BCor_tmp = (SSP5_tmp - CMIP_hist_tmp) + CRU_tmp
SSP5_BCor_tmp = SSP5_BCor_tmp.rename('mean monthly near-surface temperature (degrees Celsius)')

"""
(7.3) Precipitation Bias correction

BCor_Pre = (CRU_pre / CMIP_hist_pre) * CMIP_fut_pre
"""
print('(7.3) Performing precipitation bias-correction...')

# Precipitation correction calculations:
# First calculate alpha...
a = CRU_pre / CMIP_hist_pre
# Set limits for alpha (from Morris et al. 2018)...
a = xr.where(a < 0.25, 0.25, a)
a_ltd = xr.where(a > 4.0, 4.0, a)

# Apply the limited alpha coefficient to bias correct future precipitation
SSP1_BCor_pre = a_ltd * SSP1_pre
SSP1_BCor_pre = SSP1_BCor_pre.rename('mean monthly precipitation (mm)')
SSP2_BCor_pre = a_ltd * SSP2_pre
SSP2_BCor_pre = SSP2_BCor_pre.rename('mean monthly precipitation (mm)')
SSP3_BCor_pre = a_ltd * SSP3_pre
SSP3_BCor_pre = SSP3_BCor_pre.rename('mean monthly precipitation (mm)')
SSP5_BCor_pre = a_ltd * SSP5_pre
SSP5_BCor_pre = SSP5_BCor_pre.rename('mean monthly precipitation (mm)')

"""
(7.4) Subset to the region of interest
"""
# (OPTIONAL) This function selects only grid cells that fall within the latitudinal bands specified
# [ANSWER EITHER: yes OR no]
answer = input('(7.4) [OPTIONAL] Crop output to study region?:')
if answer.lower().startswith("y"):
      # Temperature
      CMIP_hist_tmp = CMIP_hist_tmp.sel(lat=slice(44., 90.))
      SSP1_BCor_tmp = SSP1_BCor_tmp.sel(lat=slice(44., 90.))
      SSP2_BCor_tmp = SSP2_BCor_tmp.sel(lat=slice(44., 90.))
      SSP3_BCor_tmp = SSP3_BCor_tmp.sel(lat=slice(44., 90.))
      SSP5_BCor_tmp = SSP5_BCor_tmp.sel(lat=slice(44., 90.))

      # Preciptiation
      CMIP_hist_pre = CMIP_hist_pre.sel(lat=slice(44., 90.))
      SSP1_BCor_pre = SSP1_BCor_pre.sel(lat=slice(44., 90.))
      SSP2_BCor_pre = SSP2_BCor_pre.sel(lat=slice(44., 90.))
      SSP3_BCor_pre = SSP3_BCor_pre.sel(lat=slice(44., 90.))
      SSP5_BCor_pre = SSP5_BCor_pre.sel(lat=slice(44., 90.))

      tmp_DIR= tmp_DIR+'sliced_'
      pre_DIR= pre_DIR+'sliced_'

elif answer.lower().startswith("n"):

      tmp_DIR= tmp_DIR+'global_'
      pre_DIR= pre_DIR+'global_'

else:
        print("Enter either yes/no")

print("Step 7 complete")

########################################################################################################
"""
STEP 8: OUTPUT RESULTS
"""
########################################################################################################
"""
(8.1) Exporting the results to netcdf format
"""

import sys
# Optional choice to export as netcdf or pass
answer = input('(8.1) [OPTIONAL] Export data files to netCDF?:')
if answer.lower().startswith("y"):
      print("(8.1) Data export to NetCDF...")
      # Prevent warnings from flashing up - turn off/on as desired
      # Turned off as no issue with 'true divide' (dividing by NaN).
      np.warnings.filterwarnings('ignore')
      # Temperature files
      CMIP_hist_tmp.to_netcdf(tmp_DIR+'cmip_hist.nc')
      print('tmp_CMIP_hist.nc complete')
      CRU_tmp.to_netcdf(tmp_DIR+'cru_1961_1990.nc')
      print('tmp_CRU_1961_1990.nc complete')
      SSP1_BCor_tmp.to_netcdf(tmp_DIR+'bcor_ssp1.nc')
      print('tmp_bcor_ssp1.nc complete')
      SSP2_BCor_tmp.to_netcdf(tmp_DIR+'bcor_ssp2.nc')
      print('tmp_bcor_ssp2.nc complete')
      SSP3_BCor_tmp.to_netcdf(tmp_DIR+'bcor_ssp3.nc')
      print('tmp_bcor_ssp3.nc complete')
      SSP5_BCor_tmp.to_netcdf(tmp_DIR+'bcor_ssp5.nc')
      print('tmp_bcor_ssp5.nc complete')
      # Precipitation files
      CMIP_hist_pre.to_netcdf(pre_DIR+'cmip_hist.nc')
      print('pre_CMIP_hist.nc complete')
      CRU_pre.to_netcdf(pre_DIR+'cru_1961_1990.nc')
      print('pre_CRU_1961_1990.nc complete')
      SSP1_BCor_pre.to_netcdf(pre_DIR+'bcor_ssp1.nc')
      print('pre_bcor_ssp1.nc complete')
      SSP2_BCor_pre.to_netcdf(pre_DIR+'bcor_ssp2.nc')
      print('pre_bcor_ssp2.nc complete')
      SSP3_BCor_pre.to_netcdf(pre_DIR+'bcor_ssp3.nc')
      print('pre_bcor_ssp3.nc complete')
      SSP5_BCor_pre.to_netcdf(pre_DIR+'bcor_ssp5.nc')
      print('pre_bcor_ssp5.nc complete')
      # Turn warnings back on
      np.warnings.filterwarnings('default')
elif answer.lower().startswith("n"):
    pass
else:
        print("Enter either yes/no")

"""
(8.2) Export the results as .csv
"""
# Optional choice to export as netcdf or pass
answer = input('(8.2) [OPTIONAL] Export data files to .csv?:')
if answer.lower().startswith("y"):
      print("(8.2) Data export to .csv...")
# Prevent warnings from flashing up - turn off/on as desired
      np.warnings.filterwarnings('ignore')
# Temperature files
# Historical
      CMIP_hist_tmp = CMIP_hist_tmp.rename('mean monthly near-surface temperature (degrees Celsius)') # ensure dataset is named
      hist_tmp_jan = CMIP_hist_tmp.sel(month=1) # select tas data from the first month
      hist_tmp_jan_df= hist_tmp_jan.to_dataframe() # turn this data into a pandas dataframe
      hist_tmp_jan_df = hist_tmp_jan_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jan_MMT"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      hist_tmp_feb = CMIP_hist_tmp.sel(month=2)
      hist_tmp_feb_df= hist_tmp_feb.to_dataframe()
      hist_tmp_feb_df = hist_tmp_feb_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Feb_MMT"})
      print('##')
      hist_tmp_mar = CMIP_hist_tmp.sel(month=3)
      hist_tmp_mar_df= hist_tmp_mar.to_dataframe()
      hist_tmp_mar_df = hist_tmp_mar_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Mar_MMT"})
      print('###')
      hist_tmp_apr = CMIP_hist_tmp.sel(month=4)
      hist_tmp_apr_df= hist_tmp_apr.to_dataframe()
      hist_tmp_apr_df = hist_tmp_apr_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Apr_MMT"})
      print('####')
      hist_tmp_may = CMIP_hist_tmp.sel(month=5)
      hist_tmp_may_df= hist_tmp_may.to_dataframe()
      hist_tmp_may_df = hist_tmp_may_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "May_MMT"})
      print('#####')
      hist_tmp_jun = CMIP_hist_tmp.sel(month=6)
      hist_tmp_jun_df= hist_tmp_jun.to_dataframe()
      hist_tmp_jun_df = hist_tmp_jun_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jun_MMT"})
      print('######')
      hist_tmp_jul = CMIP_hist_tmp.sel(month=7)
      hist_tmp_jul_df= hist_tmp_jul.to_dataframe()
      hist_tmp_jul_df = hist_tmp_jul_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jul_MMT"})
      print('#######')
      hist_tmp_aug = CMIP_hist_tmp.sel(month=8)
      hist_tmp_aug_df= hist_tmp_aug.to_dataframe()
      hist_tmp_aug_df = hist_tmp_aug_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Aug_MMT"})
      print('########')
      hist_tmp_sep = CMIP_hist_tmp.sel(month=9)
      hist_tmp_sep_df= hist_tmp_sep.to_dataframe()
      hist_tmp_sep_df = hist_tmp_sep_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Sep_MMT"})
      print('#########')
      hist_tmp_oct = CMIP_hist_tmp.sel(month=10)
      hist_tmp_oct_df= hist_tmp_oct.to_dataframe()
      hist_tmp_oct_df = hist_tmp_oct_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Oct_MMT"})
      print('##########')
      hist_tmp_nov = CMIP_hist_tmp.sel(month=11)
      hist_tmp_nov_df= hist_tmp_nov.to_dataframe()
      hist_tmp_nov_df = hist_tmp_nov_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Nov_MMT"})
      print('###########')
      hist_tmp_dec = CMIP_hist_tmp.sel(month=12)
      hist_tmp_dec_df= hist_tmp_dec.to_dataframe()
      hist_tmp_dec_df = hist_tmp_dec_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Dec_MMT"})
      print('############')
      hist_tmp_df = pd.concat([hist_tmp_jan_df, hist_tmp_feb_df, hist_tmp_mar_df, hist_tmp_apr_df, hist_tmp_may_df, hist_tmp_jun_df, hist_tmp_jul_df, hist_tmp_aug_df, hist_tmp_sep_df, hist_tmp_oct_df, hist_tmp_nov_df, hist_tmp_dec_df], axis=1) # add each variable as a column
      hist_tmp_df = hist_tmp_df.reset_index() # add id column
      hist_tmp_df.index = hist_tmp_df.index + 1 # start id index at 1, not 0
      hist_tmp_df.to_csv(tmp_DIR+'CMIP_hist.csv')
      print('CMIP_hist_tmp.csv complete')

# SSP1 tmp
      SSP1_tmp_jan = SSP1_BCor_tmp.sel(month=1) # select tas data from the first month
      SSP1_tmp_jan_df= SSP1_tmp_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP1_tmp_jan_df = SSP1_tmp_jan_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jan_MMT"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP1_tmp_feb = SSP1_BCor_tmp.sel(month=2)
      SSP1_tmp_feb_df= SSP1_tmp_feb.to_dataframe()
      SSP1_tmp_feb_df = SSP1_tmp_feb_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Feb_MMT"})
      print('##')
      SSP1_tmp_mar = SSP1_BCor_tmp.sel(month=3)
      SSP1_tmp_mar_df= SSP1_tmp_mar.to_dataframe()
      SSP1_tmp_mar_df = SSP1_tmp_mar_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Mar_MMT"})
      print('###')
      SSP1_tmp_apr = SSP1_BCor_tmp.sel(month=4)
      SSP1_tmp_apr_df= SSP1_tmp_apr.to_dataframe()
      SSP1_tmp_apr_df = SSP1_tmp_apr_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Apr_MMT"})
      print('####')
      SSP1_tmp_may = SSP1_BCor_tmp.sel(month=5)
      SSP1_tmp_may_df= SSP1_tmp_may.to_dataframe()
      SSP1_tmp_may_df = SSP1_tmp_may_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "May_MMT"})
      print('#####')
      SSP1_tmp_jun = SSP1_BCor_tmp.sel(month=6)
      SSP1_tmp_jun_df= SSP1_tmp_jun.to_dataframe()
      SSP1_tmp_jun_df = SSP1_tmp_jun_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jun_MMT"})
      print('######')
      SSP1_tmp_jul = SSP1_BCor_tmp.sel(month=7)
      SSP1_tmp_jul_df= SSP1_tmp_jul.to_dataframe()
      SSP1_tmp_jul_df = SSP1_tmp_jul_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jul_MMT"})
      print('#######')
      SSP1_tmp_aug = SSP1_BCor_tmp.sel(month=8)
      SSP1_tmp_aug_df= SSP1_tmp_aug.to_dataframe()
      SSP1_tmp_aug_df = SSP1_tmp_aug_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Aug_MMT"})
      print('########')
      SSP1_tmp_sep = SSP1_BCor_tmp.sel(month=9)
      SSP1_tmp_sep_df= SSP1_tmp_sep.to_dataframe()
      SSP1_tmp_sep_df = SSP1_tmp_sep_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Sep_MMT"})
      print('#########')
      SSP1_tmp_oct = SSP1_BCor_tmp.sel(month=10)
      SSP1_tmp_oct_df= SSP1_tmp_oct.to_dataframe()
      SSP1_tmp_oct_df = SSP1_tmp_oct_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Oct_MMT"})
      print('##########')
      SSP1_tmp_nov = SSP1_BCor_tmp.sel(month=11)
      SSP1_tmp_nov_df= SSP1_tmp_nov.to_dataframe()
      SSP1_tmp_nov_df = SSP1_tmp_nov_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Nov_MMT"})
      print('###########')
      SSP1_tmp_dec = SSP1_BCor_tmp.sel(month=12)
      SSP1_tmp_dec_df= SSP1_tmp_dec.to_dataframe()
      SSP1_tmp_dec_df = SSP1_tmp_dec_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Dec_MMT"})
      print('############')
      SSP1_tmp_df = pd.concat([SSP1_tmp_jan_df, SSP1_tmp_feb_df, SSP1_tmp_mar_df, SSP1_tmp_apr_df, SSP1_tmp_may_df, SSP1_tmp_jun_df, SSP1_tmp_jul_df, SSP1_tmp_aug_df, SSP1_tmp_sep_df, SSP1_tmp_oct_df, SSP1_tmp_nov_df, SSP1_tmp_dec_df], axis=1) # add each variable as a column
      SSP1_tmp_df = SSP1_tmp_df.reset_index() # add id column
      SSP1_tmp_df.index = SSP1_tmp_df.index + 1 # start id index at 1, not 0
      SSP1_tmp_df.to_csv(tmp_DIR+'bcor_ssp1.csv')
      print('SSP1_tmp.csv complete')

# SSP2 tmp
      SSP2_tmp_jan = SSP2_BCor_tmp.sel(month=1) # select tas data from the first month
      SSP2_tmp_jan_df= SSP2_tmp_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP2_tmp_jan_df = SSP2_tmp_jan_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jan_MMT"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP2_tmp_feb = SSP2_BCor_tmp.sel(month=2)
      SSP2_tmp_feb_df= SSP2_tmp_feb.to_dataframe()
      SSP2_tmp_feb_df = SSP2_tmp_feb_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Feb_MMT"})
      print('##')
      SSP2_tmp_mar = SSP2_BCor_tmp.sel(month=3)
      SSP2_tmp_mar_df= SSP2_tmp_mar.to_dataframe()
      SSP2_tmp_mar_df = SSP2_tmp_mar_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Mar_MMT"})
      print('###')
      SSP2_tmp_apr = SSP2_BCor_tmp.sel(month=4)
      SSP2_tmp_apr_df= SSP2_tmp_apr.to_dataframe()
      SSP2_tmp_apr_df = SSP2_tmp_apr_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Apr_MMT"})
      print('####')
      SSP2_tmp_may = SSP2_BCor_tmp.sel(month=5)
      SSP2_tmp_may_df= SSP2_tmp_may.to_dataframe()
      SSP2_tmp_may_df = SSP2_tmp_may_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "May_MMT"})
      print('#####')
      SSP2_tmp_jun = SSP2_BCor_tmp.sel(month=6)
      SSP2_tmp_jun_df= SSP2_tmp_jun.to_dataframe()
      SSP2_tmp_jun_df = SSP2_tmp_jun_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jun_MMT"})
      print('######')
      SSP2_tmp_jul = SSP2_BCor_tmp.sel(month=7)
      SSP2_tmp_jul_df= SSP2_tmp_jul.to_dataframe()
      SSP2_tmp_jul_df = SSP2_tmp_jul_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jul_MMT"})
      print('#######')
      SSP2_tmp_aug = SSP2_BCor_tmp.sel(month=8)
      SSP2_tmp_aug_df= SSP2_tmp_aug.to_dataframe()
      SSP2_tmp_aug_df = SSP2_tmp_aug_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Aug_MMT"})
      print('########')
      SSP2_tmp_sep = SSP2_BCor_tmp.sel(month=9)
      SSP2_tmp_sep_df= SSP2_tmp_sep.to_dataframe()
      SSP2_tmp_sep_df = SSP2_tmp_sep_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Sep_MMT"})
      print('#########')
      SSP2_tmp_oct = SSP2_BCor_tmp.sel(month=10)
      SSP2_tmp_oct_df= SSP2_tmp_oct.to_dataframe()
      SSP2_tmp_oct_df = SSP2_tmp_oct_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Oct_MMT"})
      print('##########')
      SSP2_tmp_nov = SSP2_BCor_tmp.sel(month=11)
      SSP2_tmp_nov_df= SSP2_tmp_nov.to_dataframe()
      SSP2_tmp_nov_df = SSP2_tmp_nov_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Nov_MMT"})
      print('###########')
      SSP2_tmp_dec = SSP2_BCor_tmp.sel(month=12)
      SSP2_tmp_dec_df= SSP2_tmp_dec.to_dataframe()
      SSP2_tmp_dec_df = SSP2_tmp_dec_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Dec_MMT"})
      print('############')
      SSP2_tmp_df = pd.concat([SSP2_tmp_jan_df, SSP2_tmp_feb_df, SSP2_tmp_mar_df, SSP2_tmp_apr_df, SSP2_tmp_may_df, SSP2_tmp_jun_df, SSP2_tmp_jul_df, SSP2_tmp_aug_df, SSP2_tmp_sep_df, SSP2_tmp_oct_df, SSP2_tmp_nov_df, SSP2_tmp_dec_df], axis=1) # add each variable as a column
      SSP2_tmp_df = SSP2_tmp_df.reset_index() # add id column
      SSP2_tmp_df.index = SSP2_tmp_df.index + 1 # start id index at 1, not 0
      SSP2_tmp_df.to_csv(tmp_DIR+'bcor_ssp2.csv')
      print('SSP2_tmp.csv complete')

# SSP3 tmp
      SSP3_tmp_jan = SSP3_BCor_tmp.sel(month=1) # select tas data from the first month
      SSP3_tmp_jan_df= SSP3_tmp_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP3_tmp_jan_df = SSP3_tmp_jan_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jan_MMT"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP3_tmp_feb = SSP3_BCor_tmp.sel(month=2)
      SSP3_tmp_feb_df= SSP3_tmp_feb.to_dataframe()
      SSP3_tmp_feb_df = SSP3_tmp_feb_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Feb_MMT"})
      print('##')
      SSP3_tmp_mar = SSP3_BCor_tmp.sel(month=3)
      SSP3_tmp_mar_df= SSP3_tmp_mar.to_dataframe()
      SSP3_tmp_mar_df = SSP3_tmp_mar_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Mar_MMT"})
      print('###')
      SSP3_tmp_apr = SSP3_BCor_tmp.sel(month=4)
      SSP3_tmp_apr_df= SSP3_tmp_apr.to_dataframe()
      SSP3_tmp_apr_df = SSP3_tmp_apr_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Apr_MMT"})
      print('####')
      SSP3_tmp_may = SSP3_BCor_tmp.sel(month=5)
      SSP3_tmp_may_df= SSP3_tmp_may.to_dataframe()
      SSP3_tmp_may_df = SSP3_tmp_may_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "May_MMT"})
      print('#####')
      SSP3_tmp_jun = SSP3_BCor_tmp.sel(month=6)
      SSP3_tmp_jun_df= SSP3_tmp_jun.to_dataframe()
      SSP3_tmp_jun_df = SSP3_tmp_jun_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jun_MMT"})
      print('######')
      SSP3_tmp_jul = SSP3_BCor_tmp.sel(month=7)
      SSP3_tmp_jul_df= SSP3_tmp_jul.to_dataframe()
      SSP3_tmp_jul_df = SSP3_tmp_jul_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jul_MMT"})
      print('#######')
      SSP3_tmp_aug = SSP3_BCor_tmp.sel(month=8)
      SSP3_tmp_aug_df= SSP3_tmp_aug.to_dataframe()
      SSP3_tmp_aug_df = SSP3_tmp_aug_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Aug_MMT"})
      print('########')
      SSP3_tmp_sep = SSP3_BCor_tmp.sel(month=9)
      SSP3_tmp_sep_df= SSP3_tmp_sep.to_dataframe()
      SSP3_tmp_sep_df = SSP3_tmp_sep_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Sep_MMT"})
      print('#########')
      SSP3_tmp_oct = SSP3_BCor_tmp.sel(month=10)
      SSP3_tmp_oct_df= SSP3_tmp_oct.to_dataframe()
      SSP3_tmp_oct_df = SSP3_tmp_oct_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Oct_MMT"})
      print('##########')
      SSP3_tmp_nov = SSP3_BCor_tmp.sel(month=11)
      SSP3_tmp_nov_df= SSP3_tmp_nov.to_dataframe()
      SSP3_tmp_nov_df = SSP3_tmp_nov_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Nov_MMT"})
      print('###########')
      SSP3_tmp_dec = SSP3_BCor_tmp.sel(month=12)
      SSP3_tmp_dec_df= SSP3_tmp_dec.to_dataframe()
      SSP3_tmp_dec_df = SSP3_tmp_dec_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Dec_MMT"})
      print('############')
      SSP3_tmp_df = pd.concat([SSP3_tmp_jan_df, SSP3_tmp_feb_df, SSP3_tmp_mar_df, SSP3_tmp_apr_df, SSP3_tmp_may_df, SSP3_tmp_jun_df, SSP3_tmp_jul_df, SSP3_tmp_aug_df, SSP3_tmp_sep_df, SSP3_tmp_oct_df, SSP3_tmp_nov_df, SSP3_tmp_dec_df], axis=1) # add each variable as a column
      SSP3_tmp_df = SSP3_tmp_df.reset_index() # add id column
      SSP3_tmp_df.index = SSP3_tmp_df.index + 1 # start id index at 1, not 0
      SSP3_tmp_df.to_csv(tmp_DIR+'bcor_ssp3.csv')
      print('SSP3_tmp.csv complete')

      # SSP5 tmp
      SSP5_tmp_jan = SSP5_BCor_tmp.sel(month=1) # select tas data from the first month
      SSP5_tmp_jan_df= SSP5_tmp_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP5_tmp_jan_df = SSP5_tmp_jan_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jan_MMT"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP5_tmp_feb = SSP5_BCor_tmp.sel(month=2)
      SSP5_tmp_feb_df= SSP5_tmp_feb.to_dataframe()
      SSP5_tmp_feb_df = SSP5_tmp_feb_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Feb_MMT"})
      print('##')
      SSP5_tmp_mar = SSP5_BCor_tmp.sel(month=3)
      SSP5_tmp_mar_df= SSP5_tmp_mar.to_dataframe()
      SSP5_tmp_mar_df = SSP5_tmp_mar_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Mar_MMT"})
      print('###')
      SSP5_tmp_apr = SSP5_BCor_tmp.sel(month=4)
      SSP5_tmp_apr_df= SSP5_tmp_apr.to_dataframe()
      SSP5_tmp_apr_df = SSP5_tmp_apr_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Apr_MMT"})
      print('####')
      SSP5_tmp_may = SSP5_BCor_tmp.sel(month=5)
      SSP5_tmp_may_df= SSP5_tmp_may.to_dataframe()
      SSP5_tmp_may_df = SSP5_tmp_may_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "May_MMT"})
      print('#####')
      SSP5_tmp_jun = SSP5_BCor_tmp.sel(month=6)
      SSP5_tmp_jun_df= SSP5_tmp_jun.to_dataframe()
      SSP5_tmp_jun_df = SSP5_tmp_jun_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jun_MMT"})
      print('######')
      SSP5_tmp_jul = SSP5_BCor_tmp.sel(month=7)
      SSP5_tmp_jul_df= SSP5_tmp_jul.to_dataframe()
      SSP5_tmp_jul_df = SSP5_tmp_jul_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Jul_MMT"})
      print('#######')
      SSP5_tmp_aug = SSP5_BCor_tmp.sel(month=8)
      SSP5_tmp_aug_df= SSP5_tmp_aug.to_dataframe()
      SSP5_tmp_aug_df = SSP5_tmp_aug_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Aug_MMT"})
      print('########')
      SSP5_tmp_sep = SSP5_BCor_tmp.sel(month=9)
      SSP5_tmp_sep_df= SSP5_tmp_sep.to_dataframe()
      SSP5_tmp_sep_df = SSP5_tmp_sep_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Sep_MMT"})
      print('#########')
      SSP5_tmp_oct = SSP5_BCor_tmp.sel(month=10)
      SSP5_tmp_oct_df= SSP5_tmp_oct.to_dataframe()
      SSP5_tmp_oct_df = SSP5_tmp_oct_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Oct_MMT"})
      print('##########')
      SSP5_tmp_nov = SSP5_BCor_tmp.sel(month=11)
      SSP5_tmp_nov_df= SSP5_tmp_nov.to_dataframe()
      SSP5_tmp_nov_df = SSP5_tmp_nov_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Nov_MMT"})
      print('###########')
      SSP5_tmp_dec = SSP5_BCor_tmp.sel(month=12)
      SSP5_tmp_dec_df= SSP5_tmp_dec.to_dataframe()
      SSP5_tmp_dec_df = SSP5_tmp_dec_df.drop(["month", "height"], axis=1).rename(columns={"mean monthly near-surface temperature (degrees Celsius)": "Dec_MMT"})
      print('############')
      SSP5_tmp_df = pd.concat([SSP5_tmp_jan_df, SSP5_tmp_feb_df, SSP5_tmp_mar_df, SSP5_tmp_apr_df, SSP5_tmp_may_df, SSP5_tmp_jun_df, SSP5_tmp_jul_df, SSP5_tmp_aug_df, SSP5_tmp_sep_df, SSP5_tmp_oct_df, SSP5_tmp_nov_df, SSP5_tmp_dec_df], axis=1) # add each variable as a column
      SSP5_tmp_df = SSP5_tmp_df.reset_index() # add id column
      SSP5_tmp_df.index = SSP5_tmp_df.index + 1 # start id index at 1, not 0
      SSP5_tmp_df.to_csv(tmp_DIR+'bcor_ssp5.csv')
      print('SSP5_tmp.csv complete')

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Precipitation files
# Historical
      CMIP_hist_pre = CMIP_hist_pre.rename('mean monthly precipitation (mm)') # ensure dataset is named
      hist_pre_jan = CMIP_hist_pre.sel(month=1) # select pre data from the first month
      hist_pre_jan_df= hist_pre_jan.to_dataframe() # turn this data into a pandas dataframe
      hist_pre_jan_df = hist_pre_jan_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jan_pre"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      hist_pre_feb = CMIP_hist_pre.sel(month=2)
      hist_pre_feb_df= hist_pre_feb.to_dataframe()
      hist_pre_feb_df = hist_pre_feb_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Feb_pre"})
      print('##')
      hist_pre_mar = CMIP_hist_pre.sel(month=3)
      hist_pre_mar_df= hist_pre_mar.to_dataframe()
      hist_pre_mar_df = hist_pre_mar_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Mar_pre"})
      print('###')
      hist_pre_apr = CMIP_hist_pre.sel(month=4)
      hist_pre_apr_df= hist_pre_apr.to_dataframe()
      hist_pre_apr_df = hist_pre_apr_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Apr_pre"})
      print('####')
      hist_pre_may = CMIP_hist_pre.sel(month=5)
      hist_pre_may_df= hist_pre_may.to_dataframe()
      hist_pre_may_df = hist_pre_may_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "May_pre"})
      print('#####')
      hist_pre_jun = CMIP_hist_pre.sel(month=6)
      hist_pre_jun_df= hist_pre_jun.to_dataframe()
      hist_pre_jun_df = hist_pre_jun_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jun_pre"})
      print('######')
      hist_pre_jul = CMIP_hist_pre.sel(month=7)
      hist_pre_jul_df= hist_pre_jul.to_dataframe()
      hist_pre_jul_df = hist_pre_jul_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jul_pre"})
      print('#######')
      hist_pre_aug = CMIP_hist_pre.sel(month=8)
      hist_pre_aug_df= hist_pre_aug.to_dataframe()
      hist_pre_aug_df = hist_pre_aug_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Aug_pre"})
      print('########')
      hist_pre_sep = CMIP_hist_pre.sel(month=9)
      hist_pre_sep_df= hist_pre_sep.to_dataframe()
      hist_pre_sep_df = hist_pre_sep_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Sep_pre"})
      print('#########')
      hist_pre_oct = CMIP_hist_pre.sel(month=10)
      hist_pre_oct_df= hist_pre_oct.to_dataframe()
      hist_pre_oct_df = hist_pre_oct_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Oct_pre"})
      print('##########')
      hist_pre_nov = CMIP_hist_pre.sel(month=11)
      hist_pre_nov_df= hist_pre_nov.to_dataframe()
      hist_pre_nov_df = hist_pre_nov_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Nov_pre"})
      print('###########')
      hist_pre_dec = CMIP_hist_pre.sel(month=12)
      hist_pre_dec_df= hist_pre_dec.to_dataframe()
      hist_pre_dec_df = hist_pre_dec_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Dec_pre"})
      print('############')
      hist_pre_df = pd.concat([hist_pre_jan_df, hist_pre_feb_df, hist_pre_mar_df, hist_pre_apr_df, hist_pre_may_df, hist_pre_jun_df, hist_pre_jul_df, hist_pre_aug_df, hist_pre_sep_df, hist_pre_oct_df, hist_pre_nov_df, hist_pre_dec_df], axis=1) # add each variable as a column
      hist_pre_df = hist_pre_df.reset_index() # add id column
      hist_pre_df.index = hist_pre_df.index + 1 # start id index at 1, not 0
      hist_pre_df.to_csv(pre_DIR+'CMIP_hist.csv')
      print('CMIP_hist_pre.csv complete')

# SSP1 pre
      SSP1_pre_jan = SSP1_BCor_pre.sel(month=1) # select pre data from the first month
      SSP1_pre_jan_df= SSP1_pre_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP1_pre_jan_df = SSP1_pre_jan_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jan_pre"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP1_pre_feb = SSP1_BCor_pre.sel(month=2)
      SSP1_pre_feb_df= SSP1_pre_feb.to_dataframe()
      SSP1_pre_feb_df = SSP1_pre_feb_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Feb_pre"})
      print('##')
      SSP1_pre_mar = SSP1_BCor_pre.sel(month=3)
      SSP1_pre_mar_df= SSP1_pre_mar.to_dataframe()
      SSP1_pre_mar_df = SSP1_pre_mar_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Mar_pre"})
      print('###')
      SSP1_pre_apr = SSP1_BCor_pre.sel(month=4)
      SSP1_pre_apr_df= SSP1_pre_apr.to_dataframe()
      SSP1_pre_apr_df = SSP1_pre_apr_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Apr_pre"})
      print('####')
      SSP1_pre_may = SSP1_BCor_pre.sel(month=5)
      SSP1_pre_may_df= SSP1_pre_may.to_dataframe()
      SSP1_pre_may_df = SSP1_pre_may_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "May_pre"})
      print('#####')
      SSP1_pre_jun = SSP1_BCor_pre.sel(month=6)
      SSP1_pre_jun_df= SSP1_pre_jun.to_dataframe()
      SSP1_pre_jun_df = SSP1_pre_jun_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jun_pre"})
      print('######')
      SSP1_pre_jul = SSP1_BCor_pre.sel(month=7)
      SSP1_pre_jul_df= SSP1_pre_jul.to_dataframe()
      SSP1_pre_jul_df = SSP1_pre_jul_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jul_pre"})
      print('#######')
      SSP1_pre_aug = SSP1_BCor_pre.sel(month=8)
      SSP1_pre_aug_df= SSP1_pre_aug.to_dataframe()
      SSP1_pre_aug_df = SSP1_pre_aug_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Aug_pre"})
      print('########')
      SSP1_pre_sep = SSP1_BCor_pre.sel(month=9)
      SSP1_pre_sep_df= SSP1_pre_sep.to_dataframe()
      SSP1_pre_sep_df = SSP1_pre_sep_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Sep_pre"})
      print('#########')
      SSP1_pre_oct = SSP1_BCor_pre.sel(month=10)
      SSP1_pre_oct_df= SSP1_pre_oct.to_dataframe()
      SSP1_pre_oct_df = SSP1_pre_oct_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Oct_pre"})
      print('##########')
      SSP1_pre_nov = SSP1_BCor_pre.sel(month=11)
      SSP1_pre_nov_df= SSP1_pre_nov.to_dataframe()
      SSP1_pre_nov_df = SSP1_pre_nov_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Nov_pre"})
      print('###########')
      SSP1_pre_dec = SSP1_BCor_pre.sel(month=12)
      SSP1_pre_dec_df= SSP1_pre_dec.to_dataframe()
      SSP1_pre_dec_df = SSP1_pre_dec_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Dec_pre"})
      print('############')
      SSP1_pre_df = pd.concat([SSP1_pre_jan_df, SSP1_pre_feb_df, SSP1_pre_mar_df, SSP1_pre_apr_df, SSP1_pre_may_df, SSP1_pre_jun_df, SSP1_pre_jul_df, SSP1_pre_aug_df, SSP1_pre_sep_df, SSP1_pre_oct_df, SSP1_pre_nov_df, SSP1_pre_dec_df], axis=1) # add each variable as a column
      SSP1_pre_df = SSP1_pre_df.reset_index() # add id column
      SSP1_pre_df.index = SSP1_pre_df.index + 1 # start id index at 1, not 0
      SSP1_pre_df.to_csv(pre_DIR+'bcor_SSP1.csv')
      print('SSP1_pre.csv complete')

# SSP2 pre
      SSP2_pre_jan = SSP2_BCor_pre.sel(month=1) # select pre data from the first month
      SSP2_pre_jan_df= SSP2_pre_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP2_pre_jan_df = SSP2_pre_jan_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jan_pre"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP2_pre_feb = SSP2_BCor_pre.sel(month=2)
      SSP2_pre_feb_df= SSP2_pre_feb.to_dataframe()
      SSP2_pre_feb_df = SSP2_pre_feb_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Feb_pre"})
      print('##')
      SSP2_pre_mar = SSP2_BCor_pre.sel(month=3)
      SSP2_pre_mar_df= SSP2_pre_mar.to_dataframe()
      SSP2_pre_mar_df = SSP2_pre_mar_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Mar_pre"})
      print('###')
      SSP2_pre_apr = SSP2_BCor_pre.sel(month=4)
      SSP2_pre_apr_df= SSP2_pre_apr.to_dataframe()
      SSP2_pre_apr_df = SSP2_pre_apr_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Apr_pre"})
      print('####')
      SSP2_pre_may = SSP2_BCor_pre.sel(month=5)
      SSP2_pre_may_df= SSP2_pre_may.to_dataframe()
      SSP2_pre_may_df = SSP2_pre_may_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "May_pre"})
      print('#####')
      SSP2_pre_jun = SSP2_BCor_pre.sel(month=6)
      SSP2_pre_jun_df= SSP2_pre_jun.to_dataframe()
      SSP2_pre_jun_df = SSP2_pre_jun_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jun_pre"})
      print('######')
      SSP2_pre_jul = SSP2_BCor_pre.sel(month=7)
      SSP2_pre_jul_df= SSP2_pre_jul.to_dataframe()
      SSP2_pre_jul_df = SSP2_pre_jul_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jul_pre"})
      print('#######')
      SSP2_pre_aug = SSP2_BCor_pre.sel(month=8)
      SSP2_pre_aug_df= SSP2_pre_aug.to_dataframe()
      SSP2_pre_aug_df = SSP2_pre_aug_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Aug_pre"})
      print('########')
      SSP2_pre_sep = SSP2_BCor_pre.sel(month=9)
      SSP2_pre_sep_df= SSP2_pre_sep.to_dataframe()
      SSP2_pre_sep_df = SSP2_pre_sep_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Sep_pre"})
      print('#########')
      SSP2_pre_oct = SSP2_BCor_pre.sel(month=10)
      SSP2_pre_oct_df= SSP2_pre_oct.to_dataframe()
      SSP2_pre_oct_df = SSP2_pre_oct_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Oct_pre"})
      print('##########')
      SSP2_pre_nov = SSP2_BCor_pre.sel(month=11)
      SSP2_pre_nov_df= SSP2_pre_nov.to_dataframe()
      SSP2_pre_nov_df = SSP2_pre_nov_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Nov_pre"})
      print('###########')
      SSP2_pre_dec = SSP2_BCor_pre.sel(month=12)
      SSP2_pre_dec_df= SSP2_pre_dec.to_dataframe()
      SSP2_pre_dec_df = SSP2_pre_dec_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Dec_pre"})
      print('############')
      SSP2_pre_df = pd.concat([SSP2_pre_jan_df, SSP2_pre_feb_df, SSP2_pre_mar_df, SSP2_pre_apr_df, SSP2_pre_may_df, SSP2_pre_jun_df, SSP2_pre_jul_df, SSP2_pre_aug_df, SSP2_pre_sep_df, SSP2_pre_oct_df, SSP2_pre_nov_df, SSP2_pre_dec_df], axis=1) # add each variable as a column
      SSP2_pre_df = SSP2_pre_df.reset_index() # add id column
      SSP2_pre_df.index = SSP2_pre_df.index + 1 # start id index at 1, not 0
      SSP2_pre_df.to_csv(pre_DIR+'bcor_SSP2.csv')
      print('SSP2_pre.csv complete')

# SSP3 pre
      SSP3_pre_jan = SSP3_BCor_pre.sel(month=1) # select pre data from the first month
      SSP3_pre_jan_df= SSP3_pre_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP3_pre_jan_df = SSP3_pre_jan_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jan_pre"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP3_pre_feb = SSP3_BCor_pre.sel(month=2)
      SSP3_pre_feb_df= SSP3_pre_feb.to_dataframe()
      SSP3_pre_feb_df = SSP3_pre_feb_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Feb_pre"})
      print('##')
      SSP3_pre_mar = SSP3_BCor_pre.sel(month=3)
      SSP3_pre_mar_df= SSP3_pre_mar.to_dataframe()
      SSP3_pre_mar_df = SSP3_pre_mar_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Mar_pre"})
      print('###')
      SSP3_pre_apr = SSP3_BCor_pre.sel(month=4)
      SSP3_pre_apr_df= SSP3_pre_apr.to_dataframe()
      SSP3_pre_apr_df = SSP3_pre_apr_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Apr_pre"})
      print('####')
      SSP3_pre_may = SSP3_BCor_pre.sel(month=5)
      SSP3_pre_may_df= SSP3_pre_may.to_dataframe()
      SSP3_pre_may_df = SSP3_pre_may_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "May_pre"})
      print('#####')
      SSP3_pre_jun = SSP3_BCor_pre.sel(month=6)
      SSP3_pre_jun_df= SSP3_pre_jun.to_dataframe()
      SSP3_pre_jun_df = SSP3_pre_jun_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jun_pre"})
      print('######')
      SSP3_pre_jul = SSP3_BCor_pre.sel(month=7)
      SSP3_pre_jul_df= SSP3_pre_jul.to_dataframe()
      SSP3_pre_jul_df = SSP3_pre_jul_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jul_pre"})
      print('#######')
      SSP3_pre_aug = SSP3_BCor_pre.sel(month=8)
      SSP3_pre_aug_df= SSP3_pre_aug.to_dataframe()
      SSP3_pre_aug_df = SSP3_pre_aug_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Aug_pre"})
      print('########')
      SSP3_pre_sep = SSP3_BCor_pre.sel(month=9)
      SSP3_pre_sep_df= SSP3_pre_sep.to_dataframe()
      SSP3_pre_sep_df = SSP3_pre_sep_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Sep_pre"})
      print('#########')
      SSP3_pre_oct = SSP3_BCor_pre.sel(month=10)
      SSP3_pre_oct_df= SSP3_pre_oct.to_dataframe()
      SSP3_pre_oct_df = SSP3_pre_oct_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Oct_pre"})
      print('##########')
      SSP3_pre_nov = SSP3_BCor_pre.sel(month=11)
      SSP3_pre_nov_df= SSP3_pre_nov.to_dataframe()
      SSP3_pre_nov_df = SSP3_pre_nov_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Nov_pre"})
      print('###########')
      SSP3_pre_dec = SSP3_BCor_pre.sel(month=12)
      SSP3_pre_dec_df= SSP3_pre_dec.to_dataframe()
      SSP3_pre_dec_df = SSP3_pre_dec_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Dec_pre"})
      print('############')
      SSP3_pre_df = pd.concat([SSP3_pre_jan_df, SSP3_pre_feb_df, SSP3_pre_mar_df, SSP3_pre_apr_df, SSP3_pre_may_df, SSP3_pre_jun_df, SSP3_pre_jul_df, SSP3_pre_aug_df, SSP3_pre_sep_df, SSP3_pre_oct_df, SSP3_pre_nov_df, SSP3_pre_dec_df], axis=1) # add each variable as a column
      SSP3_pre_df = SSP3_pre_df.reset_index() # add id column
      SSP3_pre_df.index = SSP3_pre_df.index + 1 # start id index at 1, not 0
      SSP3_pre_df.to_csv(pre_DIR+'bcor_SSP3.csv')
      print('SSP3_pre.csv complete')

# SSP5 pre
      SSP5_pre_jan = SSP5_BCor_pre.sel(month=1) # select pre data from the first month
      SSP5_pre_jan_df= SSP5_pre_jan.to_dataframe() # turn this data into a pandas dataframe
      SSP5_pre_jan_df = SSP5_pre_jan_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jan_pre"}) # drop unnecessary columns, rename variable columns to month
      print('#')
      SSP5_pre_feb = SSP5_BCor_pre.sel(month=2)
      SSP5_pre_feb_df= SSP5_pre_feb.to_dataframe()
      SSP5_pre_feb_df = SSP5_pre_feb_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Feb_pre"})
      print('##')
      SSP5_pre_mar = SSP5_BCor_pre.sel(month=3)
      SSP5_pre_mar_df= SSP5_pre_mar.to_dataframe()
      SSP5_pre_mar_df = SSP5_pre_mar_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Mar_pre"})
      print('###')
      SSP5_pre_apr = SSP5_BCor_pre.sel(month=4)
      SSP5_pre_apr_df= SSP5_pre_apr.to_dataframe()
      SSP5_pre_apr_df = SSP5_pre_apr_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Apr_pre"})
      print('####')
      SSP5_pre_may = SSP5_BCor_pre.sel(month=5)
      SSP5_pre_may_df= SSP5_pre_may.to_dataframe()
      SSP5_pre_may_df = SSP5_pre_may_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "May_pre"})
      print('#####')
      SSP5_pre_jun = SSP5_BCor_pre.sel(month=6)
      SSP5_pre_jun_df= SSP5_pre_jun.to_dataframe()
      SSP5_pre_jun_df = SSP5_pre_jun_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jun_pre"})
      print('######')
      SSP5_pre_jul = SSP5_BCor_pre.sel(month=7)
      SSP5_pre_jul_df= SSP5_pre_jul.to_dataframe()
      SSP5_pre_jul_df = SSP5_pre_jul_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Jul_pre"})
      print('#######')
      SSP5_pre_aug = SSP5_BCor_pre.sel(month=8)
      SSP5_pre_aug_df= SSP5_pre_aug.to_dataframe()
      SSP5_pre_aug_df = SSP5_pre_aug_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Aug_pre"})
      print('########')
      SSP5_pre_sep = SSP5_BCor_pre.sel(month=9)
      SSP5_pre_sep_df= SSP5_pre_sep.to_dataframe()
      SSP5_pre_sep_df = SSP5_pre_sep_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Sep_pre"})
      print('#########')
      SSP5_pre_oct = SSP5_BCor_pre.sel(month=10)
      SSP5_pre_oct_df= SSP5_pre_oct.to_dataframe()
      SSP5_pre_oct_df = SSP5_pre_oct_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Oct_pre"})
      print('##########')
      SSP5_pre_nov = SSP5_BCor_pre.sel(month=11)
      SSP5_pre_nov_df= SSP5_pre_nov.to_dataframe()
      SSP5_pre_nov_df = SSP5_pre_nov_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Nov_pre"})
      print('###########')
      SSP5_pre_dec = SSP5_BCor_pre.sel(month=12)
      SSP5_pre_dec_df= SSP5_pre_dec.to_dataframe()
      SSP5_pre_dec_df = SSP5_pre_dec_df.drop(["month"], axis=1).rename(columns={"mean monthly precipitation (mm)": "Dec_pre"})
      print('############')
      SSP5_pre_df = pd.concat([SSP5_pre_jan_df, SSP5_pre_feb_df, SSP5_pre_mar_df, SSP5_pre_apr_df, SSP5_pre_may_df, SSP5_pre_jun_df, SSP5_pre_jul_df, SSP5_pre_aug_df, SSP5_pre_sep_df, SSP5_pre_oct_df, SSP5_pre_nov_df, SSP5_pre_dec_df], axis=1) # add each variable as a column
      SSP5_pre_df = SSP5_pre_df.reset_index() # add id column
      SSP5_pre_df.index = SSP5_pre_df.index + 1 # start id index at 1, not 0
      SSP5_pre_df.to_csv(pre_DIR+'bcor_SSP5.csv')
      print('SSP5_pre.csv complete')

 # Turn warnings back on
      np.warnings.filterwarnings('default')
 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

elif answer.lower().startswith("n"):
    pass
else:
        print("Enter either yes/no")

print('Step 8: Data Export complete')
################################################################################################################################
print('End.')
sys.exit()