def _cleanup(self): ''' Ensure all data types are correctly assigned. ''' if self.element is not None: self.element = str(self.element) if self.x is not None: assert cast.is_numeric(self.x),\ "Error - x should be numeric." self.x = float(self.x) if self.y is not None: self.y = float(self.y) assert cast.is_numeric(self.x),\ "Error - y should be numeric." if self.z is not None: self.z = float(self.z) assert cast.is_numeric(self.x),\ "Error - z should be numeric." if self.index is not None: self.index = int(self.index) if self.molecule_index is not None: self.molecule_index = int(self.molecule_index) if self.label is not None: self.label = str(self.label) if self.charge is not None: self.charge = float(self.charge)
def parse_line(line): ''' Parse line inputs and assign to this object. **Parameters** line: *str* A string that holds a smooth parameter set. **Returns** None ''' line = line.strip().split() assert len(line) == 7,\ "Error - Invalid line to parse!" assert is_numeric(line[0]),\ "Error - Invalid line to parse!" smooth_index = int(line[0]) atom_i, atom_j = line[1:3] r_in, d_in, gcut = [float(v) for v in line[3:6]] pkg = [smooth_index, atom_i, atom_j] pkg += [r_in, d_in, gcut, str(line[6])] return pkg
def rotation_matrix(axis, theta, units="deg"): ''' Obtain a left multiplication rotation matrix, given the axis and angle you wish to rotate by. By default it assumes units of degrees. If theta is in radians, set units to rad. **Parameters** axis: *list, float* The axis in which to rotate around. theta: *float* The angle of rotation. units: *str, optional* The units of theta (deg or rad). **Returns** rotatation_matrix: *list, list, float* The left multiplication rotation matrix. **References** * http://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector/25709323#25709323 ''' cast.assert_vec(axis, length=3, numeric=True) axis = np.array(axis) assert cast.is_numeric(theta),\ "Error - Theta should be a numerical value (it is %s)." % str(theta) theta = float(theta) if "deg" in units.lower(): theta = np.radians(theta) return scipy.linalg.expm( np.cross(np.eye(3), axis / scipy.linalg.norm(axis) * theta))
def load_smrff(cls, parsed_file, pfile_name=None, restrict=None): ''' Given a parameter file, inport the smooth parameters if possible. **Parameters** parsed_file: *str* A parsed smrff parameter file input string (no comments or trailing white spaces) pfile_name: *str* The name of a parameter file to be parsed. If specified, then parsed_file is ignored (you may simply pass None as parsed_file). restrict: *list, str, optional* A list of atom labels to include when loading. If not specified, everything is loaded. **Returns** smooth_objs: *list,* :class:`squid.forcefields.sinSmooth.lr.SmoothSinInOut`, or *None* Returns a list of smooth objects if possible, else None. ''' import squid.forcefields.smrff as smrff_utils # Ensure correct parsed_file format, and that we even need to parse it. if pfile_name is not None: parsed_file = smrff_utils.parse_pfile(pfile_name) if SMOOTH_PFILE_ID not in parsed_file: return [] parsed_file = parsed_file[parsed_file.index(SMOOTH_PFILE_ID):] parsed_file = parsed_file[:parsed_file.index(END_ID)].split("\n")[1:-1] parsed_file = [ cls.parse_line(line) for line in parsed_file if is_numeric(line.split()[0]) and len(line.split()) == 9 ] return [ cls(smooth_index, atom_i, atom_j, r_in, d_in, gcut_in, r_out, d_out, gcut_out) for smooth_index, atom_i, atom_j, r_in, d_in, gcut_in, r_out, d_out, gcut_out in parsed_file if check_restriction(atom_i, restrict) and check_restriction(atom_j, restrict) ]
def parse_line(line): ''' Parse line inputs and assign to this object. **Parameters** line: *str* A string that holds a smooth parameter set. **Returns** None ''' line = line.strip().split() assert len(line) in [8, 11, 14],\ "Error - Invalid line to parse!" assert not is_numeric(line[0]),\ "Error - Invalid line to parse!" inout_index = None if len(line[0]) == 2: inout_index = int(line[0][1]) # To simplify getting things, pad line with Nones line = line + [None for i in range(14 - len(line))] smooth_index_1, smooth_index_2, atom_i, atom_j,\ r_1, d_1, gcut_1,\ r_2, d_2, gcut_2,\ r_3, d_3, gcut_3 = line[1:] f = lambda x: float(x) if x is not None else None i = lambda x: int(x) if x is not None else None return [ int(smooth_index_1), int(smooth_index_2), str(atom_i), str(atom_j), float(r_1), float(d_1), float(gcut_1), f(r_2), f(d_2), f(gcut_2), f(r_3), f(d_3), f(gcut_3), i(inout_index) ]
def get_job(s_flag, detail=0): ''' Get a list of all jobs currently on your queue. From this, only return the values that have s_flag in them. The *detail* variable can be used to specify how much information you want returned. **Parameters** s_flag: *str* A string to parse out job information with. detail: *int, optional* The amount of information you want returned. **Returns** all_jobs: *list* Depending on *detail*, you get the following: - *details* =0: *list, str* List of all jobs on the queue. - *details* =1: *list, tuple, str* List of all jobs on the queue as: (job name, time run, job status) - *details* =2: *list, tuple, str* List of all jobs on the queue as: (job name, time run, job status, queue, number of processors) ''' detail = int(detail) main_detail = detail if detail <= 0: detail = 1 # Get input from jlist as a string jlist_path = which("jlist") qlist_path = which("qlist") jshow_path = which("jshow") assert jlist_path is not None,\ "Error - Cannot find jlist." assert qlist_path is not None,\ "Error - Cannot find qlist." assert jshow_path is not None,\ "Error - Cannot find jshow." p = subprocess.Popen([jlist_path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = p.stdout.read().decode("utf-8") # Get data from string pattern = getpass.getuser() +\ '''[\s]+([\S]+)[\s]+([\S]+)[\s]+([\S]+)''' info = re.findall(pattern, output) # Get a list of names names = [] for a in info: names.append(a[0]) if len(names) > 0: out_ids = output.split("\n") out_ids = [ x.split()[0] for x in out_ids if len(x.split()) > 0 and is_numeric(x.split()[0]) ] info = [tuple(list(i) + [j]) for i, j in zip(info, out_ids)] # If user wants more information all_jobs = None if detail == 3: close_pipes(p) all_jobs = [i[-1] for i in info] elif detail == 2: for i, a in enumerate(info): p = subprocess.Popen([jshow_path, a[0]], stdout=subprocess.PIPE) s = p.stdout.read().decode("utf-8") serv = s[s.find('Queue name:'):].split()[2].strip() threads = 1 if "Slot Reservations" in s: threads = s[s.find('Slot Reservations'):].split()[4] threads = threads.strip() info[i] = info[i] + ( serv, threads, ) close_pipes(p) all_jobs = info if all_jobs is None: # Return appropriate information close_pipes(p) if detail == 1: all_jobs = info else: all_jobs = names job_indices = [i for i, j in enumerate(all_jobs) if s_flag in " ".join(j)] chosen_jobs = [all_jobs[i] for i in job_indices] if main_detail == 0: return [j[0] for j in chosen_jobs] else: return chosen_jobs
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=20, fill='+', buf=None, pad=False): ''' NOTE! THIS IS COPIED FROM STACK OVERFLOW (with minor changes), USER Greenstick Link: https://stackoverflow.com/a/34325723 Call in a loop to create terminal progress bar. **Parameters** iteration: *int* Current iteration. total: *int* Total number of iterations. prefix: *str, optional* Prefix for the loading bar. suffix: *str, optional* Suffix for the loading bar. decimals: *int, optional* Positive number of decimals in percent complete length: *int, optional* Character length of the loading bar. fill: *str, optional* Bar fill character. pad: *bool, optional* Whether to pad the right side with spaces until terminal width. ''' if buf is not None: if not hasattr(printProgressBar, "buf"): setattr(printProgressBar, "buf", buf) elif printProgressBar.buf < 0: printProgressBar.buf = buf else: printProgressBar.buf -= 1 return assert "stty" not in prefix and "stty" not in suffix,\ "Don't have 'stty' in prefix or suffix." assert is_numeric(total),\ "Error - total is not a numerical value." assert float(total) > 0,\ "Error - total is not greater than 0." assert is_numeric(iteration),\ "Error - iteration is not a numerical value." assert float(iteration) >= 0,\ "Error - iteration is less than 0." assert float(iteration) <= total,\ "Error - iteration is larger than total." percent = ("{0:." + str(decimals) + "f}").format( 100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) bar = '\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix) if pad: try: p = Popen("stty size".split(), stdout=PIPE, stderr=PIPE) cols, stderr = p.communicate() if stderr.strip() is not "": cols = 300 else: cols = int(cols.strip().split()[-1]) except IndexError: # This is a backup in the case that this code is # run on the queue or something. cols = 300 cols = max([cols, len(bar) + 1]) # Ensure we are always long enough bar = bar + "".join([" " for i in range(cols - len(bar))]) sys.stdout.write(bar) # Print New Line on Complete if iteration == total: sys.stdout.write('\n') sys.stdout.flush()