Ejemplo n.º 1
0
    def get_employee(self, employee_id, field_list=None):
        """
        API method for returning a single employee based on employee id.
        http://www.bamboohr.com/api/documentation/employees.php#getEmployee

        @param employee_id: String of the employee id.
        @param field_list: List of fields to return with the employee dictionary.
        @return: A dictionary containing employee information from the specified field list.
        """
        get_fields = []

        field_list = [utils.underscore_to_camelcase(field) for field in field_list] if field_list else None

        if field_list:
            for f in field_list:
                get_fields.append(f)
        else:
            for field in self.employee_fields:
                get_fields.append(field)

        payload = {
            'fields': ",".join(get_fields)
        }

        url = self.base_url + "employees/{0}".format(employee_id)
        r = requests.get(url, headers=self.headers, params=payload, auth=(self.api_key, 'x'))
        r.raise_for_status()

        employee = r.json()

        if self.underscore_keys:
            employee = utils.underscore_keys(employee)

        return employee
Ejemplo n.º 2
0
    def request_custom_report(self, field_list, report_format='xls', title="My Custom Report", output_filename=None):
        """
        API method for returning a custom report by field list.
        http://www.bamboohr.com/api/documentation/employees.php#requestCustomReport
        Success Response: 200
        The report will be generated in the requested format.
        The HTTP Content-type header will be set with the mime type for the response.

        @param fields: List of report fields
        @param report_format: String of the format to receive the report. (csv, pdf, xls, xml)
        @param output_filename: String (optional) if a filename/location is passed, the results will be saved to disk
        @return: A result in the format specified. (Will vary depending on format requested.)
        """
        report_formats = self.report_formats
        report_formats.pop('json')

        if report_format not in report_formats:
            raise UserWarning("You requested an invalid report type. Valid values are: {0}".format(','.join([k for k in report_formats])))

        get_fields = []
        field_list = [underscore_to_camelcase(field) for field in field_list] if field_list else None
        if field_list:
            for f in field_list:
                if not self.employee_fields.get(f):
                    raise UserWarning("You passed in an invalid field")
                else:
                    get_fields.append(f)
        else:
            for field in self.employee_fields:
                get_fields.append(field)

        xml = self._format_report_xml(get_fields, title=title, report_format=report_format)
        url = self.base_url + "reports/custom/?format={0}".format(report_format)
        r = requests.post(url, data=xml, headers=self.headers, auth=(self.api_key, ''))
        r.raise_for_status()

        if report_format == 'json':
            # return list/dict for json type
            result = r.json()
        elif report_format in ('csv', 'xml'):
            # return text for csv type
            result = r.text
        else:
            # return requests object for everything else after saving the file to the location specified.
            result = r

        if output_filename:
            with open(output_filename, 'wb') as handle:
                for block in r.iter_content(1024):
                    if not block:
                        break
                    handle.write(block)

        return result
Ejemplo n.º 3
0
    def _parserBodyCommand(self, body, delimiter='|'):
        output = {}

        if body:
            tmp = body.splitlines()
        if len(tmp) > 0:
            header = tmp[0].split(delimiter)

        for l in tmp[1:-1]:
            line = l.split(delimiter)
            if len(line) < len(header):
                continue
            i = 0
            tmp_dict = {}
            for e in line:
                tmp_dict[utils.underscore_to_camelcase(header[i])] = e
                i = i + 1
            output[line[0]] = tmp_dict

        return output
Ejemplo n.º 4
0
    def _parserBodyCommand(self, body, delimiter='|'):
        output = {}

        if body:
            tmp = body.splitlines()
        if len(tmp) > 0:
            header = tmp[0].split(delimiter)

        for l in tmp[1:-1]:
            line = l.split(delimiter)
            if len(line) < len(header):
                continue
            i = 0
            tmp_dict = {}
            for e in line:
                tmp_dict[utils.underscore_to_camelcase(header[i])] = e
                i = i + 1
            output[line[0]] = tmp_dict

        return output
Ejemplo n.º 5
0
def prepare_phase(positions_file_path,
                  topology_file_path,
                  ligand_dsl,
                  system_options,
                  gromacs_include_dir=None,
                  verbose=False):
    """Create a Yank arguments for a phase from system files.

    Parameters
    ----------
    positions_file_path : str
        Path to system position file (e.g. 'complex.inpcrd' or 'complex.gro').
    topology_file_path : str
        Path to system topology file (e.g. 'complex.prmtop' or 'complex.top').
    ligand_dsl : str
        MDTraj DSL string that specify the ligand atoms.
    system_options : dict
        system_options[phase] is a a dictionary containing options to pass to createSystem().
    gromacs_include_dir : str, optional
        Path to directory in which to look for other files included from the gromacs top file.
    verbose : bool
        Whether or not to log information (default is False).

    Returns
    -------
    alchemical_phase : AlchemicalPhase
        The alchemical phase for Yank calculation with unspecified name, and protocol.

    """
    # Load system files
    if os.path.splitext(topology_file_path)[1] == '.prmtop':
        # Read Amber prmtop and inpcrd files
        if verbose:
            logger.info("prmtop: %s" % topology_file_path)
            logger.info("inpcrd: %s" % positions_file_path)
        topology_file = openmm.app.AmberPrmtopFile(topology_file_path)
        positions_file = openmm.app.AmberInpcrdFile(positions_file_path)
        box_vectors = positions_file.boxVectors
        create_system_args = set(
            inspect.getargspec(openmm.app.AmberPrmtopFile.createSystem).args)
    else:
        # Read Gromacs top and gro files
        if verbose:
            logger.info("top: %s" % topology_file_path)
            logger.info("gro: %s" % positions_file_path)

        positions_file = openmm.app.GromacsGroFile(positions_file_path)
        box_vectors = positions_file.getPeriodicBoxVectors()
        topology_file = openmm.app.GromacsTopFile(
            topology_file_path,
            periodicBoxVectors=box_vectors,
            includeDir=gromacs_include_dir)
        create_system_args = set(
            inspect.getargspec(openmm.app.GromacsTopFile.createSystem).args)

    # Prepare createSystem() options
    # OpenMM adopts camel case convention so we need to change the options format.
    # Then we filter system options according to specific createSystem() args
    system_options = {
        utils.underscore_to_camelcase(key): value
        for key, value in system_options.items()
    }
    system_options = {
        arg: system_options[arg]
        for arg in create_system_args if arg in system_options
    }

    # Determine if this will be an explicit or implicit solvent simulation.
    if box_vectors is not None:
        is_periodic = True
    else:
        is_periodic = False

    # Adjust nonbondedMethod
    # TODO: Ensure that selected method is appropriate.
    if 'nonbondedMethod' not in system_options:
        if is_periodic:
            system_options['nonbondedMethod'] = openmm.app.CutoffPeriodic
        else:
            system_options['nonbondedMethod'] = openmm.app.NoCutoff

    # Check for solvent configuration inconsistencies
    # TODO: Check to make sure both files agree on explicit/implicit.
    err_msg = ''
    if is_periodic:
        if 'implicitSolvent' in system_options:
            err_msg = 'Found periodic box in inpcrd file and implicitSolvent specified.'
        if system_options['nonbondedMethod'] == openmm.app.NoCutoff:
            err_msg = 'Found periodic box in inpcrd file but nonbondedMethod is NoCutoff'
    else:
        if system_options['nonbondedMethod'] != openmm.app.NoCutoff:
            err_msg = 'nonbondedMethod is NoCutoff but could not find periodic box in inpcrd.'
    if len(err_msg) != 0:
        logger.error(err_msg)
        raise RuntimeError(err_msg)

    # Create system and update box vectors (if needed)
    system = topology_file.createSystem(removeCMMotion=False, **system_options)
    if is_periodic:
        system.setDefaultPeriodicBoxVectors(*box_vectors)

    # Store numpy positions
    positions = positions_file.getPositions(asNumpy=True)

    # Check to make sure number of atoms match between prmtop and inpcrd.
    topology_natoms = system.getNumParticles()
    positions_natoms = positions.shape[0]
    if topology_natoms != positions_natoms:
        err_msg = "Atom number mismatch: {} has {} atoms; {} has {} atoms.".format(
            topology_file_path, topology_natoms, positions_file_path,
            positions_natoms)
        logger.error(err_msg)
        raise RuntimeError(err_msg)

    # Find ligand atoms and receptor atoms
    atom_indices = find_components(system, topology_file.topology, ligand_dsl)

    alchemical_phase = AlchemicalPhase('', system, topology_file.topology,
                                       positions, atom_indices, None)
    return alchemical_phase
Ejemplo n.º 6
0
def prepare_phase(positions_file_path, topology_file_path, ligand_dsl, system_options,
                  gromacs_include_dir=None, verbose=False):
    """Create a Yank arguments for a phase from system files.

    Parameters
    ----------
    positions_file_path : str
        Path to system position file (e.g. 'complex.inpcrd' or 'complex.gro').
    topology_file_path : str
        Path to system topology file (e.g. 'complex.prmtop' or 'complex.top').
    ligand_dsl : str
        MDTraj DSL string that specify the ligand atoms.
    system_options : dict
        system_options[phase] is a a dictionary containing options to pass to createSystem().
    gromacs_include_dir : str, optional
        Path to directory in which to look for other files included from the gromacs top file.
    verbose : bool
        Whether or not to log information (default is False).

    Returns
    -------
    alchemical_phase : AlchemicalPhase
        The alchemical phase for Yank calculation with unspecified name, and protocol.

    """
    # Load system files
    if os.path.splitext(topology_file_path)[1] == '.prmtop':
        # Read Amber prmtop and inpcrd files
        if verbose:
            logger.info("prmtop: %s" % topology_file_path)
            logger.info("inpcrd: %s" % positions_file_path)
        topology_file = openmm.app.AmberPrmtopFile(topology_file_path)
        positions_file = openmm.app.AmberInpcrdFile(positions_file_path)
        box_vectors = positions_file.boxVectors
        create_system_args = set(inspect.getargspec(openmm.app.AmberPrmtopFile.createSystem).args)
    else:
        # Read Gromacs top and gro files
        if verbose:
            logger.info("top: %s" % topology_file_path)
            logger.info("gro: %s" % positions_file_path)

        positions_file = openmm.app.GromacsGroFile(positions_file_path)
        box_vectors = positions_file.getPeriodicBoxVectors()
        topology_file = openmm.app.GromacsTopFile(topology_file_path,
                                                  periodicBoxVectors=box_vectors,
                                                  includeDir=gromacs_include_dir)
        create_system_args = set(inspect.getargspec(openmm.app.GromacsTopFile.createSystem).args)

    # Prepare createSystem() options
    # OpenMM adopts camel case convention so we need to change the options format.
    # Then we filter system options according to specific createSystem() args
    system_options = {utils.underscore_to_camelcase(key): value
                      for key, value in system_options.items()}
    system_options = {arg: system_options[arg] for arg in create_system_args
                      if arg in system_options}

    # Determine if this will be an explicit or implicit solvent simulation.
    if box_vectors is not None:
        is_periodic = True
    else:
        is_periodic = False

    # Adjust nonbondedMethod
    # TODO: Ensure that selected method is appropriate.
    if 'nonbondedMethod' not in system_options:
        if is_periodic:
            system_options['nonbondedMethod'] = openmm.app.CutoffPeriodic
        else:
            system_options['nonbondedMethod'] = openmm.app.NoCutoff

    # Check for solvent configuration inconsistencies
    # TODO: Check to make sure both files agree on explicit/implicit.
    err_msg = ''
    if is_periodic:
        if 'implicitSolvent' in system_options:
            err_msg = 'Found periodic box in inpcrd file and implicitSolvent specified.'
        if system_options['nonbondedMethod'] == openmm.app.NoCutoff:
            err_msg = 'Found periodic box in inpcrd file but nonbondedMethod is NoCutoff'
    else:
        if system_options['nonbondedMethod'] != openmm.app.NoCutoff:
            err_msg = 'nonbondedMethod is NoCutoff but could not find periodic box in inpcrd.'
    if len(err_msg) != 0:
        logger.error(err_msg)
        raise RuntimeError(err_msg)

    # Create system and update box vectors (if needed)
    system = topology_file.createSystem(removeCMMotion=False, **system_options)
    if is_periodic:
        system.setDefaultPeriodicBoxVectors(*box_vectors)

    # Store numpy positions
    positions = positions_file.getPositions(asNumpy=True)

    # Check to make sure number of atoms match between prmtop and inpcrd.
    topology_natoms = system.getNumParticles()
    positions_natoms = positions.shape[0]
    if topology_natoms != positions_natoms:
        err_msg = "Atom number mismatch: {} has {} atoms; {} has {} atoms.".format(
            topology_file_path, topology_natoms, positions_file_path, positions_natoms)
        logger.error(err_msg)
        raise RuntimeError(err_msg)

    # Find ligand atoms and receptor atoms
    atom_indices = find_components(system, topology_file.topology, ligand_dsl)

    alchemical_phase = AlchemicalPhase('', system, topology_file.topology,
                                       positions, atom_indices, None)
    return alchemical_phase