Convert a FITS recarray to a python dictionary.
548272
def fits_recarray_to_dict(table):
    """"""

    cols = {}
    for icol, col in enumerate(table.columns.names):

        col_data = table.data[col]
        if type(col_data[0]) == np.float32:
            cols[col] = np.array(col_data, dtype=float)
        elif type(col_data[0]) == np.float64:
            cols[col] = np.array(col_data, dtype=float)
        elif type(col_data[0]) == str:
            cols[col] = np.array(col_data, dtype=str)
        elif type(col_data[0]) == np.string_:
            cols[col] = np.array(col_data, dtype=str)
        elif type(col_data[0]) == np.int16:
            cols[col] = np.array(col_data, dtype=int)
        elif type(col_data[0]) == np.ndarray:
            cols[col] = np.array(col_data)
        else:
            raise Exception(
                'Unrecognized column type: %s %s' % (col, str(type(col_data))))

    return cols
1065233
def c_array(ctype, values):
    """"""
    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
        return (ctype * len(values)).from_buffer_copy(values)
    return (ctype * len(values))(*values)
1022732
def _array_convert(a):
    
    from numpy import ndarray
    if isinstance(a, ndarray):
        larr = a.tolist()
        if len(larr) == 1:
            return larr[0]
        else:
            return larr
    else:
        return a
957763
def combine_dicts(recs):
    """"""
    if not recs:
        return None

    if len(recs) == 1:
        return recs.pop()

    new_rec = {}
    for rec in recs:
        for k, v in rec.iteritems():
            if k in new_rec:
                new_rec[k] = "%s, %s" % (new_rec[k], v)
            else:
                new_rec[k] = v
    return new_rec
925156
def to_dict(self):
        
        def _json_safe(v):
            if isinstance(v, np.ndarray):
                return v.tolist()
            elif is_unit(v)[0]:
                return v.to_string()
            else:
                return v
        d = {k:_json_safe(v) for k,v in self._descriptors.items()}
        d['nparray'] = self.__class__.__name__.lower()
        return d
458631
def to_dict(self):
        

        #TODO: Implement a more memory efficient variant
        if self.L is None:
            return { "mu": self.mu.tolist(), "Sigma": self.Sigma.tolist()}
        else:
            return { "mu": self.mu.tolist(), "Sigma": self.Sigma.tolist(), "L": self.L.tolist()}
1173565
def _unwrap_dict(dictionary, index_string):
    '''
    
    '''
    index = index_string.split(',')
    for k in index:
        dictionary = dictionary[k]
    return dictionary
1089300
def get_array_shape(self, key):
        """"""
        data = self.model.get_data()
        return data[key].shape
117606
def multidict(ordered_pairs):
    """"""
    # read all values into lists
    d = defaultdict(list)
    for k, v in ordered_pairs:
        d[k].append(v)
    # unpack lists that have only 1 item
    dict_copy = deepcopy(d)
    for k, v in iteritems(dict_copy):
        if len(v) == 1:
            d[k] = v[0]
    return dict(d)
343378
def to_dict(self):
        

        input_dict = super(RBF, self)._save_to_input_dict()
        input_dict["class"] = "GPy.kern.RBF"
        input_dict["inv_l"] = self.use_invLengthscale
        if input_dict["inv_l"] == True:
            input_dict["lengthscale"] = np.sqrt(1 / float(self.inv_l))
        return input_dict
136266
def toArray(self):
        
        if self.isTransposed:
            return np.asfortranarray(
                self.values.reshape((self.numRows, self.numCols)))
        else:
            return self.values.reshape((self.numRows, self.numCols), order='F')
249539
def toarray(self):
        
        return asarray([value.toarray() for (key, value) in sorted(self.transformations.items())])
1294438
def to_dict(self, get_value=None):
        """"""
        self.trim()
        result = {}
        for key, value in iteritems(self.counters):
            if get_value is not None:
                value = getattr(value, get_value)
            r = result
            for _key in key[:-1]:
                r = r.setdefault(_key, {})
            r[key[-1]] = value
        return result
500742
def fromfits(infilename, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "FITS import shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "FITS file BITPIX : %s" % (hdr["BITPIX"])
        print "Internal array type :", pixelarray.dtype.name
    
    return pixelarray, hdr
440128
def _pack(cls, tensors):
    """"""
    if not tensors:
      return None
    elif len(tensors) == 1:
      return array_ops.reshape(tensors[0], [-1])
    else:
      flattened = [array_ops.reshape(tensor, [-1]) for tensor in tensors]
      return array_ops.concat(flattened, 0)
559207
def from_old_dict(cls, d):
        
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {}
            for spin in d['projections']:
                dd = []
                for i in range(len(d['projections'][spin])):
                    ddd = []
                    for j in range(len(d['projections'][spin][i])):
                        dddd = []
                        ddd.append(d['projections'][spin][i][j])
                    dd.append(np.array(ddd))
                projections[Spin(int(spin))] = np.array(dd)

        return LobsterBandStructureSymmLine(
            d['kpoints'], {Spin(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
1225957
def dict_to_object(source):
    """"""
    target = inspectable_class.InspectableClass()
    for k, v in source.items():
        setattr(target, k, v)
    return target