Ejemplo n.º 1
0
    def openConfig(self):
        """
        Open and read the configuration of the interface system and simulation
        tabs. This file must end with extension .ini.
        """
        self.cfgFile = QFileDialog.getOpenFileName(self, 'Open File', '',\
                        "(*.ini)")[0]
        if self.cfgFile == '':
            return

        with open(self.cfgFile, 'r') as f:
            try:
                config.read(self.cfgFile)

                grid = config.get('System', 'Grid')
                materials = config.get('System', 'Materials')
                defects = config.get('System', 'Defects')
                gen, param = config.get('System', 'Generation rate'),\
                             config.get('System', 'Generation parameter')
                self.setSystem(ev(grid), ev(materials), ev(defects), gen, param)

                voltageLoop = config.getboolean('Simulation', 'Voltage loop')
                loopValues = config.get('Simulation', 'Loop values')
                workDir = config.get('Simulation', 'Working directory')
                fileName = config.get('Simulation', 'Simulation name')
                ext = config.get('Simulation', 'Extension')
                BCs = config.getboolean('Simulation', 'Transverse boundary conditions')
                ScnL = config.get('Simulation', 'Electron recombination velocity in 0')
                ScpL = config.get('Simulation', 'Hole recombination velocity in 0')
                ScnR = config.get('Simulation', 'Electron recombination velocity in L')
                ScpR = config.get('Simulation', 'Hole recombination velocity in L')
                L_contact = config.get('Simulation', 'Contact boundary condition in 0')
                R_contact = config.get('Simulation', 'Contact boundary condition in L')
                L_WF = config.get('Simulation', 'Contact work function in 0')
                R_WF = config.get('Simulation', 'Contact work function in L')
                precision = config.get('Simulation', 'Newton precision')
                maxSteps = config.get('Simulation', 'Maximum steps')
                useMumps = config.getboolean('Simulation', 'Use Mumps')
                iterative = config.getboolean('Simulation', 'Iterative solver')
                ramp = config.get('Simulation', 'Generation ramp')
                iterPrec = config.get('Simulation', 'Iterative solver precision')
                htpy = config.get('Simulation', 'Newton homotopy')
                self.setSimulation(voltageLoop, loopValues, workDir, fileName, \
                                   ext, BCs, L_contact, R_contact, L_WF, R_WF,\
                                   ScnL, ScpL, ScnR, ScpR, precision,\
                                   maxSteps, useMumps, iterative, ramp,\
                                   iterPrec, htpy)
                f.close()

            except Exception:
                msg = QMessageBox()
                msg.setWindowTitle("Processing error")
                msg.setIcon(QMessageBox.Critical)
                msg.setText("The file could not be read.")
                msg.setEscapeButton(QMessageBox.Ok)
                msg.exec_()
                return
Ejemplo n.º 2
0
def parseSettings(settings):
    # 1. create grid
    grid = settings['grid']
    dimension = len(grid)

    xgrid = ev(grid[0].lstrip())
    xpts = parseGrid(xgrid)
    ypts = None
    zpts = None
    if dimension == 2 or dimension == 3:
        ygrid = ev(grid[1].lstrip())
        ypts = parseGrid(ygrid)
    if dimension == 3:
        zgrid = ev(grid[2].lstrip())
        zpts = parseGrid(zgrid)
    # build a sesame system
    system = Builder(xpts, ypts, zpts)

    # 2. set materials
    materials = settings['materials']
    for mat in materials:
        location = mat['location']
        # define a function that returns true/false dpending on location
        f = parseLocation(location, dimension)
        system.add_material(mat, f)
        # set the doping
        N_D = float(mat['N_D'])
        if N_D != 0:
            system.add_donor(N_D, f)
        N_A = float(mat['N_A'])
        if N_A != 0:
            system.add_acceptor(N_A, f)

    # 4. set the defects if present
    defects = settings['defects']
    defects = defects
    for defect in defects:
        loc = ev(defect['location'])
        N = float(defect['Density'])
        E = float(defect['Energy'])
        sh = float(defect['sigma_h'])
        se = float(defect['sigma_e'])
        transition = defect['Transition'].replace("/", ",")
        transition = (ev(transition))

        if isinstance(loc, float):
            system.add_point_defects(loc, N, se, sigma_h=sh, E=E, \
                                    transition=transition)
        elif len(loc) == 2:
            system.add_line_defects(loc, N, se, sigma_h=sh, E=E,\
                                    transition=transition)
        elif len(loc) == 4:
            system.add_plane_defects(loc, N, se, sigma_h=sh, E=E,\
                                     transition=transition)
    return system
Ejemplo n.º 3
0
    def test_to_dict(self):
        t = """
        # Serializing / PrettyPrint

        Configurative state can be pretty printed and dict-dumped:
        """
        md(t)
        res = bash_run([
            'calc_tree_nav.py av=1 i.D.dv=42 du # du matched to dump',
            'calc_tree_nav.py app_var=2 inner.Deep.deep_var=42 dump asdict=true',  # long form
        ])
        assert res[0]['res'].strip().startswith('App(app_var=1,')

        assert ev(res[1]['res'].strip()) == {
            'app_var': 2,
            'inner': {
                'Deep': {
                    'deep_var': 42
                },
                'inner_var': 1
            },
        }

        md("""
        The dict format can be piped as is into a config file for subsequent runs.
        > Currently we do not serialize function parameter changes.
        """)
Ejemplo n.º 4
0
def up_tri_copy_from_file(filename):
    '''Return the upper triagular part of the array in filename. The file
    must be a binary .npy file.'''
    f = open(filename, 'rb')
    # The first 6 bytes are a magic string: exactly "\x93NUMPY".
    numpy_string = f.read(6)
    # The next 1 byte is an unsigned byte: the major version number
    # of the file format, e.g. \x01.
    major_ver = ord(f.read(1))
    # The next 1 byte is an unsigned byte: the minor version number
    # of the file format, e.g. \x00.
    minor_ver = ord(f.read(1))
    # Check that the version of the file used is what this code can handle.
    if ((numpy_string != "\x93NUMPY") or (major_ver != 1) or (minor_ver != 0)):
        msg = "Array can only be read from a '\93NUMPY' version 1.0 .npy file "
        msg += "not %s %d.%d" % (numpy_string, major_ver, minor_ver)
        raise ce.DataError(msg)
    # The next 2 bytes form a little-endian unsigned short int: the
    # length of the header data HEADER_LEN.
    byte2,byte1 = f.read(2)
    # Get the value from a short int (2 bytes) to decimal.
    header_len = (16**2)*ord(byte1) + ord(byte2)
    # The next HEADER_LEN bytes form the header data describing the
    # array's format. It is an ASCII string which contains a Python
    # literal expression of a dictionary. It is terminated by a newline
    # ('\n') and padded with spaces ('\x20') to make the total length of
    # the magic string + 4 + HEADER_LEN be evenly divisible by 16 for
    # alignment purposes.
    raw_dict = f.read(header_len)
    # Take off trailing uselessness.
    raw_dict = raw_dict.rstrip('\n')
    raw_dict = raw_dict.rstrip()
    header_dict = ev(raw_dict)
    # Check that it is possible to read array.
    # "fortran_order" : bool
    #     Whether the array data is Fortran-contiguous or not.
    if (header_dict['fortran_order']):
        msg = "Array must be in C order, not fortran order."
        raise ce.DataError(msg)
    # "shape" : tuple of int
    #     The shape of the array.
    arr_shape = header_dict['shape']
    # "descr" : dtype.descr
    #     An object that can be passed as an argument to the
    #     numpy.dtype() constructor to create the array's dtype.
    dt = np.dtype(header_dict['descr'])
    # Where to save all the data. Note this does not make a new array in memory.
    num_nums = np.product(arr_shape)
    # Assume array is square
    row_len = int(np.sqrt(num_nums))
    num_rows = row_len
    loaded_arr = np.empty((row_len,row_len))
    print "Rows copied:"
    # Load the array reading n numbers at a time. Reading one number at
    # a time is best for memory but requires too many disk seeks for a
    # memory map. Loading too many numbers at once requires too much memory,
    # so choose a happy medium.
    # Assume array is square. Reads n rows of numbers at a time.
    rows_to_read = 1000
    n = rows_to_read*row_len
    row_pos = 0
    while (row_pos < num_rows):
        # n may not divide evenly into the total number of numbers.
        # This statement can only be True at the end of the array.
        if ((num_rows-row_pos) < rows_to_read):
            rows_to_read = num_rows-row_pos
            n = rows_to_read*row_len
        read_n_numbers(f,loaded_arr,dt,n,row_len,row_pos)
        # Changing row_pos in the function called does not change it here.
        row_pos += rows_to_read
        sys.stderr.write(str(row_pos)+' ')
    print
    f.close()
    return loaded_arr
Ejemplo n.º 5
0
def init():
    global factor, polygons, colours, direcs, midpoints, rotIns, permu,moveKeys
    polygons, colours, direcs, midpoints, rotIns = [], [], [], [], []
    moveKeys, permu = {}, []

    lines = fullFile.split("\n\n\n")

    for i in range(len(lines)):
        lines[i] = ev("".join(lines[i].split()))
    
    indivFactor = lines[0]
    factor = (y/4*(y<=x) + x/4*(x<y)) / indivFactor
    
    faceLengths = []
    
    for face in lines[1]:
        if type(face) == list:
            faceDefn = len(polygons)
            
            for piece in face:
                if type(piece) == list:
                    pieceDefn = len(polygons)
                    
                    points = []
                    
                    for point in piece:
                        if type(point) == list:
                            pointDefn = len(points)
                            points += [point]
                        elif type(point) == tuple:
                            points += [tr(points[pointDefn], point)]

                    polygons += [offset(array(points), off*indivFactor)]
                    
                elif type(piece) == tuple:
                    polygons += [tr( copy(polygons[pieceDefn]), piece )]
            piecesPerFace = len(polygons) - faceDefn

        elif type(face) == tuple:
            for i in range(piecesPerFace):
                polygons += [tr( copy(polygons[faceDefn + i]) , face )]
        faceLengths += [int(len(polygons) - sum(faceLengths))]
    
    fls = faceLengths
    for face in lines[2]:
        if type(face) == tuple:
            colours += [face] * fls[0]
        elif type(face) == list:
            colours += face
        fls = fls[1:]
    
    for face in lines[3]:
        direcs += [face] * faceLengths[0]
        faceLengths = faceLengths[1:]

    for polygon in polygons:
        midpoints += [centroid(polygon)]
    
    for face in lines[4]:
        rotIns += [array(piece) for piece in face]

    for i in range(len(lines[5])):
        moveKeys[ord(lines[5][i])] = (i+1, arbiRot(lines[6][i]), lines[7][i])
    
    for i in range(len(lines[8])):
        permu += [[lines[8][i], list(array(order(lines[8][i]))+1)]]
    
    mostPoints = max(map(len,polygons))
    for i in range(len(polygons)):
        diff = mostPoints - len(polygons[i])
        polygons[i] = array(list(polygons[i]) + ([polygons[i][-1]] * diff))
    
    polygons, colours, direcs = array(polygons), array(colours), array(direcs)
    midpoints, rotIns, permu = array(midpoints), array(rotIns), array(permu)
    direcs = direcs.astype('float64')
Ejemplo n.º 6
0
def parseSettings(settings):
    # 1. create grid
    grid = settings['grid']
    dimension = len(grid)

    xgrid = ev(grid[0].lstrip())
    xpts = parseGrid(xgrid)
    ypts = np.array([0])
    if dimension == 2:
        ygrid = ev(grid[1].lstrip())
        ypts = parseGrid(ygrid)
    # build a sesame system
    if 'periodicBCs' in settings:
        system = Builder(xpts, ypts, periodic=settings['periodicBCs'])
    else:
        system = Builder(xpts, ypts)

    # 2. set materials
    materials = settings['materials']
    for mat in materials:
        location = mat['location']
        # define a function that returns true/false dpending on location
        f = parseLocation(location, dimension)
        system.add_material(mat, f)
        # set the doping
        N_D = float(mat['N_D'])
        if N_D != 0:
            system.add_donor(N_D, f)
        N_A = float(mat['N_A'])
        if N_A != 0:
            system.add_acceptor(N_A, f)

    # 4. set the defects if present
    defects = settings['defects']
    defects = defects
    for defect in defects:
        loc = ev(defect['location'])
        N = float(defect['Density'])
        E = float(defect['Energy'])
        sh = float(defect['sigma_h'])
        se = float(defect['sigma_e'])
        transition = defect['Transition'].replace("/", ",")
        transition = (ev(transition))

        if isinstance(loc, float):
            system.add_defects(loc, N, se, sigma_h=sh, E=E, \
                                    transition=transition)
        elif len(loc) == 2:
            system.add_defects(loc, N, se, sigma_h=sh, E=E,\
                                    transition=transition)

    ##  ok i would go ahead and construct g for non-manual case here!
    lambda_power = np.array([])
    power = np.array([])
    lambda_alpha = np.array([])
    alpha = np.array([])
    if settings['use_manual_g'] is False:

        ########################################
        # illumination properties
        ########################################
        # use one sun power spectrum
        if settings['ill_onesun'] is True:
            lambda_power = onesundata[:, 0]
            power = onesundata[:, 1] * 1e-4  # converting to W/cm^2

        # read lambda and power
        if settings['ill_monochromatic'] is True:
            laserlambda = float(settings['ill_wavelength'])
            powertot = float(np.asarray(settings['ill_power']))
            # generate a distribution, Gaussian with fixed spread of 10 nm
            width = 100.
            lambda_power = np.linspace(280, 4000, 745)
            power = powertot / (2 * np.pi * width**2)**.5 * np.exp(
                -(lambda_power - laserlambda)**2 / (2 * width**2))

        if not power.any():
            power = np.zeros(10)
            lambda_power = np.linspace(280, 4000, 745)

        ########################################
        # absorption properties
        ########################################
        if settings['abs_usefile'] is True:
            abs_file = settings['abs_file']
            lambda_alpha, alpha = parseAlphaFile(abs_file)
        if settings['abs_useralpha'] is True:
            alpha = np.asarray(settings['abs_alpha'])
            lambda_alpha = []
        if alpha.size == 0:
            alpha = np.zeros(745)
            lambda_alpha = np.linspace(280, 4000, 745)

    g = getgeneration(lambda_power, power, lambda_alpha, alpha, xpts)
    g = np.tile(g, system.ny)
    system.generation(g)

    return system
Ejemplo n.º 7
0
def up_tri_copy_from_file(filename):
    '''Return the upper triagular part of the array in filename. The file
    must be a binary .npy file.'''
    f = open(filename, 'rb')
    # The first 6 bytes are a magic string: exactly "\x93NUMPY".
    numpy_string = f.read(6)
    # The next 1 byte is an unsigned byte: the major version number
    # of the file format, e.g. \x01.
    major_ver = ord(f.read(1))
    # The next 1 byte is an unsigned byte: the minor version number
    # of the file format, e.g. \x00.
    minor_ver = ord(f.read(1))
    # Check that the version of the file used is what this code can handle.
    if ((numpy_string != "\x93NUMPY") or (major_ver != 1) or (minor_ver != 0)):
        msg = "Array can only be read from a '\93NUMPY' version 1.0 .npy file "
        msg += "not %s %d.%d" % (numpy_string, major_ver, minor_ver)
        raise ce.DataError(msg)
    # The next 2 bytes form a little-endian unsigned short int: the
    # length of the header data HEADER_LEN.
    byte2, byte1 = f.read(2)
    # Get the value from a short int (2 bytes) to decimal.
    header_len = (16**2) * ord(byte1) + ord(byte2)
    # The next HEADER_LEN bytes form the header data describing the
    # array's format. It is an ASCII string which contains a Python
    # literal expression of a dictionary. It is terminated by a newline
    # ('\n') and padded with spaces ('\x20') to make the total length of
    # the magic string + 4 + HEADER_LEN be evenly divisible by 16 for
    # alignment purposes.
    raw_dict = f.read(header_len)
    # Take off trailing uselessness.
    raw_dict = raw_dict.rstrip('\n')
    raw_dict = raw_dict.rstrip()
    header_dict = ev(raw_dict)
    # Check that it is possible to read array.
    # "fortran_order" : bool
    #     Whether the array data is Fortran-contiguous or not.
    if (header_dict['fortran_order']):
        msg = "Array must be in C order, not fortran order."
        raise ce.DataError(msg)
    # "shape" : tuple of int
    #     The shape of the array.
    arr_shape = header_dict['shape']
    # "descr" : dtype.descr
    #     An object that can be passed as an argument to the
    #     numpy.dtype() constructor to create the array's dtype.
    dt = np.dtype(header_dict['descr'])
    # Where to save all the data. Note this does not make a new array in memory.
    num_nums = np.product(arr_shape)
    # Assume array is square
    row_len = int(np.sqrt(num_nums))
    num_rows = row_len
    loaded_arr = np.empty((row_len, row_len))
    print "Rows copied:"
    # Load the array reading n numbers at a time. Reading one number at
    # a time is best for memory but requires too many disk seeks for a
    # memory map. Loading too many numbers at once requires too much memory,
    # so choose a happy medium.
    # Assume array is square. Reads n rows of numbers at a time.
    rows_to_read = 1000
    n = rows_to_read * row_len
    row_pos = 0
    while (row_pos < num_rows):
        # n may not divide evenly into the total number of numbers.
        # This statement can only be True at the end of the array.
        if ((num_rows - row_pos) < rows_to_read):
            rows_to_read = num_rows - row_pos
            n = rows_to_read * row_len
        read_n_numbers(f, loaded_arr, dt, n, row_len, row_pos)
        # Changing row_pos in the function called does not change it here.
        row_pos += rows_to_read
        sys.stderr.write(str(row_pos) + ' ')
    print
    f.close()
    return loaded_arr