Source code for torch._logging._internal
import functools
import itertools
import logging
import os
import re
from dataclasses import dataclass, field
from importlib import __import__
from typing import Dict, Optional, Set, Union
from weakref import WeakSet
log = logging.getLogger(__name__)
DEFAULT_LOG_LEVEL = logging.WARN
LOG_ENV_VAR = "TORCH_LOGS"
@dataclass
class LogRegistry:
# shorthand name to log qualified name
# Note: this only contains loggers registered
# from register_log
# e.g. "dynamo" -> "torch._dynamo"
log_alias_to_log_qname: Dict[str, str] = field(default_factory=dict)
# artifact logger qualified names,
# this is populated lazily, as calls to getArtifactLogger
# currently formatted as <module>.__<artifact_name>
# e.g. "torch._dynamo.convert_frame.__guards"
artifact_log_qnames: Set[str] = field(default_factory=set)
# child logs of registered logs if specified via open
# registration by the user (ie placing "torch._dynamo.output_graph" in the env var)
# these need to be tracked so their levels can be reset properly
# e.g. "torch._dynamo.output_graph"
child_log_qnames: Set[str] = field(default_factory=set)
# artifact names, populated by register_artifact
# e.g. "guards"
artifact_names: Set[str] = field(default_factory=set)
# artifacts which are not displayed unless explicitly named in the
# settings. Ex. output_code is NOT displayed even if the inductor
# log level is set to DEBUG. It must be explicitly named in the settings
off_by_default_artifact_names: Set[str] = field(default_factory=set)
# logging format string for artifacts
artifact_log_formatters: Dict[str, logging.Formatter] = field(default_factory=dict)
def is_artifact(self, name):
return name in self.artifact_names
def is_log(self, alias):
return alias in self.log_alias_to_log_qname
# register a log with an alias
def register_log(self, alias, log_qname):
self.log_alias_to_log_qname[alias] = log_qname
# register an artifact name
def register_artifact_name(self, name, off_by_default, log_format):
self.artifact_names.add(name)
# if off by default, don't enable it
# when log_name's log_level is set to DEBUG
if off_by_default:
self.off_by_default_artifact_names.add(name)
if log_format is not None:
self.artifact_log_formatters[name] = logging.Formatter(log_format)
# register the qualified name of an artifact log
# this is needed to know which logs need to be reset
# whenever the log_state is changed
def register_artifact_log(self, artifact_log_qname):
self.artifact_log_qnames.add(artifact_log_qname)
def register_child_log(self, log_qname):
self.child_log_qnames.add(log_qname)
def get_log_qnames(self):
return set(self.log_alias_to_log_qname.values())
def get_artifact_log_qnames(self):
return set(self.artifact_log_qnames)
def get_child_log_qnames(self):
return set(self.child_log_qnames)
def is_off_by_default(self, artifact_qname):
return artifact_qname in self.off_by_default_artifact_names
@dataclass
class LogState:
# qualified log names -> currently set log level
log_qname_to_level: Dict[str, str] = field(default_factory=dict)
# the set of currently enabled artifacts
artifact_names: Set[str] = field(default_factory=set)
def enable_artifact(self, artifact_name):
self.artifact_names.add(artifact_name)
def is_artifact_enabled(self, name):
return name in self.artifact_names
def enable_log(self, log_qname, log_level):
self.log_qname_to_level[log_qname] = log_level
def get_log_level_pairs(self):
return self.log_qname_to_level.items()
def clear(self):
self.log_qname_to_level.clear()
self.artifact_names.clear()
log_registry = LogRegistry()
log_state = LogState()
# sample usage: torch._logging.set_logs(**torch._logging.DEFAULT_LOGGING)
DEFAULT_LOGGING = {
"graph_breaks": True,
"recompiles": True,
"dynamic": logging.INFO,
"guards": True,
"trace_source": True,
}
[docs]def set_logs(
*,
all: Optional[int] = None,
dynamo: Optional[int] = None,
aot: Optional[int] = None,
dynamic: Optional[int] = None,
inductor: Optional[int] = None,
distributed: Optional[int] = None,
onnx: Optional[int] = None,
bytecode: bool = False,
aot_graphs: bool = False,
aot_joint_graph: bool = False,
ddp_graphs: bool = False,
graph: bool = False,
graph_code: bool = False,
graph_breaks: bool = False,
graph_sizes: bool = False,
guards: bool = False,
recompiles: bool = False,
trace_source: bool = False,
trace_call: bool = False,
output_code: bool = False,
schedule: bool = False,
perf_hints: bool = False,
onnx_diagnostics: bool = False,
modules: Optional[Dict[str, Union[int, bool]]] = None,
):
"""
Sets the log level for individual components and toggles individual log
artifact types.
.. warning:: This feature is a prototype and may have compatibility
breaking changes in the future.
.. note:: The ``TORCH_LOGS`` environment variable has complete precedence
over this function, so if it was set, this function does nothing.
A component is a set of related features in PyTorch. All of the log
messages emitted from a given component have their own log levels. If the
log level of a particular message has priority greater than or equal to its
component's log level setting, it is emitted. Otherwise, it is supressed.
This allows you to, for instance, silence large groups of log messages that
are not relevant to you and increase verbosity of logs for components that
are relevant. The expected log level values, ordered from highest to lowest
priority, are:
* ``logging.CRITICAL``
* ``logging.ERROR``
* ``logging.WARNING``
* ``logging.INFO``
* ``logging.DEBUG``
* ``logging.NOTSET``
See documentation for the Python ``logging`` module for more information on
log levels: `<https://docs.python.org/3/library/logging.html#logging-levels>`_
An artifact is a particular type of log message. Each artifact is assigned
to a parent component. A component can emit many different kinds of
artifacts. In general, an artifact is emitted if either its corresponding
setting in the argument list below is turned on or if its parent component
is set to a log level less than or equal to the log level of the artifact.
Keyword args:
all (:class:`Optional[int]`):
The default log level for all components. Default: ``logging.WARN``
dynamo (:class:`Optional[int]`):
The log level for the TorchDynamo component. Default: ``logging.WARN``
aot (:class:`Optional[int]`):
The log level for the AOTAutograd component. Default: ``logging.WARN``
inductor (:class:`Optional[int]`):
The log level for the TorchInductor component. Default: ``logging.WARN``
dynamic (:class:`Optional[int]`):
The log level for dynamic shapes. Default: ``logging.WARN``
distributed (:class:`Optional[int]`):
Whether to log communication operations and other debug info from pytorch distributed components.
Default: ``logging.WARN``
onnx (:class:`Optional[int]`):
The log level for the ONNX exporter component. Default: ``logging.WARN``
bytecode (:class:`bool`):
Whether to emit the original and generated bytecode from TorchDynamo.
Default: ``False``
aot_graphs (:class:`bool`):
Whether to emit the graphs generated by AOTAutograd. Default: ``False``
aot_joint_graph (:class:`bool`):
Whether to emit the joint forward-backward graph generated by AOTAutograd. Default: ``False``
ddp_graphs (:class:`bool`):
Whether to emit graphs generated by DDPOptimizer. Default: ``False``
graph (:class:`bool`):
Whether to emit the graph captured by TorchDynamo in tabular format.
Default: ``False``
graph_code (:class:`bool`):
Whether to emit the python source of the graph captured by TorchDynamo.
Default: ``False``
graph_breaks (:class:`bool`):
Whether to emit the graph breaks encountered by TorchDynamo.
Default: ``False``
graph_sizes (:class:`bool`):
Whether to emit tensor sizes of the graph captured by TorchDynamo.
Default: ``False``
guards (:class:`bool`):
Whether to emit the guards generated by TorchDynamo for each compiled
function. Default: ``False``
recompiles (:class:`bool`):
Whether to emit a guard failure reason and message every time
TorchDynamo recompiles a function. Default: ``False``
trace_source (:class:`bool`):
Whether to emit when TorchDynamo begins tracing a new line. Default: ``False``
trace_call (:class:`bool`):
Whether to emit detailed line location when TorchDynamo creates an FX node
corresponding to function call. Python 3.11+ only. Default: ``False``
output_code (:class:`bool`):
Whether to emit the TorchInductor output code. Default: ``False``
schedule (:class:`bool`):
Whether to emit the TorchInductor schedule. Default: ``False``
perf_hints (:class:`bool`):
Whether to emit the TorchInductor perf hints. Default: ``False``
onnx_diagnostics (:class:`bool`):
Whether to emit the ONNX exporter diagnostics in logging. Default: ``False``
modules (dict):
This argument provides an alternate way to specify the above log
component and artifact settings, in the format of a keyword args
dictionary given as a single argument. There are two cases
where this is useful (1) if a new log component or artifact has
been registered but a keyword argument for it has not been added
to this function and (2) if the log level for an unregistered module
needs to be set. This can be done by providing the fully-qualified module
name as the key, with the log level as the value. Default: ``None``
Example::
>>> # xdoctest: +SKIP
>>> import logging
# The following changes the "dynamo" component to emit DEBUG-level
# logs, and to emit "graph_code" artifacts.
>>> torch._logging.set_logs(dynamo=logging.DEBUG, graph_code=True)
# The following enables the logs for a different module
>>> torch._logging.set_logs(modules={"unregistered.module.name": logging.DEBUG})
"""
# ignore if env var is set
if LOG_ENV_VAR in os.environ:
log.warning(
"Using TORCH_LOGS environment variable for log settings, ignoring call to set_logs"
)
return
log_state.clear()
modules = modules or {}
def _set_logs(**kwargs):
default_level = kwargs.pop("all", None)
if default_level:
if default_level not in logging._levelToName:
raise ValueError(
f"Unrecognized log level for kwarg all: {default_level}, valid level values "
f"are: {','.join([str(k) for k in logging._levelToName.keys()])}"
)
# add any missing aliases to kwargs
for alias in log_registry.log_alias_to_log_qname.keys():
if alias not in kwargs:
kwargs[alias] = default_level
else:
default_level = DEFAULT_LOG_LEVEL
for alias, val in itertools.chain(kwargs.items(), modules.items()): # type: ignore[union-attr]
if val is None:
val = default_level
if log_registry.is_artifact(alias):
if not isinstance(val, bool):
raise ValueError(
f"Expected bool to enable artifact {alias}, received {val}"
)
if val:
log_state.enable_artifact(alias)
elif log_registry.is_log(alias) or alias in log_registry.child_log_qnames:
if val not in logging._levelToName:
raise ValueError(
f"Unrecognized log level for log {alias}: {val}, valid level values "
f"are: {','.join([str(k) for k in logging._levelToName.keys()])}"
)
log_state.enable_log(
log_registry.log_alias_to_log_qname.get(alias, alias), val
)
elif alias == "all":
continue
else:
raise ValueError(
f"Unrecognized log or artifact name passed to set_logs: {alias}"
)
_init_logs()
_set_logs(
all=all,
dynamo=dynamo,
aot=aot,
inductor=inductor,
dynamic=dynamic,
bytecode=bytecode,
aot_graphs=aot_graphs,
aot_joint_graph=aot_joint_graph,
ddp_graphs=ddp_graphs,
distributed=distributed,
graph=graph,
graph_code=graph_code,
graph_breaks=graph_breaks,
graph_sizes=graph_sizes,
guards=guards,
recompiles=recompiles,
trace_source=trace_source,
trace_call=trace_call,
output_code=output_code,
schedule=schedule,
perf_hints=perf_hints,
onnx=onnx,
onnx_diagnostics=onnx_diagnostics,
)
def get_loggers():
"""
Returns: a list of all registered loggers
"""
return [logging.getLogger(qname) for qname in log_registry.get_log_qnames()]
def register_log(setting_name, log_name):
"""
Enables a log to be controlled by the env var and user API with the setting_name
Args:
setting_name: the shorthand name used in the env var and user API
log_name: the log name that the setting_name is associated with
"""
log_registry.register_log(setting_name, log_name)
def register_artifact(setting_name, off_by_default=False, log_format=None):
"""
Enables an artifact to be controlled by the env var and user API with name
Args:
setting_name: the shorthand name used in the env var and user API
off_by_default: whether this artifact should be logged when the ancestor loggers
are enabled at level DEBUG
"""
log_registry.register_artifact_name(setting_name, off_by_default, log_format)
def getArtifactLogger(module_qname, artifact_name):
if artifact_name not in log_registry.artifact_names:
raise ValueError(
f"Artifact name: {repr(artifact_name)} not registered,"
f"please call register_artifact({repr(artifact_name)}) in torch._logging.registrations."
)
qname = module_qname + f".__{artifact_name}"
log = logging.getLogger(qname)
log.artifact_name = artifact_name # type: ignore[attr-defined]
log_registry.register_artifact_log(qname)
configure_artifact_log(log)
return log
INCR_VERBOSITY_CHAR = "+"
DECR_VERBOSITY_CHAR = "-"
VERBOSITY_REGEX = (
"("
+ "|".join([re.escape(INCR_VERBOSITY_CHAR), re.escape(DECR_VERBOSITY_CHAR)])
+ "?)"
)
def configure_artifact_log(log):
# If the artifact is off by default, then it should only be logged when explicitly
# enabled; set propagate to False so that this artifact is not propagated
# to its ancestor logger
if log_registry.is_off_by_default(log.artifact_name):
log.propagate = False
# enable artifact logging when explicitly enabled
if log_state.is_artifact_enabled(log.artifact_name):
log.setLevel(logging.DEBUG)
log.propagate = True
# match a comma separated list of loggable names (whitespace allowed after commas)
def _gen_settings_regex():
return re.compile(r"((\+|-)?[\w\.]+,\s*)*(\+|-)?[\w\.]+?")
def _validate_settings(settings):
return re.fullmatch(_gen_settings_regex(), settings) is not None
def _invalid_settings_err_msg(settings):
entities = "\n " + "\n ".join(
itertools.chain(
["all"],
log_registry.log_alias_to_log_qname.keys(),
log_registry.artifact_names,
)
)
msg = (
f"Invalid log settings: {settings}, must be a comma separated list of fully qualified module names, "
f"registered log names or registered artifact names.\nCurrently registered names: {entities}"
)
return msg
@functools.lru_cache
def _parse_log_settings(settings):
if settings == "":
return dict()
if not _validate_settings(settings):
raise ValueError(_invalid_settings_err_msg(settings))
settings = re.sub(r"\s+", "", settings)
log_names = settings.split(",")
def get_name_level_pair(name):
clean_name = name.replace(INCR_VERBOSITY_CHAR, "")
clean_name = clean_name.replace(DECR_VERBOSITY_CHAR, "")
if name[0] == INCR_VERBOSITY_CHAR:
level = logging.DEBUG
elif name[0] == DECR_VERBOSITY_CHAR:
level = logging.ERROR
else:
level = logging.INFO
return clean_name, level
log_state = LogState()
for name in log_names:
name, level = get_name_level_pair(name)
if name == "all":
for log_qname in log_registry.get_log_qnames():
log_state.enable_log(log_qname, level)
for name in log_names:
name, level = get_name_level_pair(name)
if log_registry.is_log(name):
assert level is not None
log_qname = log_registry.log_alias_to_log_qname[name]
log_state.enable_log(log_qname, level)
elif log_registry.is_artifact(name):
log_state.enable_artifact(name)
elif name == "all":
continue
elif _is_valid_module(name):
if not _has_registered_parent(name):
log_registry.register_log(name, name)
else:
log_registry.register_child_log(name)
log_state.enable_log(name, level)
else:
raise ValueError(_invalid_settings_err_msg(settings))
return log_state
def _is_valid_module(qname):
try:
__import__(qname)
return True
except ImportError:
return False
def _update_log_state_from_env():
global log_state
log_setting = os.environ.get(LOG_ENV_VAR, None)
if log_setting is not None:
log_state = _parse_log_settings(log_setting)
def _has_registered_parent(log_qname):
cur_log = logging.getLogger(log_qname)
registered_log_qnames = log_registry.get_log_qnames()
while cur_log.parent:
if cur_log.name in registered_log_qnames:
return True
cur_log = cur_log.parent
return False
# apply custom formats to artifacts when necessary
class TorchLogsFormatter(logging.Formatter):
def format(self, record):
artifact_name = getattr(logging.getLogger(record.name), "artifact_name", None)
if artifact_name is not None:
artifact_formatter = log_registry.artifact_log_formatters.get(
artifact_name, None
)
if artifact_formatter is not None:
return artifact_formatter.format(record)
record.message = record.getMessage()
record.asctime = self.formatTime(record, self.datefmt)
lines = record.message.split("\n")
record.rankprefix = ""
if dist.is_available() and dist.is_initialized():
record.rankprefix = f"[rank{dist.get_rank()}]:"
prefix = (
f"{record.rankprefix}[{record.asctime}] {record.name}: [{record.levelname}]"
)
return "\n".join(f"{prefix} {l}" for l in lines)
DEFAULT_FORMATTER = TorchLogsFormatter()
def _setup_handlers(create_handler_fn, log):
debug_handler = _track_handler(create_handler_fn())
debug_handler.setFormatter(DEFAULT_FORMATTER)
debug_handler.setLevel(logging.DEBUG)
log.addHandler(debug_handler)
handlers = WeakSet() # type: ignore[var-annotated]
# mark handlers that we've created
# so we don't modify user handlers
def _track_handler(handler):
handlers.add(handler)
return handler
def _is_torch_handler(handler):
return handler in handlers
# clears all torch handlers on specified loggers
def _clear_handlers(log):
to_remove = [handler for handler in log.handlers if _is_torch_handler(handler)]
for handler in to_remove:
log.removeHandler(handler)
def _reset_logs():
# reset all registered logs
for log_qname in log_registry.get_log_qnames():
log = logging.getLogger(log_qname)
log.setLevel(logging.WARNING)
log.propagate = False
_clear_handlers(log)
# reset all artifact and child logs
for artifact_log_qname in itertools.chain(
log_registry.get_artifact_log_qnames(), log_registry.get_child_log_qnames()
):
log = logging.getLogger(artifact_log_qname)
log.setLevel(logging.NOTSET)
log.propagate = True
def _get_log_state():
return log_state
def _set_log_state(state):
global log_state
log_state = state
def _init_logs(log_file_name=None):
_reset_logs()
_update_log_state_from_env()
for log_qname, level in log_state.get_log_level_pairs():
log = logging.getLogger(log_qname)
log.setLevel(level)
# setup handlers for all registered loggers
for log_qname in log_registry.get_log_qnames():
log = logging.getLogger(log_qname)
_setup_handlers(
logging.StreamHandler,
log,
)
if log_file_name is not None:
_setup_handlers(
lambda: logging.FileHandler(log_file_name),
log,
)
# configure artifact loggers, note: this must happen last
# since the levels of ancestor loggers are taken into account
for artifact_log_qname in log_registry.get_artifact_log_qnames():
log = logging.getLogger(artifact_log_qname)
configure_artifact_log(log)
@functools.lru_cache(None)
def warning_once(logger_obj, *args, **kwargs):
"""
This function is similar to `logger.warning()`, but will emit the warning with the same message only once
Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
another type of cache that includes the caller frame information in the hashing function.
"""
logger_obj.warning(*args, **kwargs)
import torch.distributed as dist


Phasellus rutrum mattis diam, sit amet euismod risuspulvinar sit amet. Susspendisse gravida scelerisque
wetsuits and Lycra clothing.
Everything for immersion to depth
wetsuits and Lycra clothing.
Everything for immersion to depth
wetsuits and Lycra clothing.
Everything for immersion to depth
wetsuits and Lycra clothing.
Everything for immersion to depth


public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar>
Calendar
class is an abstract class that provides methods
for converting between a specific instant in time and a set of calendar fields
such as YEAR
, MONTH
,
DAY_OF_MONTH
, HOUR
, and so on, and for
manipulating the calendar fields, such as getting the date of the next
week. An instant in time can be represented by a millisecond value that is
an offset from the Epoch, January 1, 1970
00:00:00.000 GMT (Gregorian).
The class also provides additional fields and methods for
implementing a concrete calendar system outside the package. Those
fields and methods are defined as protected
.
Like other locale-sensitive classes, Calendar
provides a
class method, getInstance
, for getting a generally useful
object of this type. Calendar
's getInstance
method
returns a Calendar
object whose
calendar fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance();
A Calendar
object can produce all the calendar field values
needed to implement the date-time formatting for a particular language and
calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
Calendar
defines the range of values returned by
certain calendar fields, as well as their meaning. For example,
the first month of the calendar system has value MONTH ==
JANUARY
for all calendars. Other values are defined by the
concrete subclass, such as ERA
. See individual field
documentation and subclass documentation for details.
The calendar field values can be set by calling the set
methods. Any field values set in a Calendar
will not be
interpreted until it needs to calculate its time value (milliseconds from
the Epoch) or values of the calendar fields. Calling the
get
, getTimeInMillis
, getTime
,
add
and roll
involves such calculation.
Calendar
has two modes for interpreting the calendar
fields, lenient and non-lenient. When a
Calendar
is in lenient mode, it accepts a wider range of
calendar field values than it produces. When a Calendar
recomputes calendar field values for return by get()
, all of
the calendar fields are normalized. For example, a lenient
GregorianCalendar
interprets MONTH == JANUARY
,
DAY_OF_MONTH == 32
as February 1.
When a Calendar
is in non-lenient mode, it throws an
exception if there is any inconsistency in its calendar fields. For
example, a GregorianCalendar
always produces
DAY_OF_MONTH
values between 1 and the length of the month. A
non-lenient GregorianCalendar
throws an exception upon
calculating its time or calendar field values if any out-of-range field
value has been set.
Calendar
defines a locale-specific seven day week using two
parameters: the first day of the week and the minimal days in first week
(from 1 to 7). These numbers are taken from the locale resource data when a
Calendar
is constructed. They may also be specified explicitly
through the methods for setting their values.
When setting or getting the WEEK_OF_MONTH
or
WEEK_OF_YEAR
fields, Calendar
must determine the
first week of the month or year as a reference point. The first week of a
month or year is defined as the earliest seven day period beginning on
getFirstDayOfWeek()
and containing at least
getMinimalDaysInFirstWeek()
days of that month or year. Weeks
numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
it. Note that the normalized numbering returned by get()
may be
different. For example, a specific Calendar
subclass may
designate the week before week 1 of a year as week n
of
the previous year.
Calendar
will resolve
calendar field values to determine the date and time in the
following way.
If there is any conflict in calendar field values,
Calendar
gives priorities to calendar fields that have been set
more recently. The following are the default combinations of the
calendar fields. The most recent combination, as determined by the
most recently set single field, will be used.
For the time of day fields:YEAR + MONTH + DAY_OF_MONTH YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK YEAR + DAY_OF_YEAR YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
HOUR_OF_DAY AM_PM + HOUR
If there are any calendar fields whose values haven't been set in the selected
field combination, Calendar
uses their default values. The default
value of each field may vary by concrete calendar systems. For example, in
GregorianCalendar
, the default of a field is the same as that
of the start of the Epoch: i.e., YEAR = 1970
, MONTH =
JANUARY
, DAY_OF_MONTH = 1
, etc.
Note: There are certain possible ambiguities in interpretation of certain singular times, which are resolved in the following ways:
The date or time format strings are not part of the definition of a
calendar, as those must be modifiable or overridable by the user at
runtime. Use DateFormat
to format dates.
set()
, add()
, and roll()
.
set(f, value)
changes calendar field
f
to value
. In addition, it sets an
internal member variable to indicate that calendar field f
has
been changed. Although calendar field f
is changed immediately,
the calendar's time value in milliseconds is not recomputed until the next call to
get()
, getTime()
, getTimeInMillis()
,
add()
, or roll()
is made. Thus, multiple calls to
set()
do not trigger multiple, unnecessary
computations. As a result of changing a calendar field using
set()
, other calendar fields may also change, depending on the
calendar field, the calendar field value, and the calendar system. In addition,
get(f)
will not necessarily return value
set by
the call to the set
method
after the calendar fields have been recomputed. The specifics are determined by
the concrete calendar class.
Example: Consider a GregorianCalendar
originally set to August 31, 1999. Calling set(Calendar.MONTH,
Calendar.SEPTEMBER)
sets the date to September 31,
1999. This is a temporary internal representation that resolves to
October 1, 1999 if getTime()
is then called. However, a
call to set(Calendar.DAY_OF_MONTH, 30)
before the call to
getTime()
sets the date to September 30, 1999, since
no recomputation occurs after set()
itself.
add(f, delta)
adds delta
to field f
. This is equivalent to calling set(f,
get(f) + delta)
with two adjustments:
Add rule 1. The value of field
f
after the call minus the value of fieldf
before the call isdelta
, modulo any overflow that has occurred in fieldf
. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field
f
is changed or other constraints, such as time zone offset changes, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time.HOUR
is a smaller field thanDAY_OF_MONTH
. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.
In addition, unlike set()
, add()
forces
an immediate recomputation of the calendar's milliseconds and all
fields.
Example: Consider a GregorianCalendar
originally set to August 31, 1999. Calling add(Calendar.MONTH,
13)
sets the calendar to September 30, 2000. Add rule
1 sets the MONTH
field to September, since
adding 13 months to August gives September of the next year. Since
DAY_OF_MONTH
cannot be 31 in September in a
GregorianCalendar
, add rule 2 sets the
DAY_OF_MONTH
to 30, the closest possible value. Although
it is a smaller field, DAY_OF_WEEK
is not adjusted by
rule 2, since it is expected to change when the month changes in a
GregorianCalendar
.
roll(f, delta)
adds
delta
to field f
without changing larger
fields. This is equivalent to calling add(f, delta)
with
the following adjustment:
Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time.
DAY_OF_MONTH
is a larger field thanHOUR
.
Example: See GregorianCalendar.roll(int, int)
.
Usage model. To motivate the behavior of
add()
and roll()
, consider a user interface
component with increment and decrement buttons for the month, day, and
year, and an underlying GregorianCalendar
. If the
interface reads January 31, 1999 and the user presses the month
increment button, what should it read? If the underlying
implementation uses set()
, it might read March 3, 1999. A
better result would be February 28, 1999. Furthermore, if the user
presses the month increment button again, it should read March 31,
1999, not March 28, 1999. By saving the original date and using either
add()
or roll()
, depending on whether larger
fields should be affected, the user interface can behave as most users
will intuitively expect.
System.currentTimeMillis()
,
Date
,
GregorianCalendar
,
TimeZone
,
DateFormat
,
Serialized Form| Modifier and Type | Class and Description |
|---|---|
static class |
Calendar.Builder
Calendar.Builder is used for creating a Calendar from
various date-time parameters. |
| Modifier and Type | Field and Description |
|---|---|
static int |
ALL_STYLES
A style specifier for
getDisplayNames indicating names in all styles, such as
"January" and "Jan". |
static int |
AM
Value of the
AM_PM field indicating the
period of the day from midnight to just before noon. |
static int |
AM_PM
Field number for
get and set indicating
whether the HOUR is before or after noon. |
static int |
APRIL
Value of the
MONTH field indicating the
fourth month of the year in the Gregorian and Julian calendars. |
protected boolean |
areFieldsSet
True if
fields[] are in sync with the currently set time. |
static int |
AUGUST
Value of the
MONTH field indicating the
eighth month of the year in the Gregorian and Julian calendars. |
static int |
DATE
Field number for
get and set indicating the
day of the month. |
static int |
DAY_OF_MONTH
Field number for
get and set indicating the
day of the month. |
static int |
DAY_OF_WEEK
Field number for
get and set indicating the day
of the week. |
static int |
DAY_OF_WEEK_IN_MONTH
Field number for
get and set indicating the
ordinal number of the day of the week within the current month. |
static int |
DAY_OF_YEAR
Field number for
get and set indicating the day
number within the current year. |
static int |
DECEMBER
Value of the
MONTH field indicating the
twelfth month of the year in the Gregorian and Julian calendars. |
static int |
DST_OFFSET
Field number for
get and set indicating the
daylight saving offset in milliseconds. |
static int |
ERA
Field number for
get and set indicating the
era, e.g., AD or BC in the Julian calendar. |
static int |
FEBRUARY
Value of the
MONTH field indicating the
second month of the year in the Gregorian and Julian calendars. |
static int |
FIELD_COUNT
The number of distinct fields recognized by
get and set . |
protected int[] |
fields
The calendar field values for the currently set time for this calendar.
|
static int |
FRIDAY
Value of the
DAY_OF_WEEK field indicating
Friday. |
static int |
HOUR
Field number for
get and set indicating the
hour of the morning or afternoon. |
static int |
HOUR_OF_DAY
Field number for
get and set indicating the
hour of the day. |
protected boolean[] |
isSet
The flags which tell if a specified calendar field for the calendar is set.
|
protected boolean |
isTimeSet
True if then the value of
time is valid. |
static int |
JANUARY
Value of the
MONTH field indicating the
first month of the year in the Gregorian and Julian calendars. |
static int |
JULY
Value of the
MONTH field indicating the
seventh month of the year in the Gregorian and Julian calendars. |
static int |
JUNE
Value of the
MONTH field indicating the
sixth month of the year in the Gregorian and Julian calendars. |
static int |
LONG
|
static int |
LONG_FORMAT
A style specifier for
getDisplayName and getDisplayNames indicating a long name used for format. |
static int |
LONG_STANDALONE
A style specifier for
getDisplayName and getDisplayNames indicating a long name used independently,
such as a month name as calendar headers. |
static int |
MARCH
Value of the
MONTH field indicating the
third month of the year in the Gregorian and Julian calendars. |
static int |
MAY
Value of the
MONTH field indicating the
fifth month of the year in the Gregorian and Julian calendars. |
static int |
MILLISECOND
Field number for
get and set indicating the
millisecond within the second. |
static int |
MINUTE
Field number for
get and set indicating the
minute within the hour. |
static int |
MONDAY
Value of the
DAY_OF_WEEK field indicating
Monday. |
static int |
MONTH
Field number for
get and set indicating the
month. |
static int |
NARROW_FORMAT
A style specifier for
getDisplayName and getDisplayNames indicating a narrow name used for format. |
static int |
NARROW_STANDALONE
A style specifier for
getDisplayName and getDisplayNames indicating a narrow name independently. |
static int |
NOVEMBER
Value of the
MONTH field indicating the
eleventh month of the year in the Gregorian and Julian calendars. |
static int |
OCTOBER
Value of the
MONTH field indicating the
tenth month of the year in the Gregorian and Julian calendars. |
static int |
PM
Value of the
AM_PM field indicating the
period of the day from noon to just before midnight. |
static int |
SATURDAY
Value of the
DAY_OF_WEEK field indicating
Saturday. |
static int |
SECOND
Field number for
get and set indicating the
second within the minute. |
static int |
SEPTEMBER
Value of the
MONTH field indicating the
ninth month of the year in the Gregorian and Julian calendars. |
static int |
SHORT
|
static int |
SHORT_FORMAT
A style specifier for
getDisplayName and getDisplayNames indicating a short name used for format. |
static int |
SHORT_STANDALONE
A style specifier for
getDisplayName and getDisplayNames indicating a short name used independently,
such as a month abbreviation as calendar headers. |
static int |
SUNDAY
Value of the
DAY_OF_WEEK field indicating
Sunday. |
static int |
THURSDAY
Value of the
DAY_OF_WEEK field indicating
Thursday. |
protected long |
time
The currently set time for this calendar, expressed in milliseconds after
January 1, 1970, 0:00:00 GMT.
|
static int |
TUESDAY
Value of the
DAY_OF_WEEK field indicating
Tuesday. |
static int |
UNDECIMBER
Value of the
MONTH field indicating the
thirteenth month of the year. |
static int |
WEDNESDAY
Value of the
DAY_OF_WEEK field indicating
Wednesday. |
static int |
WEEK_OF_MONTH
Field number for
get and set indicating the
week number within the current month. |
static int |
WEEK_OF_YEAR
Field number for
get and set indicating the
week number within the current year. |
static int |
YEAR
Field number for
get and set indicating the
year. |
static int |
ZONE_OFFSET
Field number for
get and set
indicating the raw offset from GMT in milliseconds. |
| Modifier | Constructor and Description |
|---|---|
protected |
Calendar()
Constructs a Calendar with the default time zone
and the default
FORMAT
locale. |
protected |
Calendar(TimeZone zone,
Locale aLocale)
Constructs a calendar with the specified time zone and locale.
|
| Modifier and Type | Method and Description |
|---|---|
abstract void |
add(int field,
int amount)
Adds or subtracts the specified amount of time to the given calendar field,
based on the calendar's rules.
|
boolean |
after(Object when)
Returns whether this
Calendar represents a time
after the time represented by the specified
Object . |
boolean |
before(Object when)
Returns whether this
Calendar represents a time
before the time represented by the specified
Object . |
void |
clear()
Sets all the calendar field values and the time value
(millisecond offset from the Epoch) of
this
Calendar undefined. |
void |
clear(int field)
Sets the given calendar field value and the time value
(millisecond offset from the Epoch) of
this
Calendar undefined. |
Object |
clone()
Creates and returns a copy of this object.
|
int |
compareTo(Calendar anotherCalendar)
Compares the time values (millisecond offsets from the Epoch) represented by two
Calendar objects. |
protected void |
complete()
Fills in any unset fields in the calendar fields.
|
protected abstract void |
computeFields()
|
protected abstract void |
computeTime()
|
boolean |
equals(Object obj)
Compares this
Calendar to the specified
Object . |
int |
get(int field)
Returns the value of the given calendar field.
|
int |
getActualMaximum(int field)
Returns the maximum value that the specified calendar field
could have, given the time value of this
Calendar . |
int |
getActualMinimum(int field)
Returns the minimum value that the specified calendar field
could have, given the time value of this
Calendar . |
static Set<String> |
getAvailableCalendarTypes()
Returns an unmodifiable
Set containing all calendar types
supported by Calendar in the runtime environment. |
static Locale[] |
getAvailableLocales()
Returns an array of all locales for which the
getInstance
methods of this class can return localized instances. |
String |
getCalendarType()
Returns the calendar type of this
Calendar . |
String |
getDisplayName(int field,
int style,
Locale locale)
Returns the string representation of the calendar
field value in the given style and
locale . |
Map<String,Integer> |
getDisplayNames(int field,
int style,
Locale locale)
Returns a
Map containing all names of the calendar
field in the given style and
locale and their corresponding field values. |
int |
getFirstDayOfWeek()
Gets what the first day of the week is; e.g.,
SUNDAY in the U.S.,
MONDAY in France. |
abstract int |
getGreatestMinimum(int field)
Returns the highest minimum value for the given calendar field
of this
Calendar instance. |
static Calendar |
getInstance()
Gets a calendar using the default time zone and locale.
|
static Calendar |
getInstance(Locale aLocale)
Gets a calendar using the default time zone and specified locale.
|
static Calendar |
getInstance(TimeZone zone)
Gets a calendar using the specified time zone and default locale.
|
static Calendar |
getInstance(TimeZone zone,
Locale aLocale)
Gets a calendar with the specified time zone and locale.
|
abstract int |
getLeastMaximum(int field)
Returns the lowest maximum value for the given calendar field
of this
Calendar instance. |
abstract int |
getMaximum(int field)
Returns the maximum value for the given calendar field of this
Calendar instance. |
int |
getMinimalDaysInFirstWeek()
Gets what the minimal days required in the first week of the year are;
e.g., if the first week is defined as one that contains the first day
of the first month of a year, this method returns 1.
|
abstract int |
getMinimum(int field)
Returns the minimum value for the given calendar field of this
Calendar instance. |
Date |
getTime()
|
long |
getTimeInMillis()
Returns this Calendar's time value in milliseconds.
|
TimeZone |
getTimeZone()
Gets the time zone.
|
int |
getWeeksInWeekYear()
Returns the number of weeks in the week year represented by this
Calendar . |
int |
getWeekYear()
Returns the week year represented by this
Calendar . |
int |
hashCode()
Returns a hash code for this calendar.
|
protected int |
internalGet(int field)
Returns the value of the given calendar field.
|
boolean |
isLenient()
Tells whether date/time interpretation is to be lenient.
|
boolean |
isSet(int field)
Determines if the given calendar field has a value set,
including cases that the value has been set by internal fields
calculations triggered by a
get method call. |
boolean |
isWeekDateSupported()
Returns whether this
Calendar supports week dates. |
abstract void |
roll(int field,
boolean up)
Adds or subtracts (up/down) a single unit of time on the given time
field without changing larger fields.
|
void |
roll(int field,
int amount)
Adds the specified (signed) amount to the specified calendar field
without changing larger fields.
|
void |
set(int field,
int value)
Sets the given calendar field to the given value.
|
void |
set(int year,
int month,
int date)
Sets the values for the calendar fields
YEAR ,
MONTH , and DAY_OF_MONTH . |
void |
set(int year,
int month,
int date,
int hourOfDay,
int minute)
Sets the values for the calendar fields
YEAR ,
MONTH , DAY_OF_MONTH ,
HOUR_OF_DAY , and MINUTE . |
void |
set(int year,
int month,
int date,
int hourOfDay,
int minute,
int second)
Sets the values for the fields
YEAR , MONTH ,
DAY_OF_MONTH , HOUR_OF_DAY , MINUTE , and
SECOND . |
void |
setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g.,
SUNDAY in the U.S.,
MONDAY in France. |
void |
setLenient(boolean lenient)
Specifies whether or not date/time interpretation is to be lenient.
|
void |
setMinimalDaysInFirstWeek(int value)
Sets what the minimal days required in the first week of the year are;
For example, if the first week is defined as one that contains the first
day of the first month of a year, call this method with value 1.
|
void |
setTime(Date date)
Sets this Calendar's time with the given
Date . |
void |
setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
|
void |
setTimeZone(TimeZone value)
Sets the time zone with the given time zone value.
|
void |
setWeekDate(int weekYear,
int weekOfYear,
int dayOfWeek)
Sets the date of this
Calendar with the the given date
specifiers - week year, week of year, and day of week. |
Instant |
toInstant()
Converts this object to an
Instant . |
String |
toString()
Return a string representation of this calendar.
|
public static final int ERA
get
and set
indicating the
era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
value; see subclass documentation.public static final int YEAR
get
and set
indicating the
year. This is a calendar-specific value; see subclass documentation.public static final int MONTH
get
and set
indicating the
month. This is a calendar-specific value. The first month of
the year in the Gregorian and Julian calendars is
JANUARY
which is 0; the last depends on the number
of months in a year.public static final int WEEK_OF_YEAR
get
and set
indicating the
week number within the current year. The first week of the year, as
defined by getFirstDayOfWeek()
and
getMinimalDaysInFirstWeek()
, has value 1. Subclasses define
the value of WEEK_OF_YEAR
for days before the first week of
the year.public static final int WEEK_OF_MONTH
get
and set
indicating the
week number within the current month. The first week of the month, as
defined by getFirstDayOfWeek()
and
getMinimalDaysInFirstWeek()
, has value 1. Subclasses define
the value of WEEK_OF_MONTH
for days before the first week of
the month.public static final int DATE
get
and set
indicating the
day of the month. This is a synonym for DAY_OF_MONTH
.
The first day of the month has value 1.DAY_OF_MONTH
,
Constant Field Valuespublic static final int DAY_OF_MONTH
get
and set
indicating the
day of the month. This is a synonym for DATE
.
The first day of the month has value 1.DATE
,
Constant Field Valuespublic static final int DAY_OF_YEAR
get
and set
indicating the day
number within the current year. The first day of the year has value 1.public static final int DAY_OF_WEEK
get
and set
indicating the day
of the week. This field takes values SUNDAY
,
MONDAY
, TUESDAY
, WEDNESDAY
,
THURSDAY
, FRIDAY
, and SATURDAY
.public static final int DAY_OF_WEEK_IN_MONTH
get
and set
indicating the
ordinal number of the day of the week within the current month. Together
with the DAY_OF_WEEK
field, this uniquely specifies a day
within a month. Unlike WEEK_OF_MONTH
and
WEEK_OF_YEAR
, this field's value does not depend on
getFirstDayOfWeek()
or
getMinimalDaysInFirstWeek()
. DAY_OF_MONTH 1
through 7
always correspond to DAY_OF_WEEK_IN_MONTH
1
; 8
through 14
correspond to
DAY_OF_WEEK_IN_MONTH 2
, and so on.
DAY_OF_WEEK_IN_MONTH 0
indicates the week before
DAY_OF_WEEK_IN_MONTH 1
. Negative values count back from the
end of the month, so the last Sunday of a month is specified as
DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1
. Because
negative values count backward they will usually be aligned differently
within the month than positive values. For example, if a month has 31
days, DAY_OF_WEEK_IN_MONTH -1
will overlap
DAY_OF_WEEK_IN_MONTH 5
and the end of 4
.DAY_OF_WEEK
,
WEEK_OF_MONTH
,
Constant Field Valuespublic static final int AM_PM
get
and set
indicating
whether the HOUR
is before or after noon.
E.g., at 10:04:15.250 PM the AM_PM
is PM
.AM
,
PM
,
HOUR
,
Constant Field Valuespublic static final int HOUR
get
and set
indicating the
hour of the morning or afternoon. HOUR
is used for the
12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
E.g., at 10:04:15.250 PM the HOUR
is 10.AM_PM
,
HOUR_OF_DAY
,
Constant Field Valuespublic static final int HOUR_OF_DAY
get
and set
indicating the
hour of the day. HOUR_OF_DAY
is used for the 24-hour clock.
E.g., at 10:04:15.250 PM the HOUR_OF_DAY
is 22.HOUR
,
Constant Field Valuespublic static final int MINUTE
get
and set
indicating the
minute within the hour.
E.g., at 10:04:15.250 PM the MINUTE
is 4.public static final int SECOND
get
and set
indicating the
second within the minute.
E.g., at 10:04:15.250 PM the SECOND
is 15.public static final int MILLISECOND
get
and set
indicating the
millisecond within the second.
E.g., at 10:04:15.250 PM the MILLISECOND
is 250.public static final int ZONE_OFFSET
get
and set
indicating the raw offset from GMT in milliseconds.
This field reflects the correct GMT offset value of the time
zone of this Calendar
if the
TimeZone
implementation subclass supports
historical GMT offset changes.
public static final int DST_OFFSET
get
and set
indicating the
daylight saving offset in milliseconds.
This field reflects the correct daylight saving offset value of
the time zone of this Calendar
if the
TimeZone
implementation subclass supports
historical Daylight Saving Time schedule changes.
public static final int FIELD_COUNT
get
and set
.
Field numbers range from 0..FIELD_COUNT-1
.public static final int SUNDAY
DAY_OF_WEEK
field indicating
Sunday.public static final int MONDAY
DAY_OF_WEEK
field indicating
Monday.public static final int TUESDAY
DAY_OF_WEEK
field indicating
Tuesday.public static final int WEDNESDAY
DAY_OF_WEEK
field indicating
Wednesday.public static final int THURSDAY
DAY_OF_WEEK
field indicating
Thursday.public static final int FRIDAY
DAY_OF_WEEK
field indicating
Friday.public static final int SATURDAY
DAY_OF_WEEK
field indicating
Saturday.public static final int JANUARY
MONTH
field indicating the
first month of the year in the Gregorian and Julian calendars.public static final int FEBRUARY
MONTH
field indicating the
second month of the year in the Gregorian and Julian calendars.public static final int MARCH
MONTH
field indicating the
third month of the year in the Gregorian and Julian calendars.public static final int APRIL
MONTH
field indicating the
fourth month of the year in the Gregorian and Julian calendars.public static final int MAY
MONTH
field indicating the
fifth month of the year in the Gregorian and Julian calendars.public static final int JUNE
MONTH
field indicating the
sixth month of the year in the Gregorian and Julian calendars.public static final int JULY
MONTH
field indicating the
seventh month of the year in the Gregorian and Julian calendars.public static final int AUGUST
MONTH
field indicating the
eighth month of the year in the Gregorian and Julian calendars.public static final int SEPTEMBER
MONTH
field indicating the
ninth month of the year in the Gregorian and Julian calendars.public static final int OCTOBER
MONTH
field indicating the
tenth month of the year in the Gregorian and Julian calendars.public static final int NOVEMBER
MONTH
field indicating the
eleventh month of the year in the Gregorian and Julian calendars.public static final int DECEMBER
MONTH
field indicating the
twelfth month of the year in the Gregorian and Julian calendars.public static final int UNDECIMBER
MONTH
field indicating the
thirteenth month of the year. Although GregorianCalendar
does not use this value, lunar calendars do.public static final int AM
AM_PM
field indicating the
period of the day from midnight to just before noon.public static final int PM
AM_PM
field indicating the
period of the day from noon to just before midnight.public static final int ALL_STYLES
getDisplayNames
indicating names in all styles, such as
"January" and "Jan".SHORT_FORMAT
,
LONG_FORMAT
,
SHORT_STANDALONE
,
LONG_STANDALONE
,
SHORT
,
LONG
,
Constant Field Valuespublic static final int SHORT
SHORT_STANDALONE
,
LONG
,
Constant Field Valuespublic static final int LONG
LONG_STANDALONE
,
SHORT
,
Constant Field Valuespublic static final int NARROW_FORMAT
getDisplayName
and getDisplayNames
indicating a narrow name used for format. Narrow names
are typically single character strings, such as "M" for Monday.NARROW_STANDALONE
,
SHORT_FORMAT
,
LONG_FORMAT
,
Constant Field Valuespublic static final int NARROW_STANDALONE
getDisplayName
and getDisplayNames
indicating a narrow name independently. Narrow names
are typically single character strings, such as "M" for Monday.NARROW_FORMAT
,
SHORT_STANDALONE
,
LONG_STANDALONE
,
Constant Field Valuespublic static final int SHORT_FORMAT
getDisplayName
and getDisplayNames
indicating a short name used for format.SHORT_STANDALONE
,
LONG_FORMAT
,
LONG_STANDALONE
,
Constant Field Valuespublic static final int LONG_FORMAT
getDisplayName
and getDisplayNames
indicating a long name used for format.LONG_STANDALONE
,
SHORT_FORMAT
,
SHORT_STANDALONE
,
Constant Field Valuespublic static final int SHORT_STANDALONE
getDisplayName
and getDisplayNames
indicating a short name used independently,
such as a month abbreviation as calendar headers.SHORT_FORMAT
,
LONG_FORMAT
,
LONG_STANDALONE
,
Constant Field Valuespublic static final int LONG_STANDALONE
getDisplayName
and getDisplayNames
indicating a long name used independently,
such as a month name as calendar headers.LONG_FORMAT
,
SHORT_FORMAT
,
SHORT_STANDALONE
,
Constant Field Valuesprotected int[] fields
FIELD_COUNT
integers, with index values
ERA
through DST_OFFSET
.protected boolean[] isSet
FIELD_COUNT
booleans, with index values
ERA
through DST_OFFSET
.protected long time
isTimeSet
protected boolean isTimeSet
time
is valid.
The time is made invalid by a change to an item of field[]
.time
protected boolean areFieldsSet
fields[]
are in sync with the currently set time.
If false, then the next attempt to get the value of a field will
force a recomputation of all fields from the current value of
time
.protected Calendar()
FORMAT
locale.TimeZone.getDefault()
public static Calendar getInstance()
Calendar
returned is based on the current time
in the default time zone with the default
FORMAT
locale.public static Calendar getInstance(TimeZone zone)
Calendar
returned is based on the current time
in the given time zone with the default
FORMAT
locale.zone
- the time zone to usepublic static Calendar getInstance(Locale aLocale)
Calendar
returned is based on the current time
in the default time zone with the given locale.aLocale
- the locale for the week datapublic static Calendar getInstance(TimeZone zone, Locale aLocale)
Calendar
returned is based on the current time
in the given time zone with the given locale.zone
- the time zone to useaLocale
- the locale for the week datapublic static Locale[] getAvailableLocales()
getInstance
methods of this class can return localized instances.
The array returned must contain at least a Locale
instance equal to Locale.US
.Calendar
instances are available.protected abstract void computeTime()
complete()
,
computeFields()
protected abstract void computeFields()
time
to calendar field values in fields[]
.
This allows you to sync up the calendar field values with
a new time that is set for the calendar. The time is not
recomputed first; to recompute the time, then the fields, call the
complete()
method.computeTime()
public final Date getTime()
Date
representing the time value.setTime(Date)
,
getTimeInMillis()
public final void setTime(Date date)
Date
.
Note: Calling setTime()
with
Date(Long.MAX_VALUE)
or Date(Long.MIN_VALUE)
may yield incorrect field values from get()
.
date
- the given Date.getTime()
,
setTimeInMillis(long)
public long getTimeInMillis()
getTime()
,
setTimeInMillis(long)
public void setTimeInMillis(long millis)
millis
- the new time in UTC milliseconds from the epoch.setTime(Date)
,
getTimeInMillis()
public int get(int field)
complete()
method, which process is calendar
system dependent.field
- the given calendar field.ArrayIndexOutOfBoundsException
- if the specified field is out of range
(field < 0 || field >= FIELD_COUNT
).set(int,int)
,
complete()
protected final int internalGet(int field)
field
- the given calendar field.get(int)
public void set(int field, int value)
field
- the given calendar field.value
- the value to be set for the given calendar field.ArrayIndexOutOfBoundsException
- if the specified field is out of range
(field < 0 || field >= FIELD_COUNT
).
in non-lenient mode.set(int,int,int)
,
set(int,int,int,int,int)
,
set(int,int,int,int,int,int)
,
get(int)
public final void set(int year, int month, int date)
YEAR
,
MONTH
, and DAY_OF_MONTH
.
Previous values of other calendar fields are retained. If this is not desired,
call clear()
first.year
- the value used to set the YEAR
calendar field.month
- the value used to set the MONTH
calendar field.
Month value is 0-based. e.g., 0 for January.date
- the value used to set the DAY_OF_MONTH
calendar field.set(int,int)
,
set(int,int,int,int,int)
,
set(int,int,int,int,int,int)
public final void set(int year, int month, int date, int hourOfDay, int minute)
YEAR
,
MONTH
, DAY_OF_MONTH
,
HOUR_OF_DAY
, and MINUTE
.
Previous values of other fields are retained. If this is not desired,
call clear()
first.year
- the value used to set the YEAR
calendar field.month
- the value used to set the MONTH
calendar field.
Month value is 0-based. e.g., 0 for January.date
- the value used to set the DAY_OF_MONTH
calendar field.hourOfDay
- the value used to set the HOUR_OF_DAY
calendar field.minute
- the value used to set the MINUTE
calendar field.set(int,int)
,
set(int,int,int)
,
set(int,int,int,int,int,int)
public final void set(int year, int month, int date, int hourOfDay, int minute, int second)
YEAR
, MONTH
,
DAY_OF_MONTH
, HOUR_OF_DAY
, MINUTE
, and
SECOND
.
Previous values of other fields are retained. If this is not desired,
call clear()
first.year
- the value used to set the YEAR
calendar field.month
- the value used to set the MONTH
calendar field.
Month value is 0-based. e.g., 0 for January.date
- the value used to set the DAY_OF_MONTH
calendar field.hourOfDay
- the value used to set the HOUR_OF_DAY
calendar field.minute
- the value used to set the MINUTE
calendar field.second
- the value used to set the SECOND
calendar field.set(int,int)
,
set(int,int,int)
,
set(int,int,int,int,int)
public final void clear()
Calendar
undefined. This means that isSet()
will return false
for all the
calendar fields, and the date and time calculations will treat
the fields as if they had never been set. A
Calendar
implementation class may use its specific
default field values for date/time calculations. For example,
GregorianCalendar
uses 1970 if the
YEAR
field value is undefined.clear(int)
public final void clear(int field)
Calendar
undefined. This means that isSet(field)
will return false
, and
the date and time calculations will treat the field as if it
had never been set. A Calendar
implementation
class may use the field's specific default value for date and
time calculations.
The HOUR_OF_DAY
, HOUR
and AM_PM
fields are handled independently and the the resolution rule for the time of
day is applied. Clearing one of the fields doesn't reset
the hour of day value of this Calendar
. Use set(Calendar.HOUR_OF_DAY, 0)
to reset the hour
value.
field
- the calendar field to be cleared.clear()
public final boolean isSet(int field)
get
method call.field
- the calendar field to testtrue
if the given calendar field has a value set;
false
otherwise.public String getDisplayName(int field, int style, Locale locale)
field
value in the given style
and
locale
. If no string representation is
applicable, null
is returned. This method calls
get(field)
to get the calendar
field
value if the string representation is
applicable to the given calendar field
.
For example, if this Calendar
is a
GregorianCalendar
and its date is 2005-01-01, then
the string representation of the MONTH
field would be
"January" in the long style in an English locale or "Jan" in
the short style. However, no string representation would be
available for the DAY_OF_MONTH
field, and this method
would return null
.
The default implementation supports the calendar fields for
which a DateFormatSymbols
has names in the given
locale
.
field
- the calendar field for which the string representation
is returnedstyle
- the style applied to the string representation; one of SHORT_FORMAT
(SHORT
), SHORT_STANDALONE
,
LONG_FORMAT
(LONG
), LONG_STANDALONE
,
NARROW_FORMAT
, or NARROW_STANDALONE
.locale
- the locale for the string representation
(any calendar types specified by locale
are ignored)field
in the given style
, or
null
if no string representation is
applicable.IllegalArgumentException
- if field
or style
is invalid,
or if this Calendar
is non-lenient and any
of the calendar fields have invalid valuesNullPointerException
- if locale
is nullpublic Map<String,Integer> getDisplayNames(int field, int style, Locale locale)
Map
containing all names of the calendar
field
in the given style
and
locale
and their corresponding field values. For
example, if this Calendar
is a GregorianCalendar
, the returned map would contain "Jan" to
JANUARY
, "Feb" to FEBRUARY
, and so on, in the
short style in an English locale.
Narrow names may not be unique due to use of single characters,
such as "S" for Sunday and Saturday. In that case narrow names are not
included in the returned Map
.
The values of other calendar fields may be taken into
account to determine a set of display names. For example, if
this Calendar
is a lunisolar calendar system and
the year value given by the YEAR
field has a leap
month, this method would return month names containing the leap
month name, and month names are mapped to their values specific
for the year.
The default implementation supports display names contained in
a DateFormatSymbols
. For example, if field
is MONTH
and style
is ALL_STYLES
, this method returns a Map
containing
all strings returned by DateFormatSymbols.getShortMonths()
and DateFormatSymbols.getMonths()
.
field
- the calendar field for which the display names are returnedstyle
- the style applied to the string representation; one of SHORT_FORMAT
(SHORT
), SHORT_STANDALONE
,
LONG_FORMAT
(LONG
), LONG_STANDALONE
,
NARROW_FORMAT
, or NARROW_STANDALONE
locale
- the locale for the display namesMap
containing all display names in
style
and locale
and their
field values, or null
if no display names
are defined for field
IllegalArgumentException
- if field
or style
is invalid,
or if this Calendar
is non-lenient and any
of the calendar fields have invalid valuesNullPointerException
- if locale
is nullprotected void complete()
computeTime()
method is called if the time value (millisecond offset
from the Epoch) has not been calculated from
calendar field values. Then, the computeFields()
method is
called to calculate all calendar field values.public static Set<String> getAvailableCalendarTypes()
Set
containing all calendar types
supported by Calendar
in the runtime environment. The available
calendar types can be used for the Unicode locale extensions.
The Set
returned contains at least "gregory"
. The
calendar types don't include aliases, such as "gregorian"
for
"gregory"
.Set
containing all available calendar typesgetCalendarType()
,
Calendar.Builder.setCalendarType(String)
,
Locale.getUnicodeLocaleType(String)
public String getCalendarType()
Calendar
. Calendar types are
defined by the Unicode Locale Data Markup Language (LDML)
specification.
The default implementation of this method returns the class name of
this Calendar
instance. Any subclasses that implement
LDML-defined calendar systems should override this method to return
appropriate calendar types.
Calendar
instanceLocale.Builder.setLocale(Locale)
,
Locale.Builder.setUnicodeLocaleKeyword(String, String)
public boolean equals(Object obj)
Calendar
to the specified
Object
. The result is true
if and only if
the argument is a Calendar
object of the same calendar
system that represents the same time value (millisecond offset from the
Epoch) under the same
Calendar
parameters as this object.
The Calendar
parameters are the values represented
by the isLenient
, getFirstDayOfWeek
,
getMinimalDaysInFirstWeek
and getTimeZone
methods. If there is any difference in those parameters
between the two Calendar
s, this method returns
false
.
Use the compareTo
method to
compare only the time values.
equals
in class Object
obj
- the object to compare with.true
if this object is equal to obj
;
false
otherwise.Object.hashCode()
,
HashMap
public int hashCode()
hashCode
in class Object
Object.equals(java.lang.Object)
,
System.identityHashCode(java.lang.Object)
public boolean before(Object when)
Calendar
represents a time
before the time represented by the specified
Object
. This method is equivalent to:
compareTo(when) < 0
if and only if when
is a Calendar
instance. Otherwise, the method returns false
.when
- the Object
to be comparedtrue
if the time of this
Calendar
is before the time represented by
when
; false
otherwise.compareTo(Calendar)
public boolean after(Object when)
Calendar
represents a time
after the time represented by the specified
Object
. This method is equivalent to:
compareTo(when) > 0
if and only if when
is a Calendar
instance. Otherwise, the method returns false
.when
- the Object
to be comparedtrue
if the time of this Calendar
is
after the time represented by when
; false
otherwise.compareTo(Calendar)
public int compareTo(Calendar anotherCalendar)
Calendar
objects.compareTo
in interface Comparable<Calendar>
anotherCalendar
- the Calendar
to be compared.0
if the time represented by the argument
is equal to the time represented by this Calendar
; a value
less than 0
if the time of this Calendar
is
before the time represented by the argument; and a value greater than
0
if the time of this Calendar
is after the
time represented by the argument.NullPointerException
- if the specified Calendar
is
null
.IllegalArgumentException
- if the time value of the
specified Calendar
object can't be obtained due to
any invalid calendar values.public abstract void add(int field, int amount)
add(Calendar.DAY_OF_MONTH, -5)
.
field
- the calendar field.amount
- the amount of date or time to be added to the field.roll(int,int)
,
set(int,int)
public abstract void roll(int field, boolean up)
roll(Calendar.DATE, true).
When rolling on the year or Calendar.YEAR field, it will roll the year
value in the range between 1 and the value returned by calling
getMaximum(Calendar.YEAR)
.
When rolling on the month or Calendar.MONTH field, other fields like
date might conflict and, need to be changed. For instance,
rolling the month on the date 01/31/96 will result in 02/29/96.
When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
roll the hour value in the range between 0 and 23, which is zero-based.
field
- the time field.up
- indicates if the value of the specified time field is to be
rolled up or rolled down. Use true if rolling up, false otherwise.add(int,int)
,
set(int,int)
public void roll(int field, int amount)
NOTE: This default implementation on Calendar
just repeatedly calls the
version of roll()
that rolls by one unit. This may not
always do the right thing. For example, if the DAY_OF_MONTH
field is 31,
rolling through February will leave it set to 28. The GregorianCalendar
version of this function takes care of this problem. Other subclasses
should also provide overrides of this function that do the right thing.
field
- the calendar field.amount
- the signed amount to add to the calendar field
.roll(int,boolean)
,
add(int,int)
,
set(int,int)
public void setTimeZone(TimeZone value)
value
- the given time zone.public TimeZone getTimeZone()
public void setLenient(boolean lenient)
lenient
- true
if the lenient mode is to be turned
on; false
if it is to be turned off.isLenient()
,
DateFormat.setLenient(boolean)
public boolean isLenient()
true
if the interpretation mode of this calendar is lenient;
false
otherwise.setLenient(boolean)
public void setFirstDayOfWeek(int value)
SUNDAY
in the U.S.,
MONDAY
in France.value
- the given first day of the week.getFirstDayOfWeek()
,
getMinimalDaysInFirstWeek()
public int getFirstDayOfWeek()
SUNDAY
in the U.S.,
MONDAY
in France.setFirstDayOfWeek(int)
,
getMinimalDaysInFirstWeek()
public void setMinimalDaysInFirstWeek(int value)
value
- the given minimal days required in the first week
of the year.getMinimalDaysInFirstWeek()
public int getMinimalDaysInFirstWeek()
setMinimalDaysInFirstWeek(int)
public boolean isWeekDateSupported()
Calendar
supports week dates.
The default implementation of this method returns false
.
true
if this Calendar
supports week dates;
false
otherwise.getWeekYear()
,
setWeekDate(int,int,int)
,
getWeeksInWeekYear()
public int getWeekYear()
Calendar
. The
week year is in sync with the week cycle. The first day of the first week is the first
day of the week year.
The default implementation of this method throws an
UnsupportedOperationException
.
Calendar
UnsupportedOperationException
- if any week year numbering isn't supported
in this Calendar
.isWeekDateSupported()
,
getFirstDayOfWeek()
,
getMinimalDaysInFirstWeek()
public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek)
Calendar
with the the given date
specifiers - week year, week of year, and day of week.
Unlike the set
method, all of the calendar fields
and time
values are calculated upon return.
If weekOfYear
is out of the valid week-of-year range
in weekYear
, the weekYear
and weekOfYear
values are adjusted in lenient mode, or an IllegalArgumentException
is thrown in non-lenient mode.
The default implementation of this method throws an
UnsupportedOperationException
.
weekYear
- the week yearweekOfYear
- the week number based on weekYear
dayOfWeek
- the day of week value: one of the constants
for the DAY_OF_WEEK
field: SUNDAY
, ..., SATURDAY
.IllegalArgumentException
- if any of the given date specifiers is invalid
or any of the calendar fields are inconsistent
with the given date specifiers in non-lenient modeUnsupportedOperationException
- if any week year numbering isn't supported in this
Calendar
.isWeekDateSupported()
,
getFirstDayOfWeek()
,
getMinimalDaysInFirstWeek()
public int getWeeksInWeekYear()
Calendar
.
The default implementation of this method throws an
UnsupportedOperationException
.
UnsupportedOperationException
- if any week year numbering isn't supported in this
Calendar
.WEEK_OF_YEAR
,
isWeekDateSupported()
,
getWeekYear()
,
getActualMaximum(int)
public abstract int getMinimum(int field)
Calendar
instance. The minimum value is defined as
the smallest value returned by the get
method
for any possible time value. The minimum value depends on
calendar system specific parameters of the instance.field
- the calendar field.getMaximum(int)
,
getGreatestMinimum(int)
,
getLeastMaximum(int)
,
getActualMinimum(int)
,
getActualMaximum(int)
public abstract int getMaximum(int field)
Calendar
instance. The maximum value is defined as
the largest value returned by the get
method
for any possible time value. The maximum value depends on
calendar system specific parameters of the instance.field
- the calendar field.getMinimum(int)
,
getGreatestMinimum(int)
,
getLeastMaximum(int)
,
getActualMinimum(int)
,
getActualMaximum(int)
public abstract int getGreatestMinimum(int field)
Calendar
instance. The highest minimum
value is defined as the largest value returned by getActualMinimum(int)
for any possible time value. The
greatest minimum value depends on calendar system specific
parameters of the instance.field
- the calendar field.getMinimum(int)
,
getMaximum(int)
,
getLeastMaximum(int)
,
getActualMinimum(int)
,
getActualMaximum(int)
public abstract int getLeastMaximum(int field)
Calendar
instance. The lowest maximum
value is defined as the smallest value returned by getActualMaximum(int)
for any possible time value. The least
maximum value depends on calendar system specific parameters of
the instance. For example, a Calendar
for the
Gregorian calendar system returns 28 for the
DAY_OF_MONTH
field, because the 28th is the last
day of the shortest month of this calendar, February in a
common year.field
- the calendar field.getMinimum(int)
,
getMaximum(int)
,
getGreatestMinimum(int)
,
getActualMinimum(int)
,
getActualMaximum(int)
public int getActualMinimum(int field)
Calendar
.
The default implementation of this method uses an iterative
algorithm to determine the actual minimum value for the
calendar field. Subclasses should, if possible, override this
with a more efficient implementation - in many cases, they can
simply return getMinimum()
.
field
- the calendar fieldCalendar
getMinimum(int)
,
getMaximum(int)
,
getGreatestMinimum(int)
,
getLeastMaximum(int)
,
getActualMaximum(int)
public int getActualMaximum(int field)
Calendar
. For example, the actual maximum value of
the MONTH
field is 12 in some years, and 13 in
other years in the Hebrew calendar system.
The default implementation of this method uses an iterative algorithm to determine the actual maximum value for the calendar field. Subclasses should, if possible, override this with a more efficient implementation.
field
- the calendar fieldCalendar
getMinimum(int)
,
getMaximum(int)
,
getGreatestMinimum(int)
,
getLeastMaximum(int)
,
getActualMinimum(int)
public Object clone()
public String toString()
null
.Dracula Javadoc Sample, Made with Allan Im.


Intro JavaScript
Stalker Exercice
- Ask the user for his/her first Name
- Ask the user for his/her Last Name
- Ask the user for his/her age
- print the full name of the user
- print the age of the user
-
Age Calculator Exercice
- Ask the user for his/her BirthDate year
- Ask the user for his/her BirthDate month
- Ask the user for his/her BirthDate day
- print how many days the user has been alive


{% extends "global/Page.html" %} {% load otree static %} {% block title %}
Here we explain the visual information of your group (how you will be represented on the screen). This information will be useful for the other parts of the experiment. In this part you will also make a decision with the other players assigned to your group: you will choose a name for your group. This is explained below:
{% if player.given_type == 1 %}
You are assigned to the group ● (internal symbol)
and your appearance is ◯ (external symbol).
There are {{ Constants.total_circles }} players in your group ●, including yourself.
There are {{ Constants.total_triangles }} players in group ▲.
Each player in your group will be displayed on the screen using the image below:
In the box on the right you can chat with the other participants in ● and
choose a name for your group, by clicking on the button with the name you prefer as a group.To choose
a name, all {{ Constants.total_circles }} players in your group must click on the same button.
{% elif player.given_type == 5 %}
You are assigned to the group ▲ (internal symbol)
and your appearance is △ (external symbol).
There are {{ Constants.total_triangles }} players in your group ▲, including yourself.
There are {{ Constants.total_circles }} players in group ●.
Each player in your group will be displayed on the screen using the image below:
In the box on the right you can chat with the other participants in ▲ and
choose a name for your group, by clicking on the button with the name you prefer as a group. To choose
a name, all {{ Constants.total_triangles }} players in your group must click on the same button.
{% endif %}
In the chat box below, you will be labeled as Player {{ player.role }}. You are not allowed to use any
offensive language. Also, to preserve anonymity you cannot send any information that can help others
identify who you are.
Write on the chat box to communicate with others in your group.
Click on the button with the name your group has chosen.
{% if player.given_type == 1 %}


torch_geometric.nn¶
Contents
Sparse Convolutional Layers¶
-
class
GCNConv
(in_channels, out_channels, improved=False, bias=True)[source]¶ The graph convolutional operator from the “Semi-supervised Classfication with Graph Convolutional Networks” paper
\[\mathbf{X}^{\prime} = \mathbf{\hat{D}}^{-1/2} \mathbf{\hat{A}} \mathbf{\hat{D}}^{-1/2} \mathbf{X} \mathbf{\Theta},\]where \(\mathbf{\hat{A}} = \mathbf{A} + \mathbf{I}\) denotes the adjacency matrix with inserted self-loops and \(\hat{D}_{ii} = \sum_{j=0} \hat{A}_{ij}\) its diagonal degree matrix.
Parameters: - in_channels (int) – Size of each input sample.
- out_channels (int) – Size of each output sample.
- improved (bool, optional) – If set to
True
, the layer computes \(\mathbf{\hat{A}}\) as \(\mathbf{A} + 2\mathbf{I}\). (default:False
) - bias (bool, optional) – If set to
False
, the layer will not learn an additive bias. (default:True
)
-
class
ChebConv
(in_channels, out_channels, K, bias=True)[source]¶ The chebyshev spectral graph convolutional operator from the “Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering” paper
\[\mathbf{X}^{\prime} = \sum_{k=0}^{K-1} \mathbf{\hat{X}}_k \cdot \mathbf{\Theta}_k\]where \(\mathbf{\hat{X}}_k\) is computed recursively by
\[ \begin{align}\begin{aligned}\mathbf{\hat{X}}_0 &= \mathbf{X}\\\mathbf{\hat{X}}_1 &= \mathbf{\hat{L}} \cdot \mathbf{X}\\\mathbf{\hat{X}}_k &= 2 \cdot \mathbf{\hat{L}} \cdot \mathbf{\hat{X}}_{k-1} - \mathbf{\hat{X}}_{k-2}\end{aligned}\end{align} \]and \(\mathbf{\hat{L}}\) denotes the scaled and normalized Lalplacian.
Parameters:
-
class
SAGEConv
(in_channels, out_channels, normalize=True, bias=True)[source]¶ The GraphSAGE operator from the “Inductive Representation Learning on Large Graphs” paper
\[ \begin{align}\begin{aligned}\mathbf{\hat{x}}_i &= \mathbf{\Theta} \cdot \mathrm{mean}_{j \in \mathcal{N(i) \cup \{ i \}}}(\mathbf{x}_j)\\\mathbf{x}^{\prime}_i &= \frac{\mathbf{\hat{x}}_i} {\| \mathbf{\hat{x}}_i \|_2}.\end{aligned}\end{align} \]Parameters:
-
class
GraphConv
(in_channels, out_channels, aggr='add', bias=True)[source]¶ The graph neural network operator from the “Weisfeiler and Leman Go Neural: Higher-order Graph Neural Networks” paper
\[\mathbf{x}^{\prime}_i = \mathbf{\Theta} \mathbf{x}_i + \sum_{j \in \mathcal{N}(i)} \mathbf{\Theta} \mathbf{x}_j.\]Parameters:
-
class
GATConv
(in_channels, out_channels, heads=1, concat=True, negative_slope=0.2, dropout=0, bias=True)[source]¶ The graph attentional operator from the “Graph Attention Networks” paper
\[\mathbf{x}^{\prime}_i = \alpha_{i,i}\mathbf{\Theta}\mathbf{x}_{j} + \sum_{j \in \mathcal{N}(i)} \alpha_{i,j}\mathbf{\Theta}\mathbf{x}_{j},\]where the attention coefficients \(\alpha_{i,j}\) are computed as
\[\alpha_{i,j} = \frac{ \exp\left(\mathrm{LeakyReLU}\left(\mathbf{a}^{\top} [\mathbf{\Theta}\mathbf{x}_i \, \Vert \, \mathbf{\Theta}\mathbf{x}_j] \right)\right)} {\sum_{k \in \mathcal{N}(i) \cup \{ i \}} \exp\left(\mathrm{LeakyReLU}\left(\mathbf{a}^{\top} [\mathbf{\Theta}\mathbf{x}_i \, \Vert \, \mathbf{\Theta}\mathbf{x}_k] \right)\right)}.\]Parameters: - in_channels (int) – Size of each input sample.
- out_channels (int) – Size of each output sample.
- heads (int, optional) – Number of multi-head-attentions. (default:
1
) - concat (bool, optional) – If set to
False
, the multi-head - are averaged instead of concatenated. (default (attentions) –
True
) - negative_slope (float, optional) – LeakyReLU angle of the negative
slope. (default:
0.2
) - dropout (float, optional) – Dropout propbability of the normalized
attention coefficients which exposes each node to a stochastically
sampled neighborhood during training. (default:
0
) - bias (bool, optional) – If set to
False
, the layer will not learn an additive bias. (default:True
)
-
class
AGNNConv
(requires_grad=True)[source]¶ Graph attentional propagation layer from the “Attention-based Graph Neural Network for Semi-Supervised Learning” paper
\[\mathbf{X}^{\prime} = \mathbf{P} \mathbf{X},\]where the propagation matrix \(\mathbf{P}\) is computed as
\[P_{i,j} = \frac{\exp( \beta \cdot \cos(\mathbf{x}_i, \mathbf{x}_j))} {\sum_{k \in \mathcal{N}(i)\cup \{ i \}} \exp( \beta \cdot \cos(\mathbf{x}_i, \mathbf{x}_k))}\]with trainable parameter \(\beta\).
Parameters: requires_grad (bool, optional) – If set to False
, \(\beta\) will not be trainable. (default:True
)
-
class
GINConv
(nn, eps=0, train_eps=False)[source]¶ The graph isomorphism operator from the “How Powerful are Graph Neural Networks?” paper
\[\mathbf{x}^{\prime}_i = h_{\mathbf{\Theta}} \left( (1 + \epsilon) \cdot \mathbf{x}_i + \sum_{j \in \mathcal{N}(i)} \mathbf{x}_j \right),\]here \(h_{\mathbf{\Theta}}\) denotes a neural network, .i.e. a MLP.
Parameters:
-
class
PointConv
(local_nn=None, global_nn=None)[source]¶ The PointNet set layer from the “PointNet: Deep Learning on Point Sets for 3D Classification and Segmentation” and “PointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space” papers
\[\mathbf{x}^{\prime}_i = \gamma_{\mathbf{\Theta}} \left( \max_{j \in \mathcal{N}(i) \cup \{ i \}} h_{\mathbf{\Theta}} ( \mathbf{x}_j \, \Vert \, \mathbf{p}_j - \mathbf{p}_i) \right)\]where \(\gamma_{\mathbf{\Theta}}\) and \(h_{\mathbf{\Theta}}\) denote neural networks, .i.e. MLPs, and \(\mathbf{P} \in \mathbb{R}^{N \times D}\) defines the position of each point.
Parameters:
-
class
GMMConv
(in_channels, out_channels, dim, bias=True)[source]¶ The gaussian mixture model convolutional operator from the “Geometric Deep Learning on Graphs and Manifolds using Mixture Model CNNs” paper
\[\mathbf{x}^{\prime}_i = \mathbf{\Theta} \cdot \sum_{j \in \mathcal{N}(i) \cup \{ i \}} w(\mathbf{e}_{i,j}) \odot \mathbf{x}_j,\]where
\[w_m(\mathbf{e}) = \exp \left( -\frac{1}{2} {\left( \mathbf{e} - \mathbf{\mu}_m \right)}^{\top} \Sigma_m^{-1} \left( \mathbf{e} - \mathbf{\mu}_m \right) \right)\]with trainable mean vector \(\mathbf{\mu}_m\) and diagonal covariance matrix \(\mathbf{\Sigma}_m\) for each input channel \(m\).
Parameters:
-
class
SplineConv
(in_channels, out_channels, dim, kernel_size, is_open_spline=True, degree=1, norm=True, root_weight=True, bias=True)[source]¶ The spline-based convolutional operator from the “SplineCNN: Fast Geometric Deep Learning with Continuous B-Spline Kernels” paper
\[\mathbf{x}^{\prime}_i = \frac{1}{|\mathcal{N}(i)|} \sum_{j \in \mathcal{N}(i)} \mathbf{x}_j \cdot h_{\mathbf{\Theta}}(\mathbf{e}_{i,j}),\]where \(h_{\mathbf{\Theta}}\) denotes a kernel function defined over the weighted B-Spline tensor product basis.
Parameters: - in_channels (int) – Size of each input sample.
- out_channels (int) – Size of each output sample.
- dim (int) – Pseudo-coordinate dimensionality.
- kernel_size (int or [int]) – Size of the convolving kernel.
- is_open_spline (bool or [bool], optional) – If set to
False
, the operator will use a closed B-spline basis in this dimension. (defaultTrue
) - degree (int, optional) – B-spline basis degrees. (default:
1
) - norm (bool, optional) – If set to
False
, output node features will not be degree-normalized. (default:True
) - root_weight (bool, optional) – If set to
False
, the layer will not add transformed root node features to the output. (default:True
) - bias (bool, optional) – If set to
False
, the layer will not learn an additive bias. (default:True
)
-
class
NNConv
(in_channels, out_channels, nn, aggr='add', root_weight=True, bias=True)[source]¶ The continuous kernel-based convolutional operator adapted from the “Neural Message Passing for Quantum Chemistry” paper
\[\mathbf{x}^{\prime}_i = \mathbf{\Theta} \mathbf{x}_i + \sum_{j \in \mathcal{N}(i)} \mathbf{x}_j \cdot h_{\mathbf{\Theta}}(\mathbf{e}_{i,j}),\]where \(h_{\mathbf{\Theta}}\) denotes a neural network, .i.e. a MLP.
Parameters: - in_channels (int) – Size of each input sample.
- out_channels (int) – Size of each output sample.
- nn (nn.Sequential) – Neural network \(h_{\mathbf{\Theta}}\).
- aggr (string) – The aggregation operator to use (one of
"add"
,"mean"
,"max"
). (default:"add"
) - root_weight (bool, optional) – If set to
False
, the layer will not add the transformed root node features to the output. (default:True
) - bias (bool, optional) – If set to
False
, the layer will not learn an additive bias. (default:True
)
-
class
EdgeConv
(nn, aggr='add')[source]¶ The edge convolutional operator from the “Dynamic Graph CNN for Learning on Point Clouds” paper
\[\mathbf{x}^{\prime}_i = \sum_{j \in \mathcal{N}(i)} h_{\mathbf{\Theta}}(\mathbf{x}_i \, \Vert \, \mathbf{x}_j - \mathbf{x}_i),\]where \(h_{\mathbf{\Theta}}\) denotes a neural network, .i.e. a MLP.
Parameters: - nn (nn.Sequential) – Neural network \(h_{\mathbf{\Theta}}\).
- aggr (string) – The aggregation operator to use (one of
"add"
,"mean"
,"max"
). (default:"add"
)
-
class
XConv
(in_channels, out_channels, dim, kernel_size, hidden_channels=None, dilation=1, bias=True)[source]¶ The convolutional operator on \(\mathcal{X}\)-transformed points from the “PointCNN: Convolution On X-Transformed Points” paper
\[\mathbf{x}^{\prime}_i = \mathrm{Conv}\left(\mathbf{K}, \gamma_{\mathbf{\Theta}}(\mathbf{P}_i - \mathbf{p}_i) \times \left( h_\mathbf{\Theta}(\mathbf{P}_i - \mathbf{p}_i) \, \Vert \, \mathbf{x}_i \right) \right),\]where \(\mathbf{K}\) and \(\mathbf{P}_i\) denote the trainable filter and neighboring point positions of \(\mathbf{x}_i\), respectively. \(\gamma_{\mathbf{\Theta}}\) and \(h_{\mathbf{\Theta}}\) describe neural networks, i.e. MLPs, where \(h_{\mathbf{\Theta}}\) individually lifts each point into a higher-dimensional space, and \(\gamma_{\mathbf{\Theta}}\) computes the \(\mathcal{X}\)- transformation matrix based on all points in a neighborhood.
Parameters: - in_channels (int) – Size of each input sample.
- out_channels (int) – Size of each output sample.
- kernel_size (int) – Size of the convolving kernel, i.e. number of neighbors including self-loops.
- hidden_channels (int, optional) – Output size of
\(h_{\mathbf{\Theta}}\), i.e. dimensionality of lifted
points. If set to
None
, will be automatically set toin_channels / 4
. (default:None
) - dilation (int, optional) – The factor by which the neighborhood is
extended, from which
kernel_size
neighbors are then uniformly sampled. Can be interpreted as the dilation rate of classical convolutional operators. (default:1
) - bias (bool, optional) – If set to
False
, the layer will not learn an additive bias. (default:True
)
-
class
MetaLayer
(edge_model=None, node_model=None, global_model=None)[source]¶ A meta layer for building any kind of graph network, inspired by the “Relational Inductive Biases, Deep Learning, and Graph Networks” paper.
A graph network takes a graph as input and returns an updated graph as output (with same connectivity). The input graph has node features
x
, edge featuresedge_attr
as well as global-level featuresu
. The output graph has the same structure, but updated features.Edge features, node features as well as global features are updated by calling the functions
edge_model
,node_model
andglobal_model
, respectively.Parameters: - edge_model (func, optional) – A callable which updates a graph’s edge
features based on its source and target node features, its current
edge features and its global features. (default:
None
) - node_model (func, optional) – A callable which updates a graph’s node
features based on its current node features, its graph
connectivity, its edge features and its global features.
(default:
None
) - global_model (func, optional) – A callable which updates a graph’s
global features based on its node features, its graph connectivity,
its edge features and its current global features. To allow for
batch-wise graph processing, the callable takes a fifth argument
batch
, which determines the assignment of nodes to their specific graphs. (default:None
)
from torch.nn import Sequential as Seq, Linear as Lin, ReLU from torch_scatter import scatter_mean from torch_geometric.nn import MetaLayer class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.edge_mlp = Seq(Lin(..., ...), ReLU(), Lin(..., ...)) self.node_mlp = Seq(Lin(..., ...), ReLU(), Lin(..., ...)) self.global_mlp = Seq(Lin(..., ...), ReLU(), Lin(..., ...)) def edge_model(source, target, edge_attr, u): # source, target: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # u: [B, F_u], where B is the number of graphs. out = torch.cat([source, target, edge_attr], dim=1) return self.edge_mlp(out) def node_model(x, edge_index, edge_attr, u): # x: [N, F_x], where N is the number of nodes. # edge_index: [2, E] with max entry N - 1. # edge_attr: [E, F_e] # u: [B, F_u] row, col = edge_index out = torch.cat([x[col], edge_attr], dim=1) out = self.node_mlp(out) return scatter_mean(out, row, dim=0, dim_size=x.size(0)) def global_model(x, edge_index, edge_attr, u, batch): # x: [N, F_x], where N is the number of nodes. # edge_index: [2, E] with max entry N - 1. # edge_attr: [E, F_e] # u: [B, F_u] # batch: [N] with max entry B - 1. out = torch.cat([u, scatter_mean(x, batch, dim=0)], dim=1) return self.global_mlp(out) self.op = MetaLayer(edge_model, node_model, global_model) def forward(self, x, edge_index, edge_attr, u, batch): return self.op(x, edge_index, edge_attr, u, batch)
- edge_model (func, optional) – A callable which updates a graph’s edge
features based on its source and target node features, its current
edge features and its global features. (default:
Dense Convolutional Layers¶
-
class
DenseSAGEConv
(in_channels, out_channels, normalize=True, bias=True)[source]¶ See
torch_geometric.nn.conv.sage_conv.SAGEConv
.Return type: Tensor
-
forward
(x, adj, mask=None, add_loop=True)[source]¶ Parameters: - x (Tensor) – Node feature tensor \(\mathbf{X} \in \mathbb{R}^{B \times N \times F}\), with batch-size \(B\), (maximum) number of nodes \(N\) for each graph, and feature dimension \(F\).
- adj (Tensor) – Adjacency tensor \(\mathbf{A} \in \mathbb{R}^{B \times N \times N}\).
- mask (ByteTensor, optional) – Mask matrix
\(\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}\) indicating
the valid nodes for each graph. (default:
None
) - add_loop (bool, optional) – If set to
False
, the layer will not automatically add self-loops to the adjacency matrices. (default:True
)
-
Global Pooling Layers¶
-
global_add_pool
(x, batch, size=None)[source]¶ Returns batch-wise graph-level-outputs by adding node features across the node node dimension, so that for a single graph \(\mathcal{G}_i\) its output is computed by
\[\mathbf{r}_i = \sum_{n=1}^{N_i} \mathbf{x}_n\]Parameters: - x (Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).
- batch (LongTensor) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific graph.
- size (int, optional) – Batch-size \(B\).
Automatically calculated if not given. (default:
None
)
Return type: Tensor
-
global_mean_pool
(x, batch, size=None)[source]¶ Returns batch-wise graph-level-outputs by averaging node features across the node node dimension, so that for a single graph \(\mathcal{G}_i\) its output is computed by
\[\mathbf{r}_i = \frac{1}{N_i} \sum_{n=1}^{N_i} \mathbf{x}_n\]Parameters: - x (Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).
- batch (LongTensor) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific graph.
- size (int, optional) – Batch-size \(B\).
Automatically calculated if not given. (default:
None
)
Return type: Tensor
-
global_max_pool
(x, batch, size=None)[source]¶ Returns batch-wise graph-level-outputs by taking the channel-wise maximum node features across the node dimension, so that for a single graph \(\mathcal{G}_i\) its output is computed by
\[\mathbf{r}_i = \mathrm{max}_{n=1}^{N_i} \, \mathbf{x}_n\]Parameters: - x (Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).
- batch (LongTensor) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific graph.
- size (int, optional) – Batch-size \(B\).
Automatically calculated if not given. (default:
None
)
Return type: Tensor
-
global_sort_pool
(x, batch, k)[source]¶ The global pooling operator from the “An End-to-End Deep Learning Architecture for Graph Classification” paper, where node features are first sorted individually and then sorted in descending order based on their last features. The first \(k\) nodes form the output of the layer.
Parameters: - x (Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{N \times F}\).
- batch (LongTensor) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific graph.
- k (int) – The number of nodes to hold for each graph.
Return type: Tensor
-
class
Set2Set
(in_channels, processing_steps, num_layers=1)[source]¶ The global pooling operator based on iterative content-based attention from the “Order Matters: Sequence to sequence for sets” paper
\[ \begin{align}\begin{aligned}\mathbf{q}_t &= \mathrm{LSTM}(\mathbf{q}^{*}_{t-1})\\\alpha_{i,t} &= \mathrm{softmax}(\mathbf{x}_i \cdot \mathbf{q}_t)\\\mathbf{r}_t &= \sum_{i=1}^N \alpha_{i,t} \mathbf{x}_i\\\mathbf{q}^{*}_t &= \mathbf{q}_t \, \Vert \, \mathbf{r}_t,\end{aligned}\end{align} \]where \(\mathbf{q}^{*}_T\) defines the output of the layer with twice the dimensionality as the input.
Parameters: - in_channels (int) – Size of each input sample.
- processing_steps (int) – Number of iterations \(T\).
- num_layers (int, optional) – Number of recurrent layers, .e.g, setting
num_layers=2
would mean stacking two LSTMs together to form a stacked LSTM, with the second LSTM taking in outputs of the first LSTM and computing the final results. (default:1
)
Sparse Hierarchical Pooling Layers¶
-
class
TopKPooling
(in_channels, ratio=0.5)[source]¶ \(\mathrm{top}_k\) pooling operator from the “Graph U-Net” and “Towards Sparse Hierarchical Graph Classifiers” papers
\[ \begin{align}\begin{aligned}\mathbf{y} &= \frac{\mathbf{X}\mathbf{p}}{\| \mathbf{p} \|}\\\mathbf{i} &= \mathrm{top}_k(\mathbf{y})\\\mathbf{X}^{\prime} &= (\mathbf{X} \odot \mathrm{tanh}(\mathbf{y}))_{\mathbf{i}}\\\mathbf{A}^{\prime} &= \mathbf{A}_{\mathbf{i},\mathbf{i}},\end{aligned}\end{align} \]where nodes are dropped based on a learnable projection score \(\mathbf{p}\).
Parameters:
Dense Hierarchical Pooling Layers¶
-
dense_diff_pool
(x, adj, s, mask=None)[source]¶ Differentiable pooling operator from the “Hierarchical Graph Representation Learning with Differentiable Pooling” paper
\[ \begin{align}\begin{aligned}\mathbf{X}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot \mathbf{X}\\\mathbf{A}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot \mathbf{A} \cdot \mathrm{softmax}(\mathbf{S})\end{aligned}\end{align} \]based on dense learned assignments \(\mathbf{S} \in \mathbb{R}^{B \times N \times C}\).
Parameters: - x (Tensor) – Node feature tensor \(\mathbf{X} \in \mathbb{R}^{B \times N \times F}\) with batch-size \(B\), (maximum) number of nodes \(N\) for each graph, and feature dimension \(F\).
- adj (Tensor) – Adjacency tensor \(\mathbf{A} \in \mathbb{R}^{B \times N \times N}\).
- s (Tensor) – Assignment tensor \(\mathbf{S} \in \mathbb{R}^{B \times N \times C}\) with number of clusters \(C\). The softmax does not have to be applied beforehand, since it is executed within this method.
- mask (ByteTensor, optional) – Mask matrix
\(\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}\) indicating
the valid nodes for each graph. (default:
None
)
Return type: (
Tensor
,Tensor
)


1,284
Daily Views
88
Sales
09
Comments
$4,284
Earnings
Recent Orders
View All| Name | Price | Payment | Status |
| Star Refrigerator | $1200 | Paid | Delivered |
| Star Refrigerator | $200 | Due | Pending |
| Star Refrigerator | $1200 | Due | In Progress |
| Star Refrigerator | $100 | Paid | Delivered |
| Star Refrigerator | $500 | Due | In Progress |
| Star Refrigerator | $600 | Paid | Pending |
Recent Customers
Omega |
|
Neema |
|
Gianna |
|
Omega |
|
Omega |


Signs
This annotation style let's you add fingerings, dynamics, ornaments and articulations into your scores.
The buttons on the left give you quick access to the most recently used annotations. Tap on any item in this list to quickly insert it into your score.
The slider allows you to precisely adjust the size of the selected annotation.
The reset button resets the annotation to its original size.
Use two fingers to select and edit multiple annotations.
Long press and drag an annotation to move it to a new location.
You can manually resize an annotation by simply dragging out its bottom right edge.