Ejemplo n.º 1
0
    def get_designs(
        self,
        name: Optional[str] = None,
        gql_filter: Optional[dict] = None,
    ) -> List[dict]:
        """Retrieves a list of designs summary.

        Args:
            name (str, optional):  Design's name to filter query. Defaults to None.

            gql_filter (dict, optional): GraphicQL filter dictionary. May be used to add additional filter \
                conditions. See api-docs. Defaults to None.

        Returns:
            List[dict]: A list of designs info. Each dict in the list contains name and id of each design.
        """
        # Prepare parameters
        args: Dict[str, Any] = {'gqlFilter': {}}
        if name is not None:
            args['gqlFilter']['name'] = name
        if gql_filter is not None:
            args['gqlFilter'].update(gql_filter)
        # Param gqlFilter should be a json string
        args['gqlFilter'] = json.dumps(args['gqlFilter'])
        # Make request and process output
        response = get(url=self.get_designs_url,
                       headers=self.headers,
                       params=args)
        out = json.loads(response['content'])
        # Remove useless key
        for el in out:
            el.pop('__typename')
        return out
Ejemplo n.º 2
0
    def rbs_calculator_organisms(
        self,
        as_dataframe: bool = True,
    ) -> Union[pd.DataFrame, Dict[str, Any]]:
        """Fetches all available organisms or host supported by the RBS Calculator tools.

        Args:
            as_dataframe(bool): Whether to return the response as a dataframe.

        Returns:
            List[Dict[str, str]]: A list of all the available organisms/hosts with their names and NCBI Accession IDs.
        """
        try:
            result = get(
                url=self.rbs_calculator_organisms_url,
                headers=self.headers,
            )
        except Exception as e:
            return {
                'error': e,
            }

        result = json.loads(result['content'])
        result = pd.DataFrame(result) if as_dataframe else result

        return result
Ejemplo n.º 3
0
 def get_codon_optimization_job_results(
     self,
     job_id,
 ):
     response = get(url=f'{self.get_codon_op_result}/{job_id}',
                    headers=self.headers)
     # params=args)
     return json.loads(response['content'])
Ejemplo n.º 4
0
    def get_current_user(self):  # -> CurrentUser
        """Gets the current user based on the header token.

        Returns:
            ( ): The current user.
        """
        # TODO : implement a method to get the expiration date of the current token
        response = get(url=self.auth_url, headers=self.headers)
        response['content'] = json.loads(response['content'])

        return response
Ejemplo n.º 5
0
    def get_multi_objective_optimization(
            self,
            taskId: TaskID,  # noqa: N803
    ) -> Any:
        response = get(
            url=self.get_multi_objective_optimization_url.format(taskId),
            headers=self.headers,
        )

        response['content'] = json.loads(response['content'])
        return response['content']
Ejemplo n.º 6
0
    def get_plates(
        self,
        pageNumber: str | int = '1',  # noqa: N803,
        pageSize: str | int = DEFAULT_PAGE_SIZE,
        sort: str = '-updatedAt',
        gqlFilter: str = '',
    ) -> List[PlateLibraryRecord]:
        """This paged entrypoint returns sets of plates.

        Args:
            pageNumber (str): 1 based paging parameter. Default: `"1"`.

            pageSize (str): Number of records to return in a page. Default: `"100"`.

            sort (str): sort column, default is id. Default: `"-updatedAt"`.

            gqlFilter (str): A `graphql` filter to apply to the data. Example:

        ```GraphQL
                { "name" : ["Plate1", "Plate2"] } or { "id": ["1", "10", "22"]}
        ```

        Returns:
            List[PlateLibraryRecord]: List of plate records.

        Example:
            >>> # To query results by a specific field such as an `id`, use the `gqlFilter` parameter.
            >>> import json
            >>> plate_id: PlateID = "...."  # NOTE: Replace with a valid id.
            >>> gqlFilter: str = json.dumps({'id': str(plate_id)})
            ...
            >>> # To query results by a specific field such as an `name`, use the `gqlFilter` parameter.
            >>> import json
            >>> plate_name: str = 'my_plate'  # NOTE: Replace with a valid name.
            >>> gqlFilter: str = json.dumps({'name': str(plate_name)})
            ...
        """
        params: GetPlatesQueryParams = {
            'pageNumber': str(pageNumber),
            'pageSize': str(pageSize),
            'sort': sort,
            'gqlFilter': gqlFilter,
        }

        response = get(
            url=self.plates_url,
            headers=self.headers,
            params=params,
        )

        assert response['content'] is not None, 'No content in response'

        return cast(List[PlateLibraryRecord], json.loads(response['content']))
Ejemplo n.º 7
0
    def get_laboratories(self) -> List[Laboratory]:
        """Get all available laboratories for the current user.

        Returns :
            (List[Laboratory]): A list of laboratories objects.
        """
        response = get(url=self.labs_url, headers=self.headers)

        # response["content"] = [{"id" : str, "name": str}, ...]
        response['content'] = json.loads(response['content'])

        return response['content']
Ejemplo n.º 8
0
    def get_server_status(self) -> str:
        """Gets the current Server Status.

        Returns:
            str: The current Server Status.
        """
        # NOTE: Response Schema is text/html
        response = get(
            url=self.status_url,
            params=None,
            headers=self.headers,
        )

        return response['content']
Ejemplo n.º 9
0
    def rbs_calculator_status(self) -> dict:
        """Checks the status of the RBS Calculator Integration API.

        Returns:
            dict: {authenticated: boolean, success: boolean}
        """
        try:
            result = get(url=self.rbs_calculator_status_url,
                         headers=self.headers)
        except Exception as e:
            return {
                'error': e,
            }

        return result['content']
Ejemplo n.º 10
0
    def get_aliquots(
        self,
        pageNumber: str | int = '1',  # noqa: N803
        pageSize: str | int = DEFAULT_PAGE_SIZE,
        sort: str = '-updatedAt',
        gqlFilter: str = '',
    ) -> List[AliquotRecord]:
        """This is a paged entrypoint for returning many aliquot records.

        Args:
            pageNumber (str): 1 based paging parameter. Default: `"1"`.

            pageSize (str): size of each page returned. Default: `"100"`.

            sort (str): field to sort on, default is id. Default: `"-updatedAt"`.

            gqlFilter (str): A `graphql` filter to apply to the data. Example:

        ```GraphQL
                { "sample.material.name" : ["PCR53.1", "Sequence2"] } or { "id": ["1", "10", "22"] }
        ```

        Returns:
            List[AliquotRecord]: List of aliquot records.

        Example:
            >>> # To query results by a specific field such as an `id`, use the `gqlFilter` parameter.
            >>> import json
            >>> aliquot_id: AliquotID = 1  # NOTE: Replace with a valid id.
            >>> gqlFilter: str = json.dumps({'id': str(aliquot_id)})
            ...
        """
        params: GetAliquotsQueryParams = {
            'pageNumber': str(pageNumber),
            'pageSize': str(pageSize),
            'sort': str(sort),
            'gqlFilter': str(gqlFilter),
        }

        response = get(
            url=self.aliquots_url,
            headers=self.headers,
            params=params,
        )

        assert response['content'] is not None, 'No content in response'

        return cast(List[AliquotRecord], json.loads(response['content']))
Ejemplo n.º 11
0
    def get_aliquot(
        self,
        aliquot_id: AliquotID,
    ) -> AliquotRecord:
        """This function returns a single aliquot record.

        Args:
            aliquot_id (str): The id of the aliquot record you want to retrieve.

        Returns:
            AliquotRecord: Aliquot record.

        Raises:
            AliquotNotFoundError: If the aliquot record is not found.
        """
        output_aliquot: AliquotRecord | None = None

        try:
            url: str = self.aliquot_url.format(str(aliquot_id))
            response: ResponseDict = get(
                url=url,
                headers=self.headers,
            )
            assert response['content'] is not None  # noqa: S101
            output_aliquot = cast(AliquotRecord,
                                  json.loads(response['content']))

        except Exception as _exc:
            # fallback to bruteforce if an error occurs

            # NOTE: Since when using a method to get a single record, the user only have control over the id parameter,
            #       we can't use the same parameters as for the method to get many records. So, we choose to use the
            #       default parameters for the method to get many records.
            #       Except for the `gqlFilter` parameter, which is used for efficient querying.
            get_records = wrapped_partial(self.get_aliquots,
                                          gqlFilter=json.dumps(
                                              {'id': str(aliquot_id)}))

            output_aliquot = get_record(
                get_records=get_records,
                record_id=aliquot_id,
            )

            if output_aliquot is None:
                raise AliquotNotFoundError(
                    f'Aliquot {aliquot_id} not found.') from _exc

        return output_aliquot
Ejemplo n.º 12
0
    def _design_crispr_grnas_get_result(
        self,
        task_id: TaskID,
    ):
        """Gets results from a design_crispr_grnas process.

        Args:
            task_id (TaskID): Process id

        Returns:
            dict: status of the process and, if finished, guides information  as described in `design_crispr_grnas`.
        """
        response = get(url=self.crispr_guide_rnas_result_url.format(task_id),
                       headers=self.headers)

        return json.loads(response['content'])
Ejemplo n.º 13
0
    def get_dna_sequences(
        self,
        name: str,
    ) -> List[dict]:
        """Get all sequences which names matches a string.

        Args:
            name (str): name of sequences to download

        Returns:
            List[dict]: List of dicts with sequence data.
        """
        args = {'name': name}
        response = get(url=self.export_dna_sequences_url,
                       headers=self.headers,
                       params=args)
        return json.loads(response['content'])
Ejemplo n.º 14
0
    def get_task(
        self,
        task_id: TaskID,
    ) -> Any:
        """Returns the status of a task based on the Task ID.

        Args:
            task_id (TaskID): The task id that wants to be canceled.

        Returns: A task object with task metadata including its ID and status.
        """
        response = get(
            url=self.get_task_url.format(task_id),
            headers=self.headers,
        )

        return json.loads(response['content'])
Ejemplo n.º 15
0
    def get_design(
        self,
        design_id: Union[int, str],
    ) -> dict:
        """Retrieves the design with specified id.

        Raises error if design_id is not found

        Args:
            design_id (str, int):  Design's id

        Returns:
            dict: A dict containing designs information
        """
        response = get(url=f'{self.get_design_url}/{design_id}',
                       headers=self.headers)
        # params=args)

        return json.loads(response['content'])
Ejemplo n.º 16
0
    def get_dna_sequence(
        self,
        seq_id: int,
        out_format: str = 'json',
        out_filepath: Optional[str] = None,
    ) -> Union[str, dict]:
        """Gets full sequence record from its ID.

        Args:
            seq_id (int): Sequence id (can be found within the sequence detail url at UI)

            out_format (str, optional): Output format. Use 'json' and the method will return a dict and 'fasta', or \
                'genbank' to return a string based on those formats. This also determines the output format when \
                writing an output file. Defaults to 'json'.

            out_filepath (Optional[str], optional): Path to output file. If None it will not create any file. \
                Defaults to None.

        Raises:
            ValueError: If format not available

        Returns:
            Union[str, dict]: A dict object with json data or a string if another format is chosen.
        """
        if out_format not in self.ALLOWED_SEQ_FORMATS:
            raise ValueError(
                f'Format {out_format} not in {self.ALLOWED_SEQ_FORMATS}')
        url = urljoin(self.export_dna_sequence_url, f'{out_format}/{seq_id}')
        response = get(url=url, headers=self.headers)
        # Write output file
        if out_filepath is not None:
            with open(out_filepath, 'w') as f:
                f.write(response['content'])
        # Parse json
        if out_format == 'json':
            response['content'] = json.loads(response['content'])
        # Finish
        return response['content']
Ejemplo n.º 17
0
    def get_api_info(self) -> str:
        """Gets the current info about CLI API.

        NOTE : To get the info, the client should be already authorized.

        Returns:
            (str): The current info about API.
        """
        try:
            response = get(
                url=self.info_url,
                headers=self.headers,
            )

        except Exception as e:
            # TODO: Verify if we need to raise an exception.
            response = ParsedJSONResponse(
                url=self.info_url,
                content=str(e),
                status=False,
            )

        return response['content']
Ejemplo n.º 18
0
    def get_plate(self, plate_id: str) -> PlateRecord:
        """This function returns a single plate by id.

        Args:
            plate_id (PlateID): The id of the plate to return.

        Returns:
            PlateRecord: Plate record.

        Raises:
            RecordNotFoundError: If the plate record is not found.
        """
        output_plate: PlateRecord | None = None

        url: str = self.plate_url.format(plate_id)
        response: ResponseDict = get(
            url=url,
            headers=self.headers,
        )
        assert response['content'] is not None  # noqa: S101
        output_plate = cast(PlateRecord, json.loads(response['content']))

        return output_plate
Ejemplo n.º 19
0
    def rbs_calculator_get_jobs(
        self,
        job_id: str = None,
    ) -> dict:
        """Fetches an RBS Calculator Job with the provided job_id.

        Args:
            job_id (str): ID of an RBS Calculator Job

        Returns:
            dict: {authenticated: boolean, success: boolean}
        """
        try:
            result = get(
                url=self.rbs_calculator_job_url.format(job_id)
                if job_id is not None else self.rbs_calculator_jobs_url,
                headers=self.headers,
            )
        except Exception as e:
            return {
                'error': e,
            }

        return result['content']
Ejemplo n.º 20
0
    def export_aa_sequence(
        self,
        aa_sequence_id: str,
        format: str = 'JSON',
    ):
        """This functions exports one amino acid sequence from TeselaGen DESIGN Module.

        It requires the TeselaGen amino acid sequence ID.

        Args:
            aa_sequence_id(int): This is an integer ID corresponding to the TeselaGen amino acid sequence ID.

            format(str): This is the format in which the amino acid sequence will be parsed into.
                Available formats are:
                    - JSON (teselagen specific)
                    - FASTA
                    - GENBANK

        Returns:
            (Any): Amino acid sequence information depending on the format chosen. The 'JSON' format will provide the following properties:

                - id: Amino acid sequence DESIGN ID.
                - name: Amino acid sequence name.
                - size: Number of residues for the amino acid sequence.
                - molecularWeight: Teselagen calculated molecular weight of the amino acid sequence.
                - extinctioCoefficient: Teselagen calculated extinction coefficient of the amino acid sequence.
                - proteinSequence: String with the amino acid sequence.
                - createdAt: Date in which the amino acid sequence record was created in TeselaGen.
                - createdAt: Date in which the amino acid sequence record was last updated in TeselaGen.
                - regionAnnotations: Teselagen region annotations (optional).
                - isoPoint: Sequence isoelectric point (optional).
                - uniprotId: UniProt ID for the amino acid sequence (optional).
                - tags: any TeselaGen tags with which the amino acid sequence has been tagged (optional).
        """
        if not isinstance(aa_sequence_id, str):
            raise ValueError(
                f"Argument 'aa_sequence_id' must be of type 'str', but received type '{type(aa_sequence_id)}'."
            )

        if format not in SUPPORTED_AA_EXPORT_FORMATS:
            raise ValueError(
                "Argument 'format' can only be one of this three strings: JSON, FASTA or GENBANK."
            )

        try:
            result = get(url=self.export_aa_url.format(format, aa_sequence_id),
                         headers=self.headers)
        except Exception as e:
            return e

        if format == 'JSON':
            parsed_response = json.loads(result['content'])
            formatted_response = {
                'id':
                parsed_response['id'],
                'name':
                parsed_response['name'],
                'isoPoint':
                parsed_response['isoPoint'],
                'uniprotId':
                parsed_response['uniprotId'],
                'size':
                parsed_response['size'],
                'molecularWeight':
                parsed_response['molecularWeight'],
                'extinctionCoefficient':
                parsed_response['extinctionCoefficient'],
                'proteinSequence':
                parsed_response['proteinSequence'],
                'regionAnnotations':
                parsed_response['regionAnnotations'],
                'tags':
                list(
                    map(
                        lambda x: {
                            'id': x['tag']['id'],
                            'name': x['tag']['name'],
                        }, parsed_response['taggedItems'])),
                'createdAt':
                parsed_response['createdAt'],
                'updatedAt':
                parsed_response['updatedAt'],
            }
        else:
            formatted_response = result['content']

        return formatted_response