Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Anyone help me to run this project?
#1
I am new in python and I am studying simulation for organic materials. I found a thesis with python code at the end of thesis (link here http://liu.diva-portal.org/smash/get/div...TEXT01.pdf)
I tried run this project with python 3.x version but it wasn't successful. Huh
Any one help me to run this project?
Many thanks!

PYTHON CODE
'''
Created on Oct 16, 2017
 **huh** 
@author: Hung
'''
#!/usr/bin/env python2.7
from mpmath.libmp.backend import xrange
"""Run simple Monte Carlo simulations of hopping charge transport."""

import argparse
import bisect
import configparser
import itertools
import math
import operator
import random
import sys

import numpy
import scipy.constants
import scipy.spatial

K = scipy.constants.value('Boltzmann constant in eV/K')

class Site(object):
    """A transport site occupiable by a charge carrier."""
    def __init__(self, position, energy = 0.0):
        self.position = numpy.asarray(position, dtype=float)
        self.energy = energy
        self.transitions = []
    
class Transition(object):
    """A representation of a transition to a site."""
    def __init__(self, acceptor, vector, rate=1.0):
        self.acceptor = acceptor
        self.vector = numpy.asarray(vector, dtype=float)
        self.rate = rate
        
class Charge(object):
    """A charge carrier."""
    def __init__(self):
        self.position = numpy.zeros(3)
        self.donor = None
        self.next_transition = None
        self.next_transition_time = float('inf')
        
    def place(self, donor):
        """Place the charge on a given donor site."""
        self.donor = donor
        
    def draw_next_transition(self, current_time):
        """Draw the next transition for the charge carrier."""
        rates = map(operator.attrgetter('rate'), self.donor.transitions)
        intervals = numpy.array(rates).cumsum()
        totalrate = intervals[-1]
        index = bisect.bisect_right(intervals, random.uniform(0.0, totalrate))
        self.next_transition = self.donor.transitions[index]
        self.next_transition_time = current_time + random.expovariate(totalrate)
    
    def hop(self):
        """Perform a previously drawn transition."""
        self.position += self.next_transition.vector
        self.donor = self.next_transition.acceptor
        self.draw_next_transition(self.next_transition_time)

def create_structure(config):
    """Create a structure of sites."""
    structfile = config.get('Structure', 'fileName')
    data = numpy.loadtxt(structfile)
    cell = data[0]
    sites = [Site(position) for position in data[1:]]
    return sites, cell

def create_transitions(sites, cell, config):
    """Create transitions between a given sequence of sites."""
    numneighbors = config.getint('Structure', 'numberOfNeighbors')
    
    
    # This creates translation vectors to move a site into each of the
    # 26 surrounding cells of the given cell.
    translations = [numpy.array(v) * cell for v in itertools.product((-1., 0., 1.), repeat=3)]
    positions = [site.position for site in sites]
    all_positions = [p + v for v in translations for p in positions]
    kdtree = scipy.spatial.cKDTree(all_positions)
    all_indices = kdtree.query(positions, numneighbors + 1)
    for site, indices in zip(sites, all_indices):
        for index in indices[1:]:
            translation_index, neighbor_index = divmod(index, len(sites))
            neighbor = sites[neighbor_index]
            translation = translations[translation_index]
            vector = neighbor.position + translation - site.position
            transition = Transition(neighbor, vector)
            site.transitions.append(transition)

def generate_diagonal_disorder(sites, config):
    """Assign site energies from a Gaussian distribution."""
    mean = config.getfloat('DiagonalDisorder', 'mean')
    std = config.getfloat('DiagonalDisorder', 'standardDeviation')
    for site in sites:
        site.energy = random.normalvariate(mean, std)

def assign_transition_rates(sites, config):
    """Assign transition rates according to Miller-Abrahams theory."""
    prefactor = config.getfloat('TransitionRate', 'prefactor')
    alpha = config.getfloat('TransitionRate', 'localizationLength')
    F = map(float, config.get('TransitionRate', 'electricField').split(','))
    T = config.getfloat('TransitionRate', 'temperature')
    for donor in sites:
        for transition in donor.transitions:
            r = numpy.linalg.norm(transition.vector)
            dE = transition.acceptor.energy - donor.energy + numpy.dot(F, transition.vector)
            transition.rate = prefactor * math.exp(-2. * r / alpha - (dE + abs(dE)) / (2. * K * T))

def run_one_simulation(sites, runtime):
    """Run a single simulation."""
    charge = Charge()
    charge.place(random.choice(sites))
    charge.draw_next_transition(0.0)
    while charge.next_transition_time < runtime:
        charge.hop()
    return charge.position

def run_simulations(sites, config):
    """Run simulations on an ensemble of systems."""
    ensemblesize = config.getint('Simulation', 'ensembleSize')
    runtime = config.getfloat('Simulation', 'runTime')
    movement = numpy.zeros(3)
    for i in xrange(ensemblesize):
        chargeposition = run_one_simulation(sites, runtime)
        movement += chargeposition
    return movement / ensemblesize

def calculate_mobility(movement, config):
    field = map(float, config.get('TransitionRate', 'electricField').split(','))
    time = config.getfloat('Simulation', 'runTime')
    velocity = movement / time
    velocity = abs(numpy.dot(velocity, field) / numpy.linalg.norm(field))
    velocity *= 1e-8 # Ang/s --> cm/s
    mobility = velocity / numpy.linalg.norm(field)
    return mobility

def main():
    """The main function of Marmoset."""
    argparser = argparse.ArgumentParser(description=__doc__)
    argparser.add_argument('inputfile', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='a configuration file (default: stdin)')
    args = argparser.parse_args()
    config = configparser.ConfigParser()
    config.optionxform = str
    config.readfp(args.inputfile)
    sites, cell = create_structure(config)
    create_transitions(sites, cell, config)
    generate_diagonal_disorder(sites, config)
    assign_transition_rates(sites, config)
    movement = run_simulations(sites, config)
    
    mobility = calculate_mobility(movement, config)
    print (mobility)
    
if __name__ == '__main__':
    main()
Quote
#2
The code in the pdf is python2. You can try to use 2to3 tool to try to convert it to python3. I see you try to solve some of the issues, like print, but you don't need to import xrange from
mpmath.libmp.backend. in python3 xrange becomes range and 2to3 tool will fix it.

As a side note - it's dishonest to claim you are author of the code, given it's not true.
Quote
#3
Hi buran

I am sorry. I know that it is not my program. I created this project in my eclipse IDE and it created automatically this header statement lines.

Thank you for your suggestion. I tried to run this program with python 3. version and have no any errors.
However, it is run continuously and I don't see any messages. You can give me some statement lines to insert in main program to see the program how to run?
Quote
#4
what program runs continuosly? The 2to3 tool? or the converted script?
In the link I posted there are instructions on how to run 2to3 tool
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)