# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import pandas as pd
import csv
import re
from num2words import num2words
from collections import OrderedDict

# Turn CSV into a pandas DataFrame

raw_data_table = pd.read_csv('./spreadsheets/group_detail.csv', sep=',')

#raw_data_table[:10]
# -

# Dictionary of FBbt IDs and short names (not labels) for new and existing terms to be used
ID_table = pd.read_csv('./spreadsheets/ID_name.csv', sep=',')
lookup = dict(zip(ID_table.Keys,ID_table.Values))
#lookup

position_dict = {"AV" : "anterior ventral", \
                "PV" : "posterior ventral", \
                "AD" : "anterior dorsal", \
                "PD" : "posterior dorsal"}

# +
# Make a dictionary with key - column header & value = template specification (first row of table).

template_seed = OrderedDict([ ('ID' , 'ID'), ('CLASS_TYPE' , 'CLASS_TYPE'),\
                             ('RDF_Type' , 'TYPE' )])

#label, definition, short synonym:
template_seed.update([("Name" , "A rdfs:label"), ("Definition" , "A IAO:0000115"),\
                      ("Xref_def" , ">A oboInOwl:hasDbXref"),\
                      ("created_by" , "A oboInOwl:created_by"),\
                      ("creation_date", "A oboInOwl:creation_date")])

#short name synonym
template_seed.update([("Synonym" , "A oboInOwl:hasExactSynonym"),\
                      ("syn_ref" , ">A oboInOwl:hasDbXref")])\

# Columns for tract superclass:
template_seed.update([("PNT" , "SC %"),\
                      ("LH", "SC 'innervates' some %"),\
                      ("Brain", "SC 'part of' some %")])

# Create dataFrame for template
template = pd.DataFrame.from_records([template_seed])

template


# -

def groupname_splitter(shortname):
    """
    Splits group names - two letters / one or more digits.
    """
    short = str(shortname)
    pattern = re.compile("[A-Z][A-Z][0-9]+")
    if pattern.fullmatch(short):
        return [short[0:2], short[2:]]
    else:
        raise ValueError("Invalid group name - must be 2 letters, followed by numbers.")
    


def definition_generator(shortname, dictionary):
    location = groupname_splitter(shortname)
    brain_area = dictionary[location[0]]

    return ("Primary neurite tract of the %s (%s) adult brain in the %s clockwise position "
            "(from %s perspective), from ventrolateral to dorsal to ventromedial, of %s "
            "tracts that enter the lateral horn (Frechter et al., 2019)."
            %(brain_area, location[0], num2words(int(location[1]), to='ordinal'),\
              brain_area.split()[0], location[0]))
    


def label_maker(shortname, dictionary):
    location = groupname_splitter(shortname)
    return "adult %s primary neurite tract %s"%(dictionary[location[0]],location[1])


# +
count = 0 # first row

for i in raw_data_table.index:

    r = raw_data_table.short[count]
    row_od = OrderedDict([]) #new template row as an empty ordered dictionary
    for c in template.columns: #make columns and blank data for new template row
        row_od.update([(c , "")])
    
    #these are the same in each row
    row_od["CLASS_TYPE"] = "subclass"
    row_od["RDF_Type"] = "owl:Class"
    row_od["Xref_def"] = "FlyBase:FBrf0242628"
    row_od["syn_ref"] = "FlyBase:FBrf0242628"
    row_od["created_by"] = "http://orcid.org/0000-0002-1373-1705"
    row_od["creation_date"] = "2020-04-29T12:00:00Z"
    row_od["PNT"] = lookup["PNT"]
    row_od["LH"] = lookup["adLH"]
    row_od["Brain"] = lookup["adBrain"]

    #easy to generate data
    row_od["ID"] = lookup[r]
    row_od["Synonym"] = "adult " + r + " primary neurite tract"
    row_od["Name"] = label_maker(r,position_dict)

    
    #STUFF FOR DEFINITION
    
    definition = definition_generator(r,position_dict)
    if raw_data_table.main_type[i] == "LHLN":
        definition += (" Lateral horn neurons that enter the neuropil via this "
        "tract are predominantly local neurons (Frechter et al., 2019).")
    elif raw_data_table.main_type[i] == "LHON":
        definition += (" Lateral horn neurons that enter the neuropil via this "
        "tract are predominantly output neurons (Frechter et al., 2019).")
    row_od["Definition"] = definition
    
            
    
    #make new row into a DataFrame and add it to template
    new_row = pd.DataFrame.from_records([row_od])
    template = pd.concat([template, new_row], ignore_index=True, sort=False)

    count +=1
    
template
# -

template.to_csv("./template.tsv", sep = "\t", header=True, index=False)



StarcoderdataJupyterScriptsDedupFiltered