# lexicon.py
# Casper van Velzen, University of Amsterdam, 11030275
# creates a network of words linked if they are phonological neighbours
# requires the networkX package to work

import networkx as nx
import csv

# file with phonological transcriptions
inputfile = 'transcriptions.csv'

# initiate empty graph
network = nx.Graph()
prev_word = ""

# load file with phonological transcritions
with open(inputfile, encoding='utf-8') as csvfile:
	# create node in network for every word
	for i, word in enumerate(csvfile):
		# test for duplicate words
		if word != prev_word:
			l = list(word.rstrip())
			for n, char in enumerate(l):
				# count long vowels as one phoneme
				if char == ":":
					l[n-1] = l[n-1] + l[n]
					del l[n]
			network.add_node(i, ipa=list(word.rstrip()))
		prev_word = word


# check for minimal pairs
for j in range(len(network)):
	for k in range(j + 1, len(network)):
		word1 = network.nodes[j]['ipa']
		word2 = network.nodes[k]['ipa']
		lenght1 = len(word1)
		lenght2 = len(word2)

		# check for minimal pair when substituting phoneme
		if lenght1 == lenght2:
			ndiff = 0
			for n, phoneme in enumerate(word1):
				if word2[n]!=phoneme:
					ndiff+=1
			if ndiff == 1:
				network.add_edge(j, k)
				print(str(word1) + ' ' + str(word2))

		# check for minimal pair when subtracting phoneme
		elif lenght1 - 1 ==  lenght2:
			ndiff = 0
			# remove every phoneme one by one to check for match
			for n, phoneme in enumerate(word1):
				# convert str to list so it is mutable
				l = list(word1)
				# remove one phoneme
				del(l[n])
				newstr = "".join(l)

				if newstr == word2:
					ndiff+=1

			if ndiff == 1:
				network.add_edge(j, k)
				print(word1 + ' ' + word2)

		# check for minimal pair when adding phoneme
		elif lenght2 - 1 ==  lenght1:
			ndiff = 0
			# remove every phoneme one by one to check for match
			for n, phoneme in enumerate(word2):
				# convert str to list so it is mutable
				l = list(word2)
				# remove one phoneme
				del(l[n])
				newstr = "".join(l)

				if newstr == word1:
					ndiff+=1

			if ndiff == 1:
				network.add_edge(j, k)
				print(word1 + ' ' + word2)

edges = network.number_of_edges()
print("Number of nodes: " + str(nx.number_of_nodes(network)))
print(edges)

# get the biggest connected component
biggest_comp = max(nx.connected_component_subgraphs(network), key=len)
nodes = nx.number_of_nodes(biggest_comp)
edges = biggest_comp.number_of_edges()
apl = nx.average_shortest_path_length(biggest_comp)
cc = nx.average_clustering(biggest_comp)
print("Biggest comp nodes: " + str(nodes))
print("Number of edges: " + str(edges))
print("APL: " + str(apl))
print("CC: " + str(cc))
