Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Literal-types #2261

Merged
merged 2 commits into from
Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@

import json
import os
import sys
import warnings
from typing import List, Literal, Tuple, Union
from typing import List, Tuple, Union

import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -39,6 +40,11 @@
from pymatgen.util.plotting import pretty_plot
from pymatgen.util.string import htmlify, latexify

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

__author__ = "Yihan Xiao, Matthew McDermott"
__maintainer__ = "Matthew McDermott"
__email__ = "[email protected]"
Expand Down
8 changes: 7 additions & 1 deletion pymatgen/analysis/magnetism/jahnteller.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@


import os
import sys
import warnings
from typing import Any, Dict, Literal, Optional, Tuple, Union, cast
from typing import Any, Dict, Optional, Tuple, Union, cast

import numpy as np

Expand All @@ -22,6 +23,11 @@
from pymatgen.core.structure import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

MODULE_DIR = os.path.dirname(os.path.abspath(__file__))


Expand Down
7 changes: 6 additions & 1 deletion pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import math
import os
import re
import sys
from functools import lru_cache
from typing import Literal

import numpy as np
import plotly.graph_objs as go
Expand All @@ -30,6 +30,11 @@
from pymatgen.util.plotting import pretty_plot
from pymatgen.util.string import htmlify, latexify

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

logger = logging.getLogger(__name__)

with open(os.path.join(os.path.dirname(__file__), "..", "util", "plotly_pd_layouts.json")) as f:
Expand Down
8 changes: 7 additions & 1 deletion pymatgen/analysis/xas/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
This module defines classes to represent all xas and stitching methods
"""
import math
import sys
import warnings
from typing import List, Literal
from typing import List

import numpy as np
from scipy.interpolate import interp1d
Expand All @@ -16,6 +17,11 @@
from pymatgen.core.spectrum import Spectrum
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

__author__ = "Chen Zheng, Yiming Chen"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "3.0"
Expand Down
8 changes: 7 additions & 1 deletion pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,26 @@
import ast
import json
import re
import sys
import warnings
from collections import Counter
from enum import Enum
from io import open
from itertools import combinations, product
from pathlib import Path
from typing import Callable, Dict, List, Literal, Optional, Tuple, Union
from typing import Callable, Dict, List, Optional, Tuple, Union

import numpy as np
from monty.json import MSONable

from pymatgen.core.units import SUPPORTED_UNIT_NAMES, FloatWithUnit, Length, Mass, Unit
from pymatgen.util.string import Stringify, formula_double_format

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

# Loads element data from json file
with open(str(Path(__file__).absolute().parent / "periodic_table.json"), "rt") as f:
_pt_data = json.load(f)
Expand Down
14 changes: 10 additions & 4 deletions pymatgen/core/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
x y value pairs.
"""

from typing import Callable, List, Literal, Union
import sys
from typing import Callable, List, Union

import numpy as np
from monty.json import MSONable
Expand All @@ -17,6 +18,11 @@
from pymatgen.util.coord import get_linear_interpolated_value
from pymatgen.util.typing import ArrayLike

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal


def lorentzian(x, x_0: float = 0, sigma: float = 1.0):
"""
Expand Down Expand Up @@ -79,9 +85,9 @@ def normalize(self, mode: Literal["max", "sum"] = "max", value: float = 1.0):
Normalize the spectrum with respect to the sum of intensity

Args:
mode ("max" | "sum"): Normalization mode. Supported modes are "max" (set
the max y value to value, e.g., in XRD patterns), "sum" (set the
sum of y to a value, i.e., like a probability density).
mode ("max" | "sum"): Normalization mode. "max" sets the max y value to value,
e.g., in XRD patterns. "sum" sets the sum of y to a value, i.e., like a
probability density.
value (float): Value to normalize to. Defaults to 1.
"""
if mode.lower() == "sum":
Expand Down
24 changes: 21 additions & 3 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,23 @@
import os
import random
import re
import sys
import warnings
from abc import ABCMeta, abstractmethod
from fnmatch import fnmatch
from typing import Any, Callable, Dict, Iterable, Iterator, List, Literal, Optional, Sequence, Set, Tuple, Union
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
)

import numpy as np
from monty.dev import deprecated
Expand All @@ -37,6 +50,11 @@
from pymatgen.util.coord import all_distances, get_angle, lattice_points_in_supercell
from pymatgen.util.typing import ArrayLike, CompositionLike, SpeciesLike

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal


class Neighbor(Site):
"""
Expand Down Expand Up @@ -2116,13 +2134,13 @@ def to_s(x):
)
return "\n".join(outs)

def get_orderings(self, mode: str = "enum", **kwargs) -> List["Structure"]:
def get_orderings(self, mode: Literal["enum", "sqs"] = "enum", **kwargs) -> List["Structure"]:
r"""
Returns list of orderings for a disordered structure. If structure
does not contain disorder, the default structure is returned.

Args:
mode (str): Either "enum" or "sqs". If enum,
mode ("enum" | "sqs"): Either "enum" or "sqs". If enum,
the enumlib will be used to return all distinct
orderings. If sqs, mcsqs will be used to return
an sqs structure.
Expand Down
14 changes: 10 additions & 4 deletions pymatgen/entries/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,21 @@
and PDEntry inherit from this class.
"""

import sys
from abc import ABCMeta, abstractmethod
from numbers import Number
from typing import Dict, Literal, Union
from typing import Dict, Union

import numpy as np
from monty.json import MSONable

from pymatgen.core.composition import Composition

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

__author__ = "Shyue Ping Ong, Anubhav Jain, Ayush Gupta"
__copyright__ = "Copyright 2020, The Materials Project"
__version__ = "1.1"
Expand Down Expand Up @@ -111,16 +117,16 @@ def normalize(self, mode: Literal["formula_unit", "atom"] = "formula_unit") -> "

return self.from_dict(new_entry_dict)

def _normalization_factor(self, mode: str = "formula_unit") -> float:
def _normalization_factor(self, mode: Literal["formula_unit", "atom"] = "formula_unit") -> float:
# NOTE here we use composition rather than _composition in order to ensure
# that we have the expected behaviour downstream in cases where composition
# that we have the expected behavior downstream in cases where composition
# is overwritten (GrandPotPDEntry, TransformedPDEntry)
if mode == "atom":
factor = self.composition.num_atoms
elif mode == "formula_unit":
factor = self.composition.get_reduced_composition_and_factor()[1]
else:
raise ValueError("`{}` is not an allowed option for normalization".format(mode))
raise ValueError(f"{mode=} is not an allowed option for normalization")

return factor

Expand Down
8 changes: 7 additions & 1 deletion pymatgen/entries/computed_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
import abc
import json
import os
import sys
import warnings
from itertools import combinations
from typing import Dict, List, Literal, Union
from typing import Dict, List, Union

import numpy as np
from monty.json import MontyDecoder, MontyEncoder, MSONable
Expand All @@ -26,6 +27,11 @@
from pymatgen.core.structure import Structure
from pymatgen.entries import Entry

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

__author__ = "Ryan Kingsbury, Matt McDermott, Shyue Ping Ong, Anubhav Jain"
__copyright__ = "Copyright 2011-2020, The Materials Project"
__version__ = "1.1"
Expand Down
Loading