Ejemplo n.º 1
0
 def __init__(self, filename):
     self.filename = filename
     self.label = filename   # May need to shorten
     self.open(filename)
     self.dimensions = self.getDimensions()        # A dictionary of XPadDataDim objects
     self.varNames  = self.handle.variables.keys() # A list of variable names
     for i,v in enumerate(self.varNames):
         try:
             # Python 2
             if isinstance(v, unicode):
                 v = v.encode('utf-8')
             v = str(v).translate(None, '\0')
         except NameError:
             # Python 3
             if isinstance(v, str):
                 v = v.encode('utf-8')
             
         self.varNames[i] = v
             
     self.variables = {}   # A dictionary of XPadDataItem objects with empty data
     for name, var in self.handle.variables.items():
         item = XPadDataItem()
         item.name   = name
         item.source = self.filename
         item.dim = map(lambda d: self.dimensions[d], var.dimensions)
         self.variables[name] = item
     self.close()
Ejemplo n.º 2
0
 def read(self, name, shot):
     """Read a variable from the file."""
     self.open()
     if self.handle == None: return None
     
     try:
         var = self.handle.variables[name]
     except KeyError:
         # Not found. Try to find using case-insensitive search
         var = None
         for n in self.handle.variables.keys():
             if n.lower() == name.lower():
                 print("WARNING: Reading '"+n+"' instead of '"+name+"'")
                 var = self.handle.variables[n]
         if var == None:
             return None
     ndims = len(var.dimensions)
     if ndims == 0:
         data = var.getValue()
     else:
         data = var[:]
     item = XPadDataItem()
     item.name   = name
     item.source = self.filename
     item.data   = data
     item.dim = map(lambda d: self.dimensions[d], var.dimensions)
     
     self.close()
     return item
Ejemplo n.º 3
0
 def newfunc(data):
     result = XPadDataItem()
     if data.name != "":
         result.name   = name + "( " + data.name + " )"
     result.source = data.source
     if data.label != "":
         result.label  = name + "( " + data.label + " )"
     result.data   = func(data.data)
     result.dim    = data.dim
     result.order  = data.order
     result.time   = data.time
     return result
Ejemplo n.º 4
0
def chop(item, t_min, t_max):
    """
        >>> from user_functions import *
        >>> a = chop(XMC_OMV_110, 0.274, 0.276)
        >>> a_amp,a_phase = fftp(a)
        >>> b = chop(a_phase, 0.0, 100.0)
        >>> plot(b)
    """
    if len(item.dim) != 1:
        raise ValueError("chop can only operate on 1D traces currently")

    if t_max < t_min or t_max < item.dim[0].data[0] or t_min > item.dim[0].data[-1]:
        raise ValueError("New time-range not defined correctly")

    idx = np.where(np.logical_and(item.dim[0].data >= t_min, item.dim[0].data <= t_max))

    if len(idx[0]) == 0:
        raise ValueError("No data in time-range specified")

    # Calculate the phase
    chopped = XPadDataItem()

    if item.name != "":
        chopped.name = "CHOP( "+item.name+", "+str(t_min)+", "+str(t_max)+" )"
    chopped.source = item.source
    if item.label != "":
        chopped.label = "CHOP( "+item.label+", "+str(t_min)+", "+str(t_max)+" )"
    chopped.units = item.units

    chopped.data = item.data[idx]

    # Create a dimension
    dim = XPadDataDim()

    dim.name = item.dim[0].name
    dim.label = item.dim[0].label
    dim.units = item.dim[0].units

    dim.data = item.dim[0].data[idx]
    chopped.dim = [dim]

    if chopped.dim[0].units in ["s", "S", "sec", "Sec", "SEC"]:
        chopped.order = 0
        chopped.time = chopped.dim[0].data

    return chopped
Ejemplo n.º 5
0
def integrate(item):
    """
    Integrate the given trace
    
    Inputs
    ------
    
    item  - an XPadDataItem object (or equivalent)
    
    Returns
    -------
    
    an XPadDataItem object
    
    """
    
    if len(item.dim) != 1:
        raise ValueError("Can only integrate 1D traces currently")
    
    # Create a result 
    result = XPadDataItem()
    if item.name != "":
        result.name = "INTG( "+item.name+" )"
    result.source = item.source
    if item.label != "":
        result.label = "INTG( "+item.label+" )"
    if item.units != "":
        result.units = item.units+"*"+item.dim[0].units

    result.data = zeros(item.data.shape)
    
    time = item.dim[0].data
    
    result.data[1:] = cumsum(0.5*(time[1:]-time[0:-1])*(item.data[1:] + item.data[0:-1]))
    
    result.dim = item.dim
    result.order = item.order
    result.time = item.time
    
    return result
Ejemplo n.º 6
0
    def __init__(self, path, parent=None):

        # Convert path to string, strip NULL chars
        path = str(path).translate(None, '\0')
        
        self.label = os.path.basename(os.path.normpath(path))
        self.dimensions = {}
        self.varNames = []
        self.variables = {}
        
        self.parent = parent
        
        # Define configuration dictionary
        if parent == None:
            self.config = {'Host':'mast.fusion.org.uk', 'Port':56565, 'verbose':False, 'debug':False}
        else:
            self.config = parent.config
        
        if os.path.isdir(path):
            # List directory
            ls = os.listdir(path)

            # Check if a name is supplied
            if 'title' in ls:
                # Read file to get the label
                f = open(os.path.join(path, 'title'), 'r')
                self.label = f.readline().strip()
                f.close()
                
            # Create a child for each subdirectory
            self.children = [ XPadSource( os.path.join(path, name), parent=self )  # Create child
                              for name in ls
                              if os.path.isdir(os.path.join(path, name)) and name[0] != '.' ]  # For each directory which isn't hidden
            
            # Find items 
            for name in ls:
                if os.path.isfile(os.path.join(path, name)) and ( os.path.splitext(name)[1] == ".item" ):
                    self.children.append( XPadSource( os.path.join(path, name), parent=self) )
        else:
            # Given an item file to read
            f = open(path, 'r')
            self.label = f.readline().strip()  # First line is the label
            nitems = int((f.readline().split('$', 1))[0].strip())  # Number of items
            for i in range(nitems):
                line = f.readline()
                # Split at '$'
                s = line.split('$', 1)
                name = s[0].strip()
                if len(name) == 0:
                    continue
                try:
                    desc = s[1].strip()
                except:
                    desc = ""
                item = XPadDataItem()
                item.name = name
                item.label = item.desc = desc
                item.source = path
                self.variables[name] = item
                self.varNames.append(name)
                
            if parent != None:
                parent.addVariables(self.variables)
            f.close()
Ejemplo n.º 7
0
def fftp(item):
    """
    Calculate amplitude and phase as a function of frequency
    
    Inputs
    ------

    item  - an XPadDataItem object
    
    Returns
    -------
    
    amplitude, phase pair of XPadDataItem objects
    
    """

    if len(item.dim) != 1:
        raise ValueError("fftp can only operate on 1D traces currently")
    
    # Calculate FFT
    data = rfft(item.data)*(1./len(item.data))
    
    # Create a dimension
    dim = XPadDataDim()
    
    dim.name = "Frequency"
    
    step = (item.dim[0].data[1] - item.dim[0].data[0])
    dim.data = rfftfreq(len(item.data), step)

    dim.units = "1/"+item.dim[0].units
    if item.dim[0].units in ["s", "S", "sec", "Sec", "SEC"]:
        dim.data /= 1000.
        dim.units = "kHz"
    
    # Calculate the amplitude
    amp = XPadDataItem()
    if item.name != "":
        amp.name = "AMP( "+item.name+" )"
    amp.source = item.source
    if item.label != "":
        amp.label = "AMP( "+item.label+" )"
    amp.units = item.units

    amp.data = abs(data)
    
    amp.dim = [dim]
    
    # Calculate the phase
    phase = XPadDataItem()
    if item.name != "":
        phase.name = "PHASE( "+item.name+" )"
    phase.source = item.source
    if item.label != "":
        phase.label = "PHASE( "+item.label+" )"
    phase.units = "Radians"
    
    phase.data = arctan2(data.real, data.imag)

    a = phase.data - 2*pi
    for i in range(1,len(phase.data)):
        if abs(phase.data[i-1] - a[i]) < 1.:
            phase.data[i] = a[i]
            
    a = phase.data + 2*pi
    for i in range(1,len(phase.data)):
        if abs(phase.data[i-1] - a[i]) < 1.:
            phase.data[i] = a[i]
    
    phase.dim = [dim]
    
    return amp, phase
Ejemplo n.º 8
0
def parse_padsav(xpad_idl_dict):
    """
        Reads data from an idl_dict object into XPadDataItem objects

        Parameters
        ----------
        xpad_idl_dict : AttrDict or dict
            Input dict from an XPad *.padsav imported using scipy.io.readsav


        Returns
        -------
        items : list
            A list of XPadDataItems
    """

    if not check_padsav(xpad_idl_dict): return None

    items = []

    for trace in xpad_idl_dict['ptr']:

        item = XPadDataItem()

        item.name = trace['NAME'][0]
        item.source = trace['SOURCE'][0]
        item.label = trace['DINFO'][0]['LABEL'][0]
        item.units = trace['DINFO'][0]['UNITS'][0]

        numdims = trace['SIZE'][0][0]

        item.data = rollaxis(trace['DATA'][0], numdims - 1)

        if numdims > 0:
            # f(t), f(t,x) or f(t,x,y)
            dim = XPadDataDim()

            # If we have a time domain, use data from TINFO
            if trace['TINFO'][0]['DOMAINS'][0] > 0:
                dim.data = linspace(trace['TINFO'][0]['START'][0],trace['TINFO'][0]['FINISH'][0],trace['TINFO'][0]['LENGTH'])
            else:
                dim.data = trace['TIME'][0]

            dim.name = trace['TINFO'][0]['LABEL'][0]
            dim.label = dim.name
            dim.units = trace['TINFO'][0]['UNITS'][0]

            item.dim.append(dim)

            item.order = len(item.dim) - 1
            item.time = item.dim[item.order].data

        if numdims > 2:
            # f(t,x,y)
            dim = XPadDataDim()
            dim.data = trace['Y'][0]
            dim.name = trace['YINFO'][0]['LABEL'][0]
            dim.label = dim.name
            dim.units = trace['YINFO'][0]['UNITS'][0]

            item.dim.append(dim)

        if numdims > 1:
            # f(t,x) or f(t,x,y)
            dim = XPadDataDim()
            dim.data = trace['X'][0]
            dim.name = trace['XINFO'][0]['LABEL'][0]
            dim.label = dim.name
            dim.units = trace['XINFO'][0]['UNITS'][0]

            item.dim.append(dim)

        item.desc = trace['TYPE'][0]

        items.append(item)

    return items