Exemple #1
0
    def forward(self, length):
        if self._reset:
            self.clear()
            self._reset = False

        fig = self.fig
        ax = self.ax

        dx = length * py.cos(py.radians(self.angle))
        dy = length * py.sin(py.radians(self.angle))

        if self.pen == 'down':
            ax.plot([self.x, self.x + dx], [self.y, self.y + dy],
                    color=self.color,
                    linestyle='-')
            self.data.append([
                [self.x, self.x + dx],
                [self.y, self.y + dy],
                self.color,
            ])
        else:
            self.data.append([
                [self.x, self.x + dx],
                [self.y, self.y + dy],
                None,
            ])

        self.x += dx
        self.y += dy
Exemple #2
0
def boxForcing(bMin, bMax, radius, c,
               angle):  #confines the particles inside the sample

    x = pl.uniform(bMin, bMax)
    y = pl.uniform(bMin, bMax)

    if x < (bMin + c * radius):
        x = x + (radius) * (1 + c * pl.absolute(pl.sin(pl.radians(angle))))
        if x > (bMax - c * radius):
            x = bMin + c * radius
    if x > (bMax - c * radius):
        x = x - (radius) * (1 + c * pl.absolute(pl.sin(pl.radians(angle))))

        if x < (bMin + c * radius):
            x = bMax - c * radius

    if y > (bMax - c * radius):
        y = y - (radius) * (1 + c * pl.absolute(pl.cos(pl.radians(angle))))
        if y < (bMin + c * radius):
            y = bMax - c * radius

    if y < (bMin + c * radius):
        y = y + (radius) * (1 + c * pl.absolute(pl.cos(pl.radians(angle))))
        if y > (bMax - c * radius):
            y = bMin + c * radius

    center = []
    center.append([x, y])

    return center
def animate(delay=0.05, skip=1, figsize=(5, 5)):

    # delay will be per 100 units

    global _t
    from IPython.display import clear_output
    import time

    i = 0
    interrupt_count = 0
    while True:

        try:

            clear_output(wait=True)
            fig = py.figure(figsize=_t.figsize)
            ax = fig.add_subplot(111)
            ax.clear()
            ax.set_facecolor(_t.facecolor)
            ax.axis('equal')
            ax.axis(_t.limits)

            for x, y, t, k in _t.texts:
                ax.text(x, y, t, **k)

            for x, y, c, a, ps in _t.data[:i]:
                if c is not None:
                    ax.plot(x, y, color=c, linestyle='-', linewidth=ps)

            x, y, c, a, ps = _t.data[i - 1]
            ax.plot(
                [x[1]],
                [y[1]],
                'g',
                marker=(3, 0, a - 90),
                markersize=20,
            )
            ax.plot([x[1] + 2 * py.cos(py.radians(a))],
                    [y[1] + 2 * py.sin(py.radians(a))], 'r.')
            py.show()

            # each step is a delay

            time.sleep(delay)

            if i == len(_t.data):
                break

            i += skip
            if i > len(_t.data):  # make sure to plot the last one
                i = len(_t.data)

        except KeyboardInterrupt:
            interrupt_count += 1
            if interrupt_count == 1:
                delay = 0
            else:
                i = len(_t.data)
Exemple #4
0
 def __init__(self,obj,ref,epoch,*args):
     '''
     *args are either a,e,i,lan,aop,M0
     or r,v
     '''
     self.obj = obj
     self.ref = ref
     self.shape2D = None
     self.shape3D = None
     self._a = None
     self._e = None
     
     if len(args) == 2:
         self.initFromStateVectors(epoch,*args)
     elif len(args) == 6:
         self.epoch = float(epoch)
         self._a = float(args[0])
         self._e = float(args[1])
         self.i = radians(float(args[2]))
         self.lan = radians(float(args[3]))
         self.aop = radians(float(args[4]))
         self.M0 = float(args[5])
         self.calculateH()
         #if self.e < 1:
         #    self.h = sqrt(self.a*self.ref.mu*(1-self.e**2))
         #elif self.e > 1:
         #    self.h = sqrt(-self.a*self.ref.mu*(self.e**2-1))
     else:
         print "error"
         print args
         print "len",len(args)
         raise AttributeError("Unable to init"+str(args))
     if len(args) == 0:
         pass
     else:
         self.updateShape()
    def circle(self, radius, extent=None, steps=50):
        R = radius
        n = steps

        b = (n - 2) * 180 / n  # polygon interior angle
        a = 180 - b  # polygon exterior angle
        L = R * py.cos(py.radians(b / 2))  # length of one side

        if not extent is None:  # partial circle
            n = n * extent // 360

        for i in range(n):
            self.forward(L)

            if radius > 0:
                self.left(a)
            else:
                self.right(a)
Exemple #6
0
import os

os.chdir(os.path.expanduser("~/Desktop/reflectivity/dynXRD/"))
import pyasf
import reflectivity
import sympy as sp
import pylab as pl

data = pl.loadtxt("test6.dat")
data[:, 0] = pl.radians(data[:, 0])
#pl.ion()

R = 1, 1, 3
thickness = 1000
Energy = 10000

#struct = pyasf.unit_cell("1011117")
struct = pyasf.unit_cell("cif/MgO_52026.cif")  #MgO
Sub = reflectivity.Substrate(struct)
v_par = sp.Matrix([1, -1, 0])
v_perp = sp.Matrix([1, 1, 0])
Sub.calc_orientation(v_par, v_perp)
layer1 = reflectivity.Epitaxial_Layer(struct, thickness)
layer1.calc_orientation(v_par, v_perp)
crystal = reflectivity.Sample(Sub, layer1)
crystal.set_Miller(R)
crystal.calc_g0_gH(Energy)
thBragg = float(
    layer1.calc_Bragg_angle(Energy).subs(layer1.structure.subs).evalf())
angle = pl.linspace(0.995, 1.005, 501) * thBragg
Exemple #7
0
import os
os.chdir(os.path.expanduser("~/Desktop/reflectivity/dynXRD/"))
import pyasf
import reflectivity
import sympy as sp
import pylab as pl

data = pl.loadtxt("test4.dat")
data[:,0] = pl.radians(data[:,0])
#pl.ion()

R = 0,0,4
thickness=1000
Energy=10000

#struct = pyasf.unit_cell("1011169")
struct = pyasf.unit_cell("1011117") #MgO
Sub=reflectivity.Substrate(struct)
v_par=sp.Matrix([1,-1,0])
v_perp=sp.Matrix([1,1,1])
Sub.calc_orientation(v_par, v_perp)
layer1=reflectivity.Epitaxial_Layer(struct, thickness)
layer1.calc_orientation(v_par, v_perp)
crystal=reflectivity.Sample(Sub, layer1)
crystal.set_Miller(R)
crystal.calc_g0_gH(Energy)
thBragg= float(layer1.calc_Bragg_angle(Energy).subs(layer1.structure.subs).evalf())
angle=pl.linspace(0.997, 1.003,501)*thBragg

crystal.calc_reflectivity(angle, Energy)
layer1.calc_amplitudes(angle, Energy)
Exemple #8
0
sim.animArm = 1  # show arm animation
sim.graphsArm = 1  #  plot arm graphs
sim.updateInterval = 20  # delay between arm updated (ms)
sim.initArmMovement = 50  # time at which to start moving arm (ms)
sim.armLen = [0.4634 - 0.173, 0.7169 - 0.4634
              ]  # elbow - shoulder from MSM;radioulnar - elbow from MSM;
sim.startAng = [
    0.62, 1.53
]  # starting shoulder and elbow angles (rad) = natural rest position
sim.targetDist = 0.15  # target distance from center (15 cm)

# Propriocpetive encoding
allCellTags = sim._gatherAllCellTags()
sim.pop_sh = [gid for gid, tags in allCellTags.items() if tags['pop'] == 'Psh']
sim.pop_el = [gid for gid, tags in allCellTags.items() if tags['pop'] == 'Pel']
sim.minPval = radians(-30)
sim.maxPval = radians(135)
sim.minPrate = 0.01
sim.maxPrate = 100

# Motor encoding
sim.nMuscles = 4  # number of muscles
motorGids = [gid for gid, tags in allCellTags.items() if tags['pop'] == 'EM']
cellsPerMuscle = len(motorGids) / sim.nMuscles
sim.motorCmdCellRange = [
    motorGids[i:i + cellsPerMuscle]
    for i in range(0, len(motorGids), cellsPerMuscle)
]  # cell gids of motor output to each muscle
sim.cmdmaxrate = 120  # value to normalize motor command num spikes
sim.cmdtimewin = 50  # window to sum spikes of motor commands
sim.antagInh = 1  # inhibition from antagonic muscle
Exemple #9
0
def stereoplot(strike, dip, filename):    
    # Here is the stereonet plotting section
    
    bigr = 1.2
    phid = pylab.arange(2, 90, 2)  # Angular range for
    phir = phid * pylab.pi / 180
    omegad = 90 - phid 
    omegar = pylab.pi / 2 - phir
    
    # Set up for plotting great circles with centers along
    # positive x-axis
    
    x1 = bigr * pylab.tan(phir)
    y1 = pylab.zeros(pylab.size(x1))
    r1 = bigr / pylab.cos(phir)
    theta1ad = (180 - 80) * pylab.ones(pylab.size(x1))
    theta1ar = theta1ad * pylab.pi / 180
    theta1bd = (180 + 80) * pylab.ones(pylab.size(x1))
    theta1br = theta1bd * pylab.pi / 180
    
    # Set up for plotting great circles 
    # with centers along the negative x-axis
    x2 = -1 * x1
    y2 = y1
    r2 = r1
    theta2ad = -80 * pylab.ones(pylab.size(x2))
    theta2ar = theta2ad * pylab.pi / 180
    theta2bd = 80 * pylab.ones(pylab.size(x2))
    theta2br = theta2bd * pylab.pi / 180
    
    
    # Set up for plotting small circles
    # with centers along the positive y-axis
    y3 = bigr / pylab.sin(omegar)
    x3 = pylab.zeros(pylab.size(y3))
    r3 = bigr / pylab.tan(omegar)
    theta3ad = 3 * 90 - omegad
    theta3ar = 3 * pylab.pi / 2 - omegar
    theta3bd = 3 * 90 + omegad
    theta3br = 3 * pylab.pi / 2 + omegar
    
    # Set up for plotting small circles
    # with centers along the negative y-axis
    y4 = -1 * y3
    x4 = x3
    r4 = r3
    
    theta4ad = 90 - omegad
    theta4ar = pylab.pi / 2 - omegar
    theta4bd = 90 + omegad
    theta4br = pylab.pi / 2 + omegar
    
    
    # Group all x, y, r, and theta information for great cricles 
    phi = pylab.append(phid, phid, 0)
    x = pylab.append(x1, x2, 0)
    y = pylab.append(y1, y2, 0)
    r = pylab.append(r1, r2)
    
    thetaad = pylab.append(theta1ad, theta2ad, 0)
    thetaar = pylab.append(theta1ar, theta2ar, 0)
    thetabd = pylab.append(theta1bd, theta2bd, 0)
    thetabr = pylab.append(theta1br, theta2br, 0)
    
    # Plot portions of all great circles that lie inside the
    # primitive circle, with thick lines (1 pt.) at 10 degree increments
    
    for i in range(0, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        # p = pylab.plot(xunit,yunit,'b',lw=.5) #commented out to remove small verticle lines
        pylab.hold(True)   
    
    
    # Now "blank out" the portions of the great circle cyclographic traces 
    # within 10 degrees of the poles of the primitive circle.
    rr = bigr / pylab.tan(80 * pylab.pi / 180)
    ang1 = pylab.arange(0, pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xx = pylab.zeros(pylab.size(ang1)) + rr * pylab.cos(ang1)
    yy = bigr / pylab.cos(10 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) - rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    yy = -bigr / pylab.cos(10 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) + rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    
    for i in range(1, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        
        if pylab.mod(phi[i], 10) == 0:
            p = pylab.plot(xunit, yunit, 'b', lw=1)
            angg = thetaad[i]
        pylab.hold(True)
    
    
    # Now "blank out" the portions of the great circle cyclographic traces 
    # within 2 degrees of the poles of the primitive circle.
    rr = bigr / pylab.tan(88 * pylab.pi / 180)
    ang1 = pylab.arange(0, pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xx = pylab.zeros(pylab.size(ang1)) + rr * pylab.cos(ang1)
    yy = bigr / pylab.cos(2 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) - rr * pylab.sin(ang1)
    
    p = pylab.fill(xx, yy, 'w')
    yy = -bigr / pylab.cos(2 * pylab.pi / 180) * pylab.ones(pylab.size(ang1)) + rr * pylab.sin(ang1)
    p = pylab.fill(xx, yy, 'w')
    
    
    # Group all x, y, r, and theta information for small circles
    phi = pylab.append(phid, phid, 0)
    x = pylab.append(x3, x4, 0)
    y = pylab.append(y3, y4, 0)
    r = pylab.append(r3, r4)
    
    thetaad = pylab.append(theta3ad, theta4ad, 0)
    thetaar = pylab.append(theta3ar, theta4ar, 0)
    thetabd = pylab.append(theta3bd, theta4bd, 0)
    thetabr = pylab.append(theta3br, theta4br, 0)
    
    # Plot primitive circle
    thd = pylab.arange(0, 360 + 1, 1)
    thr = pylab.arange(0, 2 * pylab.pi + pylab.pi / 180, pylab.pi / 180)
    xunit = bigr * pylab.cos(pylab.radians(thd))
    
    yunit = bigr * pylab.sin(pylab.radians(thd))
    p = pylab.plot(xunit, yunit)
    pylab.hold(True)
        
    # Plot portions of all small circles that lie inside the
    # primitive circle, with thick lines (1 pt.) at 10 degree increments
    
    for i in range(0, len(x)):
        thd = pylab.arange(thetaad[i], thetabd[i] + 1, 1)
        thr = pylab.arange(thetaar[i], thetabr[i] + pylab.pi / 180, pylab.pi / 180)
        xunit = x[i] + r[i] * pylab.cos(pylab.radians(thd))
        yunit = y[i] + r[i] * pylab.sin(pylab.radians(thd))
        blug = pylab.mod(thetaad[i], 10)
        if pylab.mod(phi[i], 10) == 0:
            p = pylab.plot(xunit, yunit, 'b', lw=1)
            angg = thetaad[i]
        # else: #Commented out to remove the small horizontal lines
            # p = pylab.plot(xunit,yunit,'b',lw=0.5)
        pylab.hold(True)
    
    # Draw thick north-south and east-west diameters
    xunit = [-bigr, bigr]
    yunit = [0, 0]
    p = pylab.plot(xunit, yunit, 'b', lw=1)
    pylab.hold(True)
    xunit = [0, 0]
    yunit = [-bigr, bigr]
    p = pylab.plot(xunit, yunit, 'b', lw=1)
    pylab.hold(True)
    
    '''
    This is the plotting part'''
    
   
    trend1 = strike
    plunge1 = pylab.absolute(dip)
    # num = leng(lines1(:,1));
    trendr1 = [foo * pylab.pi / 180 for foo in trend1]
    
    plunger1 = [foo * pylab.pi / 180 for foo in plunge1]
    rho1 = [bigr * pylab.tan(pylab.pi / 4 - ((foo) / 2)) for foo in plunger1]
        # polarb plots ccl from 3:00, so convert to cl from 12:00
    # pylab.polar(pylab.pi/2-trendr1,rho1,'o')
    pylab.plot(9000, 90000, 'o', markerfacecolor="b", label='Positive Dip')
    pylab.plot(9000, 90000, 'o', markerfacecolor="w", label='Negative Dip')      
    pylab.legend(loc=1) 
    for n in range(0, len(strike)):
        if dip[n] > 0:
            pylab.plot(rho1[n] * pylab.cos(pylab.pi / 2 - trendr1[n]), rho1[n] * pylab.sin(pylab.pi / 2 - trendr1[n]), 'o', markerfacecolor="b", label='Positive Dip')
        else:
            pylab.plot(rho1[n] * pylab.cos(pylab.pi / 2 - trendr1[n]), rho1[n] * pylab.sin(pylab.pi / 2 - trendr1[n]), 'o', markerfacecolor="w", label='Negative Dip')
         
    '''above is self'''
    pylab.axis([-bigr, bigr, -bigr, bigr])
Exemple #10
0
sun_azimuth =[]
sun_elevation = []
day = []
for n in days:

    d = datetime(2000,1,1,12)+timedelta(n-1)
    day.append(d)
    i3time = dataclasses.make_I3Time(d)

    sun = astro.I3GetSunDirection(i3time)

    sun_azimuth.append(90 - sun.azimuth/I3Units.degree)
    sun_elevation.append(90 - sun.zenith/I3Units.degree)

plt.plot_date(day,
              -4*plt.array(sun_azimuth)*plt.cos(plt.radians(sun_elevation)),
              ls='-',marker=None
)
plt.title("Equation of Time")
plt.ylabel("Sundial Faster [minutes]")

plt.figure()
plt.plot_date(day,sun_elevation,ls='-',marker=None)
plt.ylabel("Sun Elevation")
plt.title("Sun Elevation")
plt.axes().yaxis.set_major_formatter(FormatStrFormatter(u'%d\u00b0'))


plt.figure()
ax = plt.axes()
plt_info = ax.plot(sun_azimuth,sun_elevation)
Exemple #11
0
# Arm parameters
f.useArm = 1  # include arm in simulation
f.animArm = 1  # show arm animation
f.graphsArm = 1  #  plot arm graphs
f.updateInterval = 20  # delay between arm updated (ms)
f.initArmMovement = 50  # time at which to start moving arm (ms)
f.armLen = [0.4634 - 0.173, 0.7169 - 0.4634] # elbow - shoulder from MSM;radioulnar - elbow from MSM;  
f.startAng = [0.62,1.53] # starting shoulder and elbow angles (rad) = natural rest position
f.targetDist = 0.15 # target distance from center (15 cm)

# Propriocpetive encoding
allCellTags = f.sim.gatherAllCellTags()
f.pop_sh = [gid for gid,tags in allCellTags.iteritems() if tags['popLabel'] == 'Psh']
f.pop_el = [gid for gid,tags in allCellTags.iteritems() if tags['popLabel'] == 'Pel']
f.minPval = radians(-30) 
f.maxPval = radians(135)
f.minPrate = 0.01
f.maxPrate = 100

# Motor encoding
f.nMuscles = 4 # number of muscles
motorGids = [gid for gid,tags in allCellTags.iteritems() if tags['popLabel'] == 'EM']
cellsPerMuscle = len(motorGids) / f.nMuscles
f.motorCmdCellRange = [motorGids[i:i+cellsPerMuscle] for i in xrange(0, len(motorGids), cellsPerMuscle)]  # cell gids of motor output to each muscle
f.cmdmaxrate = 120  # value to normalize motor command num spikes
f.cmdtimewin = 50  # window to sum spikes of motor commands
f.antagInh = 1  # inhibition from antagonic muscle

# RL
f.useRL = 1
Exemple #12
0
observed['ra'] = observed.apply(lambda x: -1*float(x['ra']) if float(x['ra']) < 0 else float(x['ra']), axis = 1)


#SB Queries and data manipulation
sboffset = getSBOffsets(sbUID)
sb = getSBSummary(asdm.asdmDict['SBSummary'])
sbUID = sb.values[0][0]
target = getSBTargets(sbUID)
science = getSBScience(sbUID)
partId =  target[target['ObsParameter'] == science.entityPartId.values[0]].FieldSource.values[0]
predicted = sboffset[sboffset['partId'] == partId][['latitude','longitude']]
longitude, lat = sbfield[sbfield['entityPartId'] == partId][['longitude','latitude']].values[0]
predicted[['raoff','decoff']] = predicted[['longitude','latitude']].astype(float)
RA0 = float(longitude)*pl.pi/180.
Dec0 = float(lat)*pl.pi/180.
predicted['dRA'] = predicted.apply(lambda x: pl.radians(x['raoff']/3600.), axis = 1)
predicted['dDec'] = predicted.apply(lambda x: pl.radians(x['decoff']/3600.), axis = 1)
predicted['Pl'] = predicted.apply(lambda x: list((pl.cos(x['dRA'])*pl.cos(x['dDec']), pl.sin(x['dRA'])*pl.cos(x['dDec']), pl.sin(x['dDec']))) , axis = 1)
predicted['Ps'] = predicted.apply(lambda x: rot(x['Pl'],RA0,Dec0), axis = 1)
predicted['otcoor'] = predicted.apply(lambda x: list((pl.arctan2(x['Ps'][1], x['Ps'][0]) % (2.*pl.pi), pl.arcsin(x['Ps'][2]))), axis =1)
predicted['otcoor_ra'] = predicted.apply(lambda x: x['otcoor'][0], axis  =1 )
predicted['otcoor_dec'] = predicted.apply(lambda x: x['otcoor'][1], axis  =1 )
predictedList = list()
#predictedList.append((RA0,Dec0))
pred = pd.DataFrame(predictedList, columns = ['ra','dec'])
ot = predicted[['otcoor_ra','otcoor_dec']]
ot.columns= ['ra','dec']
pred = pd.concat([pred,ot])
pred['series'] = 'SchedBlock'

comb = combinations(geo[['lat','lon']].values, 2)
Exemple #13
0
sun_elevation = []
day = []
for n in days:

    d = datetime(2000, 1, 1, 12) + timedelta(n - 1)
    day.append(d)
    i3time = dataclasses.make_I3Time(d)

    sun = astro.I3GetSunDirection(i3time)

    sun_azimuth.append(90 - sun.azimuth / I3Units.degree)
    sun_elevation.append(90 - sun.zenith / I3Units.degree)

plt.plot_date(day,
              -4 * plt.array(sun_azimuth) *
              plt.cos(plt.radians(sun_elevation)),
              ls='-',
              marker=None)
plt.title("Equation of Time")
plt.ylabel("Sundial Faster [minutes]")

plt.figure()
plt.plot_date(day, sun_elevation, ls='-', marker=None)
plt.ylabel("Sun Elevation")
plt.title("Sun Elevation")
plt.gca().yaxis.set_major_formatter(FormatStrFormatter(u'%d\u00b0'))

plt.figure()
ax = plt.gca()
plt_info = ax.plot(sun_azimuth, sun_elevation)
def main(args):

    angles = args.haversine_distance

    affinity = args.affinity

    string = args.spectral_parameter
    nside = args.nside
    sky = get_sky(nside, 's1d1')
    if string == 'Bs':

        param = (sky.components[0].pl_index)
    elif string == 'Bd':
        param = (sky.components[1].mbb_index)
    elif string == 'Td':
        param = (sky.components[1].mbb_temperature).value

    sigmaparam = hp.read_map(args.parameter_uncertainties, verbose=False)
    Galmask = hp.read_map(args.galmask, verbose=False)
    Galmask = cu.check_nside(nsideout=nside, mapin=Galmask)
    sigmaparam = cu.check_nside(nsideout=nside, mapin=sigmaparam)

    Galmask = pl.ma.masked_not_equal(Galmask, 0).mask

    ones = pl.ma.masked_greater(Galmask, 0).mask
    fsky = (Galmask[ones].shape[0] / Galmask.shape[0])
    if args.verbose: print(f' Clustering on fsky =   {fsky:.2f}%   ')

    #param[~Galmask]=0
    #sigmaparam [~Galmask ] =0
    noisestring = ''
    if args.add_noise:
        noise_param = np.random.normal(loc=pl.zeros_like(param),
                                       scale=sigmaparam / 10.)
        param += noise_param
        param = hp.smoothing(param,
                             fwhm=pl.radians(args.parameter_resolution),
                             verbose=False)

        noisestring = '_noise'

    save_affinity = True

    anglestring = ''
    if angles:
        anglestring = '_haversine'

    fmap = (
        '/Users/peppe/work/adaptive_compsep/clusterpatches/' +
        f'clusters_{affinity}{anglestring}_galmask_{string}_{nside}{noisestring}_{args.optimization}.fits'
    )
    file_affinity = (
        f'/Users/peppe/work/adaptive_compsep/affinities/' +
        f'{affinity}{anglestring}_galmask_{string}_{nside}{noisestring}.npy')

    Cluster = ClusterData([param, sigmaparam],
                          nfeatures=2,
                          nside=nside,
                          affinity=affinity,
                          file_affinity=file_affinity,
                          include_haversine=angles,
                          verbose=args.verbose,
                          save_affinity=save_affinity,
                          scaler=None,
                          feature_weights=[1, 1],
                          galactic_mask=Galmask)

    Kmin = 2
    Kmax = 200
    Cluster(nvals=args.num_cluster_evaluation,
            Kmax=Kmax - 1,
            Kmin=Kmin,
            minimize=args.optimization,
            parameter_string=string)

    if args.optimization == 'partition':
        label1 = r'Under partition  '
        label2 = r'Over partition '
        ylabel = 'Partition measure '

    elif args.optimization == 'residuals':
        label1 = r'Syst. residuals'
        label2 = r'Stat. residuals'
        ylabel = r'Residuals [ $\mu K^2$ ]  '

    pl.title(string)
    pl.plot(Cluster.Kvals, Cluster.Vu, '.', label=label1)
    pl.plot(Cluster.Kvals, Cluster.Vo, '.', label=label2)
    pl.plot(Cluster.Kvals,
            pl.sqrt(Cluster.Vo**2 + Cluster.Vu**2),
            '-',
            label=r'Root Squared Sum ')
    pl.legend()
    pl.xlabel('K', fontsize=15)

    pl.ylabel(ylabel, fontsize=15)
    pl.show()

    patches = pl.zeros_like(param, dtype=pl.int_)

    patches[Galmask] = pl.int_(Cluster.clusters.labels_) + 1

    hp.mollview(patches, cmap=pl.cm.tab20)
    pl.show()

    hp.write_map(fmap, patches, overwrite=True)