Example #1
0
def print_matrix(A, S1, S2, C, filename, parent_dir):
    import matplotlib.pyplot as plt
    from ensure_dir import ensure_dir
    import os
    script_dir = os.getcwd()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(A, cmap='Greys')
    ax.set_title(
        'Matrice interazioni con dati reali e connettanza = {}'.format(C))
    ax.set_xlabel('Numero specie piante: S2 = {}'.format(S2))
    ax.set_ylabel('Numero specie impollinatori: S1 = {}'.format(S1))

    xtics = [x - 0.5 for x in range(0, S2 + 1)]
    ytics = [x - 0.5 for x in range(0, S1 + 1)]
    ax.grid()
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)

    path = parent_dir + '/' + filename + '//prova.txt'
    ensure_dir(path)
    directory = os.path.dirname(path)
    os.chdir(directory)
    fig.savefig(filename + '_matrix.png')
    plt.close()
    os.chdir(script_dir)
Example #2
0
def print_matrix2(A, S1, S2, C, NODF, re, parent_dir):
    import matplotlib.pyplot as plt
    from ensure_dir import ensure_dir
    import os
    script_dir = os.getcwd()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(A, cmap='Greys')
    ax.set_title('Matrice per step {} con C = {} e NODF = {}'.format(
        re, C, NODF))
    ax.set_xlabel('S2 = {}'.format(S2))
    ax.set_ylabel('S1 = {}'.format(S1))

    xtics = [x - 0.5 for x in range(0, S2 + 1)]
    ytics = [x - 0.5 for x in range(0, S1 + 1)]
    ax.grid()
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)

    path = parent_dir + '//prova.txt'
    ensure_dir(path)
    directory = os.path.dirname(path)
    os.chdir(directory)
    fig.savefig(repr(C) + '-' + repr(re) + '_matrix.png')
    plt.close()
    os.chdir(script_dir)
def search_by_reaction(number,folder,SMILES_reaction, PATH):
    files_mrv = glob.glob(folder + 'search_' + str(number+1) + '/' + '*.mrv')
    ensure_dir.ensure_dir(folder + 'temporary/')
    fn=0
    for file in files_mrv:
        g = open(file)
        ggg = g.readlines()
        g.close()
        fn+=1
        if len(ggg)>2:
            print(file)
            print ('Standardizing...')
            try:
                sp.call(['standardize', file, '-c', PATH+'/standardizer2.xml', '-f', 'rdf', '-o', file[:-3] + 'rdf'])
            except:
                print ('Not enough memory for Standardizer!!!')
                sys.exit()
            print ('Searching by reaction...')
            try:
                sp.call(['jcsearch', '-q', SMILES_reaction[number*2], '-f', 'MRV', '-o', folder + 'temporary/' + file.split('/')[-1], file[:-3] + 'rdf'])
            except:
                print ('Not enough memory for jcsearch!!!')
                sys.exit()
            print (file.split('/')[-1] + ' is done..')
            print (str(fn*100//len(files_mrv)) + '%')
    sp.call([PATH+'/molconvert_calling.sh', folder.rstrip('/'), str(number+1)])
    sp.call(["rm", "-r", folder + 'temporary/'])
    print ('Substructure search in jcsearch by reaction is done...')
Example #4
0
def write_sta_pv(staname,
                 ident,
                 eposta,
                 Xsta,
                 Ysta,
                 Zsta,
                 Xsta_err,
                 Ysta_err,
                 Zsta_err,
                 pv='P'):
    '''write the Position/Velocity of station into a text file.

    Parameters
    ----------
    staname : string
        name of station
    ident : string
        'XYZ' or 'UEN'
    eposta : array, float
        epoch of time series
    Xsta : array, float
        X- / U- component
    Ysta : array, float
        Y- / E- component
    Zsta : array, float
        Z- / N- component
    Xsta_err : array, float
        formal uncertainty of X- / U- component
    Ysta_err : array, float
        formal uncertainty of Y- / E- component
    Zsta_err : array, float
        formal uncertainty of Z- / N- component
    pv : string
        'P' or 'V'

    Returns
    ----------
    None.
    '''

    if pv == 'P' or pv == 'p':
        lab = 'sta'
    elif pv == 'V' or pv == 'v':
        lab = 'vel'
    else:
        print("pv can only be set one of 'PVpv'")
        exit()

    datname = 'ts_%s/%s_%s.dat' % (lab, staname, ident)
    ensure_dir(datname)
    fdat = open(datname, 'w')
    opfmt = "%%10.5f%s%s" % ("|%15.2f" * 3, "|%10.3f" * 3)

    for i, epoi in enumerate(eposta):
        print(opfmt % (epoi, Xsta[i], Ysta[i], Zsta[i], Xsta_err[i],
                       Ysta_err[i], Zsta_err[i]),
              file=fdat)

    fdat.close()
Example #5
0
def info_precision(N, rip, NODFs, eps, p, t, work_dir, parent_dir):
    from ensure_dir import ensure_dir
    file_path = work_dir + '/info_precision.csv'
    ensure_dir(file_path)
    with open(file_path, 'a') as f:
        print(parent_dir, N, rip, sep=',', end='', file=f)
        for i in range(len(NODFs) - 1):
            print('', NODFs[i], sep=',', end='', file=f)
        print('', NODFs[-1], eps, p, t, sep=',', file=f)
Example #6
0
def info_e(N, rip, epsilons, p, t, work_dir, parent_dir):
    from ensure_dir import ensure_dir
    file_path = work_dir + '/info_e.csv'
    ensure_dir(file_path)
    with open(file_path, 'a') as f:
        print(parent_dir, N, rip, sep=',', end='', file=f)
        for i in range(len(epsilons) - 1):
            print('', epsilons[i], sep=',', end='', file=f)
        print('', epsilons[-1], p, t, sep=',', file=f)
def substructure_search(folder_for_data, folder_for_standardized_data, SMILES):
    ensure_dir.ensure_dir(folder_for_data)
    files_stand_rdf = glob.glob(folder_for_standardized_data)
    for number, smiles in enumerate(SMILES):
        ensure_dir.ensure_dir(folder_for_data + 'search_' + str(number+1) + '/')
        for file in files_stand_rdf:
            print ('Searching of ' + smiles + ' in ' + file.split('/')[-1][0:-9] + 'mrv')
            sp.call(['jcsearch', '-q', smiles, '-f', 'MRV', '-o', folder_for_data + 'search_' + str(number+1) + '/' + file.split('/')[-1][0:-9] + 'mrv', file])
    print ('Searching ended...')
Example #8
0
def print_list_csv(l, name, dir_name, rnd=2, d=2):
    from ensure_dir import ensure_dir
    file_path = dir_name + '//data_plot//' + name + '.csv'
    ensure_dir(file_path)
    with open(file_path, 'a') as f:
        if d > 1:
            for i in range(0, d - 1):
                print("{},".format(round(l[i], rnd)), end='', file=f)
            print("{}".format(round(l[d - 1], rnd)), file=f)
        else:
            print(l, file=f)
Example #9
0
def write_sou_pv(souname,
                 eposou,
                 RAsou,
                 DCsou,
                 RAsou_err,
                 DCsou_err,
                 corsou,
                 pv='P'):
    '''Write the Position/PM of sources into text files.

    Parameters
    ----------
    souname : string
        IVS source name
    eposou : array, float
        epoch of time series
    RAsou : array, float
        RA component
    DCsou : array, float
        Dec. component
    RAsou_err : array, float
        formal uncertainty of RA component
    DCsou_err : array, float
        formal uncertainty of Dec. component
    pv : string
        'P' or 'V'

    Returns
    ----------
    None.
    '''

    if pv == 'P' or pv == 'p':
        lab = 'sou'
    elif pv == 'V' or pv == 'v':
        lab = 'pmt'
    else:
        print("pv can only be set one of 'PVpv'")
        exit()

    datname = 'ts_%s/%s.dat' % (lab, souname)
    ensure_dir(datname)
    fdat = open(datname, 'w')
    opfmt = "%%10.5f%s%s%s" % ("|%15.2f" * 2, "|%10.3f" * 2, "|%7.4f")

    for i, epoi in enumerate(eposou):
        print(
            opfmt %
            (epoi, RAsou[i], DCsou[i], RAsou_err[i], DCsou_err[i], corsou[i]),
            file=fdat)

    fdat.close()
def sdf_parse(sdf_way, PATH):
    f = open(sdf_way)
    sdf = f.read().split('$$$$\n')[:-1]
    f.close()

    ensure_dir.ensure_dir(PATH + '/temp/')
    n = 0

    for i in range(1, (len(sdf) / 1000) + 2):
        out = open(PATH + '/temp/' + str(i) + '.sdf', 'w')
        while n < i * 1000 and n <= len(sdf) - 1:
            out.write(sdf[n] + '$$$$\n')
            n += 1
        out.close()
def sdf_parse(sdf_way, PATH):
    f = open(sdf_way)
    sdf = f.read().split('$$$$\n')[:-1]
    f.close()

    ensure_dir.ensure_dir(PATH+'/temp/')
    n=0

    for i in range(1,(len(sdf)/1000)+2):
        out = open(PATH+'/temp/' + str(i) + '.sdf', 'w')
        while n<i*1000 and n<=len(sdf)-1:
            out.write(sdf[n] + '$$$$\n')
            n+=1
        out.close()
Example #12
0
def overview2(N1, S1, eps, p, rip, t_tot, dir_name):
    from ensure_dir import ensure_dir
    file_path = 'C:/Users/Utente/Anaconda3/Cooperazione//'+dir_name+'//''overview2.txt'
    ensure_dir(file_path)
    with open(file_path, 'w') as f:
        if f.seek(0,2) == 0:
            print('#N1:   S1:   eps:   p:   rip:  t_tot:', file = f)
        print(N1, S1, eps, p, rip, t_tot, sep =  '    ', file=f)
        
    file_path2 = 'C:/Users/Utente/Anaconda3/Cooperazione//overview2.txt'
    ensure_dir(file_path2)
    with open(file_path2, 'a') as f:
        if f.seek(0,2) == 0:
            print('#N1:   S1:   eps:   p:   rip:   t_tot:', file = f)
        print(N1, S1, eps, p, rip, t_tot, sep =  '    ', file=f)
def substructure_search(folder_for_data, folder_for_standardized_data, SMILES):
    ensure_dir.ensure_dir(folder_for_data)
    files_stand_rdf = glob.glob(folder_for_standardized_data)
    for number, smiles in enumerate(SMILES):
        ensure_dir.ensure_dir(folder_for_data + 'search_' + str(number + 1) +
                              '/')
        for file in files_stand_rdf:
            print('Searching of ' + smiles + ' in ' +
                  file.split('/')[-1][0:-9] + 'mrv')
            sp.call([
                'jcsearch', '-q', smiles, '-f', 'MRV', '-o',
                folder_for_data + 'search_' + str(number + 1) + '/' +
                file.split('/')[-1][0:-9] + 'mrv', file
            ])
    print('Searching ended...')
Example #14
0
def print_tuple (K, name, dir_name, d=2, rnd =2):
    """Stampa una lista di tuple fatti di d numeri.
    Di default d=2, cioè tratta coppie, e quindi è
    una generalizzazione di print_tuple1.
    Accetta una lista di tuple. Non ritorna nulla.
    """
    
    from ensure_dir import ensure_dir
    file_path = dir_name+'//data_plot//'+ name + '.txt'
    ensure_dir(file_path)
    with open(file_path, 'a') as fS:
    #with open("stat_" + name + ".txt", "w") as fS:
         
        for i in range(0,d-1):
            print("{}    ".format(round(K[i],rnd)), end ='', file = fS)
        print("{}".format(round(K[d-1],rnd)), file = fS)
Example #15
0
def print_tuple3 (K, name, dir_name, d=2):
    """Stampa una lista di tuple fatti di d numeri.
    Di default d=2, cioè tratta coppie, e quindi è
    una generalizzazione di print_tuple1.
    Accetta una lista di tuple. Non ritorna nulla.
    """
    #import os
    from ensure_dir import ensure_dir
    file_path = dir_name+"\\data_plot\\"+ name + ".txt"
    ensure_dir(file_path)
    with open(file_path, 'w') as fS:
    #with open("stat_" + name + ".txt", "w") as fS:
         
         for x in K:
            for i in range(0,d-1):
                print("{}    ".format(x[i]), end ='', file = fS)
            print("{}".format(x[d-1]), file = fS)
Example #16
0
def overview(N1, step, rip, t_tot, dir_name):
    from ensure_dir import ensure_dir
    file_path = dir_name+'//''overview1.txt'
    ensure_dir(file_path)
    with open(file_path, 'w') as f:
        print('N1 = ', N1, file=f)
        print('Numero step compiuti = ', step, file = f)
        print('Numero di realizzazioni = ', rip, file = f)
        print('Tau max = ', int(step/N1), file = f)
        print('Tempo totale impiegato per la simulazione = ', t_tot, 'min', file = f)
        
    file_path2 = 'C:/Users/Utente/Anaconda3/Cooperazione//overview.txt'
    ensure_dir(file_path2)
    with open(file_path2, 'a') as f:
        if f.seek(0,2) == 0:
            print('#N1:    Step:    Rip:    Tau:    t_tot', file = f)
        print(N1, step, int(step/N1), rip, t_tot, sep =  '    ', file=f)
Example #17
0
def plot_sou_pv(souname, eposou, RAsou, DCsou, RAsou_err, DCsou_err, pv='P'):
    '''Plot the Position/PM of sources.

    Parameters
    ----------
    souname : string
        IVS source name
    eposou : array, float
        epoch of time series
    RAsou : array, float
        RA component
    DCsou : array, float
        Dec. component
    RAsou_err : array, float
        formal uncertainty of RA component
    DCsou_err : array, float
        formal uncertainty of Dec. component
    pv : string
        'P' or 'V'

    Returns
    ----------
    None.
    '''
    if pv == 'P' or pv == 'p':
        unit = 'mas'
        lab = 'sou'
    elif pv == 'V' or pv == 'v':
        unit = 'mas/yr'
        lab = 'pmt'
    else:
        print("pv can only be set one of 'PVpv'")
        exit()

    fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
    ax0.errorbar(eposou, RAsou * 1000, yerr=RAsou_err, fmt='.')
    ax0.set_title("R.A. (%s)" % unit)
    ax1.errorbar(eposou, DCsou * 1000, yerr=DCsou_err, fmt='.')
    ax1.set_title("Dec. (%s)" % unit)
    ax1.set_xlabel("Epoch (year)")
    ax1.set_xlim([1979.0, 2018.0])

    figname = "figures/ts_%s/%s.eps" % (lab, souname)
    ensure_dir(figname)
    plt.savefig(figname)
    plt.close()
Example #18
0
def print_tuple2 (K, name, dir_name, d=2, rnd = 2):
    """Stampa una lista di tuple fatti di d numeri.
    Di default d=2, cioè tratta coppie, e quindi è
    una generalizzazione di print_tuple1.
    Accetta una lista di tuple. Non ritorna nulla.
    """
    #import os
    from ensure_dir import ensure_dir
    #attenzione qui ho aggiunto //data_plot
    file_path = dir_name+'//data_plot//'+ name + ".txt"
    ensure_dir(file_path)
    with open(file_path, 'a') as fS:
    #with open("stat_" + name + ".txt", "w") as fS:
        if fS.seek(0,2) == 0:
            for i in range(len(K)):
                for j in range(0,d-1):
                    print("{}    ".format(round(K[i][j],rnd)), end ='', file = fS)
                print("{}".format(round(K[i][d-1],2)), file = fS)
Example #19
0
def guess(N1, S1, p, eps, dir_name):
    from ensure_dir import ensure_dir
    file_path = 'C:/Users/Utente/Anaconda3/Cooperazione//'+dir_name+'//guess.txt'
    ensure_dir(file_path)
    V1 = round(1/(S1*p),4)
    Ptot = round(1+ eps*S1*p , 2)
    T_su_P = round(1 - 1/Ptot,2)
    with open(file_path, 'a') as f:
        if f.seek(0,2) == 0:
            print('#N1:   S1:   eps:   p:   V1:  P_tot:   T/P:', file = f)
        print(N1, S1, eps, p, V1, Ptot, T_su_P, sep =  '    ', file=f)
        #if T_su_P == 0:
        #    print('Regime competitivo. \n')
        #if T_su_P < 0.1 and T_su_P > 0:
        #    print('Regime perturbativo. \n')
        #elif T_su_P > 0.1 and T_su_P < 0.5 :
        #    print('Regime misto. \n')
        #else:
        #    print('Regime cooperativo. \n')
        perc = round(T_su_P*100,2)
        print('Regime cooperativo al {} %. \n'.format(perc))
Example #20
0
def csv_reader(filename, dir_path):
    from ensure_dir import ensure_dir
    file_path = dir_path + '//' + filename + ".csv"
    ensure_dir(file_path)
    with open(file_path, 'r') as f:
        l = []
        l2 = []
        T = 0
        while T == 0:
            s = f.readline().split(',')
            if s[0] != '':
                d = len(s)
                l2 = []
                for i in range(0, d - 1):
                    l2.append(int(s[i]))
                z = s[d - 1].split('\n')
                l2.append(int(z[0]))
                l.append(l2)
            else:
                T = 1
                break
    return l
Example #21
0
def tab_reader2 (name, dir_name):
    from ensure_dir import ensure_dir
    file_path = dir_name+"//data_plot//"+ name + ".txt"
    ensure_dir(file_path)
    with open (file_path, 'r') as f:
        l = []
        l2 = []
        T = 0
        while T == 0:
            s = f.readline().split('    ')
            if s[0] != '':
                d = len(s)
                l2 = []
                for i in range(0,d-1):
                    l2.append(int(s[i]))
                z = s[d-1].split('\n')
                l2.append(int(z[0]))
                l.append(l2)
            else:
                T = 1
                break
    return l
def search_by_reaction(number, folder, SMILES_reaction, PATH):
    files_mrv = glob.glob(folder + 'search_' + str(number + 1) + '/' + '*.mrv')
    ensure_dir.ensure_dir(folder + 'temporary/')
    fn = 0
    for file in files_mrv:
        g = open(file)
        ggg = g.readlines()
        g.close()
        fn += 1
        if len(ggg) > 2:
            print(file)
            print('Standardizing...')
            try:
                sp.call([
                    'standardize', file, '-c', PATH + '/standardizer2.xml',
                    '-f', 'rdf', '-o', file[:-3] + 'rdf'
                ])
            except:
                print('Not enough memory for Standardizer!!!')
                sys.exit()
            print('Searching by reaction...')
            try:
                sp.call([
                    'jcsearch', '-q', SMILES_reaction[number * 2], '-f', 'MRV',
                    '-o', folder + 'temporary/' + file.split('/')[-1],
                    file[:-3] + 'rdf'
                ])
            except:
                print('Not enough memory for jcsearch!!!')
                sys.exit()
            print(file.split('/')[-1] + ' is done..')
            print(str(fn * 100 // len(files_mrv)) + '%')
    sp.call(
        [PATH + '/molconvert_calling.sh',
         folder.rstrip('/'),
         str(number + 1)])
    sp.call(["rm", "-r", folder + 'temporary/'])
    print('Substructure search in jcsearch by reaction is done...')
Example #23
0
def tab_reader (name, dir_name, d = 2):
    #import os
    from ensure_dir import ensure_dir
    #file_path = "C:\Users\Utente\Anaconda3\Cooperazione\\"+dir_name+"\\data_plot\\"+ name + ".txt"
    file_path = dir_name+"//data_plot//"+ name + ".txt"
    ensure_dir(file_path)
    with open (file_path, 'r') as f:
        l = []
        l2 = []
        T = 0
        while T == 0:
            s = f.readline().split('    ')
            if s[0] != '':
                d = len(s)
                l2 = []
                for i in range(1,d-1):
                    l2.append(int(s[i]))
                z = s[d-1].split('\n')
                l2.append(int(z[0]))
                l.append((int(s[0]),l2))
            else:
                T = 1
                break
    return l
    n7=int(sys.argv[4])
    n6=int(sys.argv[5])
else:
    n1 = int(input('Parse?: '))
    n2 = int(input('Standardize?: '))
    n5 = int(input('Cross comparing?: '))
    n7 = int(input('Substructure searches?: '))
    n6 = int(input('Maximum number of dynamic bonds?: '))

PATH = path.dirname(__file__)

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#=======================PARSING OF INITIAL DATABASE=================================
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

ensure_dir.ensure_dir(PATH  + '/RDFs_from_INITIAL/')
if n1 == 1:
    rdf_parser.rdf_parser(PATH + '/INITIAL/*.rdf', PATH + '/RDFs_from_INITIAL/', PATH+'/descriptions.csv')
    print('Database is parsed...')

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#====================STANDARDIZING OF PARSED DATABASE===============================
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

files_mols_rdf = glob.glob(PATH+'/RDFs_from_INITIAL/*.mols.rdf')
ensure_dir.ensure_dir(PATH+'/STANDARDIZED_RDFs/')
if n2 == 1:
    for file in files_mols_rdf:
        print ('Standardizing of ' + file[18:])
        sp.call(['standardize', file, '-c', PATH + '/standardizer.xml', '-f', 'rdf', '-o', PATH+'/STANDARDIZED_RDFs/' + file.split('/')[-1][0:-9] + '.stand.rdf'])
    print ('Files are standardized!')
Example #25
0
def print_string_csv(string, name, dir_name):
    from ensure_dir import ensure_dir
    file_path = dir_name + '//' + name + 'files.csv'
    ensure_dir(file_path)
    with open(file_path, 'a') as f:
        print(string, file=f)
Example #26
0
def plot_sta_pv(staname,
                ident,
                eposta,
                Xsta,
                Ysta,
                Zsta,
                Xsta_err,
                Ysta_err,
                Zsta_err,
                pv='P'):
    '''Plot the Position/Velocity of stations.

    Parameters
    ----------
    staname : string
        name of station
    ident : string
        'XYZ' or 'UEN'
    eposta : array, float
        epoch of time series
    Xsta : array, float
        X- / U- component
    Ysta : array, float
        Y- / E- component
    Zsta : array, float
        Z- / N- component
    Xsta_err : array, float
        formal uncertainty of X- / U- component
    Ysta_err : array, float
        formal uncertainty of Y- / E- component
    Zsta_err : array, float
        formal uncertainty of Z- / N- component
    pv : string
        'P' or 'V'

    Returns
    ----------
    None.
    '''

    if pv == 'P' or pv == 'p':
        unit = 'mm'
    elif pv == 'V' or pv == 'v':
        unit = 'mm/yr'
    else:
        print("pv can only be set one of 'PVpv'")
        exit()

    fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, sharex=True)
    ax0.errorbar(eposta, Xsta, yerr=Xsta_err, fmt='.')
    ax0.set_title("%s (%s)" % (ident[0], unit))
    # ax0.set_ylim([-500, 500])
    ax1.errorbar(eposta, Ysta, yerr=Ysta_err, fmt='.')
    ax1.set_title("%s (%s)" % (ident[1], unit))
    # ax1.set_ylim([-200, 800])
    ax2.errorbar(eposta, Zsta, yerr=Zsta_err, fmt='.')
    ax2.set_title("%s (%s)" % (ident[2], unit))
    ax2.set_xlabel("Epoch (year)")
    ax2.set_xlim([1979.0, 2018.0])

    figname = "figures/ts_sta/%s_%s.eps" % (staname, ident)
    ensure_dir(figname)
    plt.savefig(figname)
    plt.close()
Example #27
0
def adjacency_matrix_rnd(S1=10,
                         S2=10,
                         p=0.35,
                         dir_name='graph',
                         index=1,
                         index2=1,
                         flag=False):
    import networkx as nx
    from networkx.algorithms import bipartite
    import matplotlib.pyplot as plt
    import os
    from ensure_dir import ensure_dir
    import my_print as my
    import my_output as O
    from grad_nestedness import NODF_calc
    plt.style.use('seaborn')
    curr_dir = os.getcwd()
    #print('dir_name = ', dir_name)
    file_path = dir_name + '/prova.txt'
    ensure_dir(file_path)
    directory = os.path.dirname(file_path)
    os.chdir(directory)
    k = int(p * S1 * S2)
    G = bipartite.gnmk_random_graph(S1, S2, k)
    G1 = ordina_grafo_1(G, S1, S2)
    G1 = ordina_grafo_2(G1, S1, S2)

    deg = list(G1.degree())
    deg1 = deg[:S1]
    deg2 = deg[S1:]
    pos = {x: [0, x] for x in range(S1)}
    for j in range(S2):
        pos[S1 + j] = [1, j]
    colors = ['r' for i in range(0, S1)]
    for j in range(S2):
        colors.append('b')

    A = nx.to_numpy_matrix(G)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])

    NODF = NODF_calc(A1)
    print('NODF prima del riordino = ', NODF, '\n')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.grid()
    xtics = [x - 0.5 for x in range(0, S2 + 1)]
    ytics = [x - 0.5 for x in range(0, S1 + 1)]
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    ax.set_ylabel('Impollinatori')
    ax.set_xlabel('Piante')
    ax.set_title('Configurazione casuale con C = ' + format(p, '.2f'))
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    plt.imshow(A1, cmap='Greys')
    plt.tight_layout()

    fig.savefig('random_' + format(p, '.2f') + '.png')
    plt.close()

    A = nx.to_numpy_matrix(G1)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])

    #NODF = NODF_calc(A1)
    #print('NODF dopo il riordino = ', NODF, '\n')

    #fig = plt.figure()
    #ax = fig.add_subplot(111)
    #ax.grid()
    #xtics = [x-0.5 for x in range(0,S2+1)]
    #ytics = [x-0.5 for x in range(0,S1+1)]
    #ax.set_yticks(ytics)
    #ax.set_xticks(xtics)
    #ax.set_ylabel('Impollinatori')
    #ax.set_xlabel('Piante')
    #ax.set_title('Configurazione casuale con C = '+format(p,'.2f'))
    #plt.setp(ax.get_xticklabels(), visible=False)
    #plt.setp(ax.get_yticklabels(), visible=False)
    #plt.imshow(A1, cmap = 'Greys')
    #plt.tight_layout()

    #fig.savefig('random_'+format(p,'.2f')+'_ordinata.png')
    #plt.close()

    fig, [ax1, ax] = plt.subplots(1, 2, figsize=(10, 4))
    ax1.set_title('Interazioni mutualistiche casuali')
    ax1.set_axis_off()
    ax1.set_autoscale_on(True)
    nx.draw_networkx(G1, pos=pos, node_color=colors, ax=ax1)

    ax.grid()
    xtics = [x - 0.5 for x in range(0, S2 + 1)]
    ytics = [x - 0.5 for x in range(0, S1 + 1)]
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    ax.set_ylabel('Impollinatori')
    ax.set_xlabel('Piante')
    ax.set_title('Configurazione casuale con C = ' + format(p, '.2f'))
    ax.set_autoscale_on(True)
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    plt.imshow(A1, cmap='Greys')
    plt.tight_layout()

    fig.savefig('random_' + format(p, '.2f') + '_ordinata.png')
    plt.close()

    print('curr_dir = ', curr_dir)
    os.chdir(curr_dir)
    return A1
Example #28
0
def adjacency_matrix_nested2(S1=10,
                             S2=10,
                             p=0.33,
                             dir_name='graph',
                             index=1,
                             index2=1,
                             flag=False):
    #balanced nested
    import networkx as nx
    import matplotlib.pyplot as plt
    import os
    from ensure_dir import ensure_dir
    import my_print as my
    import my_output as O
    script_dir = os.getcwd()
    file_path = dir_name + '/prova.txt'
    ensure_dir(file_path)
    directory = os.path.dirname(file_path)
    os.chdir(directory)
    #attenzione, funziona bene solo con S1 = S2
    G = nx.Graph()
    nodes = [x for x in range(S1 + S2)]
    G.add_nodes_from(nodes)
    #print(list(G.nodes()))
    edges = []
    for i in range(S1):
        for j in range(S1, S1 + S2 - i):
            edges.append((i, j))
    G.add_edges_from(edges)
    if p < 0.55:
        #this is where the actual edges are decided in most cases (C < 0.55) - different method
        G = adjust_edges1(G, S1, S2, p)
    if p > 0.55:
        G = adjust_edges2(G, S1, S2, p)
    deg = list(G.degree())
    deg1 = deg[:S1]
    deg2 = deg[S1:]
    pos = {x: [0, x] for x in range(S1)}
    for j in range(S2):
        pos[S1 + j] = [1, j]
    colors = ['r' for i in range(0, S1)]
    for j in range(S2):
        colors.append('b')
    A = nx.to_numpy_matrix(G)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])
    #rimettere if index == 1
    if index == 0:
        plt.style.use('seaborn')
        fig, [ax1, ax] = plt.subplots(1, 2, figsize=(10, 4))
        ax1.set_title('Interazioni mutualistiche nidificate')
        ax1.set_axis_off()
        ax1.set_autoscale_on(True)
        nx.draw_networkx(G, pos=pos, node_color=colors, ax=ax1)

        ax.grid()
        xtics = [x - 0.5 for x in range(0, S2 + 1)]
        ytics = [x - 0.5 for x in range(0, S1 + 1)]
        ax.set_yticks(ytics)
        ax.set_xticks(xtics)
        ax.set_ylabel('Impollinatori')
        ax.set_xlabel('Piante')
        ax.set_title('Configurazione nidificata con C = ' + format(p, '.2f'))
        ax.set_autoscale_on(True)
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.imshow(A1, cmap='Greys')
        plt.tight_layout()
        fig.savefig('nested_' + format(p, '.2f') + '_II.png')

    if index == 1:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.grid()
        xtics = [x - 0.5 for x in range(0, S2 + 1)]
        ytics = [x - 0.5 for x in range(0, S1 + 1)]
        ax.set_yticks(ytics)
        ax.set_xticks(xtics)
        ax.set_ylabel('Impollinatori')
        ax.set_xlabel('Piante')
        ax.set_title('Nested II tipo con C = ' + format(p, '.3f'))
        ax.set_autoscale_on(True)
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.tight_layout()
        plt.imshow(A1, cmap='Greys')

    if index == 1:
        fig.savefig('nested_' + format(p, '.2f') + '_II.png')
    if flag == False:
        if index == 1:
            my.print_tuple2(deg1, 'N_degree1-' + repr(index2), dir_name)
            my.print_tuple2(deg2, 'N_degree2-' + repr(index2), dir_name)
    else:
        O.print_list_csv(deg1, 'deg1_N-' + repr(index), dir_name)
        O.print_list_csv(deg2, 'deg2_N-' + repr(index), dir_name)
    plt.close()
    os.chdir(script_dir)
    return A1
Example #29
0
def my_pyplot(name1, name2, dir_name, info, d=2):
    from ensure_dir import ensure_dir
    #file_path = "C:\Users\Utente\Anaconda3\Cooperazione\\"+dir_name+"\\data_plot\\"+ name + ".txt"
    file_path1 = dir_name+"//data_plot//"+ name1 + ".txt"
    ensure_dir(file_path1)
    with open (file_path1, 'r') as f:
        l1 = []
        for i in range(d):
            l1.append([])
        T = 0
        while T == 0:
            s = f.readline().split('    ')
            if s[0] != '':
                b = len(s)
                l1[0].append(int(s[0]))
                
                for j in range(1,b-1):
                    l1[j].append(int(s[j]))
                    
                z = s[b-1].split('\n')
                l1[b-1].append(int(z[0]))
            else:
                T = 1
                break
    file_path2 = dir_name+"//data_plot//"+ name2 + ".txt"
    ensure_dir(file_path2)
    with open (file_path2, 'r') as f:
        l2 = []
        for i in range(d):
            l2.append([])
        T = 0
        while T == 0:
            s = f.readline().split('    ')
            if s[0] != '':
                b = len(s)
                l2[0].append(int(s[0]))
                
                for j in range(1,b-1):
                    l2[j].append(int(s[j]))
                    
                z = s[b-1].split('\n')
                l2[b-1].append(int(z[0]))
            else:
                T = 1
                break
                    
    
    import matplotlib.pyplot as plt
    plt.style.use('seaborn')
    #fig, [ax1,ax2] = plt.subplots(1,2, figsize = (9,4))
    fig, [ax1,ax2] = plt.subplots(2,1,figsize = (4,8))
    #fig, [ax1,ax2] = plt.subplots(2,1)
    ax1.plot(l1[0], l1[1], 'r.')
    ax1.set(ylabel= info['ylab1'], title = info['tit1'])
    ax1.grid()
    ax1.set_ylim(0)
    ax1.set_autoscale_on(True)
    
    ax2.plot(l2[0], l2[1], 'r.')
    ax2.set(xlabel = info['xlab'] , ylabel= info['ylab2'], title = info['tit2'])
    ax2.grid()
    ax2.set_ylim(0)
    ax2.set_autoscale_on(True)
    plt.tight_layout()
    
    import os
    path = dir_name
    
    os.chdir(path)
    fig.savefig(name1+"_plot.png")
    plt.close()
Example #30
0
def adjacency_matrix_rnd2(S1=10,
                          S2=10,
                          p=0.33,
                          dir_name='graph',
                          index=1,
                          index2=1,
                          flag=False):
    import networkx as nx
    from networkx.algorithms import bipartite
    import matplotlib.pyplot as plt
    import os
    from ensure_dir import ensure_dir
    import my_print as my
    import my_output as O
    script_dir = os.getcwd()
    #print('dir_name = ', dir_name)
    #k is the number of non-null elements of the mutualistic matrix
    #in this case p = C in each realization
    k = int(round(S1 * S2 * p, 0))
    G = bipartite.gnmk_random_graph(S1, S2, k)
    #G = bipartite.random_graph(S1, S2, p)
    num_conn = G.number_of_edges()
    if num_conn != k:  #this checks out if the number of connections of the random graphs is really k
        print('Problema numero connessioni.')  #prints an alert otherwise
        print('# = ', num_conn)
    deg = list(G.degree())
    deg1 = deg[:S1]
    deg2 = deg[S1:]

    pos = {x: [0, x] for x in range(S1)}
    for j in range(S2):
        pos[S1 + j] = [1, j]
    colors = ['r' for i in range(0, S1)]
    for j in range(S2):
        colors.append('b')

    A = nx.to_numpy_matrix(G)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])

    if index == 1:
        plt.style.use('seaborn')

        file_path = dir_name + '/prova.txt'
        ensure_dir(file_path)
        directory = os.path.dirname(file_path)
        os.chdir(directory)

        fig, [ax1, ax] = plt.subplots(1, 2, figsize=(10, 4))
        #fig, [ax1, ax] = plt.subplots(1,2)
        ax1.set_title('Interazioni mutualistiche casuali')
        ax1.set_axis_off()
        ax1.set_autoscale_on(True)
        nx.draw_networkx(G, pos=pos, node_color=colors, ax=ax1)

        ax.grid()
        xtics = [x - 0.5 for x in range(0, S2 + 1)]
        ytics = [x - 0.5 for x in range(0, S1 + 1)]
        ax.set_yticks(ytics)
        ax.set_xticks(xtics)
        ax.set_ylabel('Impollinatori')
        ax.set_xlabel('Piante')
        ax.set_title('Configurazione casuale con C = ' + format(p, '.3f'))
        ax.set_autoscale_on(True)
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.imshow(A1, cmap='Greys')
        plt.tight_layout()
        fig.savefig('random_' + format(p, '.2f') + '.png')
        plt.close()

    else:

        file_path = dir_name + '/random_matrix/prova.txt'
        ensure_dir(file_path)
        directory = os.path.dirname(file_path)
        os.chdir(directory)

        fig = plt.figure()
        ax = fig.add_subplot(111)

        ax.grid()
        xtics = [x - 0.5 for x in range(0, S2 + 1)]
        ytics = [x - 0.5 for x in range(0, S1 + 1)]
        ax.set_yticks(ytics)
        ax.set_xticks(xtics)
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
        ax.set_title('Matrice random realizzazione {}'.format(index))
        ax.set_xlabel('S2 = {}'.format(S2))
        ax.set_ylabel('S1 = {}'.format(S1))
        ax.imshow(A1, cmap='Greys')
        fig.savefig('random_' + format(p, '.2f') + '-' + repr(index) + '.png')
        plt.close()

    #else:
    #    O.print_list_csv(deg1, 'deg1_R-'+repr(index), dir_name)
    #    O.print_list_csv(deg2, 'deg2_R-'+repr(index), dir_name)
    os.chdir(script_dir)
    return A1
Example #31
0
def adjacency_matrix_nested (S1 = 10, S2 = 10, p = 0.33, dir_name = 'graph', index = 1, index2 = 1, flag = False):
    import networkx as nx
    import matplotlib.pyplot as plt
    import os
    from ensure_dir import ensure_dir
    import my_print as my
    import my_output as O
    curr_dir = os.getcwd()
    file_path = dir_name+'/prova.txt'
    ensure_dir(file_path)
    directory = os.path.dirname(file_path)
    os.chdir(directory)
    #attenzione, funziona bene solo con S1 = S2
    G = nx.Graph()
    nodes = [x for x in range(S1+S2)]
    G.add_nodes_from(nodes)
    #print(list(G.nodes()))
    edges = []
    for i in range(S1):
        for j in range(S1, S1+S2-i):
            edges.append((i,j))
    G.add_edges_from(edges)
    if p < 0.55:
        G = adjust_edges(G, S1, S2, p)
    deg = list(G.degree())
    deg1 = deg[:S1]
    deg2 = deg[S1:]
    pos = {x:[0,x] for x in range(S1)}
    for j in range(S2):
        pos[S1+j] = [1,j]
    colors = ['r' for i in range(0,S1)]
    for j in range(S2):
        colors.append('b')
        
    fig, [ax1, ax] = plt.subplots(1,2, figsize = (9,4))
    ax1.set_title('Interazioni mutualistiche nested ')
    ax1.set_axis_off()
    ax1.set_autoscale_on(True)
    nx.draw_networkx(G, pos = pos, node_color = colors, ax=ax1)
    
    
    A = nx.to_numpy_matrix(G)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])
    
    ax.grid()
    xtics = [x-0.5 for x in range(0,S2+1)]
    ytics = [x-0.5 for x in range(0,S1+1)]
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    ax.set_ylabel('Impollinatori')
    ax.set_xlabel('Piante')
    ax.set_title('Configurazione nested  con C = '+format(p,'.2f'))
    ax.set_autoscale_on(True)
    
    plt.imshow(A1, cmap = 'Greys')
    if index == 1:
        fig.savefig('nested_'+format(p,'.2f')+'.png')
    if flag == False:
        if index == 1:    
            my.print_tuple2(deg1, 'N_degree1-'+repr(index2), dir_name)
            my.print_tuple2(deg2, 'N_degree2-'+repr(index2), dir_name)
    else:
        my.print_tuple2(deg1, 'deg1_N-'+repr(index), dir_name)
        my.print_tuple2(deg2, 'deg2_N-'+repr(index), dir_name)
    plt.close()
    file_path2 = "C:/Users/Utente/Anaconda3/UserScripts/Programmi cooperazione/"
    directory2 = os.path.dirname(file_path2)
    print('directory2 = ', directory2)
    print('curr_dir = ', curr_dir)
    os.chdir(directory2)
    return A1
Example #32
0
def adjacency_matrix_rnd(S1 = 10, S2 = 10, p = 0.33, dir_name = 'graph', index = 1, index2 = 1, flag = False):
    import networkx as nx
    from networkx.algorithms import bipartite
    import matplotlib.pyplot as plt
    import os
    from ensure_dir import ensure_dir
    import my_print as my
    import my_output as O
    curr_dir = os.getcwd()
    #print('dir_name = ', dir_name)
    file_path = dir_name+'/prova.txt'
    ensure_dir(file_path)
    directory = os.path.dirname(file_path)
    os.chdir(directory)
    
    G = bipartite.random_graph(S1, S2, p)
    deg = list(G.degree())
    deg1 = deg[:S1]
    deg2 = deg[S1:]
    
    pos = {x:[0,x] for x in range(S1)}
    for j in range(S2):
        pos[S1+j] = [1,j]
    colors = ['r' for i in range(0,S1)]
    for j in range(S2):
        colors.append('b')
    fig, [ax1, ax] = plt.subplots(1,2, figsize = (9,4))
    ax1.set_title('Interazioni mutualistiche casuali')
    ax1.set_axis_off()
    ax1.set_autoscale_on(True)
    nx.draw_networkx(G, pos = pos, node_color = colors, ax = ax1)
    
    A = nx.to_numpy_matrix(G)
    A2 = A.getA()
    A1 = []
    for x in range(S1):
        A1.append(A2[x][S1:])
    
    ax.grid()
    xtics = [x-0.5 for x in range(0,S2+1)]
    ytics = [x-0.5 for x in range(0,S1+1)]
    ax.set_yticks(ytics)
    ax.set_xticks(xtics)
    ax.set_ylabel('Impollinatori')
    ax.set_xlabel('Piante')
    ax.set_title('Configurazione casuale con C = '+format(p,'.2f'))
    ax.set_autoscale_on(True)
    
    plt.imshow(A1, cmap = 'Greys')
    if index == 1:
        fig.savefig('random_'+format(p,'.2f')+'.png')
    plt.close()
    if flag == False:
        if index == 1:
            my.print_tuple2(deg1, 'R_degree1-'+repr(index2), dir_name)
            my.print_tuple2(deg2, 'R_degree2-'+repr(index2), dir_name)
    else:
        O.print_list_csv(deg1, 'deg1_R-'+repr(index), dir_name)
        O.print_list_csv(deg2, 'deg2_R-'+repr(index), dir_name)
    file_path2 = "C:/Users/Utente/Anaconda3/UserScripts/Programmi cooperazione/"
    directory2 = os.path.dirname(file_path2)
    print('directory2 = ', directory2)
    print('curr_dir = ', curr_dir)
    os.chdir(directory2)
    return A1