def post(self, queueId): args = parsers.post_name.parse_args() counter = models.Counter(name=args['name']) counter.queueId = queueId models.db.session.add(counter) models.db.session.commit() return counter
def getAPIKey(plurkAPIKey): counter = models.Counter() APIKeyToUse = None count = None for keyName in plurkAPIKey: APIKey = counter.all().filter('name ==', keyName).first() if APIKey is not None: if APIKey.count < count or count is None: APIKeyToUse = APIKey.name count = APIKey.count else: return keyName return APIKeyToUse
def RunCronJob(): APIKey = getAPIKey(plurkAPIKey) plurk = Plurk(APIKey, plurkUsername, plurkPassword) keyWordList = models.KeyWord() keyWords = keyWordList.getDecoded() result = plurk.callResponder(keyWords) counter = models.Counter() counterData = { 'name': APIKey, 'value': plurk.APICallTimes, 'default': plurk.APICallTimes } counter.updateCount(counterData) return str(result)
def update_smiles_counter(request, smiles): # Add smiles to counter countobj = (request.dbsession.query( models.Counter).filter_by(smiles=smiles).first()) if countobj is None: counter = models.Counter() counter.smiles = smiles counter.count = 1 request.dbsession.add(counter) else: countobj.count += 1 return
def ajax_submitquantum(request): """ Setup quantum calculation """ if not request.POST: return { 'error': 'Error 128 - empty post', 'message': "Error. Empty post." } if not request.POST["sdf"]: return { 'error': 'Error 132 - sdf key error', 'message': "Error. Missing information." } # Get coordinates from request sdfstr = request.POST["sdf"].encode('utf-8') # Get rdkit molobj, status = cheminfo.sdfstr_to_molobj(sdfstr) if molobj is None: status = status.split("]") status = status[-1] return {'error': 'Error 141 - rdkit error', 'message': status} try: conf = molobj.GetConformer() except ValueError: # Error return { 'error': 'Error 141 - rdkit error', 'message': "Error. Server was unable to generate conformations for this molecule" } # If hydrogens not added, assume graph and optimize with forcefield atoms = cheminfo.molobj_to_atoms(molobj) if 1 not in atoms: molobj = cheminfo.molobj_add_hydrogens(molobj) cheminfo.molobj_optimize(molobj) # TODO Check lengths of atoms # TODO Define max in settings # Fix sdfstr sdfstr = sdfstr.decode('utf8') for _ in range(3): i = sdfstr.index('\n') sdfstr = sdfstr[i + 1:] sdfstr = "\n" * 3 + sdfstr # hash on sdf (conformer) hshobj = hashlib.md5(sdfstr.encode()) hashkey = hshobj.hexdigest() calculation = request.dbsession.query(models.GamessCalculation) \ .filter_by(hashkey=hashkey).first() if calculation is not None: msg = {'hashkey': hashkey} calculation.created = datetime.datetime.now() return msg print("new:", hashkey) molecule_info = {"sdfstr": sdfstr, "molobj": molobj, "hashkey": hashkey} msg = pipelines.gamess_quantum_pipeline(request, molecule_info) return msg # # # calculation = request.dbsession.query(models.GamessCalculation) \ .filter_by(hashkey=hashkey).first() if calculation is not None: calculation.created = datetime.datetime.now() return msg else: pass # check if folder exists here = os.path.abspath(os.path.dirname(__file__)) + "/" datahere = here + "data/" if os.path.isdir(datahere + hashkey): # return msg pass else: os.mkdir(datahere + hashkey) os.chdir(datahere + hashkey) # Minimize with forcefield first molobj = cheminfo.molobj_add_hydrogens(molobj) cheminfo.molobj_optimize(molobj) header = """ $basis gbasis=pm3 $end $contrl runtyp=optimize icharg=0 $end $statpt opttol=0.0005 nstep=200 projct=.F. $end """ # Prepare gamess input # inpstr = gamess.molobj_to_gmsinp(molobj, header) # Save and run file # with open("optimize.inp", "w") as f: # f.write(inpstr) # # stdout, stderr = gamess.calculate(hashkey+".inp", store_output=False) # with open("start.sdf", 'w') as f: # f.write(cheminfo.molobj_to_sdfstr(molobj)) # Check output # status, message = gamess.check_output(stdout) os.chdir(here) # if not status: # msg["error"] = "error 192: QM Calculation fail" # msg["message"] = message # return msg # Saveable sdf and reset title sdfstr = cheminfo.molobj_to_sdfstr(molobj) sdfstr = str(sdfstr) for _ in range(2): i = sdfstr.index('\n') sdfstr = sdfstr[i + 1:] sdfstr = "\n\n" + sdfstr # Get a 2D Picture # TODO Compute 2D coordinates svgstr = cheminfo.molobj_to_svgstr(molobj, removeHs=True) # Success, setup database calculation = models.GamessCalculation() calculation.smiles = smiles calculation.hashkey = hashkey calculation.sdf = sdfstr calculation.svg = svgstr calculation.created = datetime.datetime.now() # Add calculation to the database request.dbsession.add(calculation) # Add smiles to counter countobj = request.dbsession.query(models.Counter) \ .filter_by(smiles=smiles).first() if countobj is None: counter = models.Counter() counter.smiles = smiles counter.count = 1 request.dbsession.add(counter) print(counter) else: countobj.count += 1 return msg
def gamess_quantum_pipeline(request, molinfo): """ Assumed that rdkit understands the molecule """ # TODO Read gamess settings from ini # Read input molobj = molinfo["molobj"] sdfstr = molinfo["sdfstr"] if "name " in request.POST: name = request.POST["name"].encode('utf-8') else: name = None # Get that smile on your face smiles = cheminfo.molobj_to_smiles(molobj, remove_hs=True) # hash on sdf (conformer) hshobj = hashlib.md5(sdfstr.encode()) hashkey = hshobj.hexdigest() # Start respond message msg = {"smiles": smiles, "hashkey": hashkey} # Check if calculation already exists if False: calculation = request.dbsession.query(models.GamessCalculation) \ .filter_by(hashkey=hashkey).first() if calculation is not None: calculation.created = datetime.datetime.now() return msg # Create new calculation calculation = models.GamessCalculation() # check if folder exists here = os.path.abspath(os.path.dirname(__file__)) + "/" datahere = here + "data/" if not os.path.isdir(datahere + hashkey): os.mkdir(datahere + hashkey) os.chdir(datahere + hashkey) # GAMESS DEBUG # TODO Add error messages when gamess fails # TODO add timeouts for all gamess calls # Optimize molecule gmsargs = { "scr": datahere + hashkey, "autoclean": True, "debug": False, } properties = gamess.calculate_optimize(molobj, **gmsargs) if properties is None: return { 'error': 'Error g-80 - gamess optimization error', 'message': "Error. Server was unable to optimize molecule" } print(smiles, list(properties.keys())) # Save and set coordinates coord = properties["coord"] calculation.coordinates = save_array(coord) calculation.enthalpy = properties["h"] cheminfo.molobj_set_coordinates(molobj, coord) # Optimization is finished, do other calculation async-like # Vibrate molecule vibheader = """ $basis gbasis=PM3 $end $contrl scftyp=RHF runtyp=hessian icharg={:} maxit=60 $end """ orbheader = """ $contrl coord=cart units=angs scftyp=rhf icharg={:} maxit=60 $end $basis gbasis=sto ngauss=3 $end """ solheader = """ $system mwords=125 $end $basis gbasis=PM3 $end $contrl scftyp=RHF runtyp=energy icharg={:} $end $pcm solvnt=water mxts=15000 icav=1 idisp=1 $end $tescav mthall=4 ntsall=60 $end """ headers = [vibheader, orbheader, solheader] readers = [ gamess.read_properties_vibration, gamess.read_properties_orbitals, gamess.read_properties_solvation ] def procfunc(conn, reader, *args, **kwargs): stdout, status = gamess.calculate(*args, **kwargs) try: properties = reader(stdout) except: # TODO Error reading properties properties = None conn.send(properties) conn.close() procs = [] conns = [] for header, reader in zip(headers, readers): parent_conn, child_conn = Pipe() p = Process(target=procfunc, args=(child_conn, reader, molobj, header), kwargs=gmsargs) p.start() procs.append(p) conns.append(parent_conn) for proc in procs: proc.join() properties_vib = conns[0].recv() properties_orb = conns[1].recv() properties_sol = conns[2].recv() if properties_vib is None: return { 'error': 'Error g-104 - gamess vibration error', 'message': "Error. Server was unable to vibrate molecule" } print(smiles, list(properties_vib.keys())) calculation.islinear = properties_vib["linear"] calculation.vibjsmol = properties_vib["jsmol"] calculation.vibfreq = save_array(properties_vib["freq"]) calculation.vibintens = save_array(properties_vib["intens"]) calculation.thermo = save_array(properties_vib["thermo"]) if properties_orb is None: return { 'error': 'Error g-128 - gamess orbital error', 'message': "Error. Server was unable to orbital the molecule" } print(smiles, list(properties_orb.keys())) calculation.orbitals = save_array(properties_orb["orbitals"]) calculation.orbitalstxt = properties_orb["stdout"] if properties_sol is None: return { 'error': 'Error g-159 - gamess solvation error', 'message': "Error. Server was unable to run solvation calculation" } # 'charges', 'solvation_total', 'solvation_polar', 'solvation_nonpolar', # 'surface', 'total_charge', 'dipole', 'dipole_total' print(smiles, list(properties_sol.keys())) charges = properties_sol["charges"] calculation.charges = save_array(charges) calculation.soltotal = properties_sol["solvation_total"] calculation.solpolar = properties_sol["solvation_polar"] calculation.solnonpolar = properties_sol["solvation_nonpolar"] calculation.solsurface = properties_sol["surface"] calculation.soldipole = save_array(properties_sol["dipole"]) calculation.soldipoletotal = properties_sol["dipole_total"] # GAMESS DEBUG os.chdir(here) # Saveable sdf and reset title sdfstr = cheminfo.molobj_to_sdfstr(molobj) sdfstr = str(sdfstr) for _ in range(2): i = sdfstr.index('\n') sdfstr = sdfstr[i + 1:] sdfstr = "\n\n" + sdfstr # Save mol2 fmt mol2 = cheminfo.molobj_to_mol2(molobj, charges=charges) calculation.mol2 = mol2 # Get a 2D Picture # TODO Compute 2D coordinates svgstr = cheminfo.molobj_to_svgstr(molobj, removeHs=True) # Success, setup database # calculation = models.GamessCalculation() calculation.smiles = smiles calculation.hashkey = hashkey calculation.sdf = sdfstr calculation.svg = svgstr calculation.created = datetime.datetime.now() # Add calculation to the database request.dbsession.add(calculation) # Add smiles to counter countobj = request.dbsession.query(models.Counter) \ .filter_by(smiles=smiles).first() if countobj is None: counter = models.Counter() counter.smiles = smiles counter.count = 1 request.dbsession.add(counter) else: countobj.count += 1 return msg
def delete_counter(self): models.Counter('Tag' + self.name).delete()
def get_counter(self): counter = models.Counter('Tag' + self.name) return counter
import models from app import app models.db.init_app(app) with app.app_context(): models.db.drop_all() models.db.create_all() q1 = models.Queue(name='First queue') q2 = models.Queue(name='Second queue') c11 = models.Counter(name='First queue, counter 1', queue=q1) c12 = models.Counter(name='First queue, counter 2', queue=q1) c21 = models.Counter(name='First queue, counter 1', queue=q2) c22 = models.Counter(name='First queue, counter 2', queue=q2) models.db.session.add_all([q1, q2, c11, c12, c21, c22]) models.db.session.commit() t11 = models.Ticket(queue=q1, queueId=q1.id) t11.pick_counter() t11.assign_number() models.db.session.add(t11) t12 = models.Ticket(queue=q1, queueId=q1.id) t12.pick_counter() t12.assign_number()