Skip to content
Snippets Groups Projects
TraceWin.py 40.7 KiB
Newer Older
Yngve Levinsen's avatar
Yngve Levinsen committed
                data_set.attrs['unit'] = unit
Yngve Levinsen's avatar
Yngve Levinsen committed
        for val, unit in zip(coordinates, coordinate_units):
            data_set = group.create_dataset(val, (length, 7), dtype='f')
            data_set[...] = getattr(self, val)
Yngve Levinsen's avatar
Yngve Levinsen committed
                data_set.attrs['unit'] = unit
Yngve Levinsen's avatar
Yngve Levinsen committed
        if self.version >= 7 and partran:
            # 3 numbers per location..
Yngve Levinsen's avatar
Yngve Levinsen committed
            emit_data = ['rms_emit', 'rms_emit2']
            emit_units = ['m*rad', 'm*m*rad*rad']
            for val, unit in zip(emit_data, emit_units):
                data_set = group.create_dataset(val, (length, 3), dtype='f')
                data_set[...] = getattr(self, val)
Yngve Levinsen's avatar
Yngve Levinsen committed
                    data_set.attrs['unit'] = unit
        if partran:
Yngve Levinsen's avatar
Yngve Levinsen committed
            # 1 numbers per location and per run..
Yngve Levinsen's avatar
Yngve Levinsen committed
            data = ['lost', 'powlost']
            units = ['', 'W']
            for val, unit in zip(data, units):
                data_set = group.create_dataset(val, (length, self.Nrun), dtype='f')
                data_set[...] = getattr(self, val)
Yngve Levinsen's avatar
Yngve Levinsen committed
                    data_set.attrs['unit'] = unit
Yngve Levinsen's avatar
Yngve Levinsen committed
        fout.close()
class remote_data_merger:
    def __init__(self, base='.'):
Yngve Levinsen's avatar
Yngve Levinsen committed
        self._base = base
        self._files = []
Yngve Levinsen's avatar
Yngve Levinsen committed
    def add_file(self, filepath):
        import os

        if os.path.exists(filepath):
Yngve Levinsen's avatar
Yngve Levinsen committed
            fname = filepath
Yngve Levinsen's avatar
Yngve Levinsen committed
            fullpath = os.path.join(self._base, filepath)
            if os.path.exists(fullpath):
Yngve Levinsen's avatar
Yngve Levinsen committed
                fname = fullpath
Yngve Levinsen's avatar
Yngve Levinsen committed
                raise ValueError("Could not find file " + filepath)
        if fname not in self._files:
            self._files.append(fname)

Yngve Levinsen's avatar
Yngve Levinsen committed
    def generate_partran_out(self, filename=None):
        '''
        Creates a string to be written to file
        each line is a list.

        If filename is given, writes directly to output file.

        '''
Yngve Levinsen's avatar
Yngve Levinsen committed

        import numpy as np

Yngve Levinsen's avatar
Yngve Levinsen committed
        h1 = []
        h2 = []
Yngve Levinsen's avatar
Yngve Levinsen committed

Yngve Levinsen's avatar
Yngve Levinsen committed
        d1 = []
        d2 = []
        d3 = []
Yngve Levinsen's avatar
Yngve Levinsen committed

        if self._files:
            for f in self._files:
Yngve Levinsen's avatar
Yngve Levinsen committed
                string = open(f, 'r').read()
                split = string.split('$$$')
                if split[9] != 'Data_Error':
                    raise ValueError("Magic problem, please complain to Yngve")

Yngve Levinsen's avatar
Yngve Levinsen committed
                thisdata = split[10].strip().split('\n')
Yngve Levinsen's avatar
Yngve Levinsen committed
                if not h1:
Yngve Levinsen's avatar
Yngve Levinsen committed
                    h1 = [thisdata[0] + " (std in paranthesis)"]
                    h2 = thisdata[2:10]
Yngve Levinsen's avatar
Yngve Levinsen committed
                d1.append(thisdata[1].split())
                d2.append(thisdata[10])
                d3.append(thisdata[11])

            # fix d1:
            for i in range(len(d1)):
                for j in range(len(d1[0])):
Yngve Levinsen's avatar
Yngve Levinsen committed
                    d1[i][j] = float(d1[i][j])
            d1 = np.array(d1)
            means = d1.mean(axis=0)
            stds = d1.std(axis=0)
            d1 = []
Yngve Levinsen's avatar
Yngve Levinsen committed
                if stds[i] / means[i] < 1e-10:
                    stds[i] = 0.0
Yngve Levinsen's avatar
Yngve Levinsen committed
                # some small std are removed..
Yngve Levinsen's avatar
Yngve Levinsen committed
                if stds[i] / means[i] > 1e-8:
                    d1.append('%f(%f)' % (means[i], stds[i]))
                else:  # error is 0
Yngve Levinsen's avatar
Yngve Levinsen committed
                    d1.append(str(means[i]))
Yngve Levinsen's avatar
Yngve Levinsen committed
            d1 = [' '.join(d1)]
Yngve Levinsen's avatar
Yngve Levinsen committed

            # create data:
Yngve Levinsen's avatar
Yngve Levinsen committed
            data = h1 + d1 + h2 + d2 + d3
Yngve Levinsen's avatar
Yngve Levinsen committed
                open(filename, 'w').write('\n'.join(data))
class partran(dict):
    '''
    Read partran1.out files..
    '''
Yngve Levinsen's avatar
Yngve Levinsen committed
    def __init__(self, filename):
        self.filename = filename
        self._readAsciiFile()

    def _readAsciiFile(self):

        import numpy

Yngve Levinsen's avatar
Yngve Levinsen committed
        stream = open(self.filename, 'r')
Yngve Levinsen's avatar
Yngve Levinsen committed
        for i in range(10):
Yngve Levinsen's avatar
Yngve Levinsen committed
            line = stream.readline()
            if line.strip()[0] == '#':
Yngve Levinsen's avatar
Yngve Levinsen committed
                break
Yngve Levinsen's avatar
Yngve Levinsen committed
        self.columns = ['NUM'] + line.split()[1:]
        self.data = numpy.loadtxt(stream)
Yngve Levinsen's avatar
Yngve Levinsen committed
        self._dict = {}
Yngve Levinsen's avatar
Yngve Levinsen committed
        for i in range(len(self.columns)):
Yngve Levinsen's avatar
Yngve Levinsen committed
            self[self.columns[i]] = self.data[:, i]

class field_map:
    '''
    Class to read in the field map structures

    WARNING: Work in progress!!
    '''

    def __init__(self, filename):
Yngve Levinsen's avatar
Yngve Levinsen committed
        self._filename = filename
        self._load_data(filename)

Yngve Levinsen's avatar
Yngve Levinsen committed
    def _load_data(self, filename):
        import os
        import numpy

        if not os.path.isfile(filename):
            raise ValueError("Cannot find file {}".format(filename))
Yngve Levinsen's avatar
Yngve Levinsen committed
        fin = open(filename, 'r')
        l = fin.readline().split()
        self.header = []
Yngve Levinsen's avatar
Yngve Levinsen committed
        self.start = []
        self.end = []
        numindexes = []
        while len(l) > 1:
            [self.header.append(float(i)) for i in l]
Yngve Levinsen's avatar
Yngve Levinsen committed
            numindexes.append(int(l[0]) + 1)
            if len(l) == 2:
                self.start.append(0.0)
                self.end.append(float(l[1]))
            else:
                self.start.append(float(l[1]))
                self.end.append(float(l[2]))
Yngve Levinsen's avatar
Yngve Levinsen committed
            l = fin.readline().split()
        if len(self.start) == 1:
            self.z = numpy.mgrid[self.start[0]:self.end[0]:numindexes[0]*1j]
            print(new_z,self.z)
        elif len(self.start) == 2:
            self.z, self.x = numpy.mgrid[self.start[0]:self.end[0]:numindexes[0]*1j,
                                         self.start[1]:self.end[1]:numindexes[1]*1j]
        elif len(self.start) == 3:
            self.z, self.x, self.y = numpy.mgrid[self.start[0]:self.end[0]:numindexes[0]*1j, 
                                                 self.start[1]:self.end[1]:numindexes[1]*1j, 
                                                 self.start[2]:self.end[2]:numindexes[2]*1j]
Yngve Levinsen's avatar
Yngve Levinsen committed
        self.norm = float(l[0])
        self.header.append(self.norm)
Yngve Levinsen's avatar
Yngve Levinsen committed
        self.map = numpy.loadtxt(fin).reshape(numindexes)
    def get_flat_fieldmap(self):
        totmapshape = 1
        for i in self.map.shape:
            totmapshape *= i
        return self.map.reshape(totmapshape)

    def interpolate(self, npoints: tuple, method='cubic'):
        '''
        Interpolate the map into a new mesh
        Each value should be an integer with the number of mesh points in each dimension
        intervals should be tuple-like with same number of elements
        as the map dimension, e.g. [0.8,0.8] for 2D
        Can also be a float if you want same interpolation factor in all planes

        method can be 'linear', 'nearest' or 'cubic'
        '''
        import numpy
        from scipy.interpolate import griddata

        values=self.map.flatten()

        if len(self.start) == 1:
            points=self.z[:]
            self.z = numpy.mgrid[self.start[0]:self.end[0]:npoints[0]*1j]
            self.map=griddata(points,values,self.z)
        if len(self.start) == 2:
            points=numpy.array([self.z.flatten(), self.x.flatten()]).transpose()
            self.z, self.x = numpy.mgrid[self.start[0]:self.end[0]:npoints[0]*1j,
                                         self.start[1]:self.end[1]:npoints[1]*1j]
            self.map=griddata(points,values,(self.z,self.x))
        if len(self.start) == 3:
            points=numpy.array([self.z.flatten(), self.x.flatten(), self.y.flatten()]).transpose()
            self.z, self.x, self.y = numpy.mgrid[self.start[0]:self.end[0]:npoints[0]*1j,
                                                 self.start[1]:self.end[1]:npoints[1]*1j,
                                                 self.start[2]:self.end[2]:npoints[2]*1j]
            self.map=griddata(points,values,(self.z,self.x,self.y))
            self.header[0]=npoints[0]-1
            self.header[2]=npoints[1]-1
            self.header[5]=npoints[2]-1

    def savemap(self, filename):
Yngve Levinsen's avatar
Yngve Levinsen committed
        fout = open(filename, 'w')
        for n, s in zip(self.map.shape, self.size):
            fout.write('{} {}\n'.format(n - 1, s))
        fout.write('{}\n'.format(self.norm))
Yngve Levinsen's avatar
Yngve Levinsen committed
        totmapshape = 1
        for i in self.map.shape:
Yngve Levinsen's avatar
Yngve Levinsen committed
            totmapshape *= i
        data = self.map.reshape(totmapshape)
        for j in data:
            fout.write('{}\n'.format(j))