# Notebook from saifmaq/metis-projects
Path: music recommender/pitchfork_eda_modeling.ipynb

import pandas as pd
import datetime
import nltk
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
from matplotlib.gridspec import GridSpec

%matplotlib inline_____no_output_____

### Reading In Data Using SQLite_____no_output_____

import sqlite3
conn = sqlite3.connect('database.sqlite')_____no_output_____artist = pd.read_sql_query('select * from artists', conn)
content = pd.read_sql_query('select * from content', conn)
genres = pd.read_sql_query('select * from genres', conn)
reviews = pd.read_sql_query('select * from reviews', conn)
years = pd.read_sql_query('select * from years', conn)
labels = pd.read_sql_query('select * from labels', conn)_____no_output_____pitchfork_df = pd.merge(content,reviews, on='reviewid')
pitchfork_df = pd.merge(pitchfork_df, years, on='reviewid')
pitchfork_df = pd.merge(pitchfork_df, genres, on='reviewid')_____no_output_____pitchfork_df.drop(['author_type'],inplace=True,axis=1)_____no_output_____p4k = pitchfork_df.drop(pitchfork_df[pitchfork_df.content == ''].index)_____no_output_____p4k = p4k.reset_index().drop('index',axis=1)_____no_output_____len(p4k)_____no_output_____p4k = p4k.drop_duplicates('reviewid')_____no_output_____len(p4k)_____no_output_____p4k = p4k.reset_index()_____no_output_____p4k = p4k.drop('index', axis=1)_____no_output_____

### Exploratory Data Analysis_____no_output_____

review_length = p4k.content.str.len()
sns.set()
ax = review_length.hist(bins=50)
ax.set(xlabel='Word Count', ylabel='Frequency',
      title='Distribution of Review Length on Pitchfork')_____no_output_____np.sum(list(review_length))_____no_output_____

### Taking a Sample of the Data In Order to Conduct Preliminary Modeling_____no_output_____

from sklearn.model_selection import train_test_split_____no_output_____restof_df, sample_df = train_test_split(p4k, test_size=0.20,
                                        random_state=666)_____no_output_____sample_df = sample_df.reset_index()
sample_df.drop(['index'],axis=1,inplace=True)_____no_output_____

### NLP Modeling_____no_output_____

from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import string
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer, WordNetLemmatizer
from sklearn.decomposition import NMF

#Tokenizer function
def custom_tokenizer(text):

    remove_punct = str.maketrans('', '', string.punctuation)
    text = text.translate(remove_punct).replace('" "','').replace('“','').replace("''",'').replace("’",'').replace('“ ”','').replace('” ','')

    remove_digits = str.maketrans('', '', string.digits)
    text = text.lower().translate(remove_digits)

    tokens = word_tokenize(text)

    stop_words = stopwords.words('english')
    tokens_stop = [y for y in tokens if y not in stop_words]

    lemmatizer = WordNetLemmatizer()
    tokens_lemma = [lemmatizer.lemmatize(y) for y in tokens_stop]

    # Custom stop words chosen based on results
    custom_stop_words = ['there', 'theyre', 'theyve', 'good', 'lot', 'kind', 'bit', 'that',
                         'enough', 'theyv', 'pretty', 'sound', 'like',
                        'feel', 'like', 'collabor', 'project', 'moment', 'solo', 'producer',
                         'made', 'decade', 'might', 'hard', 'rather', 'collaboration',
                         'trying', 'energy', 'sings', 'vision', 'clear', 'within', 'career',
                         'cut', 'idea', 'star', 'since', 'towards', 'mean', 'duo', 'across',
                        'im', 'think', 'youre', 'guy', 'really', 'people', 'going',
                         'got', 'ive', 'want', 'maybe',
                        'name', 'working', 'form', 'someone', 'felt',
                         'personal', 'interview', 'suggests', 'future', 'become',
                         'u', 'day', 'least', 'cant', 'probably',
                         'ever', 'man', 'kid', 'right', 'sort', 'need',
                        'recording', 'early', 'recorded', 'tape', 'released', 'four', 'three', 'five',
                        'sometimes', 'ep', 'fulllength', 'last', 'year','lp',
                        'nothing','actually','stuff','better', 'anything', 'let',
                        'isnt','bad','hear','great','sure', 'didnt', 'play', 'start', 'whole', 'everything',
                        'word', 'see', 'place', 'put', 'look', 'tell', 'mind', 'said', 'away',
                        'far', 'may', 'keep',  'set', 'collection', 'making', 'simple', 'free', 'instead', 'move',
                        'artist', 'label', 'style', 'musical', 'whose', 'art', 'genre',
                         'recent', 'musician', 'scene', 'act',  'free', 'instead', 'move',
                         'version', 'original', 'disc', 'material', 'single', 'mix', 'different', 'classic', 'later',
                        'john', 'turn', 'fact','seem', 'easy' ,'quite', 'course',
                        'face', 'perhaps', 'hand', 'next', 'half', 'give', 'group', 'member', 'however', 'listener', 'guitarist',
                         'former', 'side', 'drummer', 'studio', 'singer', 'number',
                        'big', 'hit', 'fan', 'past', 'old' ]

    tokens_final = [y for y in tokens_lemma if y not in custom_stop_words]

    return tokens_final_____no_output_____def topics(model, feature_names, n_top_words):
    for topic_id, topic in enumerate(model.components_):
        message = "Topic #%d: " % topic_id
        message += " ".join([feature_names[i] \
                             for i in topic.argsort()[:-n_top_words - 1:-1]])
        print(message)_____no_output_____def tfidf_nmf(data, n_components, min_df, max_df):
# A function that takes in a dataframe, performs TFIDF vectorization and returns topic models using
# Non-Negative Matrix Factorization

    tfidf = TfidfVectorizer(tokenizer=custom_tokenizer,
                            ngram_range=(1,2),
                            min_df=min_df, max_df=max_df)

    tfidf.fit(data)
    c = tfidf.transform(data)
    nmf = NMF(n_components=n_components)
    nmf_vecs = nmf.fit_transform(c)

    topic_lists = topics(nmf, tfidf.get_feature_names(), 11)

    print(topic_lists)

    return topic_lists, nmf, nmf_vecs_____no_output_____sample_topic_lists, sample_nmf, sample_nmf_vecs = tfidf_nmf(sample_df.content, 15, 0.08, 0.28)_____no_output_____topic_lists, nmf, nmf_vecs = tfidf_nmf(p4k.content,15, 0.08, 0.28)Topic #0: indie chorus hook production riff verse lead songwriting opener lack tune
Topic #1: rap hiphop verse production sample guest shit dj game street underground
Topic #2: metal death riff heavy vocalist bass noise slow lead section power
Topic #3: piece noise electronic drone ambient tone space loop bass sonic texture
Topic #4: dance house dj club synth bass groove sample party electronic synths
Topic #5: live show performance audience cover stage playing played already radio experience
Topic #6: black white dark key power cover fire heart light eye history
Topic #7: jazz soul funk hiphop horn rhythm groove bass compilation section tune
Topic #8: punk riff wave noise fun dead history played power hell underground
Topic #9: city york new york country street night home wave american underground sonic
Topic #10: shes woman singing girl power ballad heart character chorus emotional feeling
Topic #11: life story death friend night home dream feeling light character god
Topic #12: blue white country cover american folk brother playing note riff dead
Topic #13: acoustic piano folk string acoustic guitar arrangement instrument electric country organ harmony
Topic #14: girl young boy white cover la brother fun na woman party
Topic #14: girl young boy white cover la brother fun na woman party

### Adding Topic Names to the DataFrame for Improved Legibility_____no_output_____

topic_names = ['indie/contemporary', 'rap/hiphop', 'metal/heavy guitar', 'experimental electronic',
				'dance/house/synth', 'live/tour', 'dark/soulful', 'jazz/funk',
				'rock/punk', 'urban/trendy', 'female artist/gender', 'spiritual/emotional/philosophical',
				'folk/country', 'instrumentation', 'love/lust']_____no_output_____nmf_vecs.shape_____no_output_____def topic_column(df, nmfvecs):
#Function to add a column with topic names to the dataframe
    topics = []
    for i in range(len(df)):
        index = np.argmax(nmf_vecs[i])
        topics.append(topic_names[index])
    return pd.Series(topics)_____no_output_____p4k['topic'] = topic_column(p4k, nmf_vecs)_____no_output_____

### Adding Subtopics_____no_output_____

def subtopics(topics):
# Create subtopics for each topic in order to further engage with the data
    subtopic_vecs = []
    for topic in topics:
        df = p4k[p4k.topic == topic].content
        print(topic)
        topic_lists, sub_nmf, sub_nmf_vecs = tfidf_nmf(df, 3, 0.10, 0.35)
        subtopic_vecs.append(sub_nmf_vecs)
    return subtopic_vecs_____no_output_____subtopic_vecs = subtopics(topic_names)indie/contemporary
Topic #0: drum minute le riff part many rhythm every end hook without
Topic #1: love heart cover know synths emotional world hook songwriting fire radio
Topic #2: he tune seems around know always often world say beat behind
None
rap/hiphop
Topic #0: mixtape life young guest hook street rapping world money shit always
Topic #1: wayne lil b mixtape mixtapes rapping dj love series money bitch
Topic #2: vocal sample rock drum guitar mc underground band bass lyric dj
None
metal/heavy guitar
Topic #0: bass voice part doom noise little around beat he line go
Topic #1: black metal he room dark blast light doom split point wave influence
Topic #2: hardcore death metal punk thrash vocalist influence live many blood know lead
None
experimental electronic
Topic #0: rock part voice end space note instrument bass world sonic seems
Topic #1: film soundtrack piano composer string theme composition ambient series feature instrumental
Topic #2: pop beat ambient techno synth electronic music sample love machine synths he
None
dance/house/synth
Topic #0: techno he club sample release sense minute rhythm synth electronic melody
Topic #1: band guitar rock indie lyric debut love every voice always chorus
Topic #2: disco remix remixes love compilation rock party groove guitar electro le
None
live/tour
Topic #0: drum beat melody he line lyric rhythm bass often sense voice
Topic #1: cover demo radio session reissue compilation box included note second voice
Topic #2: audience concert crowd live album dvd stage document video tour cd point
None
dark/soulful
Topic #0: minute drum piece noise bass melody drone metal percussion second end
Topic #1: love pop cover white life soul world know without many heart
Topic #2: he beat hiphop production line hell sample point root thought getting
None
jazz/funk
Topic #0: love hiphop he pop voice sample break dont lyric know production
Topic #1: compilation country brown horn series funky american disco groove brother popular
Topic #2: piece playing trio piano mile minute player tune horn composition instrument
None
rock/punk
Topic #0: love he world know cover indie say compilation always fun punk rock
Topic #1: drum riff melody bass rhythm noise debut beat often chorus hook
Topic #2: hardcore black death dead release noise underground life fuck final eye
None
urban/trendy
Topic #0: minute drum bass sonic noise long le melody point every release
Topic #1: love country lyric night know cover heart always american world title
Topic #2: he beat doesnt production part verse black almost seems release hook
None
female artist/gender
Topic #0: melody often sense piano yet part string singing drum almost note
Topic #1: woman rock cover live girl young many life always black boy
Topic #2: beat girl world rb dance party production talk show na say
None
spiritual/emotional/philosophical
Topic #0: story friend seems almost long release without minute often night feeling
Topic #1: film soundtrack character theme piece dream story feature string night mood
Topic #2: death melody dead black drum light god yet heart chorus title track
None
folk/country
Topic #0: pop melody minute debut sense title end he beat drum part
Topic #1: white dead brother release drum black riff key yet toward hold
Topic #2: cover country folk american brother performance session he yet live show
None
instrumentation
Topic #0: instrument piece minute he around part percussion le end another almost
Topic #1: love dont heart know cover debut he say go ballad find
Topic #2: rock country american cover indie electric ballad doesnt dont yet know
None
love/lust
Topic #0: he world melody beat many end le title part release every
Topic #1: white black soul he story life heart country simply real light
Topic #2: la cover american indie heart high le na already dream playing
None
subtopic_names = [
			['hook', 'love', 'beat/tune'],
			['guest verse/hook', 'love/money', 'sampling/underground'],
			['bass', 'black metal', 'hardcore'],
			['sonic space', 'soundtrack/ambient', 'techno/synth/emotional'],
			['techno', 'indie', 'disco'],
			['rhythm/percussion', 'cover/reissue/compilation', 'concert'],
			['melodic', 'love', 'hiphop'],
			['hiphop', 'disco', 'jazz'],
			['indie','rhythm/percussion','hardcore'],
			['singer/songwriter', 'rock','r&b'],
			['melodic', 'love', 'hook'],
            ['emotional', 'dreamy','dark'],
			['folk', 'blues', 'country'],
			['instrumental', 'love', 'indie'],
			['melodic', 'soulful', 'indie']
]_____no_output_____subtopic_vecs[1].shape_____no_output_____topic = p4k.iloc[405].topic
key = topic_names.index(topic)
vec = subtopic_vecs[key]
print(vec.shape)(796, 3)
def subtopic_column(df, vecs_list):
# Adding a subtopic column for each entry in the dataframe
    subtopics = []
    for i in range(len(df)):
        topic = df.iloc[i].topic
        reviewid = df.iloc[i].reviewid
        working_df = p4k[p4k.topic == topic].reset_index()

        topic_index = working_df.index[working_df.reviewid == reviewid][0]

        key = topic_names.index(topic)

        vecs = (subtopic_vecs[key])
        vec_value = np.argmax(vecs[topic_index])

        subtopic = subtopic_names[key][vec_value]

        subtopics.append(subtopic)

    return pd.Series(subtopics)_____no_output_____subtopic = subtopic_column(p4k, subtopic_vecs)_____no_output_____p4k['subtopic'] = subtopic_____no_output_____

### Using the Topics/Subtopics to explore the data_____no_output_____

topic_review_score = p4k.groupby(['topic'])['score'].mean().sort_values(ascending=False)_____no_output_____topic_review_score_____no_output_____p4k.topic.value_counts()_____no_output_____labels = p4k.topic.value_counts().index
counts = p4k.topic.value_counts().values
plt.figure(figsize=(30,15))
the_grid = GridSpec(2, 2)
cmap = plt.get_cmap('Spectral')
colors = [cmap(i) for i in np.linspace(0, 1, 8)]
plt.subplot(the_grid[0, 1], aspect=1, title='Topics in Pitchfork Reviews')
source_pie = plt.pie(counts, labels=labels, autopct='%1.1f%%', shadow=True, colors=colors)
plt.pie(counts, labels=labels, autopct='%1.1f%%', shadow=True, colors=colors)
plt.show()_____no_output_____def top_artists_by_topic(topic):
    d = df[df['topic'] == topic].sort_values('score',ascending=False)
    a = [d.artist.unique()[:5]]
    b = [d.title.unique()[:5]]
    return list(zip(a,b))_____no_output_____

### Laying the Groundwork for the Music Recommender_____no_output_____

# Filter the pitchfork reviews on albums that they rate as better than average
good_music = p4k[p4k['score'] > (p4k['score'].mean() + 1)]
print(len(good_music) / len(p4k) * 100)_____no_output_____def rough_artist_recommender(artist, recs):
#initial function to recommend music
    d = p4k[p4k['artist']==artist]['topic']
    topics = list(d[:].unique())
    suggestions = pd.DataFrame(columns=p4k.columns)
    wildcard_picks = []
    for topic in topics:
        good_suggestions = good_music[good_music['topic'] == topic]
        good_suggestions = good_suggestions[good_suggestions['artist'] != artist]
        wildcard_picks += (list(np.random.choice(good_suggestions.artist.unique(),size=50)))
    recs = list(set(np.random.choice(wildcard_picks, size=recs)))

    return recs_____no_output_____wonky_artist_recommender('joy division', 5)_____no_output_____mean_scores = df.groupby(['genre']).mean()['score']_____no_output_____mean_scores_____no_output_____scores = p4k.score
sns.set()
ax = scores.hist(bins=25)
ax.set(xlabel='Score', ylabel='Frequency',
      title='Distribution of Album Scores on Pitchfork')_____no_output_____np.mean(p4k.score)_____no_output_____

### Sentiment Analysis_____no_output_____

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyser = SentimentIntensityAnalyzer()_____no_output_____def print_sentiment_scores(sentence):
    snt = analyser.polarity_scores(sentence)
    print(snt)_____no_output_____d = df.content.iloc[7110]_____no_output_____def sentiment_analysis(doc):
    sentences = doc.split('.')
    s = []
    for sentence in sentences:
        snt = analyser.polarity_scores(sentence)
        compound_score = snt['compound']
        s.append(compound_score)
    sentiment = (sum(s) / len(s))
    return sentiment           _____no_output_____import pickle
pickle.dump( p4k, open( "pitchfork_data.p", "wb" ) )

_____no_output_____sentiment = []
for i in range(len(p4k)):
    s = sentiment_analysis(p4k.content.iloc[i])
    sentiment.append(s)_____no_output_____p4k['sentiment'] = pd.Series(sentiment)_____no_output_____

plotting sentiment score against rating score, see if relationship looks strong visually:_____no_output_____

plt.ylim(-1,1)
plt.scatter(p4k[p4k.score < 5].score, p4k[p4k.score<5].sentiment,alpha=0.2)_____no_output_____

Unfortunately, seems that there is no relationship between VADER sentiment and Pitchfork Rating_____no_output_____

negative = p4k[p4k.sentiment < 0]_____no_output_____negative.score.mean()_____no_output_____


# Notebook from FangmingXie/scf_enhancer_paper
Path: eran/Regress_Enhancers_ReducedRank.ipynb

# Quantify mCG at the enhancers_____no_output_____

import sys, os
sys.path.insert(0, '/cndd/fangming/CEMBA/snmcseq_dev')
from __init__ import *
from CEMBA_run_mc_region_level import run_mc_region_level
from natsort import natsorted
import glob , re_____no_output_____# bed_file='enhancers_reptile.bed'
# allc_dir='/cndd2/fangming/scf_enhancers/data/bulk/round2/mc/'
# allc_files=glob.glob(allc_dir+'Round2*CGN-Merge.allc.tsv.gz')

# # bed_file='foo.bed'
# # allc_files = [allc_files[0]]

# output_files = ['enh.'+os.path.split(a)[1][:-22]+'.bed.gz' for a in allc_files]
# cap = 0 # no counts cap
# nprocs = 8
# compress = True
# bed_file_name_column = False
# chr_prefix = True
# contexts = ['CG']

# run_mc_region_level(allc_files,
#                     output_files,
#                     bed_file,
#                     chr_prefix=chr_prefix,
#                     bed_file_name_column=bed_file_name_column,
#                     contexts=contexts,
#                     compress=compress,
#                     cap=cap,
#                     nprocs=nprocs);_____no_output_____# # Gather data from all the individual bed files
# df = pd.DataFrame();
# for fn in output_files:

#     _, sample = os.path.split(fn)
#     sample = re.sub('(enh\.|\.bed)','',sample)

#     x = pd.read_csv(fn+'.gz',sep='\t')
#     x=x.rename(mapper={'mCG': sample+'_'+'mCG', 'CG': sample+'_'+'CG'}, axis=1)
#     if df.shape[0]<1:
#         df = x
#     else:
#         df = df.join(x.iloc[:,[3,4]])

# df['enh_pos'] = 'chr'+df['chr'].astype(str)+'_'+df['start'].astype(str)+'_'+df['end'].astype(str)_____no_output_____# df.to_csv('enh.AllClusters.mCG.bed.gz')_____no_output_____# for fn in output_files:
#     os.remove(fn)
#     print('Removed file %s' % fn)_____no_output_____

# Load enhancer data_____no_output_____

# Map the genes to closest enhancers
datadir = '/cndd/emukamel/enhancer_modeling/enhancer_data/'
genes2enh = pd.read_csv(datadir+'genes.gencode.vM16.closest_enhancers.bed',sep='\t',
                        names = ['gene_chr','gene_start','gene_end','ensid','gene_name','enh_chr','enh_start','enh_end'])_____no_output_____genes2enh['enh_pos'] = genes2enh['enh_chr']+'_'+genes2enh['enh_start'].astype(str)+'_'+genes2enh['enh_end'].astype(str)_____no_output_____genes2enh.ensid = [re.sub("\..*","",x) for x in genes2enh.ensid]
genes2enh = genes2enh.set_index('ensid')_____no_output_____genes = pd.read_csv(datadir+'genes.gencode.vM16.bed',sep='\t',header=None,
                   names=['chr','start','end','ensid','gene'])
genes['ensid'] = [re.sub('\..*','',ensid) for ensid in genes['ensid']]
genes = genes.set_index('ensid',drop=False)
genes_____no_output_____

# Load RNA data_____no_output_____

datadir='/cndd2/ethan/projects/scf_paper/modeling/working_data/reptile/data_for_model_01152020/'
rna = pd.read_csv(datadir+'rna_for_y_values.tsv',sep='\t')
rcol = rna.columns.values
rcol[1] = 'ensid'
rna.columns = rcol
# rna=rna.drop('10-1',axis=1)
# rna_data = rna.iloc[:,2:].to_numpy()

# Variable genes
hvg = np.var(rna.iloc[:,2:].to_numpy(),axis=1);
hvg = hvg> np.percentile(hvg,67)
np.sum(hvg)

rna = rna[hvg]_____no_output_____rna = rna.set_index('ensid')_____no_output_____rna_____no_output_____

# Load mCG data_____no_output_____

datadir = '/cndd/emukamel/enhancer_modeling/enhancer_data/'
df = pd.read_csv(datadir+'enh.AllClusters.mCG.bed.gz')
df['enh_pos'] = 'chr'+df['chr'].astype(str)+'_'+df['start'].astype(str)+'_'+df['end'].astype(str)
df = df.drop(['Unnamed: 0'],axis=1)
df/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3051: DtypeWarning: Columns (1) have mixed types.Specify dtype option on import or set low_memory=False.
  interactivity=interactivity, compiler=compiler, result=result)
# Compute mCH level
cg = df.iloc[:,3:-1:2]
mcg = df.iloc[:,4:-1:2]
mlevel = mcg.to_numpy() / cg.to_numpy()
hthresh = 10
mlevel[ cg<hthresh ] = np.nan

df_mlevel = pd.DataFrame(mlevel, columns = cg.columns, index=df.enh_pos)/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in true_divide
  after removing the cwd from sys.path.
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
  after removing the cwd from sys.path.
celltypes = df_mlevel.columns
celltypes = [re.sub("(Round2\.|_mCG)","",c) for c in celltypes]
df_mlevel.columns = celltypes_____no_output_____# Cell type names
df_cellnames = pd.read_csv('/cndd/Public_Datasets/CEMBA/BICCN_minibrain_data/data_freeze/supp_info/clusters_final/cluster_annotation_scf_round2.tsv',
                       sep='\t', index_col='cluster')_____no_output_____celltypes_label = df_cellnames.loc[celltypes,'annot']_____no_output_____

# Load ATAC data_____no_output_____

atac = pd.read_csv(datadir+'enhancers_reptile_atac_norm.tsv',sep='\t')
atac=atac.set_index('enhancer_idx',drop=False)
atac_enh_list = pd.read_csv(datadir+'enhancers_reptile.bed',sep='\t',header=None,names=['chr','start','end'])
atac = atac.join(atac_enh_list)
atac['enh_pos'] = atac['chr'].astype(str)+'_'+atac['start'].astype(str)+'_'+atac['end'].astype(str)
atac = atac.loc[~(atac['chr']=="chrY")]
df_atac = atac.set_index('enh_pos',drop=False)_____no_output_____# Make sure the ATAC and mCG data are both in the same column order
df_atac = df_atac[celltypes]
df_mlevel = df_mlevel[celltypes]_____no_output_____

# Define features_____no_output_____

# For each gene, pull all corresponding enhancers
# Get the mean, var etc. of mCG and ATAC levels over all enhancers for each cell type
# This takes ~30 s, so be patient...
features = []
tstart = time.time()
for ensid,r in rna.iterrows():
    curr_enh = genes2enh.loc[ensid]['enh_pos'].values

    ml = df_mlevel.loc[curr_enh].values
    ml_mean = np.nanmean(ml,axis=0)
    ml_var = np.nanvar(ml,axis=0)
    ml_max = np.nanmax(ml,axis=0)
    ml_min = np.nanmin(ml,axis=0)

    at = df_atac.loc[curr_enh].values
    at_mean = np.nanmean(at,axis=0)
    at_var = np.nanvar(at,axis=0)
    at_max = np.nanmax(at,axis=0)
    at_min = np.nanmin(at,axis=0)

    f = np.vstack((ml_mean, ml_var, ml_max,ml_min,
                  at_mean, at_var, at_max,at_min,))
    features.append(f)

print(time.time() - tstart)/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:10: RuntimeWarning: Mean of empty slice
  # Remove the CWD from sys.path while we load stuff.
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: Degrees of freedom <= 0 for slice.
  # This is added back by InteractiveShellApp.init_path()
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:12: RuntimeWarning: All-NaN slice encountered
  if sys.path[0] == '':
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:13: RuntimeWarning: All-NaN slice encountered
  del sys.path[0]
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:16: RuntimeWarning: Mean of empty slice
  app.launch_new_instance()
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:17: RuntimeWarning: Degrees of freedom <= 0 for slice.
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:18: RuntimeWarning: All-NaN slice encountered
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:19: RuntimeWarning: All-NaN slice encountered
farray = np.dstack(features)_____no_output_____features_labels = ['mCG mean','mCG var','mCG max','mCG min',
                   'ATAC mean','ATAC var','ATAC max','ATAC min',]_____no_output_____celltypes = df_mlevel.columns
celltypes = [re.sub("(Round2\.|_mCG)","",c) for c in celltypes]_____no_output_____farray.shape_____no_output_____

# Regression_____no_output_____

import sklearn.linear_model as sklm
import matplotlib.pyplot as plt
import scipy
from sklearn.preprocessing import StandardScaler_____no_output_____# For each cell type, correlate the RNA expression with the mean mCG level of all enhancers associated to that gene
cc_mean = []
for celltype_use in celltypes:
    y = rna[celltype_use]
    X = farray[0,celltypes.index(celltype_use),:].squeeze().T
    X.shape, y.shape

    goodgenes = np.isnan(X)==0

    X = X[goodgenes]
    y = y[goodgenes]

    cc_mean.append(np.corrcoef(y, X)[0,1])_____no_output_____# For each cell type, regress the RNA expression against mCG features
cc_features = []
coefs = []
for celltype_use in celltypes:
    y = rna[celltype_use]
    X = farray[:,celltypes.index(celltype_use),:].squeeze().T
    X2 = np.nanmedian(farray,axis=1).squeeze().T
    X = np.hstack((X,X2))

    goodgenes = np.isnan(X).sum(axis=1)==0
#     print(goodgenes.sum())
    if goodgenes.sum()>100:
        X = X[goodgenes,:]
        y = y[goodgenes]

        #X = scipy.stats.zscore(X, nan_policy='omit')
        X = StandardScaler().fit_transform(X)

        regr = sklm.LinearRegression(normalize=False).fit(X,y)

        coefs.append(regr.coef_)
        cc_features.append(np.corrcoef(y, regr.predict(X))[0,1])
    else:
        cc_features.append(np.nan)_____no_output_____plt.plot(cc_features,'o-',label='Regression (mCG+ATAC features)')
plt.plot(cc_mean,'o-',label='Mean mCG only')
plt.legend()
plt.xlabel('Cell type')
plt.ylabel('Correlation coefficient')_____no_output_____features_labels_use = features_labels+[f+' all' for f in features_labels]
features_labels_use_____no_output_____# plt.bar(np.broadcast_to(np.array(features_labels_use).reshape(-1,1), (16,28) ), np.array(coefs).T)
plt.imshow(np.array(coefs).T, vmin=-.05,vmax=.125)
plt.xticks(ticks=np.arange(len(celltypes)), labels=celltypes, rotation=90);
plt.yticks(ticks=np.arange(len(features_labels_use)), labels=features_labels_use);
# plt.yticks(ticks=features_labels_use)
plt.colorbar();
plt.title('Regression coefficients')_____no_output_____plt.bar(features_labels_use, np.array(coefs).mean(axis=0))
plt.plot(features_labels_use, np.array(coefs).T,'k.')
plt.xticks(ticks=np.arange(len(features_labels_use)), labels=features_labels_use,
          rotation=90);
plt.ylabel('Regression coefficients')
plt.grid()_____no_output______, ncelltypes, ngenes = farray.shape
X = farray.reshape(-1,ngenes*ncelltypes).T
y = rna[celltypes].to_numpy().reshape(ngenes*ncelltypes,1)
X.shape, farray.shape_____no_output_____# Formula based linear modeling
import statsmodels.formula.api as smf_____no_output_____f0 = np.nanmean(farray,axis=2)
fv = np.nanvar(farray,axis=2)
fz = farray-f0[:,:,np.newaxis]
fz = fz / fv[:,:,np.newaxis]

# fz = farray/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: Mean of empty slice
  """Entry point for launching an IPython kernel.
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:2: RuntimeWarning: Degrees of freedom <= 0 for slice.

/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
  after removing the cwd from sys.path.
# Gather all data into a big DF
data = rna.iloc[:,1:].stack()
data = pd.DataFrame(data, columns=['rna'])

for i,f in enumerate(features_labels):
    d = pd.DataFrame(fz[i,:,:].T, index=rna.index, columns=celltypes)
    d = d.stack()
    d = pd.DataFrame(d, columns=[f])
    data = data.join(d)

data = data.reset_index()
data = data.rename(mapper={'level_1': 'celltype'},axis=1)
dc = data.columns
dc = [re.sub(' ','_',dc1) for dc1 in dc]
data.columns = dc
data = data.loc[data.celltype!="10-1"]_____no_output_____dataz = StandardScaler().fit_transform(data.values[:,2:])
dataz = pd.DataFrame(dataz, index = data.index, columns=data.columns[2:])
dataz['ensid'] = data['ensid']
dataz['celltype'] = data['celltype']
dataz_____no_output_____formula = 'rna ~ 1+celltype'
for c in data.columns[3:]:
    formula += '+'+c

# formula = 'rna ~ 1+celltype+mCG_mean+mCG_max+ATAC_mean+ATAC_var'
print(formula)
mdl = smf.ols(formula, dataz).fit()
mdl.summary()rna ~ 1+celltype+mCG_mean+mCG_var+mCG_max+mCG_min+ATAC_mean+ATAC_var+ATAC_max+ATAC_min
goodgenes = np.isnan(X).sum(axis=1)==0
X = X[goodgenes,:]
y = y[goodgenes]_____no_output_____X.shape,y.shape_____no_output_____regr = sklm.LinearRegression(normalize=False).fit(X,y)_____no_output_____plt.plot(features_labels_use, regr.coef_)
plt.xticks(rotation=90)_____no_output_____yhat = regr.predict(X)
yhat.shape_____no_output_____np.corrcoef(y.T, regr.predict(X).T)_____no_output_____

# Reduced rank regression

_____no_output_____

# Code from: https://github.com/riscy/machine_learning_linear_models/blob/master/reduced_rank_regressor.py
from scipy import sparse

class ReducedRankRegressor(object):
    """
    Reduced Rank Regressor (linear 'bottlenecking' or 'multitask learning')
    - X is an n-by-d matrix of features.
    - Y is an n-by-D matrix of targets.
    - rrank is a rank constraint.
    - reg is a regularization parameter (optional).
    """
    def __init__(self, X, Y, rank, reg=None):
        if np.size(np.shape(X)) == 1:
            X = np.reshape(X, (-1, 1))
        if np.size(np.shape(Y)) == 1:
            Y = np.reshape(Y, (-1, 1))
        if reg is None:
            reg = 0
        self.rank = rank

        CXX = np.dot(X.T, X) + reg * sparse.eye(np.size(X, 1))
        CXY = np.dot(X.T, Y)
        _U, _S, V = np.linalg.svd(np.dot(CXY.T, np.dot(np.linalg.pinv(CXX), CXY)))
        self.W = V[0:rank, :].T
        self.A = np.dot(np.linalg.pinv(CXX), np.dot(CXY, self.W)).T

    def __str__(self):
        return 'Reduced Rank Regressor (rank = {})'.format(self.rank)

    def predict(self, X):
        """Predict Y from X."""
        if np.size(np.shape(X)) == 1:
            X = np.reshape(X, (-1, 1))
        return np.dot(X, np.dot(self.A.T, self.W.T))_____no_output_____Y = rna.values[:,1:]
X = farray.reshape(-1,ngenes).T

# Remove predictors with too many nan values
goodpredictors = np.sum(np.isnan(X),axis=0)<500
X = X[:,goodpredictors]

goodgenes = np.sum(np.isnan(X),axis=1)==0
X = X[goodgenes,:]
Y = Y[goodgenes,:]
X.shape, Y.shape_____no_output_____cc = []
tstart = time.time()
ranks = [1,2,5,10,20]
for rank in ranks:
    regr = ReducedRankRegressor(X,Y,rank)
    Yhat = regr.predict(X)
    cc1 = [np.corrcoef(Y[:,i].T,Yhat[:,i].T)[0,1] for i in range(Y.shape[1])]
    cc.append(cc1)
    print('Rank=%d, time=%3.3f' % (rank, time.time()-tstart))
cc = np.array(cc)Rank=1, time=1.063
Rank=2, time=2.055
Rank=5, time=2.485
Rank=10, time=3.402
Rank=20, time=3.674
plt.plot(celltypes_label, cc.T);
plt.legend(['Rank='+str(r) for r in ranks])
plt.ylabel('Correlation coefficient')
plt.xticks(rotation=90);
plt.xlabel('Cell type');
plt.grid(axis='y')_____no_output_____

# Kmers_____no_output_____

# Get fasta file
import scipy
import sklearn
from matplotlib import pyplot as plt_____no_output_____kdict=np.load(datadir+'kmers_6mers/kmer_dict.npy', allow_pickle=True)_____no_output_____# Load the kmer data per enhancer
kmer_counts=np.load(datadir+'kmers_6mers/count.npy')
kdict=np.load(datadir+'kmers_6mers/kmer_dict.npy')_____no_output_____kmer_enh = pd.read_csv(datadir+'enhancers_reptile.bed', sep='\t',
                       header=None, columns=['chr','start','end'])
kmer_enh['enh_pos'] = ['_'.join([str(i) for i in row]) for ind,row in kmer_enh.iterrows()]_____no_output_____kmer_enh['enh_num'] = np.arange(kmer_enh.shape[0])_____no_output_____kmer_enh = kmer_enh.set_index('enh_pos', drop=False)
kmer_enh, kmer_counts.shape_____no_output_____# Subset to the HVGs
genes2enhu = genes2enh.loc[rna.index]_____no_output_____# Determine the enhancer number for each gene-enhancer pair
genes2enhu['enh_num'] = kmer_enh.loc[genes2enhu['enh_pos'],'enh_num'].values_____no_output_____kmer_countsu = kmer_counts[genes2enhu['enh_num'],:]_____no_output_____df_mlevelu = df_mlevel.loc[genes2enhu['enh_pos']]
df_atacu = df_atac.loc[genes2enhu['enh_pos']]_____no_output_____kmer_countsu.shape, df_mlevelu.shape, df_atacu.shape_____no_output_____rna.shape, kmer_countsu.shape_____no_output_____ensid = 'ENSMUSG00000067879'

y = rna.loc[ensid,:]

curr_enh = genes2enh.loc[ensid]['enh_pos'].values
curr_enh_num = kmer_enh.loc[curr_enh,'enh_num']
curr_kmers = kmer_counts[curr_enh_num,:]
curr_atac = df_atac.loc[curr_enh,:]
curr_mcg = df_mlevel.loc[curr_enh,:]
curr_kmers.shape, curr_atac.shape, curr_mcg.shape_____no_output_____mdl = sklearn.linear_model.ElasticNet()_____no_output_____curr_enh = genes2enh.loc[ensid]['enh_pos'].values
curr_enh_____no_output_____# Link K-mers to genes
features = []
tstart = time.time()
for ensid,r in rna.iterrows():
    curr_enh = genes2enh.loc[ensid]['enh_pos'].values

    ml = df_mlevel.loc[curr_enh].values
    ml_mean = np.nanmean(ml,axis=0)
    ml_var = np.nanvar(ml,axis=0)
    _____no_output_____

# PyTorch_____no_output_____

# Make sure all data frames have the cell types in the same order
enh_posu = genes2enhu['enh_pos'].unique()
df_mlevelu = df_mlevel.loc[enh_posu]
df_atacu = df_atac.loc[enh_posu]
df_mlevelu_____no_output_____rnau = rna.drop(['10-1','Unnamed: 0'],axis=1)
df_mlevelu = df_mlevelu.loc[:,rnau.columns]
df_atacu = df_atacu.loc[:,rnau.columns]
df_mlevelu  = df_mlevelu.drop_duplicates()
df_atacu = df_atacu.drop_duplicates()
assert( (rnau.columns==df_mlevelu.columns).all() )
assert( (rnau.columns==df_atacu.columns).all() )
df_mlevelu.shape, df_atacu.shape_____no_output_____# Train a CNN regression to predict the mCG level of all DMRs
import pandas as pd
import csv
import numpy as np
import time
import matplotlib.pyplot as plt
# import seqlogo
# from IPython.display import clear_output
# import datetime
# from scipy.stats import spearmanr

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

torch.cuda.is_available()_____no_output_____# Impute the NaN values in mlevel
df_mlevelu_mean = np.outer(df_mlevelu.median(axis=1).values, df_mlevelu.median(axis=0).values)
df_mlevelu_mean = pd.DataFrame(df_mlevelu_mean, index=df_mlevelu.index, columns=df_mlevelu.columns)
df_mlevelu_mean = df_mlevelu_mean.fillna(df_mlevelu.median())
df_mlevelu = df_mlevelu.fillna(df_mlevelu_mean)
assert(not df_mlevelu.isna().any(axis=None))
assert(not df_atacu.isna().any(axis=None))/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/numpy/lib/nanfunctions.py:1116: RuntimeWarning: All-NaN slice encountered
  overwrite_input=overwrite_input)
kmer_counts.shape, kmer_countsu.shape_____no_output_____# Define the neural net architecture
nfilt = 10;
filt_width = 10
pool_size = 600

C = y.shape[1] # Number of cell types
K = kmer_countsu.shape[1] # Number of K-mers

def get_data(ensid):
    # For a list of ensids, return the x and y features
    x = []
    for i,ens in enumerate(ensid):
        curr_enh = genes2enhu.loc[ens,['enh_pos','enh_num']]
#         E = curr_enh.groupby('ensid').count().max(axis=0);
        mlu = df_mlevelu.loc[curr_enh['enh_pos']]
        atacu = df_atacu.loc[curr_enh['enh_pos']]
        kmeru = kmer_counts[curr_enh['enh_num']]
        Ne,Nk = kmeru.shape
        Nc = mlu.shape[1]
        kmeru = kmeru[:,np.newaxis,:]
        kmeru = np.broadcast_to(kmeru,(Ne,Nc,Nk))
        x1 = np.dstack((mlu,atacu,kmeru))
        x1 = x1[np.newaxis,:,:,:]
        x.append(x1)

    # Pad the dimensions
    max_nenh = np.max([xi.shape[1] for xi in x])
    xpad = []
    for xi in x:
        xpad.append(np.pad(xi, ((0,0),(0,max_nenh-xi.shape[1]),(0,0),(0,0))))
    x = np.concatenate(xpad, axis=0)

    y = rnau.loc[ensid].to_numpy().squeeze()

    x = torch.tensor(x, dtype=torch.float)
    y = torch.tensor(y, dtype=torch.float)

    return {'x': x, 'y': y}_____no_output_____data=get_data(ensids[indices])
data['y'].shape_____no_output_____# get_data(ensids[indices[9:11]])
ensids[indices[9]]
get_data(['ENSMUSG00000026141'])_____no_output_____N1 = 10
N2 = 5

# Define a class for the NN architecture
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        self.fc1 = nn.Linear(2+K, N1);
        self.fc2 = nn.Linear(N1, N2);
        self.fc2 = nn.Linear(N1, N2);
        self.fc3 = nn.Linear(N2, 1);

    def forward(self, x):
#         x should be mcg, atac, kmers
#         In: [mcg, atac, kmers] = N x Eg x (2+K)
        x = F.relu(self.fc1(x)) # In: N x Eg x C x (2+K), Out: N x Eg x C x N1
        x = torch.max(x, 1)[0]       # Out: N x C x N1
        x = F.relu(self.fc2(x))       # Out: N x C x N2
        x = torch.squeeze(self.fc3(x)) # Out: N x C

        return x

net = Net()_____no_output_____outputs = net(data['x'])
data['x'].shape_____no_output_____# Training
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if device is not "cpu":
    net.to(torch.device(device))
mseloss=nn.MSELoss()
lr = 0.01
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9)

if device is not "cpu":
    net.to(device)
net.train
running_time = 0
loss_vec = corr_vec = []
nepochs = 0
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer)

loss_test=np.array([])
loss_train = np.array([])
nparams = np.array([])
l1params = np.array([])

# Train/Test split
test = [c in ['chr10','chr12','chr14'] for c in rnau.join(genes)['chr']];
train = [not i for i in test]

test = np.random.permutation(np.nonzero(test)[0]).squeeze()
train = np.random.permutation(np.nonzero(train)[0]).squeeze()

ensids = rna.index.values

test.max(), train.max()_____no_output_____# test = [c in ['chr10','chr12','chr14'] for c in rnau.join(genes)['chr']];
np.nonzero(test)[0].max()_____no_output_____%load_ext line_profiler_____no_output_____%lprun -f get_data get_data([ensids[0]])
# %lprun?_____no_output_____criterion = nn.MSELoss()
num_epochs = 10;
batch_size = 1;

t0 = time.time()
for epoch in range(num_epochs):  # loop over the dataset multiple times
    nsamp = 0
    running_loss = 0;
    running_time = 0
    for i in range(0, len(train), batch_size):
        tstart = time.time()
        indices = train[i:i+batch_size]

        # Input should be of size: (batch, channels, samples)
        batch_data = get_data(ensids[indices])
        batch_X = batch_data['x']
        batch_y = batch_data['y']

        # Send training data to CUDA
        if device is not "cpu":
            batch_X = batch_X.to(device)
            batch_y = batch_y.to(device)

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(batch_X)
        loss = criterion(outputs, batch_y)
        loss.backward()
        optimizer.step()

        running_loss += mseloss(outputs, batch_dmrs_mc).item()

        running_time += time.time()-tstart
        nsamp += len(indices)
        if (time.time()-t0)>5:
            print('Epoch %d, i=%d/%d, loss=%3.3f, t=%3.3f, %3.3f s/sample' % (epoch, i, len(train),
                                                                              running_loss/nsamp, running_time, running_time/nsamp))
            t0=time.time()
    loss_train = np.append(loss_train,running_loss/nsamp)
/cndd/emukamel/conda_envs/scanpy/lib/python3.7/site-packages/ipykernel_launcher.py:15: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike
  from ipykernel import kernelapp as app
nsamp_____no_output_____ensid = ensids[indices[8]]
rnau.loc[ensids[indices[8]]]
df_mlevelu.loc[genes2enhu.loc[ensid]['enh_pos']]
# df_atacu.loc[genes2enhu.loc[ensid]['enh_pos']]
kmer_countsu.shape_____no_output_____


# Notebook from nsorense4/characterization-antenna
Path: .ipynb_checkpoints/SBAND UHF Testing Results-checkpoint.ipynb

<code>
%matplotlib widget
import os
import sys
import numpy as np
import matplotlib
import serial
import pyvisa
import csv
import struct as struct
from time import sleep, time
from pylab import *
from datetime import datetime

from scipy import integrate
from scipy.special import jv

import pylab as pyplt
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
from matplotlib.colors import LogNorm
from scipy.optimize import curve_fit
from scipy.interpolate import interp2d

import codecs
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA

from mpl_toolkits.mplot3d import Axes3D

from matplotlib import cm_____no_output_____def readMiniVNAMeasurements(fileDir,fileName,portdeg):
    results = []
    freq = [] #in Hz
    returnLoss = [] #in dB
    impedanceReal = [] #in Ohms
    impedanceImag = [] # in Ohms
    phase = [] #in Degrees
    with open(fileDir + fileName, newline='') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader)
        #next(csvreader)
        #next(csvreader)
        for row in csvreader:
             results.append(row)
    for i in range(len(results)):
        freq.append(float(results[i][0]))
        returnLoss.append(float(results[i][1]))
        phase.append(float(results[i][2]))
        impedanceReal.append(float(results[i][3]))
        impedanceImag.append(float(results[i][5]))

    phase = adjustPhase(phase,portdeg,freq)

    return freq, returnLoss, phase, impedanceReal, impedanceImag

def readSimMeasurements(fileDir,fileName):
    results = []
    freq = [] #in Hz
    returnLoss = [] #in dB
    phase = [] #in Degrees
    with open(fileDir + fileName, newline='') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader)
        #next(csvreader)
        #next(csvreader)
        for row in csvreader:
             results.append(row)
    for i in range(len(results)):
        freq.append(float(results[i][1]))
        returnLoss.append(float(results[i][2]))

    return freq, returnLoss

def adjustPhase(array,portdeg,freq):
    for i in range(len(array)):
        out0 = 18.025*1e-3/3e8*freq[i]*360
        out90 = 10.727*1e-3/3e8*freq[i]*360
        out180 = 12.139*1e-3/3e8*freq[i]*360
        out270 = 11.302*1e-3/3e8*freq[i]*360

        out0 = out0-out0
        out90 = out90 - out0
        out180 = out180 - out0
        out270 = out270 - out0

        if portdeg == 0:
            array[i] = array[i] - out0
        if portdeg == 90:
            array[i] = array[i] - out90
        if portdeg == 180:
            array[i] = array[i] - out180
        if portdeg == 270:
            array[i] = array[i] - out270

        if array[i] > 180:
            array[i] = array[i] - 360
        elif array[i] < -180:
            array[i] = array[i] + 360

    return array

def returnSParameter(ampArray, freqArray, phaseArray, freqSel, phaseOffset):
    over = 0
    pi = 3.14159
    for i in range(len(freqArray)):
        if freqArray[i] < freqSel:
            over += 1
        elif (float(freqArray[i]) >= freqSel) and (over > 1):
            place = i-1
            amp = ampArray[place]

            if phaseOffset == 0:
                phase = -phaseArray[place]
            else:
                phase = -phaseArray[place] + phaseOffset
            real = 10**(amp/20)*np.cos(phase*pi/180)
            imag = 10**(amp/20)*np.sin(phase*pi/180)

            break

    return phaseArray[place], amp, real, imag, phase
_____no_output_____##############################Initialise#####################################################
nrow = 2
ncol = 1
xsize = 4.5
ysize = 3.5

#############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))

ax[0].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
ax[0].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
ax[0].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
ax[0].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
ax[0].set_ylabel(r'S$_{11}$ (dB) - 2U', fontsize = labelfont)
ax[0].set_xlabel(r'$f$ (GHz)', fontsize = labelfont)

ax[1].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
ax[1].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
ax[1].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
ax[1].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
ax[1].set_ylabel(r'S$_{11}$ (dB) - 3U', fontsize = labelfont)
ax[1].set_xlabel(r'$f$ (GHz)', fontsize = labelfont)

#############################################################################################
#labels

#############################################################################################

freq2U, returnLoss2U, phase2U, impedanceABS2U = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_210924_114709_2U.csv")
freq3U, returnLoss3U, phase3U, impedanceABS3U = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_210924_115903_3U.csv")
freq2USim, returnLoss2USim = readSimMeasurements("S Parameter New 2U.csv")
freq3USim, returnLoss3USim = readSimMeasurements("S Parameter New 3U.csv")

p1 = ax[0].plot(np.multiply(freq2U,1e-9),returnLoss2U, linewidth = 2, color = 'dodgerblue',label='Measured - 2U Heracles')
p2 = ax[1].plot(np.multiply(freq3U,1e-9),returnLoss3U, linewidth = 2, color = 'salmon',label='Measured - 3U Heracles')

p3 = ax[0].plot(np.multiply(freq2USim,1),returnLoss2USim, "--",linewidth = 2, color = 'blue',label='Simulated - 2U Heracles')
p4 = ax[1].plot(np.multiply(freq3USim,1),returnLoss3USim, "--",linewidth = 2, color = 'red',label='Simulated - 3U Heracles')

ax[0].plot([2.428,2.428],[-40,0], "--",linewidth = 1, color = 'black')
ax[1].plot([2.428,2.428],[-40,0], "--",linewidth = 1, color = 'black')

#ax[0].set_ylim(4.45, 5.05)
#ax[1].set_ylim(2.75, 3.4)

ax[0].set_xlim(2.35, 2.55)
ax[1].set_xlim(2.35, 2.55)
ax[0].set_ylim(-40,0)
ax[1].set_ylim(-40,0)

fig.set_facecolor('w')

#ax[0].legend([s1,s3,s5,s8,s9],["OP1","OP3","OP5","OP8","OP9"],ncol = 3)
#ax[1].legend([s2,s4,s6,s7,s10],["OP2","OP4","OP6","OP7","OP10"],ncol = 3)

matplotlib.pyplot.tight_layout()
ax[0].legend( fontsize = legfont)
ax[1].legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0, hspace=0.4)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____##############################Initialise#####################################################
nrow = 2
ncol = 2
xsize = 8
ysize = 8

#############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))

for i in [0,1]:
    for j in [0,1]:
        ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].set_xlabel(r'$f$ (MHz)', fontsize = labelfont)

ax[0,0].set_ylabel(r'Input Reflection Loss (dB)', fontsize = labelfont)
ax[0,1].set_ylabel(r'Output Transmission Loss (dB)', fontsize = labelfont)
ax[1,0].set_ylabel(r'Input Transmission Loss (dB)', fontsize = labelfont)
ax[1,1].set_ylabel(r'Output Reflection Loss (dB)', fontsize = labelfont)

#############################################################################################
#labels

#############################################################################################

##Port 1 - 0 degrees
freq_0_port_S11, meas_0_port_S11, phase_0_port_S11, impedanceABS_0_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_161627_0_port_S11.csv")
freq_0_port_S21, meas_0_port_S21, phase_0_port_S21, impedanceABS_0_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_161858_0_port_S21.csv")
freq_0_port_S22, meas_0_port_S22, phase_0_port_S22, impedanceABS_0_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162113_0_port_S22.csv")
freq_0_port_S12, meas_0_port_S12, phase_0_port_S12, impedanceABS_0_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162207_0_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_0_port_S11,1e-6),meas_0_port_S11, linewidth = 1, color = 'dodgerblue',label='S(1,1)$_2$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_0_port_S21,1e-6),meas_0_port_S21, linewidth = 1, color = 'dodgerblue',label='S(2,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_0_port_S22,1e-6),meas_0_port_S22, linewidth = 1, color = 'dodgerblue',label='S(2,2)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_0_port_S12,1e-6),meas_0_port_S12, linewidth = 1, color = 'dodgerblue',label='S(1,2)')

##Port 2 - 90 degrees
freq_90_port_S11, meas_90_port_S11, phase_90_port_S11, impedanceABS_90_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_163407_90_port_S11.csv")
freq_90_port_S21, meas_90_port_S21, phase_90_port_S21, impedanceABS_90_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_163533_90_port_S21.csv")
freq_90_port_S22, meas_90_port_S22, phase_90_port_S22, impedanceABS_90_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162645_90_port_S22.csv")
freq_90_port_S12, meas_90_port_S12, phase_90_port_S12, impedanceABS_90_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162548_90_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_90_port_S11,1e-6),meas_90_port_S11, linewidth = 1, color = 'red',label='S(1,1)$_3$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_90_port_S21,1e-6),meas_90_port_S21, linewidth = 1, color = 'red',label='S(3,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_90_port_S22,1e-6),meas_90_port_S22, linewidth = 1, color = 'red',label='S(3,3)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_90_port_S12,1e-6),meas_90_port_S12, linewidth = 1, color = 'red',label='S(1,3)')

##Port 3 - 180 degrees
freq_180_port_S11, meas_180_port_S11, phase_180_port_S11, impedanceABS_180_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164114_180_port_S11.csv")
freq_180_port_S21, meas_180_port_S21, phase_180_port_S21, impedanceABS_180_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164031_180_port_S21.csv")
freq_180_port_S22, meas_180_port_S22, phase_180_port_S22, impedanceABS_180_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164250_180_port_S22.csv")
freq_180_port_S12, meas_180_port_S12, phase_180_port_S12, impedanceABS_180_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164343_180_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_180_port_S11,1e-6),meas_180_port_S11, linewidth = 1, color = 'green',label='S(1,1)$_4$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_180_port_S21,1e-6),meas_180_port_S21, linewidth = 1, color = 'green',label='S(4,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_180_port_S22,1e-6),meas_180_port_S22, linewidth = 1, color = 'green',label='S(4,4)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_180_port_S12,1e-6),meas_180_port_S12, linewidth = 1, color = 'green',label='S(1,4)')

##Port 4 - 270 degrees
freq_270_port_S11, meas_270_port_S11, phase_270_port_S11, impedanceABS_270_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164951_270_port_S11.csv")
freq_270_port_S21, meas_270_port_S21, phase_270_port_S21, impedanceABS_270_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_165030_270_port_S21.csv")
freq_270_port_S22, meas_270_port_S22, phase_270_port_S22, impedanceABS_270_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164757_270_port_S22.csv")
freq_270_port_S12, meas_270_port_S12, phase_270_port_S12, impedanceABS_270_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164722_270_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_270_port_S11,1e-6),meas_270_port_S11, linewidth = 1, color = 'goldenrod',label='S(1,1)$_5$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_270_port_S21,1e-6),meas_270_port_S21, linewidth = 1, color = 'goldenrod',label='S(5,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_270_port_S22,1e-6),meas_270_port_S22, linewidth = 1, color = 'goldenrod',label='S(5,5)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_270_port_S12,1e-6),meas_270_port_S12, linewidth = 1, color = 'goldenrod',label='S(1,5)')

ax[0,0].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[1,0].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[0,1].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[1,1].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')

ax[0,0].set_ylim(-34,-16)
ax[1,0].set_ylim(-12.6, -7.5)
ax[0,1].set_ylim(-13,-7.7)
ax[1,1].set_ylim(-27,-15)

fig.set_facecolor('w')

#ax[0].legend([s1,s3,s5,s8,s9],["OP1","OP3","OP5","OP8","OP9"],ncol = 3)
#ax[1].legend([s2,s4,s6,s7,s10],["OP2","OP4","OP6","OP7","OP10"],ncol = 3)

matplotlib.pyplot.tight_layout()
ax[0,0].legend( fontsize = legfont)
ax[1,1].legend( fontsize = legfont)
ax[0,1].legend( fontsize = legfont)
ax[1,0].legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____##############################Initialise#####################################################
nrow = 2
ncol = 2
xsize = 8
ysize = 8

#############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))

for i in [0,1]:
    for j in [0,1]:
        ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].set_xlabel(r'$f$ (MHz)', fontsize = labelfont)

ax[0,0].set_ylabel(r'Input Reflection Phase (dB)', fontsize = labelfont)
ax[0,1].set_ylabel(r'Output Transmission Phase (dB)', fontsize = labelfont)
ax[1,0].set_ylabel(r'Input Transmission Phase (dB)', fontsize = labelfont)
ax[1,1].set_ylabel(r'Output Reflection Phase (dB)', fontsize = labelfont)

#############################################################################################
#labels

#############################################################################################

##Port 1 - 0 degrees
freq_0_port_S11, meas_0_port_S11, phase_0_port_S11, impedanceABS_0_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_161627_0_port_S11.csv")
freq_0_port_S21, meas_0_port_S21, phase_0_port_S21, impedanceABS_0_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_161858_0_port_S21.csv")
freq_0_port_S22, meas_0_port_S22, phase_0_port_S22, impedanceABS_0_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162113_0_port_S22.csv")
freq_0_port_S12, meas_0_port_S12, phase_0_port_S12, impedanceABS_0_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162207_0_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_0_port_S11,1e-6),phase_0_port_S11, linewidth = 1, color = 'dodgerblue',label='S(1,1)$_2$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_0_port_S21,1e-6),phase_0_port_S21, linewidth = 1, color = 'dodgerblue',label='S(2,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_0_port_S22,1e-6),phase_0_port_S22, linewidth = 1, color = 'dodgerblue',label='S(2,2)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_0_port_S12,1e-6),phase_0_port_S12, linewidth = 1, color = 'dodgerblue',label='S(1,2)')

##Port 2 - 90 degrees
freq_90_port_S11, meas_90_port_S11, phase_90_port_S11, impedanceABS_90_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_163407_90_port_S11.csv")
freq_90_port_S21, meas_90_port_S21, phase_90_port_S21, impedanceABS_90_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_163533_90_port_S21.csv")
freq_90_port_S22, meas_90_port_S22, phase_90_port_S22, impedanceABS_90_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162645_90_port_S22.csv")
freq_90_port_S12, meas_90_port_S12, phase_90_port_S12, impedanceABS_90_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_162548_90_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_90_port_S11,1e-6),phase_90_port_S11, linewidth = 1, color = 'red',label='S(1,1)$_3$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_90_port_S21,1e-6),phase_90_port_S21, linewidth = 1, color = 'red',label='S(3,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_90_port_S22,1e-6),phase_90_port_S22, linewidth = 1, color = 'red',label='S(3,3)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_90_port_S12,1e-6),phase_90_port_S12, linewidth = 1, color = 'red',label='S(1,3)')

##Port 3 - 180 degrees
freq_180_port_S11, meas_180_port_S11, phase_180_port_S11, impedanceABS_180_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164114_180_port_S11.csv")
freq_180_port_S21, meas_180_port_S21, phase_180_port_S21, impedanceABS_180_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164031_180_port_S21.csv")
freq_180_port_S22, meas_180_port_S22, phase_180_port_S22, impedanceABS_180_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164250_180_port_S22.csv")
freq_180_port_S12, meas_180_port_S12, phase_180_port_S12, impedanceABS_180_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164343_180_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_180_port_S11,1e-6),phase_180_port_S11, linewidth = 1, color = 'green',label='S(1,1)$_4$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_180_port_S21,1e-6),phase_180_port_S21, linewidth = 1, color = 'green',label='S(4,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_180_port_S22,1e-6),phase_180_port_S22, linewidth = 1, color = 'green',label='S(4,4)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_180_port_S12,1e-6),phase_180_port_S12, linewidth = 1, color = 'green',label='S(1,4)')

##Port 4 - 270 degrees
freq_270_port_S11, meas_270_port_S11, phase_270_port_S11, impedanceABS_270_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164951_270_port_S11.csv")
freq_270_port_S21, meas_270_port_S21, phase_270_port_S21, impedanceABS_270_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_165030_270_port_S21.csv")
freq_270_port_S22, meas_270_port_S22, phase_270_port_S22, impedanceABS_270_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164757_270_port_S22.csv")
freq_270_port_S12, meas_270_port_S12, phase_270_port_S12, impedanceABS_270_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20210924/","VNA_210924_164722_270_port_S12.csv")

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_270_port_S11,1e-6),phase_270_port_S11, linewidth = 1, color = 'goldenrod',label='S(1,1)$_5$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_270_port_S21,1e-6),phase_270_port_S21, linewidth = 1, color = 'goldenrod',label='S(5,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_270_port_S22,1e-6),phase_270_port_S22, linewidth = 1, color = 'goldenrod',label='S(5,5)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_270_port_S12,1e-6),phase_270_port_S12, linewidth = 1, color = 'goldenrod',label='S(1,5)')

ax[0,0].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[1,0].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[0,1].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[1,1].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')

ax[0,0].set_ylim(-180,180)
ax[1,0].set_ylim(-180,180)
ax[0,1].set_ylim(-180,180)
ax[1,1].set_ylim(-180,180)

fig.set_facecolor('w')

#ax[0].legend([s1,s3,s5,s8,s9],["OP1","OP3","OP5","OP8","OP9"],ncol = 3)
#ax[1].legend([s2,s4,s6,s7,s10],["OP2","OP4","OP6","OP7","OP10"],ncol = 3)

matplotlib.pyplot.tight_layout()
ax[0,0].legend( fontsize = legfont)
ax[1,1].legend( fontsize = legfont)
ax[0,1].legend( fontsize = legfont)
ax[1,0].legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____##############################Initialise#####################################################
nrow = 2
ncol = 2
xsize = 8
ysize = 8

#############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))

for i in [0,1]:
    for j in [0,1]:
        ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].set_xlabel(r'$f$ (MHz)', fontsize = labelfont)

ax[0,0].set_ylabel(r'Input Reflection Loss (dB)', fontsize = labelfont)
ax[0,1].set_ylabel(r'Output Transmission Loss (dB)', fontsize = labelfont)
ax[1,0].set_ylabel(r'Input Transmission Loss (dB)', fontsize = labelfont)
ax[1,1].set_ylabel(r'Output Reflection Loss (dB)', fontsize = labelfont)

#############################################################################################
#labels

#############################################################################################

##Port 1 - 0 degrees

freq_0_port_S11, meas_0_port_S11, phase_0_port_S11, impedanceABS_0_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093855_S11_1.csv",0)
freq_0_port_S21, meas_0_port_S21, phase_0_port_S21, impedanceABS_0_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093802_S21.csv",0)
freq_0_port_S22, meas_0_port_S22, phase_0_port_S22, impedanceABS_0_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094031_S22.csv",0)
freq_0_port_S12, meas_0_port_S12, phase_0_port_S12, impedanceABS_0_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094105_S12.csv",0)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_0_port_S11,1e-6),meas_0_port_S11, linewidth = 1, color = 'dodgerblue',label='S(1,1)$_2$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_0_port_S21,1e-6),meas_0_port_S21, linewidth = 1, color = 'dodgerblue',label='S(2,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_0_port_S22,1e-6),meas_0_port_S22, linewidth = 1, color = 'dodgerblue',label='S(2,2)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_0_port_S12,1e-6),meas_0_port_S12, linewidth = 1, color = 'dodgerblue',label='S(1,2)')

##Port 2 - 90 degrees
freq_90_port_S11, meas_90_port_S11, phase_90_port_S11, impedanceABS_90_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_092620_S11_2.csv",90)
freq_90_port_S21, meas_90_port_S21, phase_90_port_S21, impedanceABS_90_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093358_S31.csv",90)
freq_90_port_S22, meas_90_port_S22, phase_90_port_S22, impedanceABS_90_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093123_S33.csv",90)
freq_90_port_S12, meas_90_port_S12, phase_90_port_S12, impedanceABS_90_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093231_S13.csv",90)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_90_port_S11,1e-6),meas_90_port_S11, linewidth = 1, color = 'red',label='S(1,1)$_3$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_90_port_S21,1e-6),meas_90_port_S21, linewidth = 1, color = 'red',label='S(3,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_90_port_S22,1e-6),meas_90_port_S22, linewidth = 1, color = 'red',label='S(3,3)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_90_port_S12,1e-6),meas_90_port_S12, linewidth = 1, color = 'red',label='S(1,3)')

##Port 3 - 180 degrees
freq_180_port_S11, meas_180_port_S11, phase_180_port_S11, impedanceABS_180_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_095000_S11_3.csv",180)
freq_180_port_S21, meas_180_port_S21, phase_180_port_S21, impedanceABS_180_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_095130_S41.csv",180)
freq_180_port_S22, meas_180_port_S22, phase_180_port_S22, impedanceABS_180_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094742_S44.csv",180)
freq_180_port_S12, meas_180_port_S12, phase_180_port_S12, impedanceABS_180_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094700_S14.csv",180)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_180_port_S11,1e-6),meas_180_port_S11, linewidth = 1, color = 'green',label='S(1,1)$_4$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_180_port_S21,1e-6),meas_180_port_S21, linewidth = 1, color = 'green',label='S(4,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_180_port_S22,1e-6),meas_180_port_S22, linewidth = 1, color = 'green',label='S(4,4)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_180_port_S12,1e-6),meas_180_port_S12, linewidth = 1, color = 'green',label='S(1,4)')

##Port 4 - 270 degrees
freq_270_port_S11, meas_270_port_S11, phase_270_port_S11, impedanceABS_270_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100803_S11_4.csv",270)
freq_270_port_S21, meas_270_port_S21, phase_270_port_S21, impedanceABS_270_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100654_S51.csv",270)
freq_270_port_S22, meas_270_port_S22, phase_270_port_S22, impedanceABS_270_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100914_S55.csv",270)
freq_270_port_S12, meas_270_port_S12, phase_270_port_S12, impedanceABS_270_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_101008_S15.csv",270)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_270_port_S11,1e-6),meas_270_port_S11, linewidth = 1, color = 'goldenrod',label='S(1,1)$_5$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_270_port_S21,1e-6),meas_270_port_S21, linewidth = 1, color = 'goldenrod',label='S(5,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_270_port_S22,1e-6),meas_270_port_S22, linewidth = 1, color = 'goldenrod',label='S(5,5)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_270_port_S12,1e-6),meas_270_port_S12, linewidth = 1, color = 'goldenrod',label='S(1,5)')

ax[0,0].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[1,0].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[0,1].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')
ax[1,1].plot([437.825,437.825],[-50,0], "--",linewidth = 1, color = 'black')

ax[0,0].set_ylim(-30,-19)
ax[1,0].set_ylim(-10, -5)
ax[0,1].set_ylim(-10, -5)
ax[1,1].set_ylim(-32,-15)

fig.set_facecolor('w')

#ax[0].legend([s1,s3,s5,s8,s9],["OP1","OP3","OP5","OP8","OP9"],ncol = 3)
#ax[1].legend([s2,s4,s6,s7,s10],["OP2","OP4","OP6","OP7","OP10"],ncol = 3)

matplotlib.pyplot.tight_layout()
ax[0,0].legend( fontsize = legfont)
ax[1,1].legend( fontsize = legfont)
ax[0,1].legend( fontsize = legfont)
ax[1,0].legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____##############################Initialise#####################################################
nrow = 2
ncol = 2
xsize = 8
ysize = 8

############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))

for i in [0,1]:
    for j in [0,1]:
        ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i,j].set_xlabel(r'$f$ (MHz)', fontsize = labelfont)

ax[0,0].set_ylabel(r'Input Reflection Phase ($^\circ$)', fontsize = labelfont)
ax[0,1].set_ylabel(r'Output Transmission Phase ($^\circ$)', fontsize = labelfont)
ax[1,0].set_ylabel(r'Input Transmission Phase ($^\circ$)', fontsize = labelfont)
ax[1,1].set_ylabel(r'Output Reflection Phase ($^\circ$)', fontsize = labelfont)

#############################################################################################
#labels

#############################################################################################

##Port 1 - 0 degrees
freq_0_port_S11, meas_0_port_S11, phase_0_port_S11, impedanceABS_0_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093855_S11_1.csv",0)
freq_0_port_S21, meas_0_port_S21, phase_0_port_S21, impedanceABS_0_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093802_S21.csv",0)
freq_0_port_S22, meas_0_port_S22, phase_0_port_S22, impedanceABS_0_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094031_S22.csv",0)
freq_0_port_S12, meas_0_port_S12, phase_0_port_S12, impedanceABS_0_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094105_S12.csv",0)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_0_port_S11,1e-6),phase_0_port_S11, linewidth = 1, color = 'dodgerblue',label='S(1,1)$_2$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_0_port_S21,1e-6),phase_0_port_S21, linewidth = 1, color = 'dodgerblue',label='S(2,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_0_port_S22,1e-6),phase_0_port_S22, linewidth = 1, color = 'dodgerblue',label='S(2,2)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_0_port_S12,1e-6),phase_0_port_S12, linewidth = 1, color = 'dodgerblue',label='S(1,2)')

##Port 2 - 90 degrees
freq_90_port_S11, meas_90_port_S11, phase_90_port_S11, impedanceABS_90_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_092620_S11_2.csv",90)
freq_90_port_S21, meas_90_port_S21, phase_90_port_S21, impedanceABS_90_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093358_S31.csv",90)
freq_90_port_S22, meas_90_port_S22, phase_90_port_S22, impedanceABS_90_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093123_S33.csv",90)
freq_90_port_S12, meas_90_port_S12, phase_90_port_S12, impedanceABS_90_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093231_S13.csv",90)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_90_port_S11,1e-6),phase_90_port_S11, linewidth = 1, color = 'red',label='S(1,1)$_3$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_90_port_S21,1e-6),phase_90_port_S21, linewidth = 1, color = 'red',label='S(3,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_90_port_S22,1e-6),phase_90_port_S22, linewidth = 1, color = 'red',label='S(3,3)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_90_port_S12,1e-6),phase_90_port_S12, linewidth = 1, color = 'red',label='S(1,3)')

##Port 3 - 180 degrees
freq_180_port_S11, meas_180_port_S11, phase_180_port_S11, impedanceABS_180_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_095000_S11_3.csv",180)
freq_180_port_S21, meas_180_port_S21, phase_180_port_S21, impedanceABS_180_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_095130_S41.csv",180)
freq_180_port_S22, meas_180_port_S22, phase_180_port_S22, impedanceABS_180_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094742_S44.csv",180)
freq_180_port_S12, meas_180_port_S12, phase_180_port_S12, impedanceABS_180_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094700_S14.csv",180)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_180_port_S11,1e-6),phase_180_port_S11, linewidth = 1, color = 'green',label='S(1,1)$_4$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_180_port_S21,1e-6),phase_180_port_S21, linewidth = 1, color = 'green',label='S(4,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_180_port_S22,1e-6),phase_180_port_S22, linewidth = 1, color = 'green',label='S(4,4)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_180_port_S12,1e-6),phase_180_port_S12, linewidth = 1, color = 'green',label='S(1,4)')

##Port 4 - 270 degrees
freq_270_port_S11, meas_270_port_S11, phase_270_port_S11, impedanceABS_270_port_S11 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100803_S11_4.csv",270)
freq_270_port_S21, meas_270_port_S21, phase_270_port_S21, impedanceABS_270_port_S21 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100654_S51.csv",270)
freq_270_port_S22, meas_270_port_S22, phase_270_port_S22, impedanceABS_270_port_S22 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100914_S55.csv",270)
freq_270_port_S12, meas_270_port_S12, phase_270_port_S12, impedanceABS_270_port_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_101008_S15.csv",270)

IRP_PORT1 = ax[0,0].plot(np.multiply(freq_270_port_S11,1e-6),phase_270_port_S11, linewidth = 1, color = 'goldenrod',label='S(1,1)$_5$')
ITP_PORT1 = ax[1,0].plot(np.multiply(freq_270_port_S21,1e-6),phase_270_port_S21, linewidth = 1, color = 'goldenrod',label='S(5,1)')
ORP_PORT1 = ax[1,1].plot(np.multiply(freq_270_port_S22,1e-6),phase_270_port_S22, linewidth = 1, color = 'goldenrod',label='S(5,5)$_1$')
OTP_PORT1 = ax[0,1].plot(np.multiply(freq_270_port_S12,1e-6),phase_270_port_S12, linewidth = 1, color = 'goldenrod',label='S(1,5)')

ax[0,0].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[1,0].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[0,1].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax[1,1].plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')

ax[0,0].set_ylim(-180,180)
ax[1,0].set_ylim(-180,180)
ax[0,1].set_ylim(-180,180)
ax[1,1].set_ylim(-180,180)

center = 625
print(freq_270_port_S11[center])
print("S12 - PHASE: /n")

print(-phase_0_port_S12[center]+phase_0_port_S12[center])
print(-phase_90_port_S12[center]+phase_0_port_S12[center])
print(-phase_180_port_S12[center]+phase_0_port_S12[center])
print(-phase_270_port_S12[center]+phase_0_port_S12[center])

fig.set_facecolor('w')

#ax[0].legend([s1,s3,s5,s8,s9],["OP1","OP3","OP5","OP8","OP9"],ncol = 3)
#ax[1].legend([s2,s4,s6,s7,s10],["OP2","OP4","OP6","OP7","OP10"],ncol = 3)

matplotlib.pyplot.tight_layout()
ax[0,0].legend( fontsize = legfont)
ax[1,1].legend( fontsize = legfont)
ax[0,1].legend( fontsize = legfont)
ax[1,0].legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____freq_S12, meas_S12, phase_S12, impedanceABS_S12 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094105_S12.csv",0)
freq_S13, meas_S13, phase_S13, impedanceABS_S13 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093231_S13.csv",90)
freq_S14, meas_S14, phase_S14, impedanceABS_S14 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094700_S14.csv",180)
freq_S15, meas_S15, phase_S15, impedanceABS_S15 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_101008_S15.csv",270)
phaseArray0, amp, real, imag, phase = returnSParameter(meas_S12, freq_S12, phase_S12, float(437.875e6), 0)
print(phaseArray)
print(amp)
print(real)
print(imag)
print(phase)
phaseArray, amp, real, imag, phase = returnSParameter(meas_S13, freq_S13, phase_S13, float(437.875e6), phaseArray0)
print(phaseArray)
print(amp)
print(real)
print(imag)
print(phase)
phaseArray, amp, real, imag, phase = returnSParameter(meas_S14, freq_S14, phase_S14, float(437.875e6), phaseArray0)
print(phaseArray)
print(amp)
print(real)
print(imag)
print(phase)
phaseArray, amp, real, imag, phase = returnSParameter(meas_S15, freq_S15, phase_S15, float(437.875e6), phaseArray0)
print(phaseArray)
print(amp)
print(real)
print(imag)
print(phase)-114.66715251250001
-8.02
-0.359330218303947
-0.16924219681737968
-154.78
66.54490576875
-8.46
0.011629165234856187
0.3773930601854772
88.23509423125
-22.14684430625
-8.28
-0.38492394649466144
0.02066687309865062
176.92684430625
-114.66715251250001
-8.43
-0.0036572505477184647
-0.3788608819260664
269.4471525125
##############################Initialise#####################################################
nrow = 1
ncol = 1
xsize = 7
ysize = 4

############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))
if (nrow == 1) and (ncol == 1):
    ax.tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
    ax.tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
    ax.tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
    ax.tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
elif ((nrow != 1) and (ncol == 1)) or ((nrow == 1) and (ncol != 1)):
    for i in [0,1]:
        ax[i].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
else:
    for i in [0,1]:
        for j in [0,1]:
            ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
            ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
            ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
            ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')

ax.set_xlabel(r'$f$ (MHz)', fontsize = labelfont)
ax.set_ylabel(r'Return Loss (dB)', fontsize = labelfont)\

#############################################################################################
#labels

#############################################################################################

freq_A1, meas_A1, phase_A1, impedanceReal_A1, impedanceImag_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_1624515_0deg_antenna_meas_3.csv",0)
freq_A2, meas_A2, phase_A2, impedanceReal_A2, impedanceImag_A2 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_163006_90deg_antenna_meas_3.csv",0)
freq_A3, meas_A3, phase_A3, impedanceReal_A3, impedanceImag_A3 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_163123_180deg_antenna_meas_3.csv",0)
freq_A4, meas_A4, phase_A4, impedanceReal_A4, impedanceImag_A4 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_162705_270deg_antenna_meas_3.csv",0)

A1 = ax.plot(np.multiply(freq_A1,1e-6),meas_A1, linewidth = 1, color = 'dodgerblue',label='0$^\circ$ Antenna')
A2 = ax.plot(np.multiply(freq_A2,1e-6),meas_A2, linewidth = 1, color = 'red',label='90$^\circ$ Antenna')
A3 = ax.plot(np.multiply(freq_A3,1e-6),meas_A3, linewidth = 1, color = 'green',label='180$^\circ$ Antenna')
A4 = ax.plot(np.multiply(freq_A4,1e-6),meas_A4, linewidth = 1, color = 'goldenrod',label='270$^\circ$ Antenna')

ax.plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax.plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax.plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')
ax.plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')

ax.set_ylim(-45,-10)

fig.set_facecolor('w')

matplotlib.pyplot.tight_layout()
ax.legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____print(impedanceReal_A1[625])
print(impedanceImag_A1[625])
print("\n")
print(impedanceReal_A2[625])
print(impedanceImag_A2[625])
print("\n")
print(impedanceReal_A3[625])
print(impedanceImag_A3[625])
print("\n")
print(impedanceReal_A4[625])
print(impedanceImag_A4[625])
print("\n")

print(meas_A1[625])
print("\n")
print(meas_A2[625])
print("\n")
print(meas_A3[625])
print("\n")
print(meas_A4[625])
print("\n")53.5
-3.6

51.8
-0.4

51.3
-2.2

53.8
-2.3

-26.3

-35.06

-31.81

-27.41

##############################Initialise#####################################################
nrow = 1
ncol = 1
xsize = 7
ysize = 4

############################################################################################
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]

#set global plotting parameters
linew = 5.0 #line width
#msize = 14 #marker size
axew = 1.0 #axes width

#set the distance to offset the numbers from the ticks
numpad = 10

#set global tick parameters
majw = axew #major tick width
majl = 2.0 #major tick length
minw = axew #minor tick width
minl = 2.0 #minor tick length

#set global font sizes
axefont = 12 #axis label font size
numsize = 12 #axis number font size
legfont = 12 #legend font size
labelfont=16

fig, ax = plt.subplots(nrows=nrow, ncols=ncol, figsize=(xsize,ysize))
if (nrow == 1) and (ncol == 1):
    ax.tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
    ax.tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
    ax.tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
    ax.tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
elif ((nrow != 1) and (ncol == 1)) or ((nrow == 1) and (ncol != 1)):
    for i in [0,1]:
        ax[i].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
        ax[i].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
        ax[i].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
else:
    for i in [0,1]:
        for j in [0,1]:
            ax[i,j].tick_params(axis='x',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
            ax[i,j].tick_params(axis='x',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,top='off')
            ax[i,j].tick_params(axis='y',which='major',width=majw,length=majl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')
            ax[i,j].tick_params(axis='y',which='minor',width=minw,length=minl,labelsize=numsize,zorder=1,direction='in',pad=numpad,right='off')

ax.set_xlabel(r'$f$ (MHz)', fontsize = labelfont)
ax.set_ylabel(r'Return Loss (dB)', fontsize = labelfont)\

#############################################################################################
#labels

#############################################################################################

freq_A1, meas_A1, phase_A1, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211015_093029_finalassembly_RL.csv",0)

A1 = ax.plot(np.multiply(freq_A1,1e-6),meas_A1, linewidth = 1, color = 'dodgerblue',label='0$^\circ$ Antenna')

ax.plot([437.825,437.825],[-180,180], "--",linewidth = 1, color = 'black')

ax.set_ylim(-45,-10)

fig.set_facecolor('w')

matplotlib.pyplot.tight_layout()
ax.legend( fontsize = legfont)
matplotlib.pyplot.tight_layout()

fig.subplots_adjust(wspace=0.3, hspace=0.2)
#plt.savefig("SBAND_Measurement_Comparison.png", dpi=400)_____no_output_____freq_S11, meas_S11, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093855_S11_1.csv",0)
freq_S12, meas_S12, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094105_S12.csv",0)
freq_S11, meas_S13, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093231_S13.csv",0)
freq_S11, meas_S14, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094700_S14.csv",0)
freq_S11, meas_S15, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_101008_S15.csv",0)
freq_S11, meas_S21, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093802_S21.csv",0)
freq_S11, meas_S22, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094031_S22.csv",0)
freq_S11, meas_S23, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105123_S32.csv",0)
freq_S11, meas_S24, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105013_S42.csv",0)
freq_S11, meas_S25, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105944_S52.csv",0)
freq_S11, meas_S31, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093358_S31.csv",0)
freq_S11, meas_S32, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105123_S32.csv",0)
freq_S11, meas_S33, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_093123_S33.csv",0)
freq_S11, meas_S34, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105458_S34.csv",0)
freq_S11, meas_S35, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105623_S35.csv",0)
freq_S11, meas_S41, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_095130_S41.csv",0)
freq_S11, meas_S42, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105013_S42.csv",0)
freq_S11, meas_S43, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_104815_S43.csv",0)
freq_S11, meas_S44, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_094742_S44.csv",0)
freq_S11, meas_S45, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_103000_S45.csv",0)
freq_S11, meas_S51, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100654_S51.csv",0)
freq_S11, meas_S52, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105944_S52.csv",0)
freq_S11, meas_S53, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_105802_S53.csv",0)
freq_S11, meas_S54, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_102733_S54.csv",0)
freq_S11, meas_S55, phase_S11, impedanceABS_A1 = readMiniVNAMeasurements("C:/Users/nicho/Desktop/AlbertaSat_Non_SVN/UHF/Arke-20211014/","VNA_211014_100914_S55.csv",0)

pr_____no_output_____
</code>