repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
timothydmorton/isochrones
isochrones/starmodel.py
StarModel.corner_observed
def corner_observed(self, **kwargs): """Makes corner plot for each observed node magnitude """ tot_mags = [] names = [] truths = [] rng = [] for n in self.obs.get_obs_nodes(): labels = [l.label for l in n.get_model_nodes()] band = n.band mags = [self.samples['{}_mag_{}'.format(band, l)] for l in labels] tot_mag = addmags(*mags) if n.relative: name = '{} $\Delta${}'.format(n.instrument, n.band) ref = n.reference if ref is None: continue ref_labels = [l.label for l in ref.get_model_nodes()] ref_mags = [self.samples['{}_mag_{}'.format(band, l)] for l in ref_labels] tot_ref_mag = addmags(*ref_mags) tot_mags.append(tot_mag - tot_ref_mag) truths.append(n.value[0] - ref.value[0]) else: name = '{} {}'.format(n.instrument, n.band) tot_mags.append(tot_mag) truths.append(n.value[0]) names.append(name) rng.append((min(truths[-1], np.percentile(tot_mags[-1],0.5)), max(truths[-1], np.percentile(tot_mags[-1],99.5)))) tot_mags = np.array(tot_mags).T return corner.corner(tot_mags, labels=names, truths=truths, range=rng, **kwargs)
python
def corner_observed(self, **kwargs): """Makes corner plot for each observed node magnitude """ tot_mags = [] names = [] truths = [] rng = [] for n in self.obs.get_obs_nodes(): labels = [l.label for l in n.get_model_nodes()] band = n.band mags = [self.samples['{}_mag_{}'.format(band, l)] for l in labels] tot_mag = addmags(*mags) if n.relative: name = '{} $\Delta${}'.format(n.instrument, n.band) ref = n.reference if ref is None: continue ref_labels = [l.label for l in ref.get_model_nodes()] ref_mags = [self.samples['{}_mag_{}'.format(band, l)] for l in ref_labels] tot_ref_mag = addmags(*ref_mags) tot_mags.append(tot_mag - tot_ref_mag) truths.append(n.value[0] - ref.value[0]) else: name = '{} {}'.format(n.instrument, n.band) tot_mags.append(tot_mag) truths.append(n.value[0]) names.append(name) rng.append((min(truths[-1], np.percentile(tot_mags[-1],0.5)), max(truths[-1], np.percentile(tot_mags[-1],99.5)))) tot_mags = np.array(tot_mags).T return corner.corner(tot_mags, labels=names, truths=truths, range=rng, **kwargs)
[ "def", "corner_observed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "tot_mags", "=", "[", "]", "names", "=", "[", "]", "truths", "=", "[", "]", "rng", "=", "[", "]", "for", "n", "in", "self", ".", "obs", ".", "get_obs_nodes", "(", ")", ":...
Makes corner plot for each observed node magnitude
[ "Makes", "corner", "plot", "for", "each", "observed", "node", "magnitude" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L1015-L1049
train
210,800
timothydmorton/isochrones
isochrones/grid.py
ModelGrid._get_df
def _get_df(self): """Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band`` """ grids = {} df = pd.DataFrame() for bnd in self.bands: s,b = self.get_band(bnd, **self.kwargs) logging.debug('loading {} band from {}'.format(b,s)) if s not in grids: grids[s] = self.get_hdf(s) if self.common_columns[0] not in df: df[list(self.common_columns)] = grids[s][list(self.common_columns)] col = grids[s][b] n_nan = np.isnan(col).sum() if n_nan > 0: logging.debug('{} NANs in {} column'.format(n_nan, b)) df.loc[:, bnd] = col.values #dunno why it has to be this way; something # funny with indexing. return df
python
def _get_df(self): """Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band`` """ grids = {} df = pd.DataFrame() for bnd in self.bands: s,b = self.get_band(bnd, **self.kwargs) logging.debug('loading {} band from {}'.format(b,s)) if s not in grids: grids[s] = self.get_hdf(s) if self.common_columns[0] not in df: df[list(self.common_columns)] = grids[s][list(self.common_columns)] col = grids[s][b] n_nan = np.isnan(col).sum() if n_nan > 0: logging.debug('{} NANs in {} column'.format(n_nan, b)) df.loc[:, bnd] = col.values #dunno why it has to be this way; something # funny with indexing. return df
[ "def", "_get_df", "(", "self", ")", ":", "grids", "=", "{", "}", "df", "=", "pd", ".", "DataFrame", "(", ")", "for", "bnd", "in", "self", ".", "bands", ":", "s", ",", "b", "=", "self", ".", "get_band", "(", "bnd", ",", "*", "*", "self", ".", ...
Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band``
[ "Returns", "stellar", "model", "grid", "with", "desired", "bandpasses", "and", "with", "standard", "column", "names" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/grid.py#L101-L122
train
210,801
timothydmorton/isochrones
isochrones/grid.py
ModelGrid.extract_master_tarball
def extract_master_tarball(cls): """Unpack tarball of tarballs """ if not os.path.exists(cls.master_tarball_file): cls.download_grids() with tarfile.open(os.path.join(ISOCHRONES, cls.master_tarball_file)) as tar: logging.info('Extracting {}...'.format(cls.master_tarball_file)) tar.extractall(ISOCHRONES)
python
def extract_master_tarball(cls): """Unpack tarball of tarballs """ if not os.path.exists(cls.master_tarball_file): cls.download_grids() with tarfile.open(os.path.join(ISOCHRONES, cls.master_tarball_file)) as tar: logging.info('Extracting {}...'.format(cls.master_tarball_file)) tar.extractall(ISOCHRONES)
[ "def", "extract_master_tarball", "(", "cls", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "cls", ".", "master_tarball_file", ")", ":", "cls", ".", "download_grids", "(", ")", "with", "tarfile", ".", "open", "(", "os", ".", "path", ".",...
Unpack tarball of tarballs
[ "Unpack", "tarball", "of", "tarballs" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/grid.py#L162-L170
train
210,802
timothydmorton/isochrones
isochrones/grid.py
ModelGrid.df_all
def df_all(self, phot): """Subclasses may want to sort this """ df = pd.concat([self.to_df(f) for f in self.get_filenames(phot)]) return df
python
def df_all(self, phot): """Subclasses may want to sort this """ df = pd.concat([self.to_df(f) for f in self.get_filenames(phot)]) return df
[ "def", "df_all", "(", "self", ",", "phot", ")", ":", "df", "=", "pd", ".", "concat", "(", "[", "self", ".", "to_df", "(", "f", ")", "for", "f", "in", "self", ".", "get_filenames", "(", "phot", ")", "]", ")", "return", "df" ]
Subclasses may want to sort this
[ "Subclasses", "may", "want", "to", "sort", "this" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/grid.py#L188-L192
train
210,803
timothydmorton/isochrones
isochrones/mist/grid.py
MISTModelGrid.get_band
def get_band(cls, b, **kwargs): """Defines what a "shortcut" band name refers to. Returns phot_system, band """ phot = None # Default to SDSS for these if b in ['u','g','r','i','z']: phot = 'SDSS' band = 'SDSS_{}'.format(b) elif b in ['U','B','V','R','I']: phot = 'UBVRIplus' band = 'Bessell_{}'.format(b) elif b in ['J','H','Ks']: phot = 'UBVRIplus' band = '2MASS_{}'.format(b) elif b=='K': phot = 'UBVRIplus' band = '2MASS_Ks' elif b in ['kep','Kepler','Kp']: phot = 'UBVRIplus' band = 'Kepler_Kp' elif b=='TESS': phot = 'UBVRIplus' band = 'TESS' elif b in ['W1','W2','W3','W4']: phot = 'WISE' band = 'WISE_{}'.format(b) elif b in ('G', 'BP', 'RP'): phot = 'UBVRIplus' band = 'Gaia_{}'.format(b) if 'version' in kwargs: if kwargs['version']=='1.1': band += '_DR2Rev' else: m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b) if m: if m.group(1) in cls.phot_systems: phot = m.group(1) if phot=='PanSTARRS': band = 'PS_{}'.format(m.group(2)) else: band = m.group(0) elif m.group(1) in ['UK','UKIRT']: phot = 'UKIDSS' band = 'UKIDSS_{}'.format(m.group(2)) if phot is None: for system, bands in cls.phot_bands.items(): if b in bands: phot = system band = b break if phot is None: raise ValueError('MIST grids cannot resolve band {}!'.format(b)) return phot, band
python
def get_band(cls, b, **kwargs): """Defines what a "shortcut" band name refers to. Returns phot_system, band """ phot = None # Default to SDSS for these if b in ['u','g','r','i','z']: phot = 'SDSS' band = 'SDSS_{}'.format(b) elif b in ['U','B','V','R','I']: phot = 'UBVRIplus' band = 'Bessell_{}'.format(b) elif b in ['J','H','Ks']: phot = 'UBVRIplus' band = '2MASS_{}'.format(b) elif b=='K': phot = 'UBVRIplus' band = '2MASS_Ks' elif b in ['kep','Kepler','Kp']: phot = 'UBVRIplus' band = 'Kepler_Kp' elif b=='TESS': phot = 'UBVRIplus' band = 'TESS' elif b in ['W1','W2','W3','W4']: phot = 'WISE' band = 'WISE_{}'.format(b) elif b in ('G', 'BP', 'RP'): phot = 'UBVRIplus' band = 'Gaia_{}'.format(b) if 'version' in kwargs: if kwargs['version']=='1.1': band += '_DR2Rev' else: m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b) if m: if m.group(1) in cls.phot_systems: phot = m.group(1) if phot=='PanSTARRS': band = 'PS_{}'.format(m.group(2)) else: band = m.group(0) elif m.group(1) in ['UK','UKIRT']: phot = 'UKIDSS' band = 'UKIDSS_{}'.format(m.group(2)) if phot is None: for system, bands in cls.phot_bands.items(): if b in bands: phot = system band = b break if phot is None: raise ValueError('MIST grids cannot resolve band {}!'.format(b)) return phot, band
[ "def", "get_band", "(", "cls", ",", "b", ",", "*", "*", "kwargs", ")", ":", "phot", "=", "None", "# Default to SDSS for these", "if", "b", "in", "[", "'u'", ",", "'g'", ",", "'r'", ",", "'i'", ",", "'z'", "]", ":", "phot", "=", "'SDSS'", "band", ...
Defines what a "shortcut" band name refers to. Returns phot_system, band
[ "Defines", "what", "a", "shortcut", "band", "name", "refers", "to", ".", "Returns", "phot_system", "band" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/mist/grid.py#L92-L147
train
210,804
timothydmorton/isochrones
isochrones/observation.py
Node.remove_child
def remove_child(self, label): """ Removes node by label """ ind = None for i,c in enumerate(self.children): if c.label==label: ind = i if ind is None: logging.warning('No child labeled {}.'.format(label)) return self.children.pop(ind) self._clear_all_leaves()
python
def remove_child(self, label): """ Removes node by label """ ind = None for i,c in enumerate(self.children): if c.label==label: ind = i if ind is None: logging.warning('No child labeled {}.'.format(label)) return self.children.pop(ind) self._clear_all_leaves()
[ "def", "remove_child", "(", "self", ",", "label", ")", ":", "ind", "=", "None", "for", "i", ",", "c", "in", "enumerate", "(", "self", ".", "children", ")", ":", "if", "c", ".", "label", "==", "label", ":", "ind", "=", "i", "if", "ind", "is", "N...
Removes node by label
[ "Removes", "node", "by", "label" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L176-L189
train
210,805
timothydmorton/isochrones
isochrones/observation.py
Node.select_leaves
def select_leaves(self, name): """Returns all leaves under all nodes matching name """ if self.is_leaf: return [self] if re.search(name, self.label) else [] else: leaves = [] if re.search(name, self.label): for c in self.children: leaves += c._get_leaves() #all leaves else: for c in self.children: leaves += c.select_leaves(name) #only matching ones return leaves
python
def select_leaves(self, name): """Returns all leaves under all nodes matching name """ if self.is_leaf: return [self] if re.search(name, self.label) else [] else: leaves = [] if re.search(name, self.label): for c in self.children: leaves += c._get_leaves() #all leaves else: for c in self.children: leaves += c.select_leaves(name) #only matching ones return leaves
[ "def", "select_leaves", "(", "self", ",", "name", ")", ":", "if", "self", ".", "is_leaf", ":", "return", "[", "self", "]", "if", "re", ".", "search", "(", "name", ",", "self", ".", "label", ")", "else", "[", "]", "else", ":", "leaves", "=", "[", ...
Returns all leaves under all nodes matching name
[ "Returns", "all", "leaves", "under", "all", "nodes", "matching", "name" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L215-L230
train
210,806
timothydmorton/isochrones
isochrones/observation.py
Node.get_obs_leaves
def get_obs_leaves(self): """Returns the last obs nodes that are leaves """ obs_leaves = [] for n in self: if n.is_leaf: if isinstance(n, ModelNode): l = n.parent else: l = n if l not in obs_leaves: obs_leaves.append(l) return obs_leaves
python
def get_obs_leaves(self): """Returns the last obs nodes that are leaves """ obs_leaves = [] for n in self: if n.is_leaf: if isinstance(n, ModelNode): l = n.parent else: l = n if l not in obs_leaves: obs_leaves.append(l) return obs_leaves
[ "def", "get_obs_leaves", "(", "self", ")", ":", "obs_leaves", "=", "[", "]", "for", "n", "in", "self", ":", "if", "n", ".", "is_leaf", ":", "if", "isinstance", "(", "n", ",", "ModelNode", ")", ":", "l", "=", "n", ".", "parent", "else", ":", "l", ...
Returns the last obs nodes that are leaves
[ "Returns", "the", "last", "obs", "nodes", "that", "are", "leaves" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L249-L261
train
210,807
timothydmorton/isochrones
isochrones/observation.py
ObsNode.distance
def distance(self, other): """Coordinate distance from another ObsNode """ return distance((self.separation, self.pa), (other.separation, other.pa))
python
def distance(self, other): """Coordinate distance from another ObsNode """ return distance((self.separation, self.pa), (other.separation, other.pa))
[ "def", "distance", "(", "self", ",", "other", ")", ":", "return", "distance", "(", "(", "self", ".", "separation", ",", "self", ".", "pa", ")", ",", "(", "other", ".", "separation", ",", "other", ".", "pa", ")", ")" ]
Coordinate distance from another ObsNode
[ "Coordinate", "distance", "from", "another", "ObsNode" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L344-L347
train
210,808
timothydmorton/isochrones
isochrones/observation.py
ObsNode.Nstars
def Nstars(self): """ dictionary of number of stars per system """ if self._Nstars is None: N = {} for n in self.get_model_nodes(): if n.index not in N: N[n.index] = 1 else: N[n.index] += 1 self._Nstars = N return self._Nstars
python
def Nstars(self): """ dictionary of number of stars per system """ if self._Nstars is None: N = {} for n in self.get_model_nodes(): if n.index not in N: N[n.index] = 1 else: N[n.index] += 1 self._Nstars = N return self._Nstars
[ "def", "Nstars", "(", "self", ")", ":", "if", "self", ".", "_Nstars", "is", "None", ":", "N", "=", "{", "}", "for", "n", "in", "self", ".", "get_model_nodes", "(", ")", ":", "if", "n", ".", "index", "not", "in", "N", ":", "N", "[", "n", ".", ...
dictionary of number of stars per system
[ "dictionary", "of", "number", "of", "stars", "per", "system" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L370-L382
train
210,809
timothydmorton/isochrones
isochrones/observation.py
ObsNode.add_model
def add_model(self, ic, N=1, index=0): """ Should only be able to do this to a leaf node. Either N and index both integers OR index is list of length=N """ if type(index) in [list,tuple]: if len(index) != N: raise ValueError('If a list, index must be of length N.') else: index = [index]*N for idx in index: existing = self.get_system(idx) tag = len(existing) self.add_child(ModelNode(ic, index=idx, tag=tag))
python
def add_model(self, ic, N=1, index=0): """ Should only be able to do this to a leaf node. Either N and index both integers OR index is list of length=N """ if type(index) in [list,tuple]: if len(index) != N: raise ValueError('If a list, index must be of length N.') else: index = [index]*N for idx in index: existing = self.get_system(idx) tag = len(existing) self.add_child(ModelNode(ic, index=idx, tag=tag))
[ "def", "add_model", "(", "self", ",", "ic", ",", "N", "=", "1", ",", "index", "=", "0", ")", ":", "if", "type", "(", "index", ")", "in", "[", "list", ",", "tuple", "]", ":", "if", "len", "(", "index", ")", "!=", "N", ":", "raise", "ValueError...
Should only be able to do this to a leaf node. Either N and index both integers OR index is list of length=N
[ "Should", "only", "be", "able", "to", "do", "this", "to", "a", "leaf", "node", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L421-L437
train
210,810
timothydmorton/isochrones
isochrones/observation.py
ObsNode.model_mag
def model_mag(self, pardict, use_cache=True): """ pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """ if pardict == self._cache_key and use_cache: #print('{}: using cached'.format(self)) return self._cache_val #print('{}: calculating'.format(self)) self._cache_key = pardict # Generate appropriate parameter vector from dictionary p = [] for l in self.leaf_labels: p.extend(pardict[l]) assert len(p) == self.n_params tot = np.inf #print('Building {} mag for {}:'.format(self.band, self)) for i,m in enumerate(self.leaves): mag = m.evaluate(p[i*5:(i+1)*5], self.band) # logging.debug('{}: mag={}'.format(self,mag)) #print('{}: {}({}) = {}'.format(m,self.band,p[i*5:(i+1)*5],mag)) tot = addmags(tot, mag) self._cache_val = tot return tot
python
def model_mag(self, pardict, use_cache=True): """ pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """ if pardict == self._cache_key and use_cache: #print('{}: using cached'.format(self)) return self._cache_val #print('{}: calculating'.format(self)) self._cache_key = pardict # Generate appropriate parameter vector from dictionary p = [] for l in self.leaf_labels: p.extend(pardict[l]) assert len(p) == self.n_params tot = np.inf #print('Building {} mag for {}:'.format(self.band, self)) for i,m in enumerate(self.leaves): mag = m.evaluate(p[i*5:(i+1)*5], self.band) # logging.debug('{}: mag={}'.format(self,mag)) #print('{}: {}({}) = {}'.format(m,self.band,p[i*5:(i+1)*5],mag)) tot = addmags(tot, mag) self._cache_val = tot return tot
[ "def", "model_mag", "(", "self", ",", "pardict", ",", "use_cache", "=", "True", ")", ":", "if", "pardict", "==", "self", ".", "_cache_key", "and", "use_cache", ":", "#print('{}: using cached'.format(self))", "return", "self", ".", "_cache_val", "#print('{}: calcul...
pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector
[ "pardict", "is", "a", "dictionary", "of", "parameters", "for", "all", "leaves", "gets", "converted", "back", "to", "traditional", "parameter", "vector" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L439-L468
train
210,811
timothydmorton/isochrones
isochrones/observation.py
ObsNode.lnlike
def lnlike(self, pardict, use_cache=True): """ returns log-likelihood of this observation pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """ mag, dmag = self.value if np.isnan(dmag): return 0 if self.relative: # If this *is* the reference, just return if self.reference is None: return 0 mod = (self.model_mag(pardict, use_cache=use_cache) - self.reference.model_mag(pardict, use_cache=use_cache)) mag -= self.reference.value[0] else: mod = self.model_mag(pardict, use_cache=use_cache) lnl = -0.5*(mag - mod)**2 / dmag**2 # logging.debug('{} {}: mag={}, mod={}, lnlike={}'.format(self.instrument, # self.band, # mag,mod,lnl)) return lnl
python
def lnlike(self, pardict, use_cache=True): """ returns log-likelihood of this observation pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector """ mag, dmag = self.value if np.isnan(dmag): return 0 if self.relative: # If this *is* the reference, just return if self.reference is None: return 0 mod = (self.model_mag(pardict, use_cache=use_cache) - self.reference.model_mag(pardict, use_cache=use_cache)) mag -= self.reference.value[0] else: mod = self.model_mag(pardict, use_cache=use_cache) lnl = -0.5*(mag - mod)**2 / dmag**2 # logging.debug('{} {}: mag={}, mod={}, lnlike={}'.format(self.instrument, # self.band, # mag,mod,lnl)) return lnl
[ "def", "lnlike", "(", "self", ",", "pardict", ",", "use_cache", "=", "True", ")", ":", "mag", ",", "dmag", "=", "self", ".", "value", "if", "np", ".", "isnan", "(", "dmag", ")", ":", "return", "0", "if", "self", ".", "relative", ":", "# If this *is...
returns log-likelihood of this observation pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector
[ "returns", "log", "-", "likelihood", "of", "this", "observation" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L470-L496
train
210,812
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.from_df
def from_df(cls, df, **kwargs): """ DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa """ tree = cls(**kwargs) for (n,b), g in df.groupby(['name','band']): #g.sort('separation', inplace=True) #ensures that the first is reference sources = [Source(**s[['mag','e_mag','separation','pa','relative']]) for _,s in g.iterrows()] obs = Observation(n, b, g.resolution.mean(), sources=sources, relative=g.relative.any()) tree.add_observation(obs) # For all relative mags, set reference to be brightest return tree
python
def from_df(cls, df, **kwargs): """ DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa """ tree = cls(**kwargs) for (n,b), g in df.groupby(['name','band']): #g.sort('separation', inplace=True) #ensures that the first is reference sources = [Source(**s[['mag','e_mag','separation','pa','relative']]) for _,s in g.iterrows()] obs = Observation(n, b, g.resolution.mean(), sources=sources, relative=g.relative.any()) tree.add_observation(obs) # For all relative mags, set reference to be brightest return tree
[ "def", "from_df", "(", "cls", ",", "df", ",", "*", "*", "kwargs", ")", ":", "tree", "=", "cls", "(", "*", "*", "kwargs", ")", "for", "(", "n", ",", "b", ")", ",", "g", "in", "df", ".", "groupby", "(", "[", "'name'", ",", "'band'", "]", ")",...
DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa
[ "DataFrame", "must", "have", "the", "right", "columns", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L770-L790
train
210,813
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.to_df
def to_df(self): """ Returns DataFrame with photometry from observations organized. This DataFrame should be able to be read back in to reconstruct the observation. """ df = pd.DataFrame() name = [] band = [] resolution = [] mag = [] e_mag = [] separation = [] pa = [] relative = [] for o in self._observations: for s in o.sources: name.append(o.name) band.append(o.band) resolution.append(o.resolution) mag.append(s.mag) e_mag.append(s.e_mag) separation.append(s.separation) pa.append(s.pa) relative.append(s.relative) return pd.DataFrame({'name':name,'band':band,'resolution':resolution, 'mag':mag,'e_mag':e_mag,'separation':separation, 'pa':pa,'relative':relative})
python
def to_df(self): """ Returns DataFrame with photometry from observations organized. This DataFrame should be able to be read back in to reconstruct the observation. """ df = pd.DataFrame() name = [] band = [] resolution = [] mag = [] e_mag = [] separation = [] pa = [] relative = [] for o in self._observations: for s in o.sources: name.append(o.name) band.append(o.band) resolution.append(o.resolution) mag.append(s.mag) e_mag.append(s.e_mag) separation.append(s.separation) pa.append(s.pa) relative.append(s.relative) return pd.DataFrame({'name':name,'band':band,'resolution':resolution, 'mag':mag,'e_mag':e_mag,'separation':separation, 'pa':pa,'relative':relative})
[ "def", "to_df", "(", "self", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", ")", "name", "=", "[", "]", "band", "=", "[", "]", "resolution", "=", "[", "]", "mag", "=", "[", "]", "e_mag", "=", "[", "]", "separation", "=", "[", "]", "pa", ...
Returns DataFrame with photometry from observations organized. This DataFrame should be able to be read back in to reconstruct the observation.
[ "Returns", "DataFrame", "with", "photometry", "from", "observations", "organized", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L796-L825
train
210,814
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.save_hdf
def save_hdf(self, filename, path='', overwrite=False, append=False): """ Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs """ if os.path.exists(filename): store = pd.HDFStore(filename) if path in store: store.close() if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. Set either overwrite or append option.'.format(path,filename)) else: store.close() df = self.to_df() df.to_hdf(filename, path+'/df') with pd.HDFStore(filename) as store: # store = pd.HDFStore(filename) attrs = store.get_storer(path+'/df').attrs attrs.spectroscopy = self.spectroscopy attrs.parallax = self.parallax attrs.N = self._N attrs.index = self._index store.close()
python
def save_hdf(self, filename, path='', overwrite=False, append=False): """ Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs """ if os.path.exists(filename): store = pd.HDFStore(filename) if path in store: store.close() if overwrite: os.remove(filename) elif not append: raise IOError('{} in {} exists. Set either overwrite or append option.'.format(path,filename)) else: store.close() df = self.to_df() df.to_hdf(filename, path+'/df') with pd.HDFStore(filename) as store: # store = pd.HDFStore(filename) attrs = store.get_storer(path+'/df').attrs attrs.spectroscopy = self.spectroscopy attrs.parallax = self.parallax attrs.N = self._N attrs.index = self._index store.close()
[ "def", "save_hdf", "(", "self", ",", "filename", ",", "path", "=", "''", ",", "overwrite", "=", "False", ",", "append", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "store", "=", "pd", ".", "HDFStore", ...
Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs
[ "Writes", "all", "info", "necessary", "to", "recreate", "object", "to", "HDF", "file" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L827-L856
train
210,815
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.load_hdf
def load_hdf(cls, filename, path='', ic=None): """ Loads stored ObservationTree from file. You can provide the isochrone to use; or it will default to MIST TODO: saving and loading must be fixed! save ic type, bands, etc. """ store = pd.HDFStore(filename) try: samples = store[path+'/df'] attrs = store.get_storer(path+'/df').attrs except: store.close() raise df = store[path+'/df'] new = cls.from_df(df) if ic is None: ic = get_ichrone('mist') new.define_models(ic, N=attrs.N, index=attrs.index) new.spectroscopy = attrs.spectroscopy new.parallax = attrs.parallax store.close() return new
python
def load_hdf(cls, filename, path='', ic=None): """ Loads stored ObservationTree from file. You can provide the isochrone to use; or it will default to MIST TODO: saving and loading must be fixed! save ic type, bands, etc. """ store = pd.HDFStore(filename) try: samples = store[path+'/df'] attrs = store.get_storer(path+'/df').attrs except: store.close() raise df = store[path+'/df'] new = cls.from_df(df) if ic is None: ic = get_ichrone('mist') new.define_models(ic, N=attrs.N, index=attrs.index) new.spectroscopy = attrs.spectroscopy new.parallax = attrs.parallax store.close() return new
[ "def", "load_hdf", "(", "cls", ",", "filename", ",", "path", "=", "''", ",", "ic", "=", "None", ")", ":", "store", "=", "pd", ".", "HDFStore", "(", "filename", ")", "try", ":", "samples", "=", "store", "[", "path", "+", "'/df'", "]", "attrs", "="...
Loads stored ObservationTree from file. You can provide the isochrone to use; or it will default to MIST TODO: saving and loading must be fixed! save ic type, bands, etc.
[ "Loads", "stored", "ObservationTree", "from", "file", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L859-L884
train
210,816
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.add_observation
def add_observation(self, obs): """Adds an observation to observation list, keeping proper order """ if len(self._observations)==0: self._observations.append(obs) else: res = obs.resolution ind = 0 for o in self._observations: if res > o.resolution: break ind += 1 self._observations.insert(ind, obs) self._build_tree() self._clear_cache()
python
def add_observation(self, obs): """Adds an observation to observation list, keeping proper order """ if len(self._observations)==0: self._observations.append(obs) else: res = obs.resolution ind = 0 for o in self._observations: if res > o.resolution: break ind += 1 self._observations.insert(ind, obs) self._build_tree() self._clear_cache()
[ "def", "add_observation", "(", "self", ",", "obs", ")", ":", "if", "len", "(", "self", ".", "_observations", ")", "==", "0", ":", "self", ".", "_observations", ".", "append", "(", "obs", ")", "else", ":", "res", "=", "obs", ".", "resolution", "ind", ...
Adds an observation to observation list, keeping proper order
[ "Adds", "an", "observation", "to", "observation", "list", "keeping", "proper", "order" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L887-L902
train
210,817
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.add_limit
def add_limit(self, label='0_0', **props): """Define limits to spectroscopic property of particular stars. Usually will be used for 'logg', but 'Teff' and 'feh' will also work. In form (min, max): e.g., t.add_limit(logg=(3.0,None)) None will be converted to (-)np.inf """ if label not in self.leaf_labels: raise ValueError('No model node named {} (must be in {}). Maybe define models first?'.format(label, self.leaf_labels)) for k,v in props.items(): if k not in self.spec_props: raise ValueError('Illegal property {} (only {} allowed).'.format(k, self.spec_props)) if len(v) != 2: raise ValueError('Must provide (min, max) for {}. (`None` is allowed value)'.format(k)) if label not in self.limits: self.limits[label] = {} for k,v in props.items(): vmin, vmax = v if vmin is None: vmin = -np.inf if vmax is None: vmax = np.inf self.limits[label][k] = (vmin, vmax) self._clear_cache()
python
def add_limit(self, label='0_0', **props): """Define limits to spectroscopic property of particular stars. Usually will be used for 'logg', but 'Teff' and 'feh' will also work. In form (min, max): e.g., t.add_limit(logg=(3.0,None)) None will be converted to (-)np.inf """ if label not in self.leaf_labels: raise ValueError('No model node named {} (must be in {}). Maybe define models first?'.format(label, self.leaf_labels)) for k,v in props.items(): if k not in self.spec_props: raise ValueError('Illegal property {} (only {} allowed).'.format(k, self.spec_props)) if len(v) != 2: raise ValueError('Must provide (min, max) for {}. (`None` is allowed value)'.format(k)) if label not in self.limits: self.limits[label] = {} for k,v in props.items(): vmin, vmax = v if vmin is None: vmin = -np.inf if vmax is None: vmax = np.inf self.limits[label][k] = (vmin, vmax) self._clear_cache()
[ "def", "add_limit", "(", "self", ",", "label", "=", "'0_0'", ",", "*", "*", "props", ")", ":", "if", "label", "not", "in", "self", ".", "leaf_labels", ":", "raise", "ValueError", "(", "'No model node named {} (must be in {}). Maybe define models first?'", ".", "...
Define limits to spectroscopic property of particular stars. Usually will be used for 'logg', but 'Teff' and 'feh' will also work. In form (min, max): e.g., t.add_limit(logg=(3.0,None)) None will be converted to (-)np.inf
[ "Define", "limits", "to", "spectroscopic", "property", "of", "particular", "stars", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L928-L957
train
210,818
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.define_models
def define_models(self, ic, leaves=None, N=1, index=0): """ N, index are either integers or lists of integers. N : number of model stars per observed star index : index of physical association leaves: either a list of leaves, or a pattern by which the leaves are selected (via `select_leaves`) If these are lists, then they are defined individually for each leaf. If `index` is a list, then each entry must be either an integer or a list of length `N` (where `N` is the corresponding entry in the `N` list.) This bugs up if you call it multiple times. If you want to re-do a call to this function, please re-define the tree. """ self.clear_models() if leaves is None: leaves = self._get_leaves() elif type(leaves)==type(''): leaves = self.select_leaves(leaves) # Sort leaves by distance, to ensure system 0 will be assigned # to the main reference star. if np.isscalar(N): N = (np.ones(len(leaves))*N) #if np.size(index) > 1: # index = [index] N = np.array(N).astype(int) if np.isscalar(index): index = (np.ones_like(N)*index) index = np.array(index).astype(int) # Add the appropriate number of model nodes to each # star in the highest-resoluion image for s,n,i in zip(leaves, N, index): # Remove any previous model nodes (should do some checks here?) s.remove_children() s.add_model(ic, n, i) # For each system, make sure tag _0 is the brightest. self._fix_labels() self._N = N self._index = index self._clear_all_leaves()
python
def define_models(self, ic, leaves=None, N=1, index=0): """ N, index are either integers or lists of integers. N : number of model stars per observed star index : index of physical association leaves: either a list of leaves, or a pattern by which the leaves are selected (via `select_leaves`) If these are lists, then they are defined individually for each leaf. If `index` is a list, then each entry must be either an integer or a list of length `N` (where `N` is the corresponding entry in the `N` list.) This bugs up if you call it multiple times. If you want to re-do a call to this function, please re-define the tree. """ self.clear_models() if leaves is None: leaves = self._get_leaves() elif type(leaves)==type(''): leaves = self.select_leaves(leaves) # Sort leaves by distance, to ensure system 0 will be assigned # to the main reference star. if np.isscalar(N): N = (np.ones(len(leaves))*N) #if np.size(index) > 1: # index = [index] N = np.array(N).astype(int) if np.isscalar(index): index = (np.ones_like(N)*index) index = np.array(index).astype(int) # Add the appropriate number of model nodes to each # star in the highest-resoluion image for s,n,i in zip(leaves, N, index): # Remove any previous model nodes (should do some checks here?) s.remove_children() s.add_model(ic, n, i) # For each system, make sure tag _0 is the brightest. self._fix_labels() self._N = N self._index = index self._clear_all_leaves()
[ "def", "define_models", "(", "self", ",", "ic", ",", "leaves", "=", "None", ",", "N", "=", "1", ",", "index", "=", "0", ")", ":", "self", ".", "clear_models", "(", ")", "if", "leaves", "is", "None", ":", "leaves", "=", "self", ".", "_get_leaves", ...
N, index are either integers or lists of integers. N : number of model stars per observed star index : index of physical association leaves: either a list of leaves, or a pattern by which the leaves are selected (via `select_leaves`) If these are lists, then they are defined individually for each leaf. If `index` is a list, then each entry must be either an integer or a list of length `N` (where `N` is the corresponding entry in the `N` list.) This bugs up if you call it multiple times. If you want to re-do a call to this function, please re-define the tree.
[ "N", "index", "are", "either", "integers", "or", "lists", "of", "integers", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L969-L1024
train
210,819
timothydmorton/isochrones
isochrones/observation.py
ObservationTree._fix_labels
def _fix_labels(self): """For each system, make sure tag _0 is the brightest, and make sure system 0 contains the brightest star in the highest-resolution image """ for s in self.systems: mag0 = np.inf n0 = None for n in self.get_system(s): if isinstance(n.parent, DummyObsNode): continue mag, _ = n.parent.value if mag < mag0: mag0 = mag n0 = n # If brightest is not tag _0, then switch them. if n0 is not None and n0.tag != 0: n_other = self.get_leaf('{}_{}'.format(s,0)) n_other.tag = n0.tag n0.tag = 0
python
def _fix_labels(self): """For each system, make sure tag _0 is the brightest, and make sure system 0 contains the brightest star in the highest-resolution image """ for s in self.systems: mag0 = np.inf n0 = None for n in self.get_system(s): if isinstance(n.parent, DummyObsNode): continue mag, _ = n.parent.value if mag < mag0: mag0 = mag n0 = n # If brightest is not tag _0, then switch them. if n0 is not None and n0.tag != 0: n_other = self.get_leaf('{}_{}'.format(s,0)) n_other.tag = n0.tag n0.tag = 0
[ "def", "_fix_labels", "(", "self", ")", ":", "for", "s", "in", "self", ".", "systems", ":", "mag0", "=", "np", ".", "inf", "n0", "=", "None", "for", "n", "in", "self", ".", "get_system", "(", "s", ")", ":", "if", "isinstance", "(", "n", ".", "p...
For each system, make sure tag _0 is the brightest, and make sure system 0 contains the brightest star in the highest-resolution image
[ "For", "each", "system", "make", "sure", "tag", "_0", "is", "the", "brightest", "and", "make", "sure", "system", "0", "contains", "the", "brightest", "star", "in", "the", "highest", "-", "resolution", "image" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1026-L1045
train
210,820
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.select_observations
def select_observations(self, name): """Returns nodes whose instrument-band matches 'name' """ return [n for n in self.get_obs_nodes() if n.obsname==name]
python
def select_observations(self, name): """Returns nodes whose instrument-band matches 'name' """ return [n for n in self.get_obs_nodes() if n.obsname==name]
[ "def", "select_observations", "(", "self", ",", "name", ")", ":", "return", "[", "n", "for", "n", "in", "self", ".", "get_obs_nodes", "(", ")", "if", "n", ".", "obsname", "==", "name", "]" ]
Returns nodes whose instrument-band matches 'name'
[ "Returns", "nodes", "whose", "instrument", "-", "band", "matches", "name" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1063-L1066
train
210,821
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.trim
def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """ # Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: if n.is_leaf: n.parent.remove_child(n.label) self._clear_all_leaves()
python
def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """ # Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: if n.is_leaf: n.parent.remove_child(n.label) self._clear_all_leaves()
[ "def", "trim", "(", "self", ")", ":", "# Only allow leaves to stay on list (highest-resolution) level", "return", "for", "l", "in", "self", ".", "_levels", "[", "-", "2", ":", ":", "-", "1", "]", ":", "for", "n", "in", "l", ":", "if", "n", ".", "is_leaf"...
Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is
[ "Trims", "leaves", "from", "tree", "that", "are", "not", "observed", "at", "highest", "-", "resolution", "level" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1075-L1089
train
210,822
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.p2pardict
def p2pardict(self, p): """ Given leaf labels, turns parameter vector into pardict """ d = {} N = self.Nstars i = 0 for s in self.systems: age, feh, dist, AV = p[i+N[s]:i+N[s]+4] for j in xrange(N[s]): l = '{}_{}'.format(s,j) mass = p[i+j] d[l] = [mass, age, feh, dist, AV] i += N[s] + 4 return d
python
def p2pardict(self, p): """ Given leaf labels, turns parameter vector into pardict """ d = {} N = self.Nstars i = 0 for s in self.systems: age, feh, dist, AV = p[i+N[s]:i+N[s]+4] for j in xrange(N[s]): l = '{}_{}'.format(s,j) mass = p[i+j] d[l] = [mass, age, feh, dist, AV] i += N[s] + 4 return d
[ "def", "p2pardict", "(", "self", ",", "p", ")", ":", "d", "=", "{", "}", "N", "=", "self", ".", "Nstars", "i", "=", "0", "for", "s", "in", "self", ".", "systems", ":", "age", ",", "feh", ",", "dist", ",", "AV", "=", "p", "[", "i", "+", "N...
Given leaf labels, turns parameter vector into pardict
[ "Given", "leaf", "labels", "turns", "parameter", "vector", "into", "pardict" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1091-L1105
train
210,823
timothydmorton/isochrones
isochrones/observation.py
ObservationTree.lnlike
def lnlike(self, p, use_cache=True): """ takes parameter vector, constructs pardict, returns sum of lnlikes of non-leaf nodes """ if use_cache and self._cache_key is not None and np.all(p==self._cache_key): return self._cache_val self._cache_key = p pardict = self.p2pardict(p) # lnlike from photometry lnl = 0 for n in self: if n is not self: lnl += n.lnlike(pardict, use_cache=use_cache) if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # lnlike from spectroscopy for l in self.spectroscopy: for prop,(val,err) in self.spectroscopy[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) lnl += -0.5*(val - mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # enforce limits for l in self.limits: for prop,(vmin,vmax) in self.limits[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) if mod < vmin or mod > vmax or not np.isfinite(mod): self._cache_val = -np.inf return -np.inf # lnlike from parallax for s,(val,err) in self.parallax.items(): dist = pardict['{}_0'.format(s)][3] mod = 1./dist * 1000. lnl += -0.5*(val-mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf self._cache_val = lnl return lnl
python
def lnlike(self, p, use_cache=True): """ takes parameter vector, constructs pardict, returns sum of lnlikes of non-leaf nodes """ if use_cache and self._cache_key is not None and np.all(p==self._cache_key): return self._cache_val self._cache_key = p pardict = self.p2pardict(p) # lnlike from photometry lnl = 0 for n in self: if n is not self: lnl += n.lnlike(pardict, use_cache=use_cache) if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # lnlike from spectroscopy for l in self.spectroscopy: for prop,(val,err) in self.spectroscopy[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) lnl += -0.5*(val - mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf # enforce limits for l in self.limits: for prop,(vmin,vmax) in self.limits[l].items(): mod = self.get_leaf(l).evaluate(pardict[l], prop) if mod < vmin or mod > vmax or not np.isfinite(mod): self._cache_val = -np.inf return -np.inf # lnlike from parallax for s,(val,err) in self.parallax.items(): dist = pardict['{}_0'.format(s)][3] mod = 1./dist * 1000. lnl += -0.5*(val-mod)**2/err**2 if not np.isfinite(lnl): self._cache_val = -np.inf return -np.inf self._cache_val = lnl return lnl
[ "def", "lnlike", "(", "self", ",", "p", ",", "use_cache", "=", "True", ")", ":", "if", "use_cache", "and", "self", ".", "_cache_key", "is", "not", "None", "and", "np", ".", "all", "(", "p", "==", "self", ".", "_cache_key", ")", ":", "return", "self...
takes parameter vector, constructs pardict, returns sum of lnlikes of non-leaf nodes
[ "takes", "parameter", "vector", "constructs", "pardict", "returns", "sum", "of", "lnlikes", "of", "non", "-", "leaf", "nodes" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1143-L1190
train
210,824
timothydmorton/isochrones
isochrones/observation.py
ObservationTree._find_closest
def _find_closest(self, n0): """returns the node in the tree that is closest to n0, but not in the same observation """ dmin = np.inf nclose = None ds = [] nodes = [] ds.append(np.inf) nodes.append(self) for n in self: if n is n0: continue try: if n._in_same_observation(n0): continue ds.append(n.distance(n0)) nodes.append(n) except AttributeError: pass inds = np.argsort(ds) ds = [ds[i] for i in inds] nodes = [nodes[i] for i in inds] for d,n in zip(ds, nodes): try: if d < n.resolution or n.resolution==-1: return n except AttributeError: pass # If nothing else works return self
python
def _find_closest(self, n0): """returns the node in the tree that is closest to n0, but not in the same observation """ dmin = np.inf nclose = None ds = [] nodes = [] ds.append(np.inf) nodes.append(self) for n in self: if n is n0: continue try: if n._in_same_observation(n0): continue ds.append(n.distance(n0)) nodes.append(n) except AttributeError: pass inds = np.argsort(ds) ds = [ds[i] for i in inds] nodes = [nodes[i] for i in inds] for d,n in zip(ds, nodes): try: if d < n.resolution or n.resolution==-1: return n except AttributeError: pass # If nothing else works return self
[ "def", "_find_closest", "(", "self", ",", "n0", ")", ":", "dmin", "=", "np", ".", "inf", "nclose", "=", "None", "ds", "=", "[", "]", "nodes", "=", "[", "]", "ds", ".", "append", "(", "np", ".", "inf", ")", "nodes", ".", "append", "(", "self", ...
returns the node in the tree that is closest to n0, but not in the same observation
[ "returns", "the", "node", "in", "the", "tree", "that", "is", "closest", "to", "n0", "but", "not", "in", "the", "same", "observation" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1192-L1228
train
210,825
timothydmorton/isochrones
isochrones/starmodel_old.py
q_prior
def q_prior(q, m=1, gamma=0.3, qmin=0.1): """Default prior on mass ratio q ~ q^gamma """ if q < qmin or q > 1: return 0 C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1))) return C*q**gamma
python
def q_prior(q, m=1, gamma=0.3, qmin=0.1): """Default prior on mass ratio q ~ q^gamma """ if q < qmin or q > 1: return 0 C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1))) return C*q**gamma
[ "def", "q_prior", "(", "q", ",", "m", "=", "1", ",", "gamma", "=", "0.3", ",", "qmin", "=", "0.1", ")", ":", "if", "q", "<", "qmin", "or", "q", ">", "1", ":", "return", "0", "C", "=", "1", "/", "(", "1", "/", "(", "gamma", "+", "1", ")"...
Default prior on mass ratio q ~ q^gamma
[ "Default", "prior", "on", "mass", "ratio", "q", "~", "q^gamma" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L1925-L1931
train
210,826
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel._clean_props
def _clean_props(self): """ Makes sure all properties are legit for isochrone. Not done in __init__ in order to save speed on loading. """ remove = [] for p in self.properties.keys(): if not hasattr(self.ic, p) and \ p not in self.ic.bands and p not in ['parallax','feh','age','mass_B','mass_C'] and \ not re.search('delta_',p): remove.append(p) for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'not present in {}: {}'.format(type(self.ic),remove)) remove = [] for p in self.properties.keys(): try: val = self.properties[p][0] if not np.isfinite(val): remove.append(p) except: pass for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'value is nan or inf: {}'.format(remove)) self._props_cleaned = True
python
def _clean_props(self): """ Makes sure all properties are legit for isochrone. Not done in __init__ in order to save speed on loading. """ remove = [] for p in self.properties.keys(): if not hasattr(self.ic, p) and \ p not in self.ic.bands and p not in ['parallax','feh','age','mass_B','mass_C'] and \ not re.search('delta_',p): remove.append(p) for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'not present in {}: {}'.format(type(self.ic),remove)) remove = [] for p in self.properties.keys(): try: val = self.properties[p][0] if not np.isfinite(val): remove.append(p) except: pass for p in remove: del self.properties[p] if len(remove) > 0: logging.warning('Properties removed from Model because ' + 'value is nan or inf: {}'.format(remove)) self._props_cleaned = True
[ "def", "_clean_props", "(", "self", ")", ":", "remove", "=", "[", "]", "for", "p", "in", "self", ".", "properties", ".", "keys", "(", ")", ":", "if", "not", "hasattr", "(", "self", ".", "ic", ",", "p", ")", "and", "p", "not", "in", "self", ".",...
Makes sure all properties are legit for isochrone. Not done in __init__ in order to save speed on loading.
[ "Makes", "sure", "all", "properties", "are", "legit", "for", "isochrone", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L181-L219
train
210,827
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.add_props
def add_props(self,**kwargs): """ Adds observable properties to ``self.properties``. """ for kw,val in kwargs.iteritems(): self.properties[kw] = val
python
def add_props(self,**kwargs): """ Adds observable properties to ``self.properties``. """ for kw,val in kwargs.iteritems(): self.properties[kw] = val
[ "def", "add_props", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "kw", ",", "val", "in", "kwargs", ".", "iteritems", "(", ")", ":", "self", ".", "properties", "[", "kw", "]", "=", "val" ]
Adds observable properties to ``self.properties``.
[ "Adds", "observable", "properties", "to", "self", ".", "properties", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L221-L227
train
210,828
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.remove_props
def remove_props(self,*args): """ Removes desired properties from ``self.properties``. """ for arg in args: if arg in self.properties: del self.properties[arg]
python
def remove_props(self,*args): """ Removes desired properties from ``self.properties``. """ for arg in args: if arg in self.properties: del self.properties[arg]
[ "def", "remove_props", "(", "self", ",", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "arg", "in", "self", ".", "properties", ":", "del", "self", ".", "properties", "[", "arg", "]" ]
Removes desired properties from ``self.properties``.
[ "Removes", "desired", "properties", "from", "self", ".", "properties", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L229-L236
train
210,829
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.fit_for_distance
def fit_for_distance(self): """ ``True`` if any of the properties are apparent magnitudes. """ for prop in self.properties.keys(): if prop in self.ic.bands: return True return False
python
def fit_for_distance(self): """ ``True`` if any of the properties are apparent magnitudes. """ for prop in self.properties.keys(): if prop in self.ic.bands: return True return False
[ "def", "fit_for_distance", "(", "self", ")", ":", "for", "prop", "in", "self", ".", "properties", ".", "keys", "(", ")", ":", "if", "prop", "in", "self", ".", "ic", ".", "bands", ":", "return", "True", "return", "False" ]
``True`` if any of the properties are apparent magnitudes.
[ "True", "if", "any", "of", "the", "properties", "are", "apparent", "magnitudes", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L239-L247
train
210,830
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.lnlike
def lnlike(self, p): """Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. :return: log-likelihood. Will be -np.inf if values out of range. """ if not self._props_cleaned: self._clean_props() if not self.use_emcee: fit_for_distance = True mass, age, feh, dist, AV = (p[0], p[1], p[2], p[3], p[4]) else: if len(p)==5: fit_for_distance = True mass,age,feh,dist,AV = p elif len(p)==3: fit_for_distance = False mass,age,feh = p if mass < self.ic.minmass or mass > self.ic.maxmass \ or age < self.ic.minage or age > self.ic.maxage \ or feh < self.ic.minfeh or feh > self.ic.maxfeh: return -np.inf if fit_for_distance: if dist < 0 or AV < 0 or dist > self.max_distance: return -np.inf if AV > self.maxAV: return -np.inf if self.min_logg is not None: logg = self.ic.logg(mass,age,feh) if logg < self.min_logg: return -np.inf logl = 0 for prop in self.properties.keys(): try: val,err = self.properties[prop] except TypeError: #property not appropriate for fitting (e.g. no error provided) continue if prop in self.ic.bands: if not fit_for_distance: raise ValueError('must fit for mass, age, feh, dist, A_V if apparent magnitudes provided.') mod = self.ic.mag[prop](mass,age,feh) + 5*np.log10(dist) - 5 A = AV*EXTINCTION[prop] mod += A elif re.search('delta_',prop): continue elif prop=='feh': mod = feh elif prop=='parallax': mod = 1./dist * 1000 else: mod = getattr(self.ic,prop)(mass,age,feh) logl += -(val-mod)**2/(2*err**2) + np.log(1/(err*np.sqrt(2*np.pi))) if np.isnan(logl): logl = -np.inf return logl
python
def lnlike(self, p): """Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. :return: log-likelihood. Will be -np.inf if values out of range. """ if not self._props_cleaned: self._clean_props() if not self.use_emcee: fit_for_distance = True mass, age, feh, dist, AV = (p[0], p[1], p[2], p[3], p[4]) else: if len(p)==5: fit_for_distance = True mass,age,feh,dist,AV = p elif len(p)==3: fit_for_distance = False mass,age,feh = p if mass < self.ic.minmass or mass > self.ic.maxmass \ or age < self.ic.minage or age > self.ic.maxage \ or feh < self.ic.minfeh or feh > self.ic.maxfeh: return -np.inf if fit_for_distance: if dist < 0 or AV < 0 or dist > self.max_distance: return -np.inf if AV > self.maxAV: return -np.inf if self.min_logg is not None: logg = self.ic.logg(mass,age,feh) if logg < self.min_logg: return -np.inf logl = 0 for prop in self.properties.keys(): try: val,err = self.properties[prop] except TypeError: #property not appropriate for fitting (e.g. no error provided) continue if prop in self.ic.bands: if not fit_for_distance: raise ValueError('must fit for mass, age, feh, dist, A_V if apparent magnitudes provided.') mod = self.ic.mag[prop](mass,age,feh) + 5*np.log10(dist) - 5 A = AV*EXTINCTION[prop] mod += A elif re.search('delta_',prop): continue elif prop=='feh': mod = feh elif prop=='parallax': mod = 1./dist * 1000 else: mod = getattr(self.ic,prop)(mass,age,feh) logl += -(val-mod)**2/(2*err**2) + np.log(1/(err*np.sqrt(2*np.pi))) if np.isnan(logl): logl = -np.inf return logl
[ "def", "lnlike", "(", "self", ",", "p", ")", ":", "if", "not", "self", ".", "_props_cleaned", ":", "self", ".", "_clean_props", "(", ")", "if", "not", "self", ".", "use_emcee", ":", "fit_for_distance", "=", "True", "mass", ",", "age", ",", "feh", ","...
Log-likelihood of model at given parameters :param p: mass, log10(age), feh, [distance, A_V (extinction)]. Final two should only be provided if ``self.fit_for_distance`` is ``True``; that is, apparent magnitudes are provided. :return: log-likelihood. Will be -np.inf if values out of range.
[ "Log", "-", "likelihood", "of", "model", "at", "given", "parameters" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L254-L325
train
210,831
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.lnprior
def lnprior(self, mass, age, feh, distance=None, AV=None, use_local_fehprior=True): """ log-prior for model parameters """ mass_prior = salpeter_prior(mass) if mass_prior==0: mass_lnprior = -np.inf else: mass_lnprior = np.log(mass_prior) if np.isnan(mass_lnprior): logging.warning('mass prior is nan at {}'.format(mass)) age_lnprior = np.log(age * (2/(self.ic.maxage**2-self.ic.minage**2))) if np.isnan(age_lnprior): logging.warning('age prior is nan at {}'.format(age)) if use_local_fehprior: fehdist = local_fehdist(feh) else: fehdist = 1/(self.ic.maxfeh - self.ic.minfeh) feh_lnprior = np.log(fehdist) if np.isnan(feh_lnprior): logging.warning('feh prior is nan at {}'.format(feh)) if distance is not None: if distance <= 0: distance_lnprior = -np.inf else: distance_lnprior = np.log(3/self.max_distance**3 * distance**2) else: distance_lnprior = 0 if np.isnan(distance_lnprior): logging.warning('distance prior is nan at {}'.format(distance)) if AV is not None: AV_lnprior = np.log(1/self.maxAV) else: AV_lnprior = 0 if np.isnan(AV_lnprior): logging.warning('AV prior is nan at {}'.format(AV)) lnprior = (mass_lnprior + age_lnprior + feh_lnprior + distance_lnprior + AV_lnprior) return lnprior
python
def lnprior(self, mass, age, feh, distance=None, AV=None, use_local_fehprior=True): """ log-prior for model parameters """ mass_prior = salpeter_prior(mass) if mass_prior==0: mass_lnprior = -np.inf else: mass_lnprior = np.log(mass_prior) if np.isnan(mass_lnprior): logging.warning('mass prior is nan at {}'.format(mass)) age_lnprior = np.log(age * (2/(self.ic.maxage**2-self.ic.minage**2))) if np.isnan(age_lnprior): logging.warning('age prior is nan at {}'.format(age)) if use_local_fehprior: fehdist = local_fehdist(feh) else: fehdist = 1/(self.ic.maxfeh - self.ic.minfeh) feh_lnprior = np.log(fehdist) if np.isnan(feh_lnprior): logging.warning('feh prior is nan at {}'.format(feh)) if distance is not None: if distance <= 0: distance_lnprior = -np.inf else: distance_lnprior = np.log(3/self.max_distance**3 * distance**2) else: distance_lnprior = 0 if np.isnan(distance_lnprior): logging.warning('distance prior is nan at {}'.format(distance)) if AV is not None: AV_lnprior = np.log(1/self.maxAV) else: AV_lnprior = 0 if np.isnan(AV_lnprior): logging.warning('AV prior is nan at {}'.format(AV)) lnprior = (mass_lnprior + age_lnprior + feh_lnprior + distance_lnprior + AV_lnprior) return lnprior
[ "def", "lnprior", "(", "self", ",", "mass", ",", "age", ",", "feh", ",", "distance", "=", "None", ",", "AV", "=", "None", ",", "use_local_fehprior", "=", "True", ")", ":", "mass_prior", "=", "salpeter_prior", "(", "mass", ")", "if", "mass_prior", "==",...
log-prior for model parameters
[ "log", "-", "prior", "for", "model", "parameters" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L327-L379
train
210,832
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.triangle_plots
def triangle_plots(self, basename=None, format='png', **kwargs): """Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]_observed.[format]" :param format: Format in which to save figures (e.g., 'png' or 'pdf') :param **kwargs: Additional keyword arguments passed to :func:`StarModel.triangle` and :func:`StarModel.prop_triangle` :return: * Physical parameters triangle plot (mass, radius, Teff, feh, age, distance) * Observed properties triangle plot. """ if self.fit_for_distance: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','logg','feh','age', 'distance','AV'], **kwargs) else: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','feh','age'], **kwargs) if basename is not None: plt.savefig('{}_physical.{}'.format(basename,format)) plt.close() fig2 = self.prop_triangle(**kwargs) if basename is not None: plt.savefig('{}_observed.{}'.format(basename,format)) plt.close() return fig1, fig2
python
def triangle_plots(self, basename=None, format='png', **kwargs): """Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]_observed.[format]" :param format: Format in which to save figures (e.g., 'png' or 'pdf') :param **kwargs: Additional keyword arguments passed to :func:`StarModel.triangle` and :func:`StarModel.prop_triangle` :return: * Physical parameters triangle plot (mass, radius, Teff, feh, age, distance) * Observed properties triangle plot. """ if self.fit_for_distance: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','logg','feh','age', 'distance','AV'], **kwargs) else: fig1 = self.triangle(plot_datapoints=False, params=['mass','radius','Teff','feh','age'], **kwargs) if basename is not None: plt.savefig('{}_physical.{}'.format(basename,format)) plt.close() fig2 = self.prop_triangle(**kwargs) if basename is not None: plt.savefig('{}_observed.{}'.format(basename,format)) plt.close() return fig1, fig2
[ "def", "triangle_plots", "(", "self", ",", "basename", "=", "None", ",", "format", "=", "'png'", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "fit_for_distance", ":", "fig1", "=", "self", ".", "triangle", "(", "plot_datapoints", "=", "False", ...
Returns two triangle plots, one with physical params, one observational :param basename: If basename is provided, then plots will be saved as "[basename]_physical.[format]" and "[basename]_observed.[format]" :param format: Format in which to save figures (e.g., 'png' or 'pdf') :param **kwargs: Additional keyword arguments passed to :func:`StarModel.triangle` and :func:`StarModel.prop_triangle` :return: * Physical parameters triangle plot (mass, radius, Teff, feh, age, distance) * Observed properties triangle plot.
[ "Returns", "two", "triangle", "plots", "one", "with", "physical", "params", "one", "observational" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L727-L765
train
210,833
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.prop_triangle
def prop_triangle(self, **kwargs): """ Makes corner plot of only observable properties. The idea here is to compare the predictions of the samples with the actual observed data---this can be a quick way to check if there are outlier properties that aren't predicted well by the model. :param **kwargs: Keyword arguments passed to :func:`StarModel.triangle`. :return: Figure object containing corner plot. """ truths = [] params = [] for p in self.properties: try: val, err = self.properties[p] except: continue if p in self.ic.bands: params.append('{}_mag'.format(p)) truths.append(val) elif p=='parallax': params.append('distance') truths.append(1/(val/1000.)) else: params.append(p) truths.append(val) return self.triangle(params, truths=truths, **kwargs)
python
def prop_triangle(self, **kwargs): """ Makes corner plot of only observable properties. The idea here is to compare the predictions of the samples with the actual observed data---this can be a quick way to check if there are outlier properties that aren't predicted well by the model. :param **kwargs: Keyword arguments passed to :func:`StarModel.triangle`. :return: Figure object containing corner plot. """ truths = [] params = [] for p in self.properties: try: val, err = self.properties[p] except: continue if p in self.ic.bands: params.append('{}_mag'.format(p)) truths.append(val) elif p=='parallax': params.append('distance') truths.append(1/(val/1000.)) else: params.append(p) truths.append(val) return self.triangle(params, truths=truths, **kwargs)
[ "def", "prop_triangle", "(", "self", ",", "*", "*", "kwargs", ")", ":", "truths", "=", "[", "]", "params", "=", "[", "]", "for", "p", "in", "self", ".", "properties", ":", "try", ":", "val", ",", "err", "=", "self", ".", "properties", "[", "p", ...
Makes corner plot of only observable properties. The idea here is to compare the predictions of the samples with the actual observed data---this can be a quick way to check if there are outlier properties that aren't predicted well by the model. :param **kwargs: Keyword arguments passed to :func:`StarModel.triangle`. :return: Figure object containing corner plot.
[ "Makes", "corner", "plot", "of", "only", "observable", "properties", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L843-L876
train
210,834
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.prop_samples
def prop_samples(self,prop,return_values=True,conf=0.683): """Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (median, lo_err, hi_err) corresponding to desired credible interval. :param conf: (optional) Desired quantile for credible interval. Default = 0.683. :return: :class:`np.ndarray` of desired samples :return: Optionally also return summary statistics (median, lo_err, hi_err), if ``returns_values == True`` (this is default behavior) """ samples = self.samples[prop].values if return_values: sorted = np.sort(samples) med = np.median(samples) n = len(samples) lo_ind = int(n*(0.5 - conf/2)) hi_ind = int(n*(0.5 + conf/2)) lo = med - sorted[lo_ind] hi = sorted[hi_ind] - med return samples, (med,lo,hi) else: return samples
python
def prop_samples(self,prop,return_values=True,conf=0.683): """Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (median, lo_err, hi_err) corresponding to desired credible interval. :param conf: (optional) Desired quantile for credible interval. Default = 0.683. :return: :class:`np.ndarray` of desired samples :return: Optionally also return summary statistics (median, lo_err, hi_err), if ``returns_values == True`` (this is default behavior) """ samples = self.samples[prop].values if return_values: sorted = np.sort(samples) med = np.median(samples) n = len(samples) lo_ind = int(n*(0.5 - conf/2)) hi_ind = int(n*(0.5 + conf/2)) lo = med - sorted[lo_ind] hi = sorted[hi_ind] - med return samples, (med,lo,hi) else: return samples
[ "def", "prop_samples", "(", "self", ",", "prop", ",", "return_values", "=", "True", ",", "conf", "=", "0.683", ")", ":", "samples", "=", "self", ".", "samples", "[", "prop", "]", ".", "values", "if", "return_values", ":", "sorted", "=", "np", ".", "s...
Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (median, lo_err, hi_err) corresponding to desired credible interval. :param conf: (optional) Desired quantile for credible interval. Default = 0.683. :return: :class:`np.ndarray` of desired samples :return: Optionally also return summary statistics (median, lo_err, hi_err), if ``returns_values == True`` (this is default behavior)
[ "Returns", "samples", "of", "given", "property", "based", "on", "MCMC", "sampling" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L975-L1008
train
210,835
timothydmorton/isochrones
isochrones/starmodel_old.py
StarModel.plot_samples
def plot_samples(self,prop,fig=None,label=True, histtype='step',bins=50,lw=3, **kwargs): """Plots histogram of samples of desired property. :param prop: Desired property (must be legit column of samples) :param fig: Argument for :func:`plotutils.setfig` (``None`` or int). :param histtype, bins, lw: Passed to :func:`plt.hist`. :param **kwargs: Additional keyword arguments passed to `plt.hist` :return: Figure object. """ setfig(fig) samples,stats = self.prop_samples(prop) fig = plt.hist(samples,bins=bins,normed=True, histtype=histtype,lw=lw,**kwargs) plt.xlabel(prop) plt.ylabel('Normalized count') if label: med,lo,hi = stats plt.annotate('$%.2f^{+%.2f}_{-%.2f}$' % (med,hi,lo), xy=(0.7,0.8),xycoords='axes fraction',fontsize=20) return fig
python
def plot_samples(self,prop,fig=None,label=True, histtype='step',bins=50,lw=3, **kwargs): """Plots histogram of samples of desired property. :param prop: Desired property (must be legit column of samples) :param fig: Argument for :func:`plotutils.setfig` (``None`` or int). :param histtype, bins, lw: Passed to :func:`plt.hist`. :param **kwargs: Additional keyword arguments passed to `plt.hist` :return: Figure object. """ setfig(fig) samples,stats = self.prop_samples(prop) fig = plt.hist(samples,bins=bins,normed=True, histtype=histtype,lw=lw,**kwargs) plt.xlabel(prop) plt.ylabel('Normalized count') if label: med,lo,hi = stats plt.annotate('$%.2f^{+%.2f}_{-%.2f}$' % (med,hi,lo), xy=(0.7,0.8),xycoords='axes fraction',fontsize=20) return fig
[ "def", "plot_samples", "(", "self", ",", "prop", ",", "fig", "=", "None", ",", "label", "=", "True", ",", "histtype", "=", "'step'", ",", "bins", "=", "50", ",", "lw", "=", "3", ",", "*", "*", "kwargs", ")", ":", "setfig", "(", "fig", ")", "sam...
Plots histogram of samples of desired property. :param prop: Desired property (must be legit column of samples) :param fig: Argument for :func:`plotutils.setfig` (``None`` or int). :param histtype, bins, lw: Passed to :func:`plt.hist`. :param **kwargs: Additional keyword arguments passed to `plt.hist` :return: Figure object.
[ "Plots", "histogram", "of", "samples", "of", "desired", "property", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel_old.py#L1010-L1042
train
210,836
timothydmorton/isochrones
isochrones/dartmouth/grid.py
DartmouthModelGrid.get_band
def get_band(cls, b, **kwargs): """Defines what a "shortcut" band name refers to. """ phot = None # Default to SDSS for these if b in ['u','g','r','i','z']: phot = 'SDSSugriz' band = 'sdss_{}'.format(b) elif b in ['U','B','V','R','I','J','H','Ks']: phot = 'UBVRIJHKsKp' band = b elif b=='K': phot = 'UBVRIJHKsKp' band = 'Ks' elif b in ['kep','Kepler','Kp']: phot = 'UBVRIJHKsKp' band = 'Kp' elif b in ['W1','W2','W3','W4']: phot = 'WISE' band = b elif re.match('uvf', b) or re.match('irf', b): phot = 'HST_WFC3' band = b else: m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b) if m: if m.group(1) in cls.phot_systems: phot = m.group(1) if phot=='LSST': band = b else: band = m.group(2) elif m.group(1) in ['UK','UKIRT']: phot = 'UKIDSS' band = m.group(2) if phot is None: raise ValueError('Dartmouth Models cannot resolve band {}!'.format(b)) return phot, band
python
def get_band(cls, b, **kwargs): """Defines what a "shortcut" band name refers to. """ phot = None # Default to SDSS for these if b in ['u','g','r','i','z']: phot = 'SDSSugriz' band = 'sdss_{}'.format(b) elif b in ['U','B','V','R','I','J','H','Ks']: phot = 'UBVRIJHKsKp' band = b elif b=='K': phot = 'UBVRIJHKsKp' band = 'Ks' elif b in ['kep','Kepler','Kp']: phot = 'UBVRIJHKsKp' band = 'Kp' elif b in ['W1','W2','W3','W4']: phot = 'WISE' band = b elif re.match('uvf', b) or re.match('irf', b): phot = 'HST_WFC3' band = b else: m = re.match('([a-zA-Z]+)_([a-zA-Z_]+)',b) if m: if m.group(1) in cls.phot_systems: phot = m.group(1) if phot=='LSST': band = b else: band = m.group(2) elif m.group(1) in ['UK','UKIRT']: phot = 'UKIDSS' band = m.group(2) if phot is None: raise ValueError('Dartmouth Models cannot resolve band {}!'.format(b)) return phot, band
[ "def", "get_band", "(", "cls", ",", "b", ",", "*", "*", "kwargs", ")", ":", "phot", "=", "None", "# Default to SDSS for these", "if", "b", "in", "[", "'u'", ",", "'g'", ",", "'r'", ",", "'i'", ",", "'z'", "]", ":", "phot", "=", "'SDSSugriz'", "band...
Defines what a "shortcut" band name refers to.
[ "Defines", "what", "a", "shortcut", "band", "name", "refers", "to", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/dartmouth/grid.py#L62-L101
train
210,837
timothydmorton/isochrones
isochrones/mist/utils.py
searchsorted
def searchsorted(arr, N, x): """N is length of arr """ L = 0 R = N-1 done = False m = (L+R)//2 while not done: if arr[m] < x: L = m + 1 elif arr[m] > x: R = m - 1 elif arr[m] == x: done = True m = (L+R)//2 if L>R: done = True return L
python
def searchsorted(arr, N, x): """N is length of arr """ L = 0 R = N-1 done = False m = (L+R)//2 while not done: if arr[m] < x: L = m + 1 elif arr[m] > x: R = m - 1 elif arr[m] == x: done = True m = (L+R)//2 if L>R: done = True return L
[ "def", "searchsorted", "(", "arr", ",", "N", ",", "x", ")", ":", "L", "=", "0", "R", "=", "N", "-", "1", "done", "=", "False", "m", "=", "(", "L", "+", "R", ")", "//", "2", "while", "not", "done", ":", "if", "arr", "[", "m", "]", "<", "...
N is length of arr
[ "N", "is", "length", "of", "arr" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/mist/utils.py#L26-L43
train
210,838
alecthomas/flask_injector
flask_injector.py
wrap_flask_restful_resource
def wrap_flask_restful_resource( fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector ) -> Callable: """ This is needed because of how flask_restful views are registered originally. :type flask_restful_api: :class:`flask_restful.Api` """ # The following fragment of code is copied from flask_restful project """ Copyright (c) 2013, Twilio, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Twilio, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ @functools.wraps(fun) def wrapper(*args: Any, **kwargs: Any) -> Any: resp = fun(*args, **kwargs) if isinstance(resp, Response): # There may be a better way to test return resp data, code, headers = flask_response_unpack(resp) return flask_restful_api.make_response(data, code, headers=headers) # end of flask_restful code return wrapper
python
def wrap_flask_restful_resource( fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector ) -> Callable: """ This is needed because of how flask_restful views are registered originally. :type flask_restful_api: :class:`flask_restful.Api` """ # The following fragment of code is copied from flask_restful project """ Copyright (c) 2013, Twilio, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Twilio, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ @functools.wraps(fun) def wrapper(*args: Any, **kwargs: Any) -> Any: resp = fun(*args, **kwargs) if isinstance(resp, Response): # There may be a better way to test return resp data, code, headers = flask_response_unpack(resp) return flask_restful_api.make_response(data, code, headers=headers) # end of flask_restful code return wrapper
[ "def", "wrap_flask_restful_resource", "(", "fun", ":", "Callable", ",", "flask_restful_api", ":", "FlaskRestfulApi", ",", "injector", ":", "Injector", ")", "->", "Callable", ":", "# The following fragment of code is copied from flask_restful project", "\"\"\"\n Copyright (c)...
This is needed because of how flask_restful views are registered originally. :type flask_restful_api: :class:`flask_restful.Api`
[ "This", "is", "needed", "because", "of", "how", "flask_restful", "views", "are", "registered", "originally", "." ]
18282a42539c8a8809feff1f466f763116e10bda
https://github.com/alecthomas/flask_injector/blob/18282a42539c8a8809feff1f466f763116e10bda/flask_injector.py#L174-L222
train
210,839
niklasb/dryscrape
dryscrape/session.py
Session.complete_url
def complete_url(self, url): """ Completes a given URL with this instance's URL base. """ if self.base_url: return urlparse.urljoin(self.base_url, url) else: return url
python
def complete_url(self, url): """ Completes a given URL with this instance's URL base. """ if self.base_url: return urlparse.urljoin(self.base_url, url) else: return url
[ "def", "complete_url", "(", "self", ",", "url", ")", ":", "if", "self", ".", "base_url", ":", "return", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "else", ":", "return", "url" ]
Completes a given URL with this instance's URL base.
[ "Completes", "a", "given", "URL", "with", "this", "instance", "s", "URL", "base", "." ]
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/session.py#L42-L47
train
210,840
niklasb/dryscrape
dryscrape/session.py
Session.interact
def interact(self, **local): """ Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arguments are supplied, these names will also be available within the session. """ import code code.interact(local=dict(sess=self, **local))
python
def interact(self, **local): """ Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arguments are supplied, these names will also be available within the session. """ import code code.interact(local=dict(sess=self, **local))
[ "def", "interact", "(", "self", ",", "*", "*", "local", ")", ":", "import", "code", "code", ".", "interact", "(", "local", "=", "dict", "(", "sess", "=", "self", ",", "*", "*", "local", ")", ")" ]
Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arguments are supplied, these names will also be available within the session.
[ "Drops", "the", "user", "into", "an", "interactive", "Python", "session", "with", "the", "sess", "variable", "set", "to", "the", "current", "session", "instance", ".", "If", "keyword", "arguments", "are", "supplied", "these", "names", "will", "also", "be", "...
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/session.py#L49-L54
train
210,841
niklasb/dryscrape
dryscrape/mixins.py
WaitMixin.wait_for
def wait_for(self, condition, interval = DEFAULT_WAIT_INTERVAL, timeout = DEFAULT_WAIT_TIMEOUT): """ Wait until a condition holds by checking it in regular intervals. Raises ``WaitTimeoutError`` on timeout. """ start = time.time() # at least execute the check once! while True: res = condition() if res: return res # timeout? if time.time() - start > timeout: break # wait a bit time.sleep(interval) # timeout occured! raise WaitTimeoutError("wait_for timed out")
python
def wait_for(self, condition, interval = DEFAULT_WAIT_INTERVAL, timeout = DEFAULT_WAIT_TIMEOUT): """ Wait until a condition holds by checking it in regular intervals. Raises ``WaitTimeoutError`` on timeout. """ start = time.time() # at least execute the check once! while True: res = condition() if res: return res # timeout? if time.time() - start > timeout: break # wait a bit time.sleep(interval) # timeout occured! raise WaitTimeoutError("wait_for timed out")
[ "def", "wait_for", "(", "self", ",", "condition", ",", "interval", "=", "DEFAULT_WAIT_INTERVAL", ",", "timeout", "=", "DEFAULT_WAIT_TIMEOUT", ")", ":", "start", "=", "time", ".", "time", "(", ")", "# at least execute the check once!", "while", "True", ":", "res"...
Wait until a condition holds by checking it in regular intervals. Raises ``WaitTimeoutError`` on timeout.
[ "Wait", "until", "a", "condition", "holds", "by", "checking", "it", "in", "regular", "intervals", ".", "Raises", "WaitTimeoutError", "on", "timeout", "." ]
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/mixins.py#L77-L100
train
210,842
niklasb/dryscrape
dryscrape/mixins.py
WaitMixin.wait_while
def wait_while(self, condition, *args, **kw): """ Wait while a condition holds. """ return self.wait_for(lambda: not condition(), *args, **kw)
python
def wait_while(self, condition, *args, **kw): """ Wait while a condition holds. """ return self.wait_for(lambda: not condition(), *args, **kw)
[ "def", "wait_while", "(", "self", ",", "condition", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "wait_for", "(", "lambda", ":", "not", "condition", "(", ")", ",", "*", "args", ",", "*", "*", "kw", ")" ]
Wait while a condition holds.
[ "Wait", "while", "a", "condition", "holds", "." ]
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/mixins.py#L110-L112
train
210,843
niklasb/dryscrape
dryscrape/mixins.py
WaitMixin.at_css
def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw): """ Returns the first node matching the given CSSv3 expression or ``None`` if a timeout occurs. """ return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css), timeout = timeout, **kw)
python
def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw): """ Returns the first node matching the given CSSv3 expression or ``None`` if a timeout occurs. """ return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css), timeout = timeout, **kw)
[ "def", "at_css", "(", "self", ",", "css", ",", "timeout", "=", "DEFAULT_AT_TIMEOUT", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "wait_for_safe", "(", "lambda", ":", "super", "(", "WaitMixin", ",", "self", ")", ".", "at_css", "(", "css", ")...
Returns the first node matching the given CSSv3 expression or ``None`` if a timeout occurs.
[ "Returns", "the", "first", "node", "matching", "the", "given", "CSSv3", "expression", "or", "None", "if", "a", "timeout", "occurs", "." ]
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/mixins.py#L114-L119
train
210,844
niklasb/dryscrape
dryscrape/mixins.py
WaitMixin.at_xpath
def at_xpath(self, xpath, timeout = DEFAULT_AT_TIMEOUT, **kw): """ Returns the first node matching the given XPath 2.0 expression or ``None`` if a timeout occurs. """ return self.wait_for_safe(lambda: super(WaitMixin, self).at_xpath(xpath), timeout = timeout, **kw)
python
def at_xpath(self, xpath, timeout = DEFAULT_AT_TIMEOUT, **kw): """ Returns the first node matching the given XPath 2.0 expression or ``None`` if a timeout occurs. """ return self.wait_for_safe(lambda: super(WaitMixin, self).at_xpath(xpath), timeout = timeout, **kw)
[ "def", "at_xpath", "(", "self", ",", "xpath", ",", "timeout", "=", "DEFAULT_AT_TIMEOUT", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "wait_for_safe", "(", "lambda", ":", "super", "(", "WaitMixin", ",", "self", ")", ".", "at_xpath", "(", "xpat...
Returns the first node matching the given XPath 2.0 expression or ``None`` if a timeout occurs.
[ "Returns", "the", "first", "node", "matching", "the", "given", "XPath", "2", ".", "0", "expression", "or", "None", "if", "a", "timeout", "occurs", "." ]
4d3dabdec02f321a37325ff8dbb43d049d451931
https://github.com/niklasb/dryscrape/blob/4d3dabdec02f321a37325ff8dbb43d049d451931/dryscrape/mixins.py#L121-L126
train
210,845
olgabot/prettyplotlib
prettyplotlib/__init__.py
switch_axis_limits
def switch_axis_limits(ax, which_axis): ''' Switch the axis limits of either x or y. Or both! ''' for a in which_axis: assert a in ('x', 'y') ax_limits = ax.axis() if a == 'x': ax.set_xlim(ax_limits[1], ax_limits[0]) else: ax.set_ylim(ax_limits[3], ax_limits[2])
python
def switch_axis_limits(ax, which_axis): ''' Switch the axis limits of either x or y. Or both! ''' for a in which_axis: assert a in ('x', 'y') ax_limits = ax.axis() if a == 'x': ax.set_xlim(ax_limits[1], ax_limits[0]) else: ax.set_ylim(ax_limits[3], ax_limits[2])
[ "def", "switch_axis_limits", "(", "ax", ",", "which_axis", ")", ":", "for", "a", "in", "which_axis", ":", "assert", "a", "in", "(", "'x'", ",", "'y'", ")", "ax_limits", "=", "ax", ".", "axis", "(", ")", "if", "a", "==", "'x'", ":", "ax", ".", "se...
Switch the axis limits of either x or y. Or both!
[ "Switch", "the", "axis", "limits", "of", "either", "x", "or", "y", ".", "Or", "both!" ]
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/__init__.py#L30-L40
train
210,846
olgabot/prettyplotlib
prettyplotlib/utils.py
remove_chartjunk
def remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False, xkcd=False): ''' Removes "chartjunk", such as extra lines of axes and tick marks. If grid="y" or "x", will add a white grid at the "y" or "x" axes, respectively If ticklabels="y" or "x", or ['x', 'y'] will remove ticklabels from that axis ''' all_spines = ['top', 'bottom', 'right', 'left', 'polar'] for spine in spines: # The try/except is for polar coordinates, which only have a 'polar' # spine and none of the others try: ax.spines[spine].set_visible(False) except KeyError: pass # For the remaining spines, make their line thinner and a slightly # off-black dark grey if not xkcd: for spine in set(all_spines).difference(set(spines)): # The try/except is for polar coordinates, which only have a # 'polar' spine and none of the others try: ax.spines[spine].set_linewidth(0.5) except KeyError: pass # ax.spines[spine].set_color(almost_black) # ax.spines[spine].set_tick_params(color=almost_black) # Check that the axes are not log-scale. If they are, leave # the ticks because otherwise people assume a linear scale. x_pos = set(['top', 'bottom']) y_pos = set(['left', 'right']) xy_pos = [x_pos, y_pos] xy_ax_names = ['xaxis', 'yaxis'] for ax_name, pos in zip(xy_ax_names, xy_pos): axis = ax.__dict__[ax_name] # axis.set_tick_params(color=almost_black) #print 'axis.get_scale()', axis.get_scale() if show_ticks or axis.get_scale() == 'log': # if this spine is not in the list of spines to remove for p in pos.difference(spines): #print 'p', p axis.set_tick_params(direction='out') axis.set_ticks_position(p) # axis.set_tick_params(which='both', p) else: axis.set_ticks_position('none') if grid is not None: for g in grid: assert g in ('x', 'y') ax.grid(axis=grid, color='white', linestyle='-', linewidth=0.5) if ticklabels is not None: if type(ticklabels) is str: assert ticklabels in set(('x', 'y')) if ticklabels == 'x': ax.set_xticklabels([]) if ticklabels == 'y': ax.set_yticklabels([]) else: assert set(ticklabels) | set(('x', 'y')) > 0 if 'x' in ticklabels: ax.set_xticklabels([]) elif 'y' in ticklabels: ax.set_yticklabels([])
python
def remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False, xkcd=False): ''' Removes "chartjunk", such as extra lines of axes and tick marks. If grid="y" or "x", will add a white grid at the "y" or "x" axes, respectively If ticklabels="y" or "x", or ['x', 'y'] will remove ticklabels from that axis ''' all_spines = ['top', 'bottom', 'right', 'left', 'polar'] for spine in spines: # The try/except is for polar coordinates, which only have a 'polar' # spine and none of the others try: ax.spines[spine].set_visible(False) except KeyError: pass # For the remaining spines, make their line thinner and a slightly # off-black dark grey if not xkcd: for spine in set(all_spines).difference(set(spines)): # The try/except is for polar coordinates, which only have a # 'polar' spine and none of the others try: ax.spines[spine].set_linewidth(0.5) except KeyError: pass # ax.spines[spine].set_color(almost_black) # ax.spines[spine].set_tick_params(color=almost_black) # Check that the axes are not log-scale. If they are, leave # the ticks because otherwise people assume a linear scale. x_pos = set(['top', 'bottom']) y_pos = set(['left', 'right']) xy_pos = [x_pos, y_pos] xy_ax_names = ['xaxis', 'yaxis'] for ax_name, pos in zip(xy_ax_names, xy_pos): axis = ax.__dict__[ax_name] # axis.set_tick_params(color=almost_black) #print 'axis.get_scale()', axis.get_scale() if show_ticks or axis.get_scale() == 'log': # if this spine is not in the list of spines to remove for p in pos.difference(spines): #print 'p', p axis.set_tick_params(direction='out') axis.set_ticks_position(p) # axis.set_tick_params(which='both', p) else: axis.set_ticks_position('none') if grid is not None: for g in grid: assert g in ('x', 'y') ax.grid(axis=grid, color='white', linestyle='-', linewidth=0.5) if ticklabels is not None: if type(ticklabels) is str: assert ticklabels in set(('x', 'y')) if ticklabels == 'x': ax.set_xticklabels([]) if ticklabels == 'y': ax.set_yticklabels([]) else: assert set(ticklabels) | set(('x', 'y')) > 0 if 'x' in ticklabels: ax.set_xticklabels([]) elif 'y' in ticklabels: ax.set_yticklabels([])
[ "def", "remove_chartjunk", "(", "ax", ",", "spines", ",", "grid", "=", "None", ",", "ticklabels", "=", "None", ",", "show_ticks", "=", "False", ",", "xkcd", "=", "False", ")", ":", "all_spines", "=", "[", "'top'", ",", "'bottom'", ",", "'right'", ",", ...
Removes "chartjunk", such as extra lines of axes and tick marks. If grid="y" or "x", will add a white grid at the "y" or "x" axes, respectively If ticklabels="y" or "x", or ['x', 'y'] will remove ticklabels from that axis
[ "Removes", "chartjunk", "such", "as", "extra", "lines", "of", "axes", "and", "tick", "marks", "." ]
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/utils.py#L7-L77
train
210,847
olgabot/prettyplotlib
prettyplotlib/utils.py
maybe_get_ax
def maybe_get_ax(*args, **kwargs): """ It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype: """ if 'ax' in kwargs: ax = kwargs.pop('ax') elif len(args) == 0: fig = plt.gcf() ax = plt.gca() elif isinstance(args[0], mpl.axes.Axes): ax = args[0] args = args[1:] else: ax = plt.gca() return ax, args, dict(kwargs)
python
def maybe_get_ax(*args, **kwargs): """ It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype: """ if 'ax' in kwargs: ax = kwargs.pop('ax') elif len(args) == 0: fig = plt.gcf() ax = plt.gca() elif isinstance(args[0], mpl.axes.Axes): ax = args[0] args = args[1:] else: ax = plt.gca() return ax, args, dict(kwargs)
[ "def", "maybe_get_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'ax'", "in", "kwargs", ":", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ")", "elif", "len", "(", "args", ")", "==", "0", ":", "fig", "=", "plt", ".", "gcf", ...
It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype:
[ "It", "used", "to", "be", "that", "the", "first", "argument", "of", "prettyplotlib", "had", "to", "be", "the", "ax", "object", "but", "that", "s", "not", "the", "case", "anymore", "." ]
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/utils.py#L80-L103
train
210,848
olgabot/prettyplotlib
prettyplotlib/utils.py
maybe_get_fig_ax
def maybe_get_fig_ax(*args, **kwargs): """ It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. This is specially made for pcolormesh. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype: """ if 'ax' in kwargs: ax = kwargs.pop('ax') if 'fig' in kwargs: fig = kwargs.pop('fig') else: fig = plt.gcf() elif len(args) == 0: fig = plt.gcf() ax = plt.gca() elif isinstance(args[0], mpl.figure.Figure) and \ isinstance(args[1], mpl.axes.Axes): fig = args[0] ax = args[1] args = args[2:] else: fig, ax = plt.subplots(1) return fig, ax, args, dict(kwargs)
python
def maybe_get_fig_ax(*args, **kwargs): """ It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. This is specially made for pcolormesh. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype: """ if 'ax' in kwargs: ax = kwargs.pop('ax') if 'fig' in kwargs: fig = kwargs.pop('fig') else: fig = plt.gcf() elif len(args) == 0: fig = plt.gcf() ax = plt.gca() elif isinstance(args[0], mpl.figure.Figure) and \ isinstance(args[1], mpl.axes.Axes): fig = args[0] ax = args[1] args = args[2:] else: fig, ax = plt.subplots(1) return fig, ax, args, dict(kwargs)
[ "def", "maybe_get_fig_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'ax'", "in", "kwargs", ":", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ")", "if", "'fig'", "in", "kwargs", ":", "fig", "=", "kwargs", ".", "pop", "(", "'fig...
It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. This is specially made for pcolormesh. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype:
[ "It", "used", "to", "be", "that", "the", "first", "argument", "of", "prettyplotlib", "had", "to", "be", "the", "ax", "object", "but", "that", "s", "not", "the", "case", "anymore", ".", "This", "is", "specially", "made", "for", "pcolormesh", "." ]
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/utils.py#L106-L135
train
210,849
olgabot/prettyplotlib
prettyplotlib/_scatter.py
scatter
def scatter(*args, **kwargs): """ This will plot a scatterplot of x and y, iterating over the ColorBrewer "Set2" color cycle unless a color is specified. The symbols produced are empty circles, with the outline in the color specified by either 'color' or 'edgecolor'. If you want to fill the circle, specify 'facecolor'. Besides the matplotlib scatter(), will also take the parameter @param show_ticks: Whether or not to show the x and y axis ticks """ # Force 'color' to indicate the edge color, so the middle of the # scatter patches are empty. Can specify ax, args, kwargs = utils.maybe_get_ax(*args, **kwargs) if 'color' not in kwargs: # Assume that color means the edge color. You can assign the color_cycle = ax._get_lines.color_cycle kwargs['color'] = next(color_cycle) kwargs.setdefault('edgecolor', almost_black) kwargs.setdefault('alpha', 0.5) lw = utils.maybe_get_linewidth(**kwargs) kwargs['lw'] = lw show_ticks = kwargs.pop('show_ticks', False) scatterpoints = ax.scatter(*args, **kwargs) utils.remove_chartjunk(ax, ['top', 'right'], show_ticks=show_ticks) return scatterpoints
python
def scatter(*args, **kwargs): """ This will plot a scatterplot of x and y, iterating over the ColorBrewer "Set2" color cycle unless a color is specified. The symbols produced are empty circles, with the outline in the color specified by either 'color' or 'edgecolor'. If you want to fill the circle, specify 'facecolor'. Besides the matplotlib scatter(), will also take the parameter @param show_ticks: Whether or not to show the x and y axis ticks """ # Force 'color' to indicate the edge color, so the middle of the # scatter patches are empty. Can specify ax, args, kwargs = utils.maybe_get_ax(*args, **kwargs) if 'color' not in kwargs: # Assume that color means the edge color. You can assign the color_cycle = ax._get_lines.color_cycle kwargs['color'] = next(color_cycle) kwargs.setdefault('edgecolor', almost_black) kwargs.setdefault('alpha', 0.5) lw = utils.maybe_get_linewidth(**kwargs) kwargs['lw'] = lw show_ticks = kwargs.pop('show_ticks', False) scatterpoints = ax.scatter(*args, **kwargs) utils.remove_chartjunk(ax, ['top', 'right'], show_ticks=show_ticks) return scatterpoints
[ "def", "scatter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Force 'color' to indicate the edge color, so the middle of the", "# scatter patches are empty. Can specify", "ax", ",", "args", ",", "kwargs", "=", "utils", ".", "maybe_get_ax", "(", "*", "args"...
This will plot a scatterplot of x and y, iterating over the ColorBrewer "Set2" color cycle unless a color is specified. The symbols produced are empty circles, with the outline in the color specified by either 'color' or 'edgecolor'. If you want to fill the circle, specify 'facecolor'. Besides the matplotlib scatter(), will also take the parameter @param show_ticks: Whether or not to show the x and y axis ticks
[ "This", "will", "plot", "a", "scatterplot", "of", "x", "and", "y", "iterating", "over", "the", "ColorBrewer", "Set2", "color", "cycle", "unless", "a", "color", "is", "specified", ".", "The", "symbols", "produced", "are", "empty", "circles", "with", "the", ...
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/_scatter.py#L8-L36
train
210,850
olgabot/prettyplotlib
prettyplotlib/_boxplot.py
boxplot
def boxplot(*args, **kwargs): """ Create a box-and-whisker plot showing the mean, 25th percentile, and 75th percentile. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual boxplot, any argument for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot @return: """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) # If no ticklabels are specified, don't draw any xticklabels = kwargs.pop('xticklabels', None) fontsize = kwargs.pop('fontsize', 10) kwargs.setdefault('widths', 0.15) bp = ax.boxplot(*args, **kwargs) if xticklabels: ax.xaxis.set_ticklabels(xticklabels, fontsize=fontsize) show_caps = kwargs.pop('show_caps', True) show_ticks = kwargs.pop('show_ticks', False) remove_chartjunk(ax, ['top', 'right', 'bottom'], show_ticks=show_ticks) linewidth = 0.75 blue = colors.set1[1] red = colors.set1[0] plt.setp(bp['boxes'], color=blue, linewidth=linewidth) plt.setp(bp['medians'], color=red) plt.setp(bp['whiskers'], color=blue, linestyle='solid', linewidth=linewidth) plt.setp(bp['fliers'], color=blue) if show_caps: plt.setp(bp['caps'], color=blue, linewidth=linewidth) else: plt.setp(bp['caps'], color='none') ax.spines['left']._linewidth = 0.5 return bp
python
def boxplot(*args, **kwargs): """ Create a box-and-whisker plot showing the mean, 25th percentile, and 75th percentile. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual boxplot, any argument for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot @return: """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) # If no ticklabels are specified, don't draw any xticklabels = kwargs.pop('xticklabels', None) fontsize = kwargs.pop('fontsize', 10) kwargs.setdefault('widths', 0.15) bp = ax.boxplot(*args, **kwargs) if xticklabels: ax.xaxis.set_ticklabels(xticklabels, fontsize=fontsize) show_caps = kwargs.pop('show_caps', True) show_ticks = kwargs.pop('show_ticks', False) remove_chartjunk(ax, ['top', 'right', 'bottom'], show_ticks=show_ticks) linewidth = 0.75 blue = colors.set1[1] red = colors.set1[0] plt.setp(bp['boxes'], color=blue, linewidth=linewidth) plt.setp(bp['medians'], color=red) plt.setp(bp['whiskers'], color=blue, linestyle='solid', linewidth=linewidth) plt.setp(bp['fliers'], color=blue) if show_caps: plt.setp(bp['caps'], color=blue, linewidth=linewidth) else: plt.setp(bp['caps'], color='none') ax.spines['left']._linewidth = 0.5 return bp
[ "def", "boxplot", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", ",", "args", ",", "kwargs", "=", "maybe_get_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# If no ticklabels are specified, don't draw any", "xticklabels", "=", "kwargs", ...
Create a box-and-whisker plot showing the mean, 25th percentile, and 75th percentile. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual boxplot, any argument for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot @return:
[ "Create", "a", "box", "-", "and", "-", "whisker", "plot", "showing", "the", "mean", "25th", "percentile", "and", "75th", "percentile", ".", "The", "difference", "from", "matplotlib", "is", "only", "the", "left", "axis", "line", "is", "shown", "and", "tickl...
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/_boxplot.py#L7-L51
train
210,851
olgabot/prettyplotlib
prettyplotlib/_hist.py
hist
def hist(*args, **kwargs): """ Plots a histogram of the provided data. Can provide optional argument "grid='x'" or "grid='y'" to draw a white grid over the histogram. Almost like "erasing" some of the plot, but it adds more information! """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) color_cycle = ax._get_lines.color_cycle # Reassign the default colors to Set2 by Colorbrewer if iterable(args[0]): if isinstance(args[0], list): ncolors = len(args[0]) else: if len(args[0].shape) == 2: ncolors = args[0].shape[1] else: ncolors = 1 kwargs.setdefault('color', [next(color_cycle) for _ in range(ncolors)]) else: kwargs.setdefault('color', next(color_cycle)) kwargs.setdefault('edgecolor', 'white') show_ticks = kwargs.pop('show_ticks', False) # If no grid specified, don't draw one. grid = kwargs.pop('grid', None) # print 'hist kwargs', kwargs patches = ax.hist(*args, **kwargs) remove_chartjunk(ax, ['top', 'right'], grid=grid, show_ticks=show_ticks) return patches
python
def hist(*args, **kwargs): """ Plots a histogram of the provided data. Can provide optional argument "grid='x'" or "grid='y'" to draw a white grid over the histogram. Almost like "erasing" some of the plot, but it adds more information! """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) color_cycle = ax._get_lines.color_cycle # Reassign the default colors to Set2 by Colorbrewer if iterable(args[0]): if isinstance(args[0], list): ncolors = len(args[0]) else: if len(args[0].shape) == 2: ncolors = args[0].shape[1] else: ncolors = 1 kwargs.setdefault('color', [next(color_cycle) for _ in range(ncolors)]) else: kwargs.setdefault('color', next(color_cycle)) kwargs.setdefault('edgecolor', 'white') show_ticks = kwargs.pop('show_ticks', False) # If no grid specified, don't draw one. grid = kwargs.pop('grid', None) # print 'hist kwargs', kwargs patches = ax.hist(*args, **kwargs) remove_chartjunk(ax, ['top', 'right'], grid=grid, show_ticks=show_ticks) return patches
[ "def", "hist", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", ",", "args", ",", "kwargs", "=", "maybe_get_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", "color_cycle", "=", "ax", ".", "_get_lines", ".", "color_cycle", "# Reassign th...
Plots a histogram of the provided data. Can provide optional argument "grid='x'" or "grid='y'" to draw a white grid over the histogram. Almost like "erasing" some of the plot, but it adds more information!
[ "Plots", "a", "histogram", "of", "the", "provided", "data", ".", "Can", "provide", "optional", "argument", "grid", "=", "x", "or", "grid", "=", "y", "to", "draw", "a", "white", "grid", "over", "the", "histogram", ".", "Almost", "like", "erasing", "some",...
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/_hist.py#L10-L40
train
210,852
olgabot/prettyplotlib
prettyplotlib/_beeswarm.py
beeswarm
def beeswarm(*args, **kwargs): """ Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual beeswarm, many arguments for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot Additional arguments include: *median_color* : (default gray) The color of median lines *median_width* : (default 2) Median line width *colors* : (default None) Colors to use when painting a dataseries, for example list1 = [1,2,3] list2 = [5,6,7] ppl.beeswarm([list1, list2], colors=["red", "blue"], xticklabels=["data1", "data2"]) @return: """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) # If no ticklabels are specified, don't draw any xticklabels = kwargs.pop('xticklabels', None) colors = kwargs.pop('colors', None) fontsize = kwargs.pop('fontsize', 10) gray = _colors.set1[8] red = _colors.set1[0] blue = kwargs.pop('color', _colors.set1[1]) kwargs.setdefault('widths', 0.25) kwargs.setdefault('sym', "o") bp = _beeswarm(ax, *args, **kwargs) kwargs.setdefault("median_color", gray) kwargs.setdefault("median_linewidth", 2) if xticklabels: ax.xaxis.set_ticklabels(xticklabels, fontsize=fontsize) show_caps = kwargs.pop('show_caps', True) show_ticks = kwargs.pop('show_ticks', False) remove_chartjunk(ax, ['top', 'right', 'bottom'], show_ticks=show_ticks) linewidth = 0.75 plt.setp(bp['boxes'], color=blue, linewidth=linewidth) plt.setp(bp['medians'], color=kwargs.pop("median_color"), linewidth=kwargs.pop("median_linewidth")) #plt.setp(bp['whiskers'], color=blue, linestyle='solid', # linewidth=linewidth) for color, flier in zip(colors, bp['fliers']): plt.setp(flier, color=color) #if show_caps: # plt.setp(bp['caps'], color=blue, linewidth=linewidth) #else: # plt.setp(bp['caps'], color='none') ax.spines['left']._linewidth = 0.5 return bp
python
def beeswarm(*args, **kwargs): """ Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual beeswarm, many arguments for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot Additional arguments include: *median_color* : (default gray) The color of median lines *median_width* : (default 2) Median line width *colors* : (default None) Colors to use when painting a dataseries, for example list1 = [1,2,3] list2 = [5,6,7] ppl.beeswarm([list1, list2], colors=["red", "blue"], xticklabels=["data1", "data2"]) @return: """ ax, args, kwargs = maybe_get_ax(*args, **kwargs) # If no ticklabels are specified, don't draw any xticklabels = kwargs.pop('xticklabels', None) colors = kwargs.pop('colors', None) fontsize = kwargs.pop('fontsize', 10) gray = _colors.set1[8] red = _colors.set1[0] blue = kwargs.pop('color', _colors.set1[1]) kwargs.setdefault('widths', 0.25) kwargs.setdefault('sym', "o") bp = _beeswarm(ax, *args, **kwargs) kwargs.setdefault("median_color", gray) kwargs.setdefault("median_linewidth", 2) if xticklabels: ax.xaxis.set_ticklabels(xticklabels, fontsize=fontsize) show_caps = kwargs.pop('show_caps', True) show_ticks = kwargs.pop('show_ticks', False) remove_chartjunk(ax, ['top', 'right', 'bottom'], show_ticks=show_ticks) linewidth = 0.75 plt.setp(bp['boxes'], color=blue, linewidth=linewidth) plt.setp(bp['medians'], color=kwargs.pop("median_color"), linewidth=kwargs.pop("median_linewidth")) #plt.setp(bp['whiskers'], color=blue, linestyle='solid', # linewidth=linewidth) for color, flier in zip(colors, bp['fliers']): plt.setp(flier, color=color) #if show_caps: # plt.setp(bp['caps'], color=blue, linewidth=linewidth) #else: # plt.setp(bp['caps'], color='none') ax.spines['left']._linewidth = 0.5 return bp
[ "def", "beeswarm", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", ",", "args", ",", "kwargs", "=", "maybe_get_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# If no ticklabels are specified, don't draw any", "xticklabels", "=", "kwargs", ...
Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is shown, and ticklabels labeling each category of data can be added. @param ax: @param x: @param kwargs: Besides xticklabels, which is a prettyplotlib-specific argument which will label each individual beeswarm, many arguments for matplotlib.pyplot.boxplot will be accepted: http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.boxplot Additional arguments include: *median_color* : (default gray) The color of median lines *median_width* : (default 2) Median line width *colors* : (default None) Colors to use when painting a dataseries, for example list1 = [1,2,3] list2 = [5,6,7] ppl.beeswarm([list1, list2], colors=["red", "blue"], xticklabels=["data1", "data2"]) @return:
[ "Create", "a", "R", "-", "like", "beeswarm", "plot", "showing", "the", "mean", "and", "datapoints", ".", "The", "difference", "from", "matplotlib", "is", "only", "the", "left", "axis", "line", "is", "shown", "and", "ticklabels", "labeling", "each", "category...
aa964ff777e60d26f078d8ace386936bf41cbd15
https://github.com/olgabot/prettyplotlib/blob/aa964ff777e60d26f078d8ace386936bf41cbd15/prettyplotlib/_beeswarm.py#L278-L346
train
210,853
scopely-devops/skew
skew/resources/aws/__init__.py
AWSResource.tags
def tags(self): """ Convert the ugly Tags JSON into a real dictionary and memorize the result. """ if self._tags is None: LOG.debug('need to build tags') self._tags = {} if hasattr(self.Meta, 'tags_spec') and (self.Meta.tags_spec is not None): LOG.debug('have a tags_spec') method, path, param_name, param_value = self.Meta.tags_spec[:4] kwargs = {} filter_type = getattr(self.Meta, 'filter_type', None) if filter_type == 'arn': kwargs = {param_name: [getattr(self, param_value)]} elif filter_type == 'list': kwargs = {param_name: [getattr(self, param_value)]} else: kwargs = {param_name: getattr(self, param_value)} if len(self.Meta.tags_spec) > 4: kwargs.update(self.Meta.tags_spec[4]) LOG.debug('fetching tags') self.data['Tags'] = self._client.call( method, query=path, **kwargs) LOG.debug(self.data['Tags']) if 'Tags' in self.data: _tags = self.data['Tags'] if isinstance(_tags, list): for kvpair in _tags: if kvpair['Key'] in self._tags: if not isinstance(self._tags[kvpair['Key']], list): self._tags[kvpair['Key']] = [self._tags[kvpair['Key']]] self._tags[kvpair['Key']].append(kvpair['Value']) else: self._tags[kvpair['Key']] = kvpair['Value'] elif isinstance(_tags, dict): self._tags = _tags return self._tags
python
def tags(self): """ Convert the ugly Tags JSON into a real dictionary and memorize the result. """ if self._tags is None: LOG.debug('need to build tags') self._tags = {} if hasattr(self.Meta, 'tags_spec') and (self.Meta.tags_spec is not None): LOG.debug('have a tags_spec') method, path, param_name, param_value = self.Meta.tags_spec[:4] kwargs = {} filter_type = getattr(self.Meta, 'filter_type', None) if filter_type == 'arn': kwargs = {param_name: [getattr(self, param_value)]} elif filter_type == 'list': kwargs = {param_name: [getattr(self, param_value)]} else: kwargs = {param_name: getattr(self, param_value)} if len(self.Meta.tags_spec) > 4: kwargs.update(self.Meta.tags_spec[4]) LOG.debug('fetching tags') self.data['Tags'] = self._client.call( method, query=path, **kwargs) LOG.debug(self.data['Tags']) if 'Tags' in self.data: _tags = self.data['Tags'] if isinstance(_tags, list): for kvpair in _tags: if kvpair['Key'] in self._tags: if not isinstance(self._tags[kvpair['Key']], list): self._tags[kvpair['Key']] = [self._tags[kvpair['Key']]] self._tags[kvpair['Key']].append(kvpair['Value']) else: self._tags[kvpair['Key']] = kvpair['Value'] elif isinstance(_tags, dict): self._tags = _tags return self._tags
[ "def", "tags", "(", "self", ")", ":", "if", "self", ".", "_tags", "is", "None", ":", "LOG", ".", "debug", "(", "'need to build tags'", ")", "self", ".", "_tags", "=", "{", "}", "if", "hasattr", "(", "self", ".", "Meta", ",", "'tags_spec'", ")", "an...
Convert the ugly Tags JSON into a real dictionary and memorize the result.
[ "Convert", "the", "ugly", "Tags", "JSON", "into", "a", "real", "dictionary", "and", "memorize", "the", "result", "." ]
e90d5e2220b2284502a06430bb94b4aba9ea60db
https://github.com/scopely-devops/skew/blob/e90d5e2220b2284502a06430bb94b4aba9ea60db/skew/resources/aws/__init__.py#L143-L182
train
210,854
scopely-devops/skew
skew/resources/aws/__init__.py
AWSResource.get_metric_data
def get_metric_data(self, metric_name=None, metric=None, days=None, hours=1, minutes=None, statistics=None, period=None): """ Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``period`` to return the maximum number of data points up to the CloudWatch max of 1440. :type metric_name: str :param metric_name: The name of the metric this data will pertain to. :type days: int :param days: The number of days worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type hours: int :param hours: The number of hours worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type statistics: list of str :param statistics: The metric statistics to return. The default value is **Average**. Possible values are: * Average * Sum * SampleCount * Maximum * Minimum :returns: A ``MetricData`` object that contains both the CloudWatch data as well as the ``period`` used since this value may have been calculated by skew. """ if not statistics: statistics = ['Average'] if days: delta = datetime.timedelta(days=days) elif hours: delta = datetime.timedelta(hours=hours) else: delta = datetime.timedelta(minutes=minutes) if not period: period = max(60, self._total_seconds(delta) // 1440) if not metric: metric = self.find_metric(metric_name) if metric and self._cloudwatch: end = datetime.datetime.utcnow() start = end - delta data = self._cloudwatch.call( 'get_metric_statistics', Dimensions=metric['Dimensions'], Namespace=metric['Namespace'], MetricName=metric['MetricName'], StartTime=start.isoformat(), EndTime=end.isoformat(), Statistics=statistics, Period=period) return MetricData(jmespath.search('Datapoints', data), period) else: raise ValueError('Metric (%s) not available' % metric_name)
python
def get_metric_data(self, metric_name=None, metric=None, days=None, hours=1, minutes=None, statistics=None, period=None): """ Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``period`` to return the maximum number of data points up to the CloudWatch max of 1440. :type metric_name: str :param metric_name: The name of the metric this data will pertain to. :type days: int :param days: The number of days worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type hours: int :param hours: The number of hours worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type statistics: list of str :param statistics: The metric statistics to return. The default value is **Average**. Possible values are: * Average * Sum * SampleCount * Maximum * Minimum :returns: A ``MetricData`` object that contains both the CloudWatch data as well as the ``period`` used since this value may have been calculated by skew. """ if not statistics: statistics = ['Average'] if days: delta = datetime.timedelta(days=days) elif hours: delta = datetime.timedelta(hours=hours) else: delta = datetime.timedelta(minutes=minutes) if not period: period = max(60, self._total_seconds(delta) // 1440) if not metric: metric = self.find_metric(metric_name) if metric and self._cloudwatch: end = datetime.datetime.utcnow() start = end - delta data = self._cloudwatch.call( 'get_metric_statistics', Dimensions=metric['Dimensions'], Namespace=metric['Namespace'], MetricName=metric['MetricName'], StartTime=start.isoformat(), EndTime=end.isoformat(), Statistics=statistics, Period=period) return MetricData(jmespath.search('Datapoints', data), period) else: raise ValueError('Metric (%s) not available' % metric_name)
[ "def", "get_metric_data", "(", "self", ",", "metric_name", "=", "None", ",", "metric", "=", "None", ",", "days", "=", "None", ",", "hours", "=", "1", ",", "minutes", "=", "None", ",", "statistics", "=", "None", ",", "period", "=", "None", ")", ":", ...
Get metric data for this resource. You can specify the time frame for the data as either the number of days or number of hours. The maximum window is 14 days. Based on the time frame this method will calculate the correct ``period`` to return the maximum number of data points up to the CloudWatch max of 1440. :type metric_name: str :param metric_name: The name of the metric this data will pertain to. :type days: int :param days: The number of days worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type hours: int :param hours: The number of hours worth of data to return. You can specify either ``days`` or ``hours``. The default is one hour. The maximum value is 14 days. :type statistics: list of str :param statistics: The metric statistics to return. The default value is **Average**. Possible values are: * Average * Sum * SampleCount * Maximum * Minimum :returns: A ``MetricData`` object that contains both the CloudWatch data as well as the ``period`` used since this value may have been calculated by skew.
[ "Get", "metric", "data", "for", "this", "resource", ".", "You", "can", "specify", "the", "time", "frame", "for", "the", "data", "as", "either", "the", "number", "of", "days", "or", "number", "of", "hours", ".", "The", "maximum", "window", "is", "14", "...
e90d5e2220b2284502a06430bb94b4aba9ea60db
https://github.com/scopely-devops/skew/blob/e90d5e2220b2284502a06430bb94b4aba9ea60db/skew/resources/aws/__init__.py#L197-L261
train
210,855
cokelaer/fitter
src/fitter/fitter.py
Fitter.fit
def fit(self): r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data, we populate a set of dataframes: - :attr:`df_errors` :sum of the square errors between the data and the fitted distribution i.e., :math:`\sum_i \left( Y_i - pdf(X_i) \right)^2` - :attr:`fitted_param` : the parameters that best fit the data - :attr:`fitted_pdf` : the PDF generated with the parameters that best fit the data Indices of the dataframes contains the name of the distribution. """ for distribution in self.distributions: try: # need a subprocess to check time it takes. If too long, skip it dist = eval("scipy.stats." + distribution) # TODO here, dist.fit may take a while or just hang forever # with some distributions. So, I thought to use signal module # to catch the error when signal takes too long. It did not work # presumably because another try/exception is inside the # fit function, so I used threading with arecipe from stackoverflow # See timed_run function above param = self._timed_run(dist.fit, distribution, args=self._data) # with signal, does not work. maybe because another expection is caught pdf_fitted = dist.pdf(self.x, *param) # hoping the order returned by fit is the same as in pdf self.fitted_param[distribution] = param[:] self.fitted_pdf[distribution] = pdf_fitted sq_error = pylab.sum((self.fitted_pdf[distribution] - self.y)**2) if self.verbose: print("Fitted {} distribution with error={})".format(distribution, sq_error)) # compute some errors now self._fitted_errors[distribution] = sq_error except Exception as err: if self.verbose: print("SKIPPED {} distribution (taking more than {} seconds)".format(distribution, self.timeout)) # if we cannot compute the error, set it to large values # FIXME use inf self._fitted_errors[distribution] = 1e6 self.df_errors = pd.DataFrame({'sumsquare_error':self._fitted_errors})
python
def fit(self): r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data, we populate a set of dataframes: - :attr:`df_errors` :sum of the square errors between the data and the fitted distribution i.e., :math:`\sum_i \left( Y_i - pdf(X_i) \right)^2` - :attr:`fitted_param` : the parameters that best fit the data - :attr:`fitted_pdf` : the PDF generated with the parameters that best fit the data Indices of the dataframes contains the name of the distribution. """ for distribution in self.distributions: try: # need a subprocess to check time it takes. If too long, skip it dist = eval("scipy.stats." + distribution) # TODO here, dist.fit may take a while or just hang forever # with some distributions. So, I thought to use signal module # to catch the error when signal takes too long. It did not work # presumably because another try/exception is inside the # fit function, so I used threading with arecipe from stackoverflow # See timed_run function above param = self._timed_run(dist.fit, distribution, args=self._data) # with signal, does not work. maybe because another expection is caught pdf_fitted = dist.pdf(self.x, *param) # hoping the order returned by fit is the same as in pdf self.fitted_param[distribution] = param[:] self.fitted_pdf[distribution] = pdf_fitted sq_error = pylab.sum((self.fitted_pdf[distribution] - self.y)**2) if self.verbose: print("Fitted {} distribution with error={})".format(distribution, sq_error)) # compute some errors now self._fitted_errors[distribution] = sq_error except Exception as err: if self.verbose: print("SKIPPED {} distribution (taking more than {} seconds)".format(distribution, self.timeout)) # if we cannot compute the error, set it to large values # FIXME use inf self._fitted_errors[distribution] = 1e6 self.df_errors = pd.DataFrame({'sumsquare_error':self._fitted_errors})
[ "def", "fit", "(", "self", ")", ":", "for", "distribution", "in", "self", ".", "distributions", ":", "try", ":", "# need a subprocess to check time it takes. If too long, skip it", "dist", "=", "eval", "(", "\"scipy.stats.\"", "+", "distribution", ")", "# TODO here, d...
r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data, we populate a set of dataframes: - :attr:`df_errors` :sum of the square errors between the data and the fitted distribution i.e., :math:`\sum_i \left( Y_i - pdf(X_i) \right)^2` - :attr:`fitted_param` : the parameters that best fit the data - :attr:`fitted_pdf` : the PDF generated with the parameters that best fit the data Indices of the dataframes contains the name of the distribution.
[ "r", "Loop", "over", "distributions", "and", "find", "best", "parameter", "to", "fit", "the", "data", "for", "each" ]
1f07a42ad44b38a1f944afe456b7c8401bd50402
https://github.com/cokelaer/fitter/blob/1f07a42ad44b38a1f944afe456b7c8401bd50402/src/fitter/fitter.py#L197-L244
train
210,856
cokelaer/fitter
src/fitter/fitter.py
Fitter.plot_pdf
def plot_pdf(self, names=None, Nbest=5, lw=2): """Plots Probability density functions of the distributions :param str,list names: names can be a single distribution name, or a list of distribution names, or kept as None, in which case, the first Nbest distribution will be taken (default to best 5) """ assert Nbest > 0 if Nbest > len(self.distributions): Nbest = len(self.distributions) if isinstance(names, list): for name in names: pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name) elif names: pylab.plot(self.x, self.fitted_pdf[names], lw=lw, label=names) else: try: names = self.df_errors.sort_values( by="sumsquare_error").index[0:Nbest] except: names = self.df_errors.sort("sumsquare_error").index[0:Nbest] for name in names: if name in self.fitted_pdf.keys(): pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name) else: print("%s was not fitted. no parameters available" % name) pylab.grid(True) pylab.legend()
python
def plot_pdf(self, names=None, Nbest=5, lw=2): """Plots Probability density functions of the distributions :param str,list names: names can be a single distribution name, or a list of distribution names, or kept as None, in which case, the first Nbest distribution will be taken (default to best 5) """ assert Nbest > 0 if Nbest > len(self.distributions): Nbest = len(self.distributions) if isinstance(names, list): for name in names: pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name) elif names: pylab.plot(self.x, self.fitted_pdf[names], lw=lw, label=names) else: try: names = self.df_errors.sort_values( by="sumsquare_error").index[0:Nbest] except: names = self.df_errors.sort("sumsquare_error").index[0:Nbest] for name in names: if name in self.fitted_pdf.keys(): pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name) else: print("%s was not fitted. no parameters available" % name) pylab.grid(True) pylab.legend()
[ "def", "plot_pdf", "(", "self", ",", "names", "=", "None", ",", "Nbest", "=", "5", ",", "lw", "=", "2", ")", ":", "assert", "Nbest", ">", "0", "if", "Nbest", ">", "len", "(", "self", ".", "distributions", ")", ":", "Nbest", "=", "len", "(", "se...
Plots Probability density functions of the distributions :param str,list names: names can be a single distribution name, or a list of distribution names, or kept as None, in which case, the first Nbest distribution will be taken (default to best 5)
[ "Plots", "Probability", "density", "functions", "of", "the", "distributions" ]
1f07a42ad44b38a1f944afe456b7c8401bd50402
https://github.com/cokelaer/fitter/blob/1f07a42ad44b38a1f944afe456b7c8401bd50402/src/fitter/fitter.py#L246-L277
train
210,857
cokelaer/fitter
src/fitter/fitter.py
Fitter.get_best
def get_best(self): """Return best fitted distribution and its parameters a dictionary with one key (the distribution name) and its parameters """ # self.df should be sorted, so then us take the first one as the best name = self.df_errors.sort_values('sumsquare_error').iloc[0].name params = self.fitted_param[name] return {name: params}
python
def get_best(self): """Return best fitted distribution and its parameters a dictionary with one key (the distribution name) and its parameters """ # self.df should be sorted, so then us take the first one as the best name = self.df_errors.sort_values('sumsquare_error').iloc[0].name params = self.fitted_param[name] return {name: params}
[ "def", "get_best", "(", "self", ")", ":", "# self.df should be sorted, so then us take the first one as the best", "name", "=", "self", ".", "df_errors", ".", "sort_values", "(", "'sumsquare_error'", ")", ".", "iloc", "[", "0", "]", ".", "name", "params", "=", "se...
Return best fitted distribution and its parameters a dictionary with one key (the distribution name) and its parameters
[ "Return", "best", "fitted", "distribution", "and", "its", "parameters" ]
1f07a42ad44b38a1f944afe456b7c8401bd50402
https://github.com/cokelaer/fitter/blob/1f07a42ad44b38a1f944afe456b7c8401bd50402/src/fitter/fitter.py#L279-L288
train
210,858
cokelaer/fitter
src/fitter/fitter.py
Fitter.summary
def summary(self, Nbest=5, lw=2, plot=True): """Plots the distribution of the data and Nbest distribution """ if plot: pylab.clf() self.hist() self.plot_pdf(Nbest=Nbest, lw=lw) pylab.grid(True) Nbest = min(Nbest, len(self.distributions)) try: names = self.df_errors.sort_values( by="sumsquare_error").index[0:Nbest] except: names = self.df_errors.sort("sumsquare_error").index[0:Nbest] return self.df_errors.loc[names]
python
def summary(self, Nbest=5, lw=2, plot=True): """Plots the distribution of the data and Nbest distribution """ if plot: pylab.clf() self.hist() self.plot_pdf(Nbest=Nbest, lw=lw) pylab.grid(True) Nbest = min(Nbest, len(self.distributions)) try: names = self.df_errors.sort_values( by="sumsquare_error").index[0:Nbest] except: names = self.df_errors.sort("sumsquare_error").index[0:Nbest] return self.df_errors.loc[names]
[ "def", "summary", "(", "self", ",", "Nbest", "=", "5", ",", "lw", "=", "2", ",", "plot", "=", "True", ")", ":", "if", "plot", ":", "pylab", ".", "clf", "(", ")", "self", ".", "hist", "(", ")", "self", ".", "plot_pdf", "(", "Nbest", "=", "Nbes...
Plots the distribution of the data and Nbest distribution
[ "Plots", "the", "distribution", "of", "the", "data", "and", "Nbest", "distribution" ]
1f07a42ad44b38a1f944afe456b7c8401bd50402
https://github.com/cokelaer/fitter/blob/1f07a42ad44b38a1f944afe456b7c8401bd50402/src/fitter/fitter.py#L290-L306
train
210,859
cokelaer/fitter
src/fitter/fitter.py
Fitter._timed_run
def _timed_run(self, func, distribution, args=(), kwargs={}, default=None): """This function will spawn a thread and run the given function using the args, kwargs and return the given default value if the timeout is exceeded. http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call """ class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default self.exc_info = (None, None, None) def run(self): try: self.result = func(args, **kwargs) except Exception as err: self.exc_info = sys.exc_info() def suicide(self): raise RuntimeError('Stop has been called') it = InterruptableThread() it.start() started_at = datetime.now() it.join(self.timeout) ended_at = datetime.now() diff = ended_at - started_at if it.exc_info[0] is not None: # if there were any exceptions a,b,c = it.exc_info raise Exception(a,b,c) # communicate that to caller if it.isAlive(): it.suicide() raise RuntimeError else: return it.result
python
def _timed_run(self, func, distribution, args=(), kwargs={}, default=None): """This function will spawn a thread and run the given function using the args, kwargs and return the given default value if the timeout is exceeded. http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call """ class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default self.exc_info = (None, None, None) def run(self): try: self.result = func(args, **kwargs) except Exception as err: self.exc_info = sys.exc_info() def suicide(self): raise RuntimeError('Stop has been called') it = InterruptableThread() it.start() started_at = datetime.now() it.join(self.timeout) ended_at = datetime.now() diff = ended_at - started_at if it.exc_info[0] is not None: # if there were any exceptions a,b,c = it.exc_info raise Exception(a,b,c) # communicate that to caller if it.isAlive(): it.suicide() raise RuntimeError else: return it.result
[ "def", "_timed_run", "(", "self", ",", "func", ",", "distribution", ",", "args", "=", "(", ")", ",", "kwargs", "=", "{", "}", ",", "default", "=", "None", ")", ":", "class", "InterruptableThread", "(", "threading", ".", "Thread", ")", ":", "def", "__...
This function will spawn a thread and run the given function using the args, kwargs and return the given default value if the timeout is exceeded. http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call
[ "This", "function", "will", "spawn", "a", "thread", "and", "run", "the", "given", "function", "using", "the", "args", "kwargs", "and", "return", "the", "given", "default", "value", "if", "the", "timeout", "is", "exceeded", "." ]
1f07a42ad44b38a1f944afe456b7c8401bd50402
https://github.com/cokelaer/fitter/blob/1f07a42ad44b38a1f944afe456b7c8401bd50402/src/fitter/fitter.py#L308-L345
train
210,860
epfl-lts2/pygsp
pygsp/features.py
compute_avg_adj_deg
def compute_avg_adj_deg(G): r""" Compute the average adjacency degree for each node. The average adjacency degree is the average of the degrees of a node and its neighbors. Parameters ---------- G: Graph Graph on which the statistic is extracted """ return np.sum(np.dot(G.A, G.A), axis=1) / (np.sum(G.A, axis=1) + 1.)
python
def compute_avg_adj_deg(G): r""" Compute the average adjacency degree for each node. The average adjacency degree is the average of the degrees of a node and its neighbors. Parameters ---------- G: Graph Graph on which the statistic is extracted """ return np.sum(np.dot(G.A, G.A), axis=1) / (np.sum(G.A, axis=1) + 1.)
[ "def", "compute_avg_adj_deg", "(", "G", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "dot", "(", "G", ".", "A", ",", "G", ".", "A", ")", ",", "axis", "=", "1", ")", "/", "(", "np", ".", "sum", "(", "G", ".", "A", ",", "axis", "="...
r""" Compute the average adjacency degree for each node. The average adjacency degree is the average of the degrees of a node and its neighbors. Parameters ---------- G: Graph Graph on which the statistic is extracted
[ "r", "Compute", "the", "average", "adjacency", "degree", "for", "each", "node", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/features.py#L13-L25
train
210,861
epfl-lts2/pygsp
pygsp/features.py
compute_spectrogram
def compute_spectrogram(G, atom=None, M=100, **kwargs): r""" Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis. Parameters ---------- G : Graph Graph on which to compute the spectrogram. atom : func Kernel to use in the spectrogram (default = exp(-M*(x/lmax)²)). M : int (optional) Number of samples on the spectral scale. (default = 100) kwargs: dict Additional parameters to be passed to the :func:`pygsp.filters.Filter.filter` method. """ if not atom: def atom(x): return np.exp(-M * (x / G.lmax)**2) scale = np.linspace(0, G.lmax, M) spectr = np.empty((G.N, M)) for shift_idx in range(M): shift_filter = filters.Filter(G, lambda x: atom(x - scale[shift_idx])) tig = compute_norm_tig(shift_filter, **kwargs).squeeze()**2 spectr[:, shift_idx] = tig G.spectr = spectr return spectr
python
def compute_spectrogram(G, atom=None, M=100, **kwargs): r""" Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis. Parameters ---------- G : Graph Graph on which to compute the spectrogram. atom : func Kernel to use in the spectrogram (default = exp(-M*(x/lmax)²)). M : int (optional) Number of samples on the spectral scale. (default = 100) kwargs: dict Additional parameters to be passed to the :func:`pygsp.filters.Filter.filter` method. """ if not atom: def atom(x): return np.exp(-M * (x / G.lmax)**2) scale = np.linspace(0, G.lmax, M) spectr = np.empty((G.N, M)) for shift_idx in range(M): shift_filter = filters.Filter(G, lambda x: atom(x - scale[shift_idx])) tig = compute_norm_tig(shift_filter, **kwargs).squeeze()**2 spectr[:, shift_idx] = tig G.spectr = spectr return spectr
[ "def", "compute_spectrogram", "(", "G", ",", "atom", "=", "None", ",", "M", "=", "100", ",", "*", "*", "kwargs", ")", ":", "if", "not", "atom", ":", "def", "atom", "(", "x", ")", ":", "return", "np", ".", "exp", "(", "-", "M", "*", "(", "x", ...
r""" Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis. Parameters ---------- G : Graph Graph on which to compute the spectrogram. atom : func Kernel to use in the spectrogram (default = exp(-M*(x/lmax)²)). M : int (optional) Number of samples on the spectral scale. (default = 100) kwargs: dict Additional parameters to be passed to the :func:`pygsp.filters.Filter.filter` method.
[ "r", "Compute", "the", "norm", "of", "the", "Tig", "for", "all", "nodes", "with", "a", "kernel", "shifted", "along", "the", "spectral", "axis", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/features.py#L64-L95
train
210,862
epfl-lts2/pygsp
pygsp/filters/filter.py
Filter.evaluate
def evaluate(self, x): r"""Evaluate the kernels at given frequencies. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter. Returns ------- y : ndarray Frequency response of the filters. Shape ``(g.Nf, len(x))``. Examples -------- Frequency response of a low-pass filter: >>> import matplotlib.pyplot as plt >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> f = filters.Expwin(G) >>> G.compute_fourier_basis() >>> y = f.evaluate(G.e) >>> plt.plot(G.e, y[0]) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at ...>] """ x = np.asanyarray(x) # Avoid to copy data as with np.array([g(x) for g in self._kernels]). y = np.empty([self.Nf] + list(x.shape)) for i, kernel in enumerate(self._kernels): y[i] = kernel(x) return y
python
def evaluate(self, x): r"""Evaluate the kernels at given frequencies. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter. Returns ------- y : ndarray Frequency response of the filters. Shape ``(g.Nf, len(x))``. Examples -------- Frequency response of a low-pass filter: >>> import matplotlib.pyplot as plt >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> f = filters.Expwin(G) >>> G.compute_fourier_basis() >>> y = f.evaluate(G.e) >>> plt.plot(G.e, y[0]) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at ...>] """ x = np.asanyarray(x) # Avoid to copy data as with np.array([g(x) for g in self._kernels]). y = np.empty([self.Nf] + list(x.shape)) for i, kernel in enumerate(self._kernels): y[i] = kernel(x) return y
[ "def", "evaluate", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "asanyarray", "(", "x", ")", "# Avoid to copy data as with np.array([g(x) for g in self._kernels]).", "y", "=", "np", ".", "empty", "(", "[", "self", ".", "Nf", "]", "+", "list", "(",...
r"""Evaluate the kernels at given frequencies. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter. Returns ------- y : ndarray Frequency response of the filters. Shape ``(g.Nf, len(x))``. Examples -------- Frequency response of a low-pass filter: >>> import matplotlib.pyplot as plt >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> f = filters.Expwin(G) >>> G.compute_fourier_basis() >>> y = f.evaluate(G.e) >>> plt.plot(G.e, y[0]) # doctest: +ELLIPSIS [<matplotlib.lines.Line2D object at ...>]
[ "r", "Evaluate", "the", "kernels", "at", "given", "frequencies", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L114-L146
train
210,863
epfl-lts2/pygsp
pygsp/filters/filter.py
Filter.estimate_frame_bounds
def estimate_frame_bounds(self, x=None): r"""Estimate lower and upper frame bounds. A filter bank forms a frame if there are positive real numbers :math:`A` and :math:`B`, :math:`0 < A \leq B < \infty`, that satisfy the *frame condition* .. math:: A \|x\|^2 \leq \| g(L) x \|^2 \leq B \|x\|^2 for all signals :math:`x \in \mathbb{R}^N`, where :math:`g(L)` is the analysis operator of the filter bank. As :math:`g(L) = U g(\Lambda) U^\top` is diagonalized by the Fourier basis :math:`U` with eigenvalues :math:`\Lambda`, :math:`\| g(L) x \|^2 = \| g(\Lambda) U^\top x \|^2`, and :math:`A = \min g^2(\Lambda)`, :math:`B = \max g^2(\Lambda)`. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter bank `g(x)`. The default is ``x = np.linspace(0, G.lmax, 1000)``. The exact bounds are given by evaluating the filter bank at the eigenvalues of the graph Laplacian, i.e., ``x = G.e``. Returns ------- A : float Lower frame bound of the filter bank. B : float Upper frame bound of the filter bank. See Also -------- compute_frame: compute the frame complement: complement a filter bank to become a tight frame Examples -------- >>> from matplotlib import pyplot as plt >>> fig, axes = plt.subplots(2, 2, figsize=(10, 6)) >>> G = graphs.Sensor(64, seed=42) >>> G.compute_fourier_basis() >>> g = filters.Abspline(G, 7) Estimation quality (loose, precise, exact): >>> A, B = g.estimate_frame_bounds(np.linspace(0, G.lmax, 5)) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.883, B=2.288 >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.708, B=2.359 >>> A, B = g.estimate_frame_bounds(G.e) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.723, B=2.359 The frame bounds can be seen in the plot of the filter bank as the minimum and maximum of their squared sum (the black curve): >>> def plot(g, ax): ... g.plot(ax=ax, title='') ... ax.hlines(B, 0, G.lmax, colors='r', zorder=3, ... label='upper bound $B={:.2f}$'.format(B)) ... ax.hlines(A, 0, G.lmax, colors='b', zorder=3, ... label='lower bound $A={:.2f}$'.format(A)) ... ax.legend(loc='center right') >>> plot(g, axes[0, 0]) The heat kernel has a null-space and doesn't define a frame (the lower bound should be greater than 0 to have a frame): >>> g = filters.Heat(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.000, B=1.000 >>> plot(g, axes[0, 1]) Without a null-space, the heat kernel forms a frame: >>> g = filters.Heat(G, scale=[1, 10]) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.135, B=2.000 >>> plot(g, axes[1, 0]) A kernel and its dual form a tight frame (A=B): >>> g = filters.Regular(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> plot(g, axes[1, 1]) >>> fig.tight_layout() The Itersine filter bank forms a tight frame (A=B): >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 """ if x is None: x = np.linspace(0, self.G.lmax, 1000) else: x = np.asanyarray(x) sum_filters = np.sum(self.evaluate(x)**2, axis=0) return sum_filters.min(), sum_filters.max()
python
def estimate_frame_bounds(self, x=None): r"""Estimate lower and upper frame bounds. A filter bank forms a frame if there are positive real numbers :math:`A` and :math:`B`, :math:`0 < A \leq B < \infty`, that satisfy the *frame condition* .. math:: A \|x\|^2 \leq \| g(L) x \|^2 \leq B \|x\|^2 for all signals :math:`x \in \mathbb{R}^N`, where :math:`g(L)` is the analysis operator of the filter bank. As :math:`g(L) = U g(\Lambda) U^\top` is diagonalized by the Fourier basis :math:`U` with eigenvalues :math:`\Lambda`, :math:`\| g(L) x \|^2 = \| g(\Lambda) U^\top x \|^2`, and :math:`A = \min g^2(\Lambda)`, :math:`B = \max g^2(\Lambda)`. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter bank `g(x)`. The default is ``x = np.linspace(0, G.lmax, 1000)``. The exact bounds are given by evaluating the filter bank at the eigenvalues of the graph Laplacian, i.e., ``x = G.e``. Returns ------- A : float Lower frame bound of the filter bank. B : float Upper frame bound of the filter bank. See Also -------- compute_frame: compute the frame complement: complement a filter bank to become a tight frame Examples -------- >>> from matplotlib import pyplot as plt >>> fig, axes = plt.subplots(2, 2, figsize=(10, 6)) >>> G = graphs.Sensor(64, seed=42) >>> G.compute_fourier_basis() >>> g = filters.Abspline(G, 7) Estimation quality (loose, precise, exact): >>> A, B = g.estimate_frame_bounds(np.linspace(0, G.lmax, 5)) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.883, B=2.288 >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.708, B=2.359 >>> A, B = g.estimate_frame_bounds(G.e) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.723, B=2.359 The frame bounds can be seen in the plot of the filter bank as the minimum and maximum of their squared sum (the black curve): >>> def plot(g, ax): ... g.plot(ax=ax, title='') ... ax.hlines(B, 0, G.lmax, colors='r', zorder=3, ... label='upper bound $B={:.2f}$'.format(B)) ... ax.hlines(A, 0, G.lmax, colors='b', zorder=3, ... label='lower bound $A={:.2f}$'.format(A)) ... ax.legend(loc='center right') >>> plot(g, axes[0, 0]) The heat kernel has a null-space and doesn't define a frame (the lower bound should be greater than 0 to have a frame): >>> g = filters.Heat(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.000, B=1.000 >>> plot(g, axes[0, 1]) Without a null-space, the heat kernel forms a frame: >>> g = filters.Heat(G, scale=[1, 10]) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.135, B=2.000 >>> plot(g, axes[1, 0]) A kernel and its dual form a tight frame (A=B): >>> g = filters.Regular(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> plot(g, axes[1, 1]) >>> fig.tight_layout() The Itersine filter bank forms a tight frame (A=B): >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 """ if x is None: x = np.linspace(0, self.G.lmax, 1000) else: x = np.asanyarray(x) sum_filters = np.sum(self.evaluate(x)**2, axis=0) return sum_filters.min(), sum_filters.max()
[ "def", "estimate_frame_bounds", "(", "self", ",", "x", "=", "None", ")", ":", "if", "x", "is", "None", ":", "x", "=", "np", ".", "linspace", "(", "0", ",", "self", ".", "G", ".", "lmax", ",", "1000", ")", "else", ":", "x", "=", "np", ".", "as...
r"""Estimate lower and upper frame bounds. A filter bank forms a frame if there are positive real numbers :math:`A` and :math:`B`, :math:`0 < A \leq B < \infty`, that satisfy the *frame condition* .. math:: A \|x\|^2 \leq \| g(L) x \|^2 \leq B \|x\|^2 for all signals :math:`x \in \mathbb{R}^N`, where :math:`g(L)` is the analysis operator of the filter bank. As :math:`g(L) = U g(\Lambda) U^\top` is diagonalized by the Fourier basis :math:`U` with eigenvalues :math:`\Lambda`, :math:`\| g(L) x \|^2 = \| g(\Lambda) U^\top x \|^2`, and :math:`A = \min g^2(\Lambda)`, :math:`B = \max g^2(\Lambda)`. Parameters ---------- x : array_like Graph frequencies at which to evaluate the filter bank `g(x)`. The default is ``x = np.linspace(0, G.lmax, 1000)``. The exact bounds are given by evaluating the filter bank at the eigenvalues of the graph Laplacian, i.e., ``x = G.e``. Returns ------- A : float Lower frame bound of the filter bank. B : float Upper frame bound of the filter bank. See Also -------- compute_frame: compute the frame complement: complement a filter bank to become a tight frame Examples -------- >>> from matplotlib import pyplot as plt >>> fig, axes = plt.subplots(2, 2, figsize=(10, 6)) >>> G = graphs.Sensor(64, seed=42) >>> G.compute_fourier_basis() >>> g = filters.Abspline(G, 7) Estimation quality (loose, precise, exact): >>> A, B = g.estimate_frame_bounds(np.linspace(0, G.lmax, 5)) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.883, B=2.288 >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.708, B=2.359 >>> A, B = g.estimate_frame_bounds(G.e) >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.723, B=2.359 The frame bounds can be seen in the plot of the filter bank as the minimum and maximum of their squared sum (the black curve): >>> def plot(g, ax): ... g.plot(ax=ax, title='') ... ax.hlines(B, 0, G.lmax, colors='r', zorder=3, ... label='upper bound $B={:.2f}$'.format(B)) ... ax.hlines(A, 0, G.lmax, colors='b', zorder=3, ... label='lower bound $A={:.2f}$'.format(A)) ... ax.legend(loc='center right') >>> plot(g, axes[0, 0]) The heat kernel has a null-space and doesn't define a frame (the lower bound should be greater than 0 to have a frame): >>> g = filters.Heat(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.000, B=1.000 >>> plot(g, axes[0, 1]) Without a null-space, the heat kernel forms a frame: >>> g = filters.Heat(G, scale=[1, 10]) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.135, B=2.000 >>> plot(g, axes[1, 0]) A kernel and its dual form a tight frame (A=B): >>> g = filters.Regular(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> plot(g, axes[1, 1]) >>> fig.tight_layout() The Itersine filter bank forms a tight frame (A=B): >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000
[ "r", "Estimate", "lower", "and", "upper", "frame", "bounds", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L395-L506
train
210,864
epfl-lts2/pygsp
pygsp/filters/filter.py
Filter.compute_frame
def compute_frame(self, **kwargs): r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that may be linearly dependent. See `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_. The frame of a filter bank is the union of the frames of its constituent filters. The vectors forming the frame are the rows of the *analysis operator* .. math:: g(L) = \begin{pmatrix} g_1(L) \\ \vdots \\ g_F(L) \end{pmatrix} \in \mathbb{R}^{NF \times N}, \quad g_i(L) = U g_i(\Lambda) U^\top, where :math:`g_i` are the filter kernels, :math:`N` is the number of nodes, :math:`F` is the number of filters, :math:`L` is the graph Laplacian, :math:`\Lambda` is a diagonal matrix of the Laplacian's eigenvalues, and :math:`U` is the Fourier basis, i.e., its columns are the eigenvectors of the Laplacian. The matrix :math:`g(L)` represents the *analysis operator* of the frame. Its adjoint :math:`g(L)^\top` represents the *synthesis operator*. A signal :math:`x` is thus analyzed with the frame by :math:`y = g(L) x`, and synthesized from its frame coefficients by :math:`z = g(L)^\top y`. Computing this matrix is however a rather inefficient way of doing those operations. If :math:`F > 1`, the frame is said to be over-complete and the representation :math:`g(L) x` of the signal :math:`x` is said to be redundant. If the frame is tight, the *frame operator* :math:`g(L)^\top g(L)` is diagonal, with entries equal to the frame bound :math:`A = B`. Parameters ---------- kwargs: dict Parameters to be passed to the :meth:`analyze` method. Returns ------- frame : ndarray Array of size (#nodes x #filters) x #nodes. See Also -------- estimate_frame_bounds: estimate the frame bounds filter: more efficient way to filter signals Examples -------- >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() Filtering as a multiplication with the matrix representation of the frame analysis operator: >>> g = filters.MexicanHat(G, Nf=6) >>> s = np.random.uniform(size=G.N) >>> >>> gL = g.compute_frame() >>> gL.shape (600, 100) >>> s1 = gL.dot(s) >>> s1 = s1.reshape(G.N, -1, order='F') >>> >>> s2 = g.filter(s) >>> np.all(np.abs(s1 - s2) < 1e-10) True The frame operator of a tight frame is the identity matrix times the frame bound: >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> gL = g.compute_frame(method='exact') >>> gL.shape (600, 100) >>> np.all(gL.T.dot(gL) - np.identity(G.N) < 1e-10) True """ if self.G.N > 2000: _logger.warning('Creating a big matrix. ' 'You should prefer the filter method.') # Filter one delta per vertex. s = np.identity(self.G.N) return self.filter(s, **kwargs).T.reshape(-1, self.G.N)
python
def compute_frame(self, **kwargs): r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that may be linearly dependent. See `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_. The frame of a filter bank is the union of the frames of its constituent filters. The vectors forming the frame are the rows of the *analysis operator* .. math:: g(L) = \begin{pmatrix} g_1(L) \\ \vdots \\ g_F(L) \end{pmatrix} \in \mathbb{R}^{NF \times N}, \quad g_i(L) = U g_i(\Lambda) U^\top, where :math:`g_i` are the filter kernels, :math:`N` is the number of nodes, :math:`F` is the number of filters, :math:`L` is the graph Laplacian, :math:`\Lambda` is a diagonal matrix of the Laplacian's eigenvalues, and :math:`U` is the Fourier basis, i.e., its columns are the eigenvectors of the Laplacian. The matrix :math:`g(L)` represents the *analysis operator* of the frame. Its adjoint :math:`g(L)^\top` represents the *synthesis operator*. A signal :math:`x` is thus analyzed with the frame by :math:`y = g(L) x`, and synthesized from its frame coefficients by :math:`z = g(L)^\top y`. Computing this matrix is however a rather inefficient way of doing those operations. If :math:`F > 1`, the frame is said to be over-complete and the representation :math:`g(L) x` of the signal :math:`x` is said to be redundant. If the frame is tight, the *frame operator* :math:`g(L)^\top g(L)` is diagonal, with entries equal to the frame bound :math:`A = B`. Parameters ---------- kwargs: dict Parameters to be passed to the :meth:`analyze` method. Returns ------- frame : ndarray Array of size (#nodes x #filters) x #nodes. See Also -------- estimate_frame_bounds: estimate the frame bounds filter: more efficient way to filter signals Examples -------- >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() Filtering as a multiplication with the matrix representation of the frame analysis operator: >>> g = filters.MexicanHat(G, Nf=6) >>> s = np.random.uniform(size=G.N) >>> >>> gL = g.compute_frame() >>> gL.shape (600, 100) >>> s1 = gL.dot(s) >>> s1 = s1.reshape(G.N, -1, order='F') >>> >>> s2 = g.filter(s) >>> np.all(np.abs(s1 - s2) < 1e-10) True The frame operator of a tight frame is the identity matrix times the frame bound: >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> gL = g.compute_frame(method='exact') >>> gL.shape (600, 100) >>> np.all(gL.T.dot(gL) - np.identity(G.N) < 1e-10) True """ if self.G.N > 2000: _logger.warning('Creating a big matrix. ' 'You should prefer the filter method.') # Filter one delta per vertex. s = np.identity(self.G.N) return self.filter(s, **kwargs).T.reshape(-1, self.G.N)
[ "def", "compute_frame", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "G", ".", "N", ">", "2000", ":", "_logger", ".", "warning", "(", "'Creating a big matrix. '", "'You should prefer the filter method.'", ")", "# Filter one delta per vertex."...
r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that may be linearly dependent. See `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_. The frame of a filter bank is the union of the frames of its constituent filters. The vectors forming the frame are the rows of the *analysis operator* .. math:: g(L) = \begin{pmatrix} g_1(L) \\ \vdots \\ g_F(L) \end{pmatrix} \in \mathbb{R}^{NF \times N}, \quad g_i(L) = U g_i(\Lambda) U^\top, where :math:`g_i` are the filter kernels, :math:`N` is the number of nodes, :math:`F` is the number of filters, :math:`L` is the graph Laplacian, :math:`\Lambda` is a diagonal matrix of the Laplacian's eigenvalues, and :math:`U` is the Fourier basis, i.e., its columns are the eigenvectors of the Laplacian. The matrix :math:`g(L)` represents the *analysis operator* of the frame. Its adjoint :math:`g(L)^\top` represents the *synthesis operator*. A signal :math:`x` is thus analyzed with the frame by :math:`y = g(L) x`, and synthesized from its frame coefficients by :math:`z = g(L)^\top y`. Computing this matrix is however a rather inefficient way of doing those operations. If :math:`F > 1`, the frame is said to be over-complete and the representation :math:`g(L) x` of the signal :math:`x` is said to be redundant. If the frame is tight, the *frame operator* :math:`g(L)^\top g(L)` is diagonal, with entries equal to the frame bound :math:`A = B`. Parameters ---------- kwargs: dict Parameters to be passed to the :meth:`analyze` method. Returns ------- frame : ndarray Array of size (#nodes x #filters) x #nodes. See Also -------- estimate_frame_bounds: estimate the frame bounds filter: more efficient way to filter signals Examples -------- >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() Filtering as a multiplication with the matrix representation of the frame analysis operator: >>> g = filters.MexicanHat(G, Nf=6) >>> s = np.random.uniform(size=G.N) >>> >>> gL = g.compute_frame() >>> gL.shape (600, 100) >>> s1 = gL.dot(s) >>> s1 = s1.reshape(G.N, -1, order='F') >>> >>> s2 = g.filter(s) >>> np.all(np.abs(s1 - s2) < 1e-10) True The frame operator of a tight frame is the identity matrix times the frame bound: >>> g = filters.Itersine(G) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.000, B=1.000 >>> gL = g.compute_frame(method='exact') >>> gL.shape (600, 100) >>> np.all(gL.T.dot(gL) - np.identity(G.N) < 1e-10) True
[ "r", "Compute", "the", "associated", "frame", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L508-L601
train
210,865
epfl-lts2/pygsp
pygsp/filters/filter.py
Filter.complement
def complement(self, frame_bound=None): r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter bank and its complementary filter forms a tight frame. Parameters ---------- frame_bound : float or None The desired frame bound :math:`A = B` of the resulting tight frame. The chosen bound should be larger than the sum of squared evaluations of all filters in the filter bank. If None (the default), the method chooses the smallest feasible bound. Returns ------- complement: Filter The complementary filter. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.estimate_lmax() >>> g = filters.Abspline(G, 4) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.200, B=1.971 >>> fig, axes = plt.subplots(1, 2) >>> fig, ax = g.plot(ax=axes[0]) >>> g += g.complement() >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.971, B=1.971 >>> fig, ax = g.plot(ax=axes[1]) """ def kernel(x, *args, **kwargs): y = self.evaluate(x) np.power(y, 2, out=y) y = np.sum(y, axis=0) if frame_bound is None: bound = y.max() elif y.max() > frame_bound: raise ValueError('The chosen bound is not feasible. ' 'Choose at least {}.'.format(y.max())) else: bound = frame_bound return np.sqrt(bound - y) return Filter(self.G, kernel)
python
def complement(self, frame_bound=None): r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter bank and its complementary filter forms a tight frame. Parameters ---------- frame_bound : float or None The desired frame bound :math:`A = B` of the resulting tight frame. The chosen bound should be larger than the sum of squared evaluations of all filters in the filter bank. If None (the default), the method chooses the smallest feasible bound. Returns ------- complement: Filter The complementary filter. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.estimate_lmax() >>> g = filters.Abspline(G, 4) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.200, B=1.971 >>> fig, axes = plt.subplots(1, 2) >>> fig, ax = g.plot(ax=axes[0]) >>> g += g.complement() >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.971, B=1.971 >>> fig, ax = g.plot(ax=axes[1]) """ def kernel(x, *args, **kwargs): y = self.evaluate(x) np.power(y, 2, out=y) y = np.sum(y, axis=0) if frame_bound is None: bound = y.max() elif y.max() > frame_bound: raise ValueError('The chosen bound is not feasible. ' 'Choose at least {}.'.format(y.max())) else: bound = frame_bound return np.sqrt(bound - y) return Filter(self.G, kernel)
[ "def", "complement", "(", "self", ",", "frame_bound", "=", "None", ")", ":", "def", "kernel", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "y", "=", "self", ".", "evaluate", "(", "x", ")", "np", ".", "power", "(", "y", ",", ...
r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter bank and its complementary filter forms a tight frame. Parameters ---------- frame_bound : float or None The desired frame bound :math:`A = B` of the resulting tight frame. The chosen bound should be larger than the sum of squared evaluations of all filters in the filter bank. If None (the default), the method chooses the smallest feasible bound. Returns ------- complement: Filter The complementary filter. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.estimate_lmax() >>> g = filters.Abspline(G, 4) >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=0.200, B=1.971 >>> fig, axes = plt.subplots(1, 2) >>> fig, ax = g.plot(ax=axes[0]) >>> g += g.complement() >>> A, B = g.estimate_frame_bounds() >>> print('A={:.3f}, B={:.3f}'.format(A, B)) A=1.971, B=1.971 >>> fig, ax = g.plot(ax=axes[1])
[ "r", "Return", "the", "filter", "that", "makes", "the", "frame", "tight", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L603-L661
train
210,866
epfl-lts2/pygsp
pygsp/filters/filter.py
Filter.inverse
def inverse(self): r"""Return the pseudo-inverse filter bank. The pseudo-inverse of the *analysis filter bank* :math:`g` is the *synthesis filter bank* :math:`g^+` such that .. math:: g(L)^+ g(L) = I, where :math:`I` is the identity matrix, and the *synthesis operator* .. math:: g(L)^+ = (g(L)\top g(L))^{-1} g(L)^\top = (g_1(L)^+, \dots, g_F(L)^+) \in \mathbb{R}^{N \times NF} is the left pseudo-inverse of the analysis operator :math:`g(L)`. Note that :math:`g_i(L)^+` is the pseudo-inverse of :math:`g_i(L)`, :math:`N` is the number of vertices, and :math:`F` is the number of filters in the bank. The above relation holds, and the reconstruction is exact, if and only if :math:`g(L)` is a frame. To be a frame, the rows of :math:`g(L)` must span the whole space (i.e., :math:`g(L)` must have full row rank). That is the case if the lower frame bound :math:`A > 0`. If :math:`g(L)` is not a frame, the reconstruction :math:`g(L)^+ g(L) x` will be the closest to :math:`x` in the least square sense. While there exists infinitely many inverses of the analysis operator of a frame, the pseudo-inverse is unique and corresponds to the *canonical dual* of the filter kernel. The *frame operator* of :math:`g^+` is :math:`g(L)^+ (g(L)^+)^\top = (g(L)\top g(L))^{-1}`, the inverse of the frame operator of :math:`g`. Similarly, its *frame bounds* are :math:`A^{-1}` and :math:`B^{-1}`, where :math:`A` and :math:`B` are the frame bounds of :math:`g`. If :math:`g` is tight (i.e., :math:`A=B`), the canonical dual is given by :math:`g^+ = g / A` (i.e., :math:`g^+_i = g_i / A \ \forall i`). Returns ------- inverse : :class:`pygsp.filters.Filter` The pseudo-inverse filter bank, which synthesizes (or reconstructs) a signal from its coefficients using the canonical dual frame. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() >>> # Create a filter and its inverse. >>> g = filters.Abspline(G, 5) >>> h = g.inverse() >>> # Plot them. >>> fig, axes = plt.subplots(1, 2) >>> _ = g.plot(ax=axes[0], title='original filter bank') >>> _ = h.plot(ax=axes[1], title='inverse filter bank') >>> # Filtering with the inverse reconstructs the original signal. >>> x = np.random.RandomState(42).normal(size=G.N) >>> y = g.filter(x, method='exact') >>> z = h.filter(y, method='exact') >>> print('error: {:.0e}'.format(np.linalg.norm(x - z))) error: 3e-14 >>> # Indeed, they cancel each others' effect. >>> Ag, Bg = g.estimate_frame_bounds() >>> Ah, Bh = h.estimate_frame_bounds() >>> print('A(g)*B(h) = {:.3f} * {:.3f} = {:.3f}'.format(Ag, Bh, Ag*Bh)) A(g)*B(h) = 0.687 * 1.457 = 1.000 >>> print('B(g)*A(h) = {:.3f} * {:.3f} = {:.3f}'.format(Bg, Ah, Bg*Ah)) B(g)*A(h) = 1.994 * 0.501 = 1.000 """ A, _ = self.estimate_frame_bounds() if A == 0: _logger.warning('The filter bank is not invertible as it is not ' 'a frame (lower frame bound A=0).') def kernel(g, i, x): y = g.evaluate(x).T z = np.linalg.pinv(np.expand_dims(y, axis=-1)).squeeze(axis=-2) return z[:, i] # Return one filter. kernels = [partial(kernel, self, i) for i in range(self.n_filters)] return Filter(self.G, kernels)
python
def inverse(self): r"""Return the pseudo-inverse filter bank. The pseudo-inverse of the *analysis filter bank* :math:`g` is the *synthesis filter bank* :math:`g^+` such that .. math:: g(L)^+ g(L) = I, where :math:`I` is the identity matrix, and the *synthesis operator* .. math:: g(L)^+ = (g(L)\top g(L))^{-1} g(L)^\top = (g_1(L)^+, \dots, g_F(L)^+) \in \mathbb{R}^{N \times NF} is the left pseudo-inverse of the analysis operator :math:`g(L)`. Note that :math:`g_i(L)^+` is the pseudo-inverse of :math:`g_i(L)`, :math:`N` is the number of vertices, and :math:`F` is the number of filters in the bank. The above relation holds, and the reconstruction is exact, if and only if :math:`g(L)` is a frame. To be a frame, the rows of :math:`g(L)` must span the whole space (i.e., :math:`g(L)` must have full row rank). That is the case if the lower frame bound :math:`A > 0`. If :math:`g(L)` is not a frame, the reconstruction :math:`g(L)^+ g(L) x` will be the closest to :math:`x` in the least square sense. While there exists infinitely many inverses of the analysis operator of a frame, the pseudo-inverse is unique and corresponds to the *canonical dual* of the filter kernel. The *frame operator* of :math:`g^+` is :math:`g(L)^+ (g(L)^+)^\top = (g(L)\top g(L))^{-1}`, the inverse of the frame operator of :math:`g`. Similarly, its *frame bounds* are :math:`A^{-1}` and :math:`B^{-1}`, where :math:`A` and :math:`B` are the frame bounds of :math:`g`. If :math:`g` is tight (i.e., :math:`A=B`), the canonical dual is given by :math:`g^+ = g / A` (i.e., :math:`g^+_i = g_i / A \ \forall i`). Returns ------- inverse : :class:`pygsp.filters.Filter` The pseudo-inverse filter bank, which synthesizes (or reconstructs) a signal from its coefficients using the canonical dual frame. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() >>> # Create a filter and its inverse. >>> g = filters.Abspline(G, 5) >>> h = g.inverse() >>> # Plot them. >>> fig, axes = plt.subplots(1, 2) >>> _ = g.plot(ax=axes[0], title='original filter bank') >>> _ = h.plot(ax=axes[1], title='inverse filter bank') >>> # Filtering with the inverse reconstructs the original signal. >>> x = np.random.RandomState(42).normal(size=G.N) >>> y = g.filter(x, method='exact') >>> z = h.filter(y, method='exact') >>> print('error: {:.0e}'.format(np.linalg.norm(x - z))) error: 3e-14 >>> # Indeed, they cancel each others' effect. >>> Ag, Bg = g.estimate_frame_bounds() >>> Ah, Bh = h.estimate_frame_bounds() >>> print('A(g)*B(h) = {:.3f} * {:.3f} = {:.3f}'.format(Ag, Bh, Ag*Bh)) A(g)*B(h) = 0.687 * 1.457 = 1.000 >>> print('B(g)*A(h) = {:.3f} * {:.3f} = {:.3f}'.format(Bg, Ah, Bg*Ah)) B(g)*A(h) = 1.994 * 0.501 = 1.000 """ A, _ = self.estimate_frame_bounds() if A == 0: _logger.warning('The filter bank is not invertible as it is not ' 'a frame (lower frame bound A=0).') def kernel(g, i, x): y = g.evaluate(x).T z = np.linalg.pinv(np.expand_dims(y, axis=-1)).squeeze(axis=-2) return z[:, i] # Return one filter. kernels = [partial(kernel, self, i) for i in range(self.n_filters)] return Filter(self.G, kernels)
[ "def", "inverse", "(", "self", ")", ":", "A", ",", "_", "=", "self", ".", "estimate_frame_bounds", "(", ")", "if", "A", "==", "0", ":", "_logger", ".", "warning", "(", "'The filter bank is not invertible as it is not '", "'a frame (lower frame bound A=0).'", ")", ...
r"""Return the pseudo-inverse filter bank. The pseudo-inverse of the *analysis filter bank* :math:`g` is the *synthesis filter bank* :math:`g^+` such that .. math:: g(L)^+ g(L) = I, where :math:`I` is the identity matrix, and the *synthesis operator* .. math:: g(L)^+ = (g(L)\top g(L))^{-1} g(L)^\top = (g_1(L)^+, \dots, g_F(L)^+) \in \mathbb{R}^{N \times NF} is the left pseudo-inverse of the analysis operator :math:`g(L)`. Note that :math:`g_i(L)^+` is the pseudo-inverse of :math:`g_i(L)`, :math:`N` is the number of vertices, and :math:`F` is the number of filters in the bank. The above relation holds, and the reconstruction is exact, if and only if :math:`g(L)` is a frame. To be a frame, the rows of :math:`g(L)` must span the whole space (i.e., :math:`g(L)` must have full row rank). That is the case if the lower frame bound :math:`A > 0`. If :math:`g(L)` is not a frame, the reconstruction :math:`g(L)^+ g(L) x` will be the closest to :math:`x` in the least square sense. While there exists infinitely many inverses of the analysis operator of a frame, the pseudo-inverse is unique and corresponds to the *canonical dual* of the filter kernel. The *frame operator* of :math:`g^+` is :math:`g(L)^+ (g(L)^+)^\top = (g(L)\top g(L))^{-1}`, the inverse of the frame operator of :math:`g`. Similarly, its *frame bounds* are :math:`A^{-1}` and :math:`B^{-1}`, where :math:`A` and :math:`B` are the frame bounds of :math:`g`. If :math:`g` is tight (i.e., :math:`A=B`), the canonical dual is given by :math:`g^+ = g / A` (i.e., :math:`g^+_i = g_i / A \ \forall i`). Returns ------- inverse : :class:`pygsp.filters.Filter` The pseudo-inverse filter bank, which synthesizes (or reconstructs) a signal from its coefficients using the canonical dual frame. See Also -------- estimate_frame_bounds: estimate the frame bounds Examples -------- >>> from matplotlib import pyplot as plt >>> G = graphs.Sensor(100, seed=42) >>> G.compute_fourier_basis() >>> # Create a filter and its inverse. >>> g = filters.Abspline(G, 5) >>> h = g.inverse() >>> # Plot them. >>> fig, axes = plt.subplots(1, 2) >>> _ = g.plot(ax=axes[0], title='original filter bank') >>> _ = h.plot(ax=axes[1], title='inverse filter bank') >>> # Filtering with the inverse reconstructs the original signal. >>> x = np.random.RandomState(42).normal(size=G.N) >>> y = g.filter(x, method='exact') >>> z = h.filter(y, method='exact') >>> print('error: {:.0e}'.format(np.linalg.norm(x - z))) error: 3e-14 >>> # Indeed, they cancel each others' effect. >>> Ag, Bg = g.estimate_frame_bounds() >>> Ah, Bh = h.estimate_frame_bounds() >>> print('A(g)*B(h) = {:.3f} * {:.3f} = {:.3f}'.format(Ag, Bh, Ag*Bh)) A(g)*B(h) = 0.687 * 1.457 = 1.000 >>> print('B(g)*A(h) = {:.3f} * {:.3f} = {:.3f}'.format(Bg, Ah, Bg*Ah)) B(g)*A(h) = 1.994 * 0.501 = 1.000
[ "r", "Return", "the", "pseudo", "-", "inverse", "filter", "bank", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L663-L751
train
210,867
epfl-lts2/pygsp
pygsp/graphs/difference.py
DifferenceMixIn.grad
def grad(self, x): r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_\mathcal{G} x = D^\top x, where :math:`D` is the differential operator :attr:`D`. The value of the gradient on the edge :math:`e_k = (v_i, v_j)` from :math:`v_i` to :math:`v_j` with weight :math:`W[i, j]` is .. math:: y[k] = D[i, k] x[i] + D[j, k] x[j] = \sqrt{\frac{W[i, j]}{2}} (x[j] - x[i]) for the combinatorial Laplacian, and .. math:: y[k] = \sqrt{\frac{W[i, j]}{2}} \left( \frac{x[j]}{\sqrt{d[j]}} - \frac{x[i]}{\sqrt{d[i]}} \right) for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- y : ndarray Gradient signal of length :attr:`n_edges` living on the edges. See Also -------- compute_differential_operator div : compute the divergence of an edge signal dirichlet_energy : compute the norm of the gradient Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 2., 2., -2.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -1.41421356]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712]) """ x = self._check_signal(x) return self.D.T.dot(x)
python
def grad(self, x): r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_\mathcal{G} x = D^\top x, where :math:`D` is the differential operator :attr:`D`. The value of the gradient on the edge :math:`e_k = (v_i, v_j)` from :math:`v_i` to :math:`v_j` with weight :math:`W[i, j]` is .. math:: y[k] = D[i, k] x[i] + D[j, k] x[j] = \sqrt{\frac{W[i, j]}{2}} (x[j] - x[i]) for the combinatorial Laplacian, and .. math:: y[k] = \sqrt{\frac{W[i, j]}{2}} \left( \frac{x[j]}{\sqrt{d[j]}} - \frac{x[i]}{\sqrt{d[i]}} \right) for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- y : ndarray Gradient signal of length :attr:`n_edges` living on the edges. See Also -------- compute_differential_operator div : compute the divergence of an edge signal dirichlet_energy : compute the norm of the gradient Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 2., 2., -2.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -1.41421356]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712]) """ x = self._check_signal(x) return self.D.T.dot(x)
[ "def", "grad", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "_check_signal", "(", "x", ")", "return", "self", ".", "D", ".", "T", ".", "dot", "(", "x", ")" ]
r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_\mathcal{G} x = D^\top x, where :math:`D` is the differential operator :attr:`D`. The value of the gradient on the edge :math:`e_k = (v_i, v_j)` from :math:`v_i` to :math:`v_j` with weight :math:`W[i, j]` is .. math:: y[k] = D[i, k] x[i] + D[j, k] x[j] = \sqrt{\frac{W[i, j]}{2}} (x[j] - x[i]) for the combinatorial Laplacian, and .. math:: y[k] = \sqrt{\frac{W[i, j]}{2}} \left( \frac{x[j]}{\sqrt{d[j]}} - \frac{x[i]}{\sqrt{d[i]}} \right) for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- y : ndarray Gradient signal of length :attr:`n_edges` living on the edges. See Also -------- compute_differential_operator div : compute the divergence of an edge signal dirichlet_energy : compute the norm of the gradient Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 2., 2., -2.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -1.41421356]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.grad([0, 2, 4, 2]) array([ 1.41421356, 1.41421356, -0.82842712])
[ "r", "Compute", "the", "gradient", "of", "a", "signal", "defined", "on", "the", "vertices", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/difference.py#L171-L247
train
210,868
epfl-lts2/pygsp
pygsp/graphs/difference.py
DifferenceMixIn.div
def div(self, y): r"""Compute the divergence of a signal defined on the edges. The divergence :math:`z` of a signal :math:`y` is defined as .. math:: z = \operatorname{div}_\mathcal{G} y = D y, where :math:`D` is the differential operator :attr:`D`. The value of the divergence on the vertex :math:`v_i` is .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2}} y[k] for the combinatorial Laplacian, and .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2 d[i]}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2 d[i]}} y[k] for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- y : array_like Signal of length :attr:`n_edges` living on the edges. Returns ------- z : ndarray Divergence signal of length :attr:`n_vertices` living on the vertices. See Also -------- compute_differential_operator grad : compute the gradient of a vertex signal Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2., 4., -2., 0.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-1.41421356, 2.82842712, -1.41421356, 0. ]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ]) """ y = np.asanyarray(y) if y.shape[0] != self.Ne: raise ValueError('First dimension must be the number of edges ' 'G.Ne = {}, got {}.'.format(self.Ne, y.shape)) return self.D.dot(y)
python
def div(self, y): r"""Compute the divergence of a signal defined on the edges. The divergence :math:`z` of a signal :math:`y` is defined as .. math:: z = \operatorname{div}_\mathcal{G} y = D y, where :math:`D` is the differential operator :attr:`D`. The value of the divergence on the vertex :math:`v_i` is .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2}} y[k] for the combinatorial Laplacian, and .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2 d[i]}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2 d[i]}} y[k] for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- y : array_like Signal of length :attr:`n_edges` living on the edges. Returns ------- z : ndarray Divergence signal of length :attr:`n_vertices` living on the vertices. See Also -------- compute_differential_operator grad : compute the gradient of a vertex signal Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2., 4., -2., 0.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-1.41421356, 2.82842712, -1.41421356, 0. ]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ]) """ y = np.asanyarray(y) if y.shape[0] != self.Ne: raise ValueError('First dimension must be the number of edges ' 'G.Ne = {}, got {}.'.format(self.Ne, y.shape)) return self.D.dot(y)
[ "def", "div", "(", "self", ",", "y", ")", ":", "y", "=", "np", ".", "asanyarray", "(", "y", ")", "if", "y", ".", "shape", "[", "0", "]", "!=", "self", ".", "Ne", ":", "raise", "ValueError", "(", "'First dimension must be the number of edges '", "'G.Ne ...
r"""Compute the divergence of a signal defined on the edges. The divergence :math:`z` of a signal :math:`y` is defined as .. math:: z = \operatorname{div}_\mathcal{G} y = D y, where :math:`D` is the differential operator :attr:`D`. The value of the divergence on the vertex :math:`v_i` is .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2}} y[k] for the combinatorial Laplacian, and .. math:: z[i] = \sum_k D[i, k] y[k] = \sum_{\{k,j | e_k=(v_j, v_i) \in \mathcal{E}\}} \sqrt{\frac{W[j, i]}{2 d[i]}} y[k] - \sum_{\{k,j | e_k=(v_i, v_j) \in \mathcal{E}\}} \sqrt{\frac{W[i, j]}{2 d[i]}} y[k] for the normalized Laplacian. For undirected graphs, only half the edges are kept and the :math:`1/\sqrt{2}` factor disappears from the above equations. See :meth:`compute_differential_operator` for details. Parameters ---------- y : array_like Signal of length :attr:`n_edges` living on the edges. Returns ------- z : ndarray Divergence signal of length :attr:`n_vertices` living on the vertices. See Also -------- compute_differential_operator grad : compute the gradient of a vertex signal Examples -------- Non-directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2., 4., -2., 0.]) Directed graph and combinatorial Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-1.41421356, 2.82842712, -1.41421356, 0. ]) Non-directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=False, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ]) Directed graph and normalized Laplacian: >>> graph = graphs.Path(4, directed=True, lap_type='normalized') >>> graph.compute_differential_operator() >>> graph.div([2, -2, 0]) array([-2. , 2.82842712, -1.41421356, 0. ])
[ "r", "Compute", "the", "divergence", "of", "a", "signal", "defined", "on", "the", "edges", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/difference.py#L249-L332
train
210,869
epfl-lts2/pygsp
pygsp/graphs/fourier.py
FourierMixIn.gft
def gft(self, s): r"""Compute the graph Fourier transform. The graph Fourier transform of a signal :math:`s` is defined as .. math:: \hat{s} = U^* s, where :math:`U` is the Fourier basis attr:`U` and :math:`U^*` denotes the conjugate transpose or Hermitian transpose of :math:`U`. Parameters ---------- s : array_like Graph signal in the vertex domain. Returns ------- s_hat : ndarray Representation of s in the Fourier domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s = np.random.normal(size=(G.N, 5, 1)) >>> s_hat = G.gft(s) >>> s_star = G.igft(s_hat) >>> np.all((s - s_star) < 1e-10) True """ s = self._check_signal(s) U = np.conjugate(self.U) # True Hermitian. (Although U is often real.) return np.tensordot(U, s, ([0], [0]))
python
def gft(self, s): r"""Compute the graph Fourier transform. The graph Fourier transform of a signal :math:`s` is defined as .. math:: \hat{s} = U^* s, where :math:`U` is the Fourier basis attr:`U` and :math:`U^*` denotes the conjugate transpose or Hermitian transpose of :math:`U`. Parameters ---------- s : array_like Graph signal in the vertex domain. Returns ------- s_hat : ndarray Representation of s in the Fourier domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s = np.random.normal(size=(G.N, 5, 1)) >>> s_hat = G.gft(s) >>> s_star = G.igft(s_hat) >>> np.all((s - s_star) < 1e-10) True """ s = self._check_signal(s) U = np.conjugate(self.U) # True Hermitian. (Although U is often real.) return np.tensordot(U, s, ([0], [0]))
[ "def", "gft", "(", "self", ",", "s", ")", ":", "s", "=", "self", ".", "_check_signal", "(", "s", ")", "U", "=", "np", ".", "conjugate", "(", "self", ".", "U", ")", "# True Hermitian. (Although U is often real.)", "return", "np", ".", "tensordot", "(", ...
r"""Compute the graph Fourier transform. The graph Fourier transform of a signal :math:`s` is defined as .. math:: \hat{s} = U^* s, where :math:`U` is the Fourier basis attr:`U` and :math:`U^*` denotes the conjugate transpose or Hermitian transpose of :math:`U`. Parameters ---------- s : array_like Graph signal in the vertex domain. Returns ------- s_hat : ndarray Representation of s in the Fourier domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s = np.random.normal(size=(G.N, 5, 1)) >>> s_hat = G.gft(s) >>> s_star = G.igft(s_hat) >>> np.all((s - s_star) < 1e-10) True
[ "r", "Compute", "the", "graph", "Fourier", "transform", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/fourier.py#L197-L230
train
210,870
epfl-lts2/pygsp
pygsp/graphs/fourier.py
FourierMixIn.igft
def igft(self, s_hat): r"""Compute the inverse graph Fourier transform. The inverse graph Fourier transform of a Fourier domain signal :math:`\hat{s}` is defined as .. math:: s = U \hat{s}, where :math:`U` is the Fourier basis :attr:`U`. Parameters ---------- s_hat : array_like Graph signal in the Fourier domain. Returns ------- s : ndarray Representation of s_hat in the vertex domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s_hat = np.random.normal(size=(G.N, 5, 1)) >>> s = G.igft(s_hat) >>> s_hat_star = G.gft(s) >>> np.all((s_hat - s_hat_star) < 1e-10) True """ s_hat = self._check_signal(s_hat) return np.tensordot(self.U, s_hat, ([1], [0]))
python
def igft(self, s_hat): r"""Compute the inverse graph Fourier transform. The inverse graph Fourier transform of a Fourier domain signal :math:`\hat{s}` is defined as .. math:: s = U \hat{s}, where :math:`U` is the Fourier basis :attr:`U`. Parameters ---------- s_hat : array_like Graph signal in the Fourier domain. Returns ------- s : ndarray Representation of s_hat in the vertex domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s_hat = np.random.normal(size=(G.N, 5, 1)) >>> s = G.igft(s_hat) >>> s_hat_star = G.gft(s) >>> np.all((s_hat - s_hat_star) < 1e-10) True """ s_hat = self._check_signal(s_hat) return np.tensordot(self.U, s_hat, ([1], [0]))
[ "def", "igft", "(", "self", ",", "s_hat", ")", ":", "s_hat", "=", "self", ".", "_check_signal", "(", "s_hat", ")", "return", "np", ".", "tensordot", "(", "self", ".", "U", ",", "s_hat", ",", "(", "[", "1", "]", ",", "[", "0", "]", ")", ")" ]
r"""Compute the inverse graph Fourier transform. The inverse graph Fourier transform of a Fourier domain signal :math:`\hat{s}` is defined as .. math:: s = U \hat{s}, where :math:`U` is the Fourier basis :attr:`U`. Parameters ---------- s_hat : array_like Graph signal in the Fourier domain. Returns ------- s : ndarray Representation of s_hat in the vertex domain. Examples -------- >>> G = graphs.Logo() >>> G.compute_fourier_basis() >>> s_hat = np.random.normal(size=(G.N, 5, 1)) >>> s = G.igft(s_hat) >>> s_hat_star = G.gft(s) >>> np.all((s_hat - s_hat_star) < 1e-10) True
[ "r", "Compute", "the", "inverse", "graph", "Fourier", "transform", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/fourier.py#L232-L264
train
210,871
epfl-lts2/pygsp
pygsp/filters/approximations.py
compute_cheby_coeff
def compute_cheby_coeff(f, m=30, N=None, *args, **kwargs): r""" Compute Chebyshev coefficients for a Filterbank. Parameters ---------- f : Filter Filterbank with at least 1 filter m : int Maximum order of Chebyshev coeff to compute (default = 30) N : int Grid order used to compute quadrature (default = m + 1) i : int Index of the Filterbank element to compute (default = 0) Returns ------- c : ndarray Matrix of Chebyshev coefficients """ G = f.G i = kwargs.pop('i', 0) if not N: N = m + 1 a_arange = [0, G.lmax] a1 = (a_arange[1] - a_arange[0]) / 2 a2 = (a_arange[1] + a_arange[0]) / 2 c = np.zeros(m + 1) tmpN = np.arange(N) num = np.cos(np.pi * (tmpN + 0.5) / N) for o in range(m + 1): c[o] = 2. / N * np.dot(f._kernels[i](a1 * num + a2), np.cos(np.pi * o * (tmpN + 0.5) / N)) return c
python
def compute_cheby_coeff(f, m=30, N=None, *args, **kwargs): r""" Compute Chebyshev coefficients for a Filterbank. Parameters ---------- f : Filter Filterbank with at least 1 filter m : int Maximum order of Chebyshev coeff to compute (default = 30) N : int Grid order used to compute quadrature (default = m + 1) i : int Index of the Filterbank element to compute (default = 0) Returns ------- c : ndarray Matrix of Chebyshev coefficients """ G = f.G i = kwargs.pop('i', 0) if not N: N = m + 1 a_arange = [0, G.lmax] a1 = (a_arange[1] - a_arange[0]) / 2 a2 = (a_arange[1] + a_arange[0]) / 2 c = np.zeros(m + 1) tmpN = np.arange(N) num = np.cos(np.pi * (tmpN + 0.5) / N) for o in range(m + 1): c[o] = 2. / N * np.dot(f._kernels[i](a1 * num + a2), np.cos(np.pi * o * (tmpN + 0.5) / N)) return c
[ "def", "compute_cheby_coeff", "(", "f", ",", "m", "=", "30", ",", "N", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "G", "=", "f", ".", "G", "i", "=", "kwargs", ".", "pop", "(", "'i'", ",", "0", ")", "if", "not", "N", ...
r""" Compute Chebyshev coefficients for a Filterbank. Parameters ---------- f : Filter Filterbank with at least 1 filter m : int Maximum order of Chebyshev coeff to compute (default = 30) N : int Grid order used to compute quadrature (default = m + 1) i : int Index of the Filterbank element to compute (default = 0) Returns ------- c : ndarray Matrix of Chebyshev coefficients
[ "r", "Compute", "Chebyshev", "coefficients", "for", "a", "Filterbank", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/approximations.py#L13-L55
train
210,872
epfl-lts2/pygsp
pygsp/filters/approximations.py
cheby_op
def cheby_op(G, c, signal, **kwargs): r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters ---------- G : Graph c : ndarray or list of ndarrays Chebyshev coefficients for a Filter or a Filterbank signal : ndarray Signal to filter Returns ------- r : ndarray Result of the filtering """ # Handle if we do not have a list of filters but only a simple filter in cheby_coeff. if not isinstance(c, np.ndarray): c = np.array(c) c = np.atleast_2d(c) Nscales, M = c.shape if M < 2: raise TypeError("The coefficients have an invalid shape") # thanks to that, we can also have 1d signal. try: Nv = np.shape(signal)[1] r = np.zeros((G.N * Nscales, Nv)) except IndexError: r = np.zeros((G.N * Nscales)) a_arange = [0, G.lmax] a1 = float(a_arange[1] - a_arange[0]) / 2. a2 = float(a_arange[1] + a_arange[0]) / 2. twf_old = signal twf_cur = (G.L.dot(signal) - a2 * signal) / a1 tmpN = np.arange(G.N, dtype=int) for i in range(Nscales): r[tmpN + G.N*i] = 0.5 * c[i, 0] * twf_old + c[i, 1] * twf_cur factor = 2/a1 * (G.L - a2 * sparse.eye(G.N)) for k in range(2, M): twf_new = factor.dot(twf_cur) - twf_old for i in range(Nscales): r[tmpN + G.N*i] += c[i, k] * twf_new twf_old = twf_cur twf_cur = twf_new return r
python
def cheby_op(G, c, signal, **kwargs): r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters ---------- G : Graph c : ndarray or list of ndarrays Chebyshev coefficients for a Filter or a Filterbank signal : ndarray Signal to filter Returns ------- r : ndarray Result of the filtering """ # Handle if we do not have a list of filters but only a simple filter in cheby_coeff. if not isinstance(c, np.ndarray): c = np.array(c) c = np.atleast_2d(c) Nscales, M = c.shape if M < 2: raise TypeError("The coefficients have an invalid shape") # thanks to that, we can also have 1d signal. try: Nv = np.shape(signal)[1] r = np.zeros((G.N * Nscales, Nv)) except IndexError: r = np.zeros((G.N * Nscales)) a_arange = [0, G.lmax] a1 = float(a_arange[1] - a_arange[0]) / 2. a2 = float(a_arange[1] + a_arange[0]) / 2. twf_old = signal twf_cur = (G.L.dot(signal) - a2 * signal) / a1 tmpN = np.arange(G.N, dtype=int) for i in range(Nscales): r[tmpN + G.N*i] = 0.5 * c[i, 0] * twf_old + c[i, 1] * twf_cur factor = 2/a1 * (G.L - a2 * sparse.eye(G.N)) for k in range(2, M): twf_new = factor.dot(twf_cur) - twf_old for i in range(Nscales): r[tmpN + G.N*i] += c[i, k] * twf_new twf_old = twf_cur twf_cur = twf_new return r
[ "def", "cheby_op", "(", "G", ",", "c", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "# Handle if we do not have a list of filters but only a simple filter in cheby_coeff.", "if", "not", "isinstance", "(", "c", ",", "np", ".", "ndarray", ")", ":", "c", "=", ...
r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters ---------- G : Graph c : ndarray or list of ndarrays Chebyshev coefficients for a Filter or a Filterbank signal : ndarray Signal to filter Returns ------- r : ndarray Result of the filtering
[ "r", "Chebyshev", "polynomial", "of", "graph", "Laplacian", "applied", "to", "vector", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/approximations.py#L58-L114
train
210,873
epfl-lts2/pygsp
pygsp/filters/approximations.py
cheby_rect
def cheby_rect(G, bounds, signal, **kwargs): r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) Order of the Chebyshev polynomial (default: 30) Returns ------- r : array_like Result of the filtering """ if not (isinstance(bounds, (list, np.ndarray)) and len(bounds) == 2): raise ValueError('Bounds of wrong shape.') bounds = np.array(bounds) m = int(kwargs.pop('order', 30) + 1) try: Nv = np.shape(signal)[1] r = np.zeros((G.N, Nv)) except IndexError: r = np.zeros((G.N)) b1, b2 = np.arccos(2. * bounds / G.lmax - 1.) factor = 4./G.lmax * G.L - 2.*sparse.eye(G.N) T_old = signal T_cur = factor.dot(signal) / 2. r = (b1 - b2)/np.pi * signal + 2./np.pi * (np.sin(b1) - np.sin(b2)) * T_cur for k in range(2, m): T_new = factor.dot(T_cur) - T_old r += 2./(k*np.pi) * (np.sin(k*b1) - np.sin(k*b2)) * T_new T_old = T_cur T_cur = T_new return r
python
def cheby_rect(G, bounds, signal, **kwargs): r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) Order of the Chebyshev polynomial (default: 30) Returns ------- r : array_like Result of the filtering """ if not (isinstance(bounds, (list, np.ndarray)) and len(bounds) == 2): raise ValueError('Bounds of wrong shape.') bounds = np.array(bounds) m = int(kwargs.pop('order', 30) + 1) try: Nv = np.shape(signal)[1] r = np.zeros((G.N, Nv)) except IndexError: r = np.zeros((G.N)) b1, b2 = np.arccos(2. * bounds / G.lmax - 1.) factor = 4./G.lmax * G.L - 2.*sparse.eye(G.N) T_old = signal T_cur = factor.dot(signal) / 2. r = (b1 - b2)/np.pi * signal + 2./np.pi * (np.sin(b1) - np.sin(b2)) * T_cur for k in range(2, m): T_new = factor.dot(T_cur) - T_old r += 2./(k*np.pi) * (np.sin(k*b1) - np.sin(k*b2)) * T_new T_old = T_cur T_cur = T_new return r
[ "def", "cheby_rect", "(", "G", ",", "bounds", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "isinstance", "(", "bounds", ",", "(", "list", ",", "np", ".", "ndarray", ")", ")", "and", "len", "(", "bounds", ")", "==", "2", "...
r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters ---------- G : Graph bounds : array_like The bounds of the pass-band filter signal : array_like Signal to filter order : int (optional) Order of the Chebyshev polynomial (default: 30) Returns ------- r : array_like Result of the filtering
[ "r", "Fast", "filtering", "using", "Chebyshev", "polynomial", "for", "a", "perfect", "rectangle", "filter", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/approximations.py#L117-L163
train
210,874
epfl-lts2/pygsp
pygsp/filters/approximations.py
compute_jackson_cheby_coeff
def compute_jackson_cheby_coeff(filter_bounds, delta_lambda, m): r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int Returns ------- ch : ndarray jch : ndarray References ---------- :cite:`tremblay2016compressive` """ # Parameters check if delta_lambda[0] > filter_bounds[0] or delta_lambda[1] < filter_bounds[1]: _logger.error("Bounds of the filter are out of the lambda values") raise() elif delta_lambda[0] > delta_lambda[1]: _logger.error("lambda_min is greater than lambda_max") raise() # Scaling and translating to standard cheby interval a1 = (delta_lambda[1]-delta_lambda[0])/2 a2 = (delta_lambda[1]+delta_lambda[0])/2 # Scaling bounds of the band pass according to lrange filter_bounds[0] = (filter_bounds[0]-a2)/a1 filter_bounds[1] = (filter_bounds[1]-a2)/a1 # First compute cheby coeffs ch = np.empty(m+1, dtype=float) ch[0] = (2/(np.pi))*(np.arccos(filter_bounds[0])-np.arccos(filter_bounds[1])) for i in range(1, len(ch)): ch[i] = (2/(np.pi * i)) * \ (np.sin(i * np.arccos(filter_bounds[0])) - np.sin(i * np.arccos(filter_bounds[1]))) # Then compute jackson coeffs jch = np.empty(m+1, dtype=float) alpha = (np.pi/(m+2)) for i in range(len(jch)): jch[i] = (1/np.sin(alpha)) * \ ((1 - i/(m+2)) * np.sin(alpha) * np.cos(i * alpha) + (1/(m+2)) * np.cos(alpha) * np.sin(i * alpha)) # Combine jackson and cheby coeffs jch = ch * jch return ch, jch
python
def compute_jackson_cheby_coeff(filter_bounds, delta_lambda, m): r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int Returns ------- ch : ndarray jch : ndarray References ---------- :cite:`tremblay2016compressive` """ # Parameters check if delta_lambda[0] > filter_bounds[0] or delta_lambda[1] < filter_bounds[1]: _logger.error("Bounds of the filter are out of the lambda values") raise() elif delta_lambda[0] > delta_lambda[1]: _logger.error("lambda_min is greater than lambda_max") raise() # Scaling and translating to standard cheby interval a1 = (delta_lambda[1]-delta_lambda[0])/2 a2 = (delta_lambda[1]+delta_lambda[0])/2 # Scaling bounds of the band pass according to lrange filter_bounds[0] = (filter_bounds[0]-a2)/a1 filter_bounds[1] = (filter_bounds[1]-a2)/a1 # First compute cheby coeffs ch = np.empty(m+1, dtype=float) ch[0] = (2/(np.pi))*(np.arccos(filter_bounds[0])-np.arccos(filter_bounds[1])) for i in range(1, len(ch)): ch[i] = (2/(np.pi * i)) * \ (np.sin(i * np.arccos(filter_bounds[0])) - np.sin(i * np.arccos(filter_bounds[1]))) # Then compute jackson coeffs jch = np.empty(m+1, dtype=float) alpha = (np.pi/(m+2)) for i in range(len(jch)): jch[i] = (1/np.sin(alpha)) * \ ((1 - i/(m+2)) * np.sin(alpha) * np.cos(i * alpha) + (1/(m+2)) * np.cos(alpha) * np.sin(i * alpha)) # Combine jackson and cheby coeffs jch = ch * jch return ch, jch
[ "def", "compute_jackson_cheby_coeff", "(", "filter_bounds", ",", "delta_lambda", ",", "m", ")", ":", "# Parameters check", "if", "delta_lambda", "[", "0", "]", ">", "filter_bounds", "[", "0", "]", "or", "delta_lambda", "[", "1", "]", "<", "filter_bounds", "[",...
r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass between a and b, between a range of values defined by lambda_min and lambda_max. Parameters ---------- filter_bounds : list [a, b] delta_lambda : list [lambda_min, lambda_max] m : int Returns ------- ch : ndarray jch : ndarray References ---------- :cite:`tremblay2016compressive`
[ "r", "To", "compute", "the", "m", "+", "1", "coefficients", "of", "the", "polynomial", "approximation", "of", "an", "ideal", "band", "-", "pass", "between", "a", "and", "b", "between", "a", "range", "of", "values", "defined", "by", "lambda_min", "and", "...
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/approximations.py#L166-L222
train
210,875
epfl-lts2/pygsp
pygsp/filters/approximations.py
lanczos_op
def lanczos_op(f, s, order=30): r""" Perform the lanczos approximation of the signal s. Parameters ---------- f: Filter s : ndarray Signal to approximate. order : int Degree of the lanczos approximation. (default = 30) Returns ------- L : ndarray lanczos approximation of s """ G = f.G Nf = len(f.g) # To have the right shape for the output array depending on the signal dim try: Nv = np.shape(s)[1] is2d = True c = np.zeros((G.N*Nf, Nv)) except IndexError: Nv = 1 is2d = False c = np.zeros((G.N*Nf)) tmpN = np.arange(G.N, dtype=int) for j in range(Nv): if is2d: V, H, _ = lanczos(G.L.toarray(), order, s[:, j]) else: V, H, _ = lanczos(G.L.toarray(), order, s) Eh, Uh = np.linalg.eig(H) Eh[Eh < 0] = 0 fe = f.evaluate(Eh) V = np.dot(V, Uh) for i in range(Nf): if is2d: c[tmpN + i*G.N, j] = np.dot(V, fe[:][i] * np.dot(V.T, s[:, j])) else: c[tmpN + i*G.N] = np.dot(V, fe[:][i] * np.dot(V.T, s)) return c
python
def lanczos_op(f, s, order=30): r""" Perform the lanczos approximation of the signal s. Parameters ---------- f: Filter s : ndarray Signal to approximate. order : int Degree of the lanczos approximation. (default = 30) Returns ------- L : ndarray lanczos approximation of s """ G = f.G Nf = len(f.g) # To have the right shape for the output array depending on the signal dim try: Nv = np.shape(s)[1] is2d = True c = np.zeros((G.N*Nf, Nv)) except IndexError: Nv = 1 is2d = False c = np.zeros((G.N*Nf)) tmpN = np.arange(G.N, dtype=int) for j in range(Nv): if is2d: V, H, _ = lanczos(G.L.toarray(), order, s[:, j]) else: V, H, _ = lanczos(G.L.toarray(), order, s) Eh, Uh = np.linalg.eig(H) Eh[Eh < 0] = 0 fe = f.evaluate(Eh) V = np.dot(V, Uh) for i in range(Nf): if is2d: c[tmpN + i*G.N, j] = np.dot(V, fe[:][i] * np.dot(V.T, s[:, j])) else: c[tmpN + i*G.N] = np.dot(V, fe[:][i] * np.dot(V.T, s)) return c
[ "def", "lanczos_op", "(", "f", ",", "s", ",", "order", "=", "30", ")", ":", "G", "=", "f", ".", "G", "Nf", "=", "len", "(", "f", ".", "g", ")", "# To have the right shape for the output array depending on the signal dim", "try", ":", "Nv", "=", "np", "."...
r""" Perform the lanczos approximation of the signal s. Parameters ---------- f: Filter s : ndarray Signal to approximate. order : int Degree of the lanczos approximation. (default = 30) Returns ------- L : ndarray lanczos approximation of s
[ "r", "Perform", "the", "lanczos", "approximation", "of", "the", "signal", "s", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/approximations.py#L225-L275
train
210,876
epfl-lts2/pygsp
pygsp/reduction.py
interpolate
def interpolate(G, f_subsampled, keep_inds, order=100, reg_eps=0.005, **kwargs): r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : int Degree of the Chebyshev approximation (default = 100). reg_eps : float The regularized graph Laplacian is $\bar{L}=L+\epsilon I$. A smaller epsilon may lead to better regularization, but will also require a higher order Chebyshev approximation. Returns ------- f_interpolated : ndarray Interpolated graph signal on the full vertex set of G. References ---------- See :cite:`pesenson2009variational` """ L_reg = G.L + reg_eps * sparse.eye(G.N) K_reg = getattr(G.mr, 'K_reg', kron_reduction(L_reg, keep_inds)) green_kernel = getattr(G.mr, 'green_kernel', filters.Filter(G, lambda x: 1. / (reg_eps + x))) alpha = K_reg.dot(f_subsampled) try: Nv = np.shape(f_subsampled)[1] f_interpolated = np.zeros((G.N, Nv)) except IndexError: f_interpolated = np.zeros((G.N)) f_interpolated[keep_inds] = alpha return _analysis(green_kernel, f_interpolated, order=order, **kwargs)
python
def interpolate(G, f_subsampled, keep_inds, order=100, reg_eps=0.005, **kwargs): r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : int Degree of the Chebyshev approximation (default = 100). reg_eps : float The regularized graph Laplacian is $\bar{L}=L+\epsilon I$. A smaller epsilon may lead to better regularization, but will also require a higher order Chebyshev approximation. Returns ------- f_interpolated : ndarray Interpolated graph signal on the full vertex set of G. References ---------- See :cite:`pesenson2009variational` """ L_reg = G.L + reg_eps * sparse.eye(G.N) K_reg = getattr(G.mr, 'K_reg', kron_reduction(L_reg, keep_inds)) green_kernel = getattr(G.mr, 'green_kernel', filters.Filter(G, lambda x: 1. / (reg_eps + x))) alpha = K_reg.dot(f_subsampled) try: Nv = np.shape(f_subsampled)[1] f_interpolated = np.zeros((G.N, Nv)) except IndexError: f_interpolated = np.zeros((G.N)) f_interpolated[keep_inds] = alpha return _analysis(green_kernel, f_interpolated, order=order, **kwargs)
[ "def", "interpolate", "(", "G", ",", "f_subsampled", ",", "keep_inds", ",", "order", "=", "100", ",", "reg_eps", "=", "0.005", ",", "*", "*", "kwargs", ")", ":", "L_reg", "=", "G", ".", "L", "+", "reg_eps", "*", "sparse", ".", "eye", "(", "G", "....
r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : int Degree of the Chebyshev approximation (default = 100). reg_eps : float The regularized graph Laplacian is $\bar{L}=L+\epsilon I$. A smaller epsilon may lead to better regularization, but will also require a higher order Chebyshev approximation. Returns ------- f_interpolated : ndarray Interpolated graph signal on the full vertex set of G. References ---------- See :cite:`pesenson2009variational`
[ "r", "Interpolate", "a", "graph", "signal", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L145-L187
train
210,877
epfl-lts2/pygsp
pygsp/reduction.py
kron_reduction
def kron_reduction(G, ind): r"""Compute the Kron reduction. This function perform the Kron reduction of the weight matrix in the graph *G*, with boundary nodes labeled by *ind*. This function will create a new graph with a weight matrix Wnew that contain only boundary nodes and is computed as the Schur complement of the original matrix with respect to the selected indices. Parameters ---------- G : Graph or sparse matrix Graph structure or weight matrix ind : list indices of the nodes to keep Returns ------- Gnew : Graph or sparse matrix New graph structure or weight matrix References ---------- See :cite:`dorfler2013kron` """ if isinstance(G, graphs.Graph): if G.lap_type != 'combinatorial': msg = 'Unknown reduction for {} Laplacian.'.format(G.lap_type) raise NotImplementedError(msg) if G.is_directed(): msg = 'This method only work for undirected graphs.' raise NotImplementedError(msg) L = G.L else: L = G N = np.shape(L)[0] ind_comp = np.setdiff1d(np.arange(N, dtype=int), ind) L_red = L[np.ix_(ind, ind)] L_in_out = L[np.ix_(ind, ind_comp)] L_out_in = L[np.ix_(ind_comp, ind)].tocsc() L_comp = L[np.ix_(ind_comp, ind_comp)].tocsc() Lnew = L_red - L_in_out.dot(linalg.spsolve(L_comp, L_out_in)) # Make the laplacian symmetric if it is almost symmetric! if np.abs(Lnew - Lnew.T).sum() < np.spacing(1) * np.abs(Lnew).sum(): Lnew = (Lnew + Lnew.T) / 2. if isinstance(G, graphs.Graph): # Suppress the diagonal ? This is a good question? Wnew = sparse.diags(Lnew.diagonal(), 0) - Lnew Snew = Lnew.diagonal() - np.ravel(Wnew.sum(0)) if np.linalg.norm(Snew, 2) >= np.spacing(1000): Wnew = Wnew + sparse.diags(Snew, 0) # Removing diagonal for stability Wnew = Wnew - Wnew.diagonal() coords = G.coords[ind, :] if len(G.coords.shape) else np.ndarray(None) Gnew = graphs.Graph(Wnew, coords=coords, lap_type=G.lap_type, plotting=G.plotting) else: Gnew = Lnew return Gnew
python
def kron_reduction(G, ind): r"""Compute the Kron reduction. This function perform the Kron reduction of the weight matrix in the graph *G*, with boundary nodes labeled by *ind*. This function will create a new graph with a weight matrix Wnew that contain only boundary nodes and is computed as the Schur complement of the original matrix with respect to the selected indices. Parameters ---------- G : Graph or sparse matrix Graph structure or weight matrix ind : list indices of the nodes to keep Returns ------- Gnew : Graph or sparse matrix New graph structure or weight matrix References ---------- See :cite:`dorfler2013kron` """ if isinstance(G, graphs.Graph): if G.lap_type != 'combinatorial': msg = 'Unknown reduction for {} Laplacian.'.format(G.lap_type) raise NotImplementedError(msg) if G.is_directed(): msg = 'This method only work for undirected graphs.' raise NotImplementedError(msg) L = G.L else: L = G N = np.shape(L)[0] ind_comp = np.setdiff1d(np.arange(N, dtype=int), ind) L_red = L[np.ix_(ind, ind)] L_in_out = L[np.ix_(ind, ind_comp)] L_out_in = L[np.ix_(ind_comp, ind)].tocsc() L_comp = L[np.ix_(ind_comp, ind_comp)].tocsc() Lnew = L_red - L_in_out.dot(linalg.spsolve(L_comp, L_out_in)) # Make the laplacian symmetric if it is almost symmetric! if np.abs(Lnew - Lnew.T).sum() < np.spacing(1) * np.abs(Lnew).sum(): Lnew = (Lnew + Lnew.T) / 2. if isinstance(G, graphs.Graph): # Suppress the diagonal ? This is a good question? Wnew = sparse.diags(Lnew.diagonal(), 0) - Lnew Snew = Lnew.diagonal() - np.ravel(Wnew.sum(0)) if np.linalg.norm(Snew, 2) >= np.spacing(1000): Wnew = Wnew + sparse.diags(Snew, 0) # Removing diagonal for stability Wnew = Wnew - Wnew.diagonal() coords = G.coords[ind, :] if len(G.coords.shape) else np.ndarray(None) Gnew = graphs.Graph(Wnew, coords=coords, lap_type=G.lap_type, plotting=G.plotting) else: Gnew = Lnew return Gnew
[ "def", "kron_reduction", "(", "G", ",", "ind", ")", ":", "if", "isinstance", "(", "G", ",", "graphs", ".", "Graph", ")", ":", "if", "G", ".", "lap_type", "!=", "'combinatorial'", ":", "msg", "=", "'Unknown reduction for {} Laplacian.'", ".", "format", "(",...
r"""Compute the Kron reduction. This function perform the Kron reduction of the weight matrix in the graph *G*, with boundary nodes labeled by *ind*. This function will create a new graph with a weight matrix Wnew that contain only boundary nodes and is computed as the Schur complement of the original matrix with respect to the selected indices. Parameters ---------- G : Graph or sparse matrix Graph structure or weight matrix ind : list indices of the nodes to keep Returns ------- Gnew : Graph or sparse matrix New graph structure or weight matrix References ---------- See :cite:`dorfler2013kron`
[ "r", "Compute", "the", "Kron", "reduction", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L295-L368
train
210,878
epfl-lts2/pygsp
pygsp/reduction.py
pyramid_analysis
def pyramid_analysis(Gs, f, **kwargs): r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used for the analysis and sythesis operator. If only one filter is given, it will be used for all levels. Default is h(x) = 1 / (2x+1) Returns ------- ca : ndarray Coarse approximation at each level pe : ndarray Prediction error at each level h_filters : list Graph spectral filters applied References ---------- See :cite:`shuman2013framework` and :cite:`pesenson2009variational`. """ if np.shape(f)[0] != Gs[0].N: raise ValueError("PYRAMID ANALYSIS: The signal to analyze should have the same dimension as the first graph.") levels = len(Gs) - 1 # check if the type of filters is right. h_filters = kwargs.pop('h_filters', lambda x: 1. / (2*x+1)) if not isinstance(h_filters, list): if hasattr(h_filters, '__call__'): logger.warning('Converting filters into a list.') h_filters = [h_filters] else: logger.error('Filters must be a list of functions.') if len(h_filters) == 1: h_filters = h_filters * levels elif len(h_filters) != levels: message = 'The number of filters must be one or equal to {}.'.format(levels) raise ValueError(message) ca = [f] pe = [] for i in range(levels): # Low pass the signal s_low = _analysis(filters.Filter(Gs[i], h_filters[i]), ca[i], **kwargs) # Keep only the coefficient on the selected nodes ca.append(s_low[Gs[i+1].mr['idx']]) # Compute prediction s_pred = interpolate(Gs[i], ca[i+1], Gs[i+1].mr['idx'], **kwargs) # Compute errors pe.append(ca[i] - s_pred) return ca, pe
python
def pyramid_analysis(Gs, f, **kwargs): r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used for the analysis and sythesis operator. If only one filter is given, it will be used for all levels. Default is h(x) = 1 / (2x+1) Returns ------- ca : ndarray Coarse approximation at each level pe : ndarray Prediction error at each level h_filters : list Graph spectral filters applied References ---------- See :cite:`shuman2013framework` and :cite:`pesenson2009variational`. """ if np.shape(f)[0] != Gs[0].N: raise ValueError("PYRAMID ANALYSIS: The signal to analyze should have the same dimension as the first graph.") levels = len(Gs) - 1 # check if the type of filters is right. h_filters = kwargs.pop('h_filters', lambda x: 1. / (2*x+1)) if not isinstance(h_filters, list): if hasattr(h_filters, '__call__'): logger.warning('Converting filters into a list.') h_filters = [h_filters] else: logger.error('Filters must be a list of functions.') if len(h_filters) == 1: h_filters = h_filters * levels elif len(h_filters) != levels: message = 'The number of filters must be one or equal to {}.'.format(levels) raise ValueError(message) ca = [f] pe = [] for i in range(levels): # Low pass the signal s_low = _analysis(filters.Filter(Gs[i], h_filters[i]), ca[i], **kwargs) # Keep only the coefficient on the selected nodes ca.append(s_low[Gs[i+1].mr['idx']]) # Compute prediction s_pred = interpolate(Gs[i], ca[i+1], Gs[i+1].mr['idx'], **kwargs) # Compute errors pe.append(ca[i] - s_pred) return ca, pe
[ "def", "pyramid_analysis", "(", "Gs", ",", "f", ",", "*", "*", "kwargs", ")", ":", "if", "np", ".", "shape", "(", "f", ")", "[", "0", "]", "!=", "Gs", "[", "0", "]", ".", "N", ":", "raise", "ValueError", "(", "\"PYRAMID ANALYSIS: The signal to analyz...
r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used for the analysis and sythesis operator. If only one filter is given, it will be used for all levels. Default is h(x) = 1 / (2x+1) Returns ------- ca : ndarray Coarse approximation at each level pe : ndarray Prediction error at each level h_filters : list Graph spectral filters applied References ---------- See :cite:`shuman2013framework` and :cite:`pesenson2009variational`.
[ "r", "Compute", "the", "graph", "pyramid", "transform", "coefficients", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L371-L434
train
210,879
epfl-lts2/pygsp
pygsp/reduction.py
pyramid_synthesis
def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs): r"""Synthesize a signal from its pyramid coefficients. Parameters ---------- Gs : Array of Graphs A multiresolution sequence of graph structures. cap : ndarray Coarsest approximation of the original signal. pe : ndarray Prediction error at each level. use_exact : bool To use exact graph spectral filtering instead of the Chebyshev approximation. order : int Degree of the Chebyshev approximation (default=30). least_squares : bool To use the least squares synthesis (default=False). h_filters : ndarray The filters used in the analysis operator. These are required for least squares synthesis, but not for the direct synthesis method. use_landweber : bool To use the Landweber iteration approximation in the least squares synthesis. reg_eps : float Interpolation parameter. landweber_its : int Number of iterations in the Landweber approximation for least squares synthesis. landweber_tau : float Parameter for the Landweber iteration. Returns ------- reconstruction : ndarray The reconstructed signal. ca : ndarray Coarse approximations at each level """ least_squares = bool(kwargs.pop('least_squares', False)) def_ul = Gs[0].N > 3000 or Gs[0]._e is None or Gs[0]._U is None use_landweber = bool(kwargs.pop('use_landweber', def_ul)) reg_eps = float(kwargs.get('reg_eps', 0.005)) if least_squares and 'h_filters' not in kwargs: ValueError('h-filters not provided.') levels = len(Gs) - 1 if len(pe) != levels: ValueError('Gs and pe have different shapes.') ca = [cap] # Reconstruct each level for i in range(levels): if not least_squares: s_pred = interpolate(Gs[levels - i - 1], ca[i], Gs[levels - i].mr['idx'], order=order, reg_eps=reg_eps, **kwargs) ca.append(s_pred + pe[levels - i - 1]) else: ca.append(_pyramid_single_interpolation(Gs[levels - i - 1], ca[i], pe[levels - i - 1], h_filters[levels - i - 1], use_landweber=use_landweber, **kwargs)) ca.reverse() reconstruction = ca[0] return reconstruction, ca
python
def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs): r"""Synthesize a signal from its pyramid coefficients. Parameters ---------- Gs : Array of Graphs A multiresolution sequence of graph structures. cap : ndarray Coarsest approximation of the original signal. pe : ndarray Prediction error at each level. use_exact : bool To use exact graph spectral filtering instead of the Chebyshev approximation. order : int Degree of the Chebyshev approximation (default=30). least_squares : bool To use the least squares synthesis (default=False). h_filters : ndarray The filters used in the analysis operator. These are required for least squares synthesis, but not for the direct synthesis method. use_landweber : bool To use the Landweber iteration approximation in the least squares synthesis. reg_eps : float Interpolation parameter. landweber_its : int Number of iterations in the Landweber approximation for least squares synthesis. landweber_tau : float Parameter for the Landweber iteration. Returns ------- reconstruction : ndarray The reconstructed signal. ca : ndarray Coarse approximations at each level """ least_squares = bool(kwargs.pop('least_squares', False)) def_ul = Gs[0].N > 3000 or Gs[0]._e is None or Gs[0]._U is None use_landweber = bool(kwargs.pop('use_landweber', def_ul)) reg_eps = float(kwargs.get('reg_eps', 0.005)) if least_squares and 'h_filters' not in kwargs: ValueError('h-filters not provided.') levels = len(Gs) - 1 if len(pe) != levels: ValueError('Gs and pe have different shapes.') ca = [cap] # Reconstruct each level for i in range(levels): if not least_squares: s_pred = interpolate(Gs[levels - i - 1], ca[i], Gs[levels - i].mr['idx'], order=order, reg_eps=reg_eps, **kwargs) ca.append(s_pred + pe[levels - i - 1]) else: ca.append(_pyramid_single_interpolation(Gs[levels - i - 1], ca[i], pe[levels - i - 1], h_filters[levels - i - 1], use_landweber=use_landweber, **kwargs)) ca.reverse() reconstruction = ca[0] return reconstruction, ca
[ "def", "pyramid_synthesis", "(", "Gs", ",", "cap", ",", "pe", ",", "order", "=", "30", ",", "*", "*", "kwargs", ")", ":", "least_squares", "=", "bool", "(", "kwargs", ".", "pop", "(", "'least_squares'", ",", "False", ")", ")", "def_ul", "=", "Gs", ...
r"""Synthesize a signal from its pyramid coefficients. Parameters ---------- Gs : Array of Graphs A multiresolution sequence of graph structures. cap : ndarray Coarsest approximation of the original signal. pe : ndarray Prediction error at each level. use_exact : bool To use exact graph spectral filtering instead of the Chebyshev approximation. order : int Degree of the Chebyshev approximation (default=30). least_squares : bool To use the least squares synthesis (default=False). h_filters : ndarray The filters used in the analysis operator. These are required for least squares synthesis, but not for the direct synthesis method. use_landweber : bool To use the Landweber iteration approximation in the least squares synthesis. reg_eps : float Interpolation parameter. landweber_its : int Number of iterations in the Landweber approximation for least squares synthesis. landweber_tau : float Parameter for the Landweber iteration. Returns ------- reconstruction : ndarray The reconstructed signal. ca : ndarray Coarse approximations at each level
[ "r", "Synthesize", "a", "signal", "from", "its", "pyramid", "coefficients", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L437-L504
train
210,880
epfl-lts2/pygsp
pygsp/reduction.py
tree_multiresolution
def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance', compute_full_eigen=False, root=None): r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (default = 'resistance_distance') compute_full_eigen : bool To also compute the graph Laplacian eigenvalues for every tree in the sequence Returns ------- Gs : ndarray Ndarray, with each element containing a graph structure represent a reduced tree. subsampled_vertex_indices : ndarray Indices of the vertices of the previous tree that are kept for the subsequent tree. """ if not root: if hasattr(G, 'root'): root = G.root else: root = 1 Gs = [G] if compute_full_eigen: Gs[0].compute_fourier_basis() subsampled_vertex_indices = [] depths, parents = _tree_depths(G.A, root) old_W = G.W for lev in range(Nlevel): # Identify the vertices in the even depths of the current tree down_odd = round(depths) % 2 down_even = np.ones((Gs[lev].N)) - down_odd keep_inds = np.where(down_even == 1)[0] subsampled_vertex_indices.append(keep_inds) # There will be one undirected edge in the new graph connecting each # non-root subsampled vertex to its new parent. Here, we find the new # indices of the new parents non_root_keep_inds, new_non_root_inds = np.setdiff1d(keep_inds, root) old_parents_of_non_root_keep_inds = parents[non_root_keep_inds] old_grandparents_of_non_root_keep_inds = parents[old_parents_of_non_root_keep_inds] # TODO new_non_root_parents = dsearchn(keep_inds, old_grandparents_of_non_root_keep_inds) old_W_i_inds, old_W_j_inds, old_W_weights = sparse.find(old_W) i_inds = np.concatenate((new_non_root_inds, new_non_root_parents)) j_inds = np.concatenate((new_non_root_parents, new_non_root_inds)) new_N = np.sum(down_even) if reduction_method == "unweighted": new_weights = np.ones(np.shape(i_inds)) elif reduction_method == "sum": # TODO old_weights_to_parents_inds = dsearchn([old_W_i_inds,old_W_j_inds], [non_root_keep_inds, old_parents_of_non_root_keep_inds]); old_weights_to_parents = old_W_weights[old_weights_to_parents_inds] # old_W(non_root_keep_inds,old_parents_of_non_root_keep_inds); # TODO old_weights_parents_to_grandparents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [old_parents_of_non_root_keep_inds, old_grandparents_of_non_root_keep_inds]) old_weights_parents_to_grandparents = old_W_weights[old_weights_parents_to_grandparents_inds] # old_W(old_parents_of_non_root_keep_inds,old_grandparents_of_non_root_keep_inds); new_weights = old_weights_to_parents + old_weights_parents_to_grandparents new_weights = np.concatenate((new_weights. new_weights)) elif reduction_method == "resistance_distance": # TODO old_weights_to_parents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [non_root_keep_inds, old_parents_of_non_root_keep_inds]) old_weights_to_parents = old_W_weight[sold_weights_to_parents_inds] # old_W(non_root_keep_inds,old_parents_of_non_root_keep_inds); # TODO old_weights_parents_to_grandparents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [old_parents_of_non_root_keep_inds, old_grandparents_of_non_root_keep_inds]) old_weights_parents_to_grandparents = old_W_weights[old_weights_parents_to_grandparents_inds] # old_W(old_parents_of_non_root_keep_inds,old_grandparents_of_non_root_keep_inds); new_weights = 1./(1./old_weights_to_parents + 1./old_weights_parents_to_grandparents) new_weights = np.concatenate(([new_weights, new_weights])) else: raise ValueError('Unknown graph reduction method.') new_W = sparse.csc_matrix((new_weights, (i_inds, j_inds)), shape=(new_N, new_N)) # Update parents new_root = np.where(keep_inds == root)[0] parents = np.zeros(np.shape(keep_inds)[0], np.shape(keep_inds)[0]) parents[:new_root - 1, new_root:] = new_non_root_parents # Update depths depths = depths[keep_inds] depths = depths/2. # Store new tree Gtemp = graphs.Graph(new_W, coords=Gs[lev].coords[keep_inds], limits=G.limits, root=new_root) #Gs[lev].copy_graph_attributes(Gtemp, False) if compute_full_eigen: Gs[lev + 1].compute_fourier_basis() # Replace current adjacency matrix and root Gs.append(Gtemp) old_W = new_W root = new_root return Gs, subsampled_vertex_indices
python
def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance', compute_full_eigen=False, root=None): r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (default = 'resistance_distance') compute_full_eigen : bool To also compute the graph Laplacian eigenvalues for every tree in the sequence Returns ------- Gs : ndarray Ndarray, with each element containing a graph structure represent a reduced tree. subsampled_vertex_indices : ndarray Indices of the vertices of the previous tree that are kept for the subsequent tree. """ if not root: if hasattr(G, 'root'): root = G.root else: root = 1 Gs = [G] if compute_full_eigen: Gs[0].compute_fourier_basis() subsampled_vertex_indices = [] depths, parents = _tree_depths(G.A, root) old_W = G.W for lev in range(Nlevel): # Identify the vertices in the even depths of the current tree down_odd = round(depths) % 2 down_even = np.ones((Gs[lev].N)) - down_odd keep_inds = np.where(down_even == 1)[0] subsampled_vertex_indices.append(keep_inds) # There will be one undirected edge in the new graph connecting each # non-root subsampled vertex to its new parent. Here, we find the new # indices of the new parents non_root_keep_inds, new_non_root_inds = np.setdiff1d(keep_inds, root) old_parents_of_non_root_keep_inds = parents[non_root_keep_inds] old_grandparents_of_non_root_keep_inds = parents[old_parents_of_non_root_keep_inds] # TODO new_non_root_parents = dsearchn(keep_inds, old_grandparents_of_non_root_keep_inds) old_W_i_inds, old_W_j_inds, old_W_weights = sparse.find(old_W) i_inds = np.concatenate((new_non_root_inds, new_non_root_parents)) j_inds = np.concatenate((new_non_root_parents, new_non_root_inds)) new_N = np.sum(down_even) if reduction_method == "unweighted": new_weights = np.ones(np.shape(i_inds)) elif reduction_method == "sum": # TODO old_weights_to_parents_inds = dsearchn([old_W_i_inds,old_W_j_inds], [non_root_keep_inds, old_parents_of_non_root_keep_inds]); old_weights_to_parents = old_W_weights[old_weights_to_parents_inds] # old_W(non_root_keep_inds,old_parents_of_non_root_keep_inds); # TODO old_weights_parents_to_grandparents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [old_parents_of_non_root_keep_inds, old_grandparents_of_non_root_keep_inds]) old_weights_parents_to_grandparents = old_W_weights[old_weights_parents_to_grandparents_inds] # old_W(old_parents_of_non_root_keep_inds,old_grandparents_of_non_root_keep_inds); new_weights = old_weights_to_parents + old_weights_parents_to_grandparents new_weights = np.concatenate((new_weights. new_weights)) elif reduction_method == "resistance_distance": # TODO old_weights_to_parents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [non_root_keep_inds, old_parents_of_non_root_keep_inds]) old_weights_to_parents = old_W_weight[sold_weights_to_parents_inds] # old_W(non_root_keep_inds,old_parents_of_non_root_keep_inds); # TODO old_weights_parents_to_grandparents_inds = dsearchn([old_W_i_inds, old_W_j_inds], [old_parents_of_non_root_keep_inds, old_grandparents_of_non_root_keep_inds]) old_weights_parents_to_grandparents = old_W_weights[old_weights_parents_to_grandparents_inds] # old_W(old_parents_of_non_root_keep_inds,old_grandparents_of_non_root_keep_inds); new_weights = 1./(1./old_weights_to_parents + 1./old_weights_parents_to_grandparents) new_weights = np.concatenate(([new_weights, new_weights])) else: raise ValueError('Unknown graph reduction method.') new_W = sparse.csc_matrix((new_weights, (i_inds, j_inds)), shape=(new_N, new_N)) # Update parents new_root = np.where(keep_inds == root)[0] parents = np.zeros(np.shape(keep_inds)[0], np.shape(keep_inds)[0]) parents[:new_root - 1, new_root:] = new_non_root_parents # Update depths depths = depths[keep_inds] depths = depths/2. # Store new tree Gtemp = graphs.Graph(new_W, coords=Gs[lev].coords[keep_inds], limits=G.limits, root=new_root) #Gs[lev].copy_graph_attributes(Gtemp, False) if compute_full_eigen: Gs[lev + 1].compute_fourier_basis() # Replace current adjacency matrix and root Gs.append(Gtemp) old_W = new_W root = new_root return Gs, subsampled_vertex_indices
[ "def", "tree_multiresolution", "(", "G", ",", "Nlevel", ",", "reduction_method", "=", "'resistance_distance'", ",", "compute_full_eigen", "=", "False", ",", "root", "=", "None", ")", ":", "if", "not", "root", ":", "if", "hasattr", "(", "G", ",", "'root'", ...
r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (default = 'resistance_distance') compute_full_eigen : bool To also compute the graph Laplacian eigenvalues for every tree in the sequence Returns ------- Gs : ndarray Ndarray, with each element containing a graph structure represent a reduced tree. subsampled_vertex_indices : ndarray Indices of the vertices of the previous tree that are kept for the subsequent tree.
[ "r", "Compute", "a", "multiresolution", "of", "trees" ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L616-L726
train
210,881
epfl-lts2/pygsp
pygsp/plotting.py
close_all
def close_all(): r"""Close all opened windows.""" # Windows can be closed by releasing all references to them so they can be # garbage collected. May not be necessary to call close(). global _qtg_windows for window in _qtg_windows: window.close() _qtg_windows = [] global _qtg_widgets for widget in _qtg_widgets: widget.close() _qtg_widgets = [] global _plt_figures for fig in _plt_figures: _, plt, _ = _import_plt() plt.close(fig) _plt_figures = []
python
def close_all(): r"""Close all opened windows.""" # Windows can be closed by releasing all references to them so they can be # garbage collected. May not be necessary to call close(). global _qtg_windows for window in _qtg_windows: window.close() _qtg_windows = [] global _qtg_widgets for widget in _qtg_widgets: widget.close() _qtg_widgets = [] global _plt_figures for fig in _plt_figures: _, plt, _ = _import_plt() plt.close(fig) _plt_figures = []
[ "def", "close_all", "(", ")", ":", "# Windows can be closed by releasing all references to them so they can be", "# garbage collected. May not be necessary to call close().", "global", "_qtg_windows", "for", "window", "in", "_qtg_windows", ":", "window", ".", "close", "(", ")", ...
r"""Close all opened windows.
[ "r", "Close", "all", "opened", "windows", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/plotting.py#L108-L127
train
210,882
epfl-lts2/pygsp
pygsp/plotting.py
_plot_filter
def _plot_filter(filters, n, eigenvalues, sum, title, ax, **kwargs): r"""Plot the spectral response of a filter bank. Parameters ---------- n : int Number of points where the filters are evaluated. eigenvalues : boolean Whether to show the eigenvalues of the graph Laplacian. The eigenvalues should have been computed with :meth:`~pygsp.graphs.Graph.compute_fourier_basis`. By default, the eigenvalues are shown if they are available. sum : boolean Whether to plot the sum of the squared magnitudes of the filters. Default True if there is multiple filters. title : str Title of the figure. ax : :class:`matplotlib.axes.Axes` Axes where to draw the graph. Optional, created if not passed. Only available with the matplotlib backend. kwargs : dict Additional parameters passed to the matplotlib plot function. Useful for example to change the linewidth, linestyle, or set a label. Only available with the matplotlib backend. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure the plot belongs to. Only with the matplotlib backend. ax : :class:`matplotlib.axes.Axes` The axes the plot belongs to. Only with the matplotlib backend. Notes ----- This function is only implemented for the matplotlib backend at the moment. Examples -------- >>> import matplotlib >>> G = graphs.Logo() >>> mh = filters.MexicanHat(G) >>> fig, ax = mh.plot() """ if eigenvalues is None: eigenvalues = (filters.G._e is not None) if sum is None: sum = filters.n_filters > 1 if title is None: title = repr(filters) return _plt_plot_filter(filters, n=n, eigenvalues=eigenvalues, sum=sum, title=title, ax=ax, **kwargs)
python
def _plot_filter(filters, n, eigenvalues, sum, title, ax, **kwargs): r"""Plot the spectral response of a filter bank. Parameters ---------- n : int Number of points where the filters are evaluated. eigenvalues : boolean Whether to show the eigenvalues of the graph Laplacian. The eigenvalues should have been computed with :meth:`~pygsp.graphs.Graph.compute_fourier_basis`. By default, the eigenvalues are shown if they are available. sum : boolean Whether to plot the sum of the squared magnitudes of the filters. Default True if there is multiple filters. title : str Title of the figure. ax : :class:`matplotlib.axes.Axes` Axes where to draw the graph. Optional, created if not passed. Only available with the matplotlib backend. kwargs : dict Additional parameters passed to the matplotlib plot function. Useful for example to change the linewidth, linestyle, or set a label. Only available with the matplotlib backend. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure the plot belongs to. Only with the matplotlib backend. ax : :class:`matplotlib.axes.Axes` The axes the plot belongs to. Only with the matplotlib backend. Notes ----- This function is only implemented for the matplotlib backend at the moment. Examples -------- >>> import matplotlib >>> G = graphs.Logo() >>> mh = filters.MexicanHat(G) >>> fig, ax = mh.plot() """ if eigenvalues is None: eigenvalues = (filters.G._e is not None) if sum is None: sum = filters.n_filters > 1 if title is None: title = repr(filters) return _plt_plot_filter(filters, n=n, eigenvalues=eigenvalues, sum=sum, title=title, ax=ax, **kwargs)
[ "def", "_plot_filter", "(", "filters", ",", "n", ",", "eigenvalues", ",", "sum", ",", "title", ",", "ax", ",", "*", "*", "kwargs", ")", ":", "if", "eigenvalues", "is", "None", ":", "eigenvalues", "=", "(", "filters", ".", "G", ".", "_e", "is", "not...
r"""Plot the spectral response of a filter bank. Parameters ---------- n : int Number of points where the filters are evaluated. eigenvalues : boolean Whether to show the eigenvalues of the graph Laplacian. The eigenvalues should have been computed with :meth:`~pygsp.graphs.Graph.compute_fourier_basis`. By default, the eigenvalues are shown if they are available. sum : boolean Whether to plot the sum of the squared magnitudes of the filters. Default True if there is multiple filters. title : str Title of the figure. ax : :class:`matplotlib.axes.Axes` Axes where to draw the graph. Optional, created if not passed. Only available with the matplotlib backend. kwargs : dict Additional parameters passed to the matplotlib plot function. Useful for example to change the linewidth, linestyle, or set a label. Only available with the matplotlib backend. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure the plot belongs to. Only with the matplotlib backend. ax : :class:`matplotlib.axes.Axes` The axes the plot belongs to. Only with the matplotlib backend. Notes ----- This function is only implemented for the matplotlib backend at the moment. Examples -------- >>> import matplotlib >>> G = graphs.Logo() >>> mh = filters.MexicanHat(G) >>> fig, ax = mh.plot()
[ "r", "Plot", "the", "spectral", "response", "of", "a", "filter", "bank", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/plotting.py#L194-L249
train
210,883
epfl-lts2/pygsp
pygsp/plotting.py
_plot_spectrogram
def _plot_spectrogram(G, node_idx): r"""Plot the graph's spectrogram. Parameters ---------- node_idx : ndarray Order to sort the nodes in the spectrogram. By default, does not reorder the nodes. Notes ----- This function is only implemented for the pyqtgraph backend at the moment. Examples -------- >>> G = graphs.Ring(15) >>> G.plot_spectrogram() """ from pygsp import features qtg, _, _ = _import_qtg() if not hasattr(G, 'spectr'): features.compute_spectrogram(G) M = G.spectr.shape[1] spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr spectr = np.ravel(spectr) min_spec, max_spec = spectr.min(), spectr.max() pos = np.array([0., 0.25, 0.5, 0.75, 1.]) color = [[20, 133, 212, 255], [53, 42, 135, 255], [48, 174, 170, 255], [210, 184, 87, 255], [249, 251, 14, 255]] color = np.array(color, dtype=np.ubyte) cmap = qtg.ColorMap(pos, color) spectr = (spectr.astype(float) - min_spec) / (max_spec - min_spec) w = qtg.GraphicsWindow() w.setWindowTitle("Spectrogram of {}".format(G.__repr__(limit=4))) label = 'frequencies {}:{:.2f}:{:.2f}'.format(0, G.lmax/M, G.lmax) v = w.addPlot(labels={'bottom': 'nodes', 'left': label}) v.setAspectLocked() spi = qtg.ScatterPlotItem(np.repeat(np.arange(G.N), M), np.ravel(np.tile(np.arange(M), (1, G.N))), pxMode=False, symbol='s', size=1, brush=cmap.map(spectr, 'qcolor')) v.addItem(spi) global _qtg_windows _qtg_windows.append(w)
python
def _plot_spectrogram(G, node_idx): r"""Plot the graph's spectrogram. Parameters ---------- node_idx : ndarray Order to sort the nodes in the spectrogram. By default, does not reorder the nodes. Notes ----- This function is only implemented for the pyqtgraph backend at the moment. Examples -------- >>> G = graphs.Ring(15) >>> G.plot_spectrogram() """ from pygsp import features qtg, _, _ = _import_qtg() if not hasattr(G, 'spectr'): features.compute_spectrogram(G) M = G.spectr.shape[1] spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr spectr = np.ravel(spectr) min_spec, max_spec = spectr.min(), spectr.max() pos = np.array([0., 0.25, 0.5, 0.75, 1.]) color = [[20, 133, 212, 255], [53, 42, 135, 255], [48, 174, 170, 255], [210, 184, 87, 255], [249, 251, 14, 255]] color = np.array(color, dtype=np.ubyte) cmap = qtg.ColorMap(pos, color) spectr = (spectr.astype(float) - min_spec) / (max_spec - min_spec) w = qtg.GraphicsWindow() w.setWindowTitle("Spectrogram of {}".format(G.__repr__(limit=4))) label = 'frequencies {}:{:.2f}:{:.2f}'.format(0, G.lmax/M, G.lmax) v = w.addPlot(labels={'bottom': 'nodes', 'left': label}) v.setAspectLocked() spi = qtg.ScatterPlotItem(np.repeat(np.arange(G.N), M), np.ravel(np.tile(np.arange(M), (1, G.N))), pxMode=False, symbol='s', size=1, brush=cmap.map(spectr, 'qcolor')) v.addItem(spi) global _qtg_windows _qtg_windows.append(w)
[ "def", "_plot_spectrogram", "(", "G", ",", "node_idx", ")", ":", "from", "pygsp", "import", "features", "qtg", ",", "_", ",", "_", "=", "_import_qtg", "(", ")", "if", "not", "hasattr", "(", "G", ",", "'spectr'", ")", ":", "features", ".", "compute_spec...
r"""Plot the graph's spectrogram. Parameters ---------- node_idx : ndarray Order to sort the nodes in the spectrogram. By default, does not reorder the nodes. Notes ----- This function is only implemented for the pyqtgraph backend at the moment. Examples -------- >>> G = graphs.Ring(15) >>> G.plot_spectrogram()
[ "r", "Plot", "the", "graph", "s", "spectrogram", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/plotting.py#L632-L687
train
210,884
epfl-lts2/pygsp
pygsp/learning.py
classification_tikhonov
def classification_tikhonov(G, y, M, tau=0): r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_X tr(X^T L X) \ \text{ s. t. } \ Y = M X otherwise, where :math:`X` and :math:`Y` are logits. The function returns the maximum of the logits. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- logits : array, length G.n_vertices The logits :math:`X`. Examples -------- >>> from pygsp import graphs, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Logo() Create a ground truth signal: >>> signal = np.zeros(G.n_vertices) >>> signal[G.info['idx_s']] = 1 >>> signal[G.info['idx_p']] = 2 Construct a measurement signal from a binary mask: >>> rs = np.random.RandomState(42) >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the classification problem by reconstructing the signal: >>> recovery = learning.classification_tikhonov(G, measures, mask, tau=0) Plot the results. Note that we recover the class with ``np.argmax(recovery, axis=1)``. >>> prediction = np.argmax(recovery, axis=1) >>> fig, ax = plt.subplots(2, 3, sharey=True, figsize=(10, 6)) >>> _ = G.plot_signal(signal, ax=ax[0, 0], title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax[0, 1], title='Measurements') >>> _ = G.plot_signal(prediction, ax=ax[0, 2], title='Recovered class') >>> _ = G.plot_signal(recovery[:, 0], ax=ax[1, 0], title='Logit 0') >>> _ = G.plot_signal(recovery[:, 1], ax=ax[1, 1], title='Logit 1') >>> _ = G.plot_signal(recovery[:, 2], ax=ax[1, 2], title='Logit 2') >>> _ = fig.tight_layout() """ y[M == False] = 0 Y = _to_logits(y.astype(np.int)) return regression_tikhonov(G, Y, M, tau)
python
def classification_tikhonov(G, y, M, tau=0): r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_X tr(X^T L X) \ \text{ s. t. } \ Y = M X otherwise, where :math:`X` and :math:`Y` are logits. The function returns the maximum of the logits. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- logits : array, length G.n_vertices The logits :math:`X`. Examples -------- >>> from pygsp import graphs, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Logo() Create a ground truth signal: >>> signal = np.zeros(G.n_vertices) >>> signal[G.info['idx_s']] = 1 >>> signal[G.info['idx_p']] = 2 Construct a measurement signal from a binary mask: >>> rs = np.random.RandomState(42) >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the classification problem by reconstructing the signal: >>> recovery = learning.classification_tikhonov(G, measures, mask, tau=0) Plot the results. Note that we recover the class with ``np.argmax(recovery, axis=1)``. >>> prediction = np.argmax(recovery, axis=1) >>> fig, ax = plt.subplots(2, 3, sharey=True, figsize=(10, 6)) >>> _ = G.plot_signal(signal, ax=ax[0, 0], title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax[0, 1], title='Measurements') >>> _ = G.plot_signal(prediction, ax=ax[0, 2], title='Recovered class') >>> _ = G.plot_signal(recovery[:, 0], ax=ax[1, 0], title='Logit 0') >>> _ = G.plot_signal(recovery[:, 1], ax=ax[1, 1], title='Logit 1') >>> _ = G.plot_signal(recovery[:, 2], ax=ax[1, 2], title='Logit 2') >>> _ = fig.tight_layout() """ y[M == False] = 0 Y = _to_logits(y.astype(np.int)) return regression_tikhonov(G, Y, M, tau)
[ "def", "classification_tikhonov", "(", "G", ",", "y", ",", "M", ",", "tau", "=", "0", ")", ":", "y", "[", "M", "==", "False", "]", "=", "0", "Y", "=", "_to_logits", "(", "y", ".", "astype", "(", "np", ".", "int", ")", ")", "return", "regression...
r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_X tr(X^T L X) \ \text{ s. t. } \ Y = M X otherwise, where :math:`X` and :math:`Y` are logits. The function returns the maximum of the logits. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- logits : array, length G.n_vertices The logits :math:`X`. Examples -------- >>> from pygsp import graphs, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Logo() Create a ground truth signal: >>> signal = np.zeros(G.n_vertices) >>> signal[G.info['idx_s']] = 1 >>> signal[G.info['idx_p']] = 2 Construct a measurement signal from a binary mask: >>> rs = np.random.RandomState(42) >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the classification problem by reconstructing the signal: >>> recovery = learning.classification_tikhonov(G, measures, mask, tau=0) Plot the results. Note that we recover the class with ``np.argmax(recovery, axis=1)``. >>> prediction = np.argmax(recovery, axis=1) >>> fig, ax = plt.subplots(2, 3, sharey=True, figsize=(10, 6)) >>> _ = G.plot_signal(signal, ax=ax[0, 0], title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax[0, 1], title='Measurements') >>> _ = G.plot_signal(prediction, ax=ax[0, 2], title='Recovered class') >>> _ = G.plot_signal(recovery[:, 0], ax=ax[1, 0], title='Logit 0') >>> _ = G.plot_signal(recovery[:, 1], ax=ax[1, 1], title='Logit 1') >>> _ = G.plot_signal(recovery[:, 2], ax=ax[1, 2], title='Logit 2') >>> _ = fig.tight_layout()
[ "r", "Solve", "a", "classification", "problem", "on", "graph", "via", "Tikhonov", "minimization", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/learning.py#L182-L251
train
210,885
epfl-lts2/pygsp
pygsp/learning.py
regression_tikhonov
def regression_tikhonov(G, y, M, tau=0): r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x otherwise. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- x : array, length G.n_vertices Recovered values :math:`x`. Examples -------- >>> from pygsp import graphs, filters, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Sensor(N=100, seed=42) >>> G.estimate_lmax() Create a smooth ground truth signal: >>> filt = lambda x: 1 / (1 + 10*x) >>> filt = filters.Filter(G, filt) >>> rs = np.random.RandomState(42) >>> signal = filt.analyze(rs.normal(size=G.n_vertices)) Construct a measurement signal from a binary mask: >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the regression problem by reconstructing the signal: >>> recovery = learning.regression_tikhonov(G, measures, mask, tau=0) Plot the results: >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(10, 3)) >>> limits = [signal.min(), signal.max()] >>> _ = G.plot_signal(signal, ax=ax1, limits=limits, title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax2, limits=limits, title='Measures') >>> _ = G.plot_signal(recovery, ax=ax3, limits=limits, title='Recovery') >>> _ = fig.tight_layout() """ if tau > 0: y[M == False] = 0 if sparse.issparse(G.L): def Op(x): return (M * x.T).T + tau * (G.L.dot(x)) LinearOp = sparse.linalg.LinearOperator([G.N, G.N], Op) if y.ndim > 1: sol = np.empty(shape=y.shape) res = np.empty(shape=y.shape[1]) for i in range(y.shape[1]): sol[:, i], res[i] = sparse.linalg.cg( LinearOp, y[:, i]) else: sol, res = sparse.linalg.cg(LinearOp, y) # TODO: do something with the residual... return sol else: # Creating this matrix may be problematic in term of memory. # Consider using an operator instead... if type(G.L).__module__ == np.__name__: LinearOp = np.diag(M*1) + tau * G.L return np.linalg.solve(LinearOp, M * y) else: if np.prod(M.shape) != G.n_vertices: raise ValueError("M should be of size [G.n_vertices,]") indl = M indu = (M == False) Luu = G.L[indu, :][:, indu] Wul = - G.L[indu, :][:, indl] if sparse.issparse(G.L): sol_part = sparse.linalg.spsolve(Luu, Wul.dot(y[indl])) else: sol_part = np.linalg.solve(Luu, np.matmul(Wul, y[indl])) sol = y.copy() sol[indu] = sol_part return sol
python
def regression_tikhonov(G, y, M, tau=0): r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x otherwise. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- x : array, length G.n_vertices Recovered values :math:`x`. Examples -------- >>> from pygsp import graphs, filters, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Sensor(N=100, seed=42) >>> G.estimate_lmax() Create a smooth ground truth signal: >>> filt = lambda x: 1 / (1 + 10*x) >>> filt = filters.Filter(G, filt) >>> rs = np.random.RandomState(42) >>> signal = filt.analyze(rs.normal(size=G.n_vertices)) Construct a measurement signal from a binary mask: >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the regression problem by reconstructing the signal: >>> recovery = learning.regression_tikhonov(G, measures, mask, tau=0) Plot the results: >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(10, 3)) >>> limits = [signal.min(), signal.max()] >>> _ = G.plot_signal(signal, ax=ax1, limits=limits, title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax2, limits=limits, title='Measures') >>> _ = G.plot_signal(recovery, ax=ax3, limits=limits, title='Recovery') >>> _ = fig.tight_layout() """ if tau > 0: y[M == False] = 0 if sparse.issparse(G.L): def Op(x): return (M * x.T).T + tau * (G.L.dot(x)) LinearOp = sparse.linalg.LinearOperator([G.N, G.N], Op) if y.ndim > 1: sol = np.empty(shape=y.shape) res = np.empty(shape=y.shape[1]) for i in range(y.shape[1]): sol[:, i], res[i] = sparse.linalg.cg( LinearOp, y[:, i]) else: sol, res = sparse.linalg.cg(LinearOp, y) # TODO: do something with the residual... return sol else: # Creating this matrix may be problematic in term of memory. # Consider using an operator instead... if type(G.L).__module__ == np.__name__: LinearOp = np.diag(M*1) + tau * G.L return np.linalg.solve(LinearOp, M * y) else: if np.prod(M.shape) != G.n_vertices: raise ValueError("M should be of size [G.n_vertices,]") indl = M indu = (M == False) Luu = G.L[indu, :][:, indu] Wul = - G.L[indu, :][:, indl] if sparse.issparse(G.L): sol_part = sparse.linalg.spsolve(Luu, Wul.dot(y[indl])) else: sol_part = np.linalg.solve(Luu, np.matmul(Wul, y[indl])) sol = y.copy() sol[indu] = sol_part return sol
[ "def", "regression_tikhonov", "(", "G", ",", "y", ",", "M", ",", "tau", "=", "0", ")", ":", "if", "tau", ">", "0", ":", "y", "[", "M", "==", "False", "]", "=", "0", "if", "sparse", ".", "issparse", "(", "G", ".", "L", ")", ":", "def", "Op",...
r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x otherwise. Parameters ---------- G : :class:`pygsp.graphs.Graph` y : array, length G.n_vertices Measurements. M : array of boolean, length G.n_vertices Masking vector. tau : float Regularization parameter. Returns ------- x : array, length G.n_vertices Recovered values :math:`x`. Examples -------- >>> from pygsp import graphs, filters, learning >>> import matplotlib.pyplot as plt >>> >>> G = graphs.Sensor(N=100, seed=42) >>> G.estimate_lmax() Create a smooth ground truth signal: >>> filt = lambda x: 1 / (1 + 10*x) >>> filt = filters.Filter(G, filt) >>> rs = np.random.RandomState(42) >>> signal = filt.analyze(rs.normal(size=G.n_vertices)) Construct a measurement signal from a binary mask: >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5 >>> measures = signal.copy() >>> measures[~mask] = np.nan Solve the regression problem by reconstructing the signal: >>> recovery = learning.regression_tikhonov(G, measures, mask, tau=0) Plot the results: >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(10, 3)) >>> limits = [signal.min(), signal.max()] >>> _ = G.plot_signal(signal, ax=ax1, limits=limits, title='Ground truth') >>> _ = G.plot_signal(measures, ax=ax2, limits=limits, title='Measures') >>> _ = G.plot_signal(recovery, ax=ax3, limits=limits, title='Recovery') >>> _ = fig.tight_layout()
[ "r", "Solve", "a", "regression", "problem", "on", "graph", "via", "Tikhonov", "minimization", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/learning.py#L254-L368
train
210,886
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.set_signal
def set_signal(self, signal, name): r"""Attach a signal to the graph. Attached signals can be accessed (and modified or deleted) through the :attr:`signals` dictionary. Parameters ---------- signal : array_like A sequence that assigns a value to each vertex. The value of the signal at vertex `i` is ``signal[i]``. name : String Name of the signal used as a key in the :attr:`signals` dictionary. Examples -------- >>> graph = graphs.Sensor(10) >>> signal = np.arange(graph.n_vertices) >>> graph.set_signal(signal, 'mysignal') >>> graph.signals {'mysignal': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])} """ signal = self._check_signal(signal) self.signals[name] = signal
python
def set_signal(self, signal, name): r"""Attach a signal to the graph. Attached signals can be accessed (and modified or deleted) through the :attr:`signals` dictionary. Parameters ---------- signal : array_like A sequence that assigns a value to each vertex. The value of the signal at vertex `i` is ``signal[i]``. name : String Name of the signal used as a key in the :attr:`signals` dictionary. Examples -------- >>> graph = graphs.Sensor(10) >>> signal = np.arange(graph.n_vertices) >>> graph.set_signal(signal, 'mysignal') >>> graph.signals {'mysignal': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])} """ signal = self._check_signal(signal) self.signals[name] = signal
[ "def", "set_signal", "(", "self", ",", "signal", ",", "name", ")", ":", "signal", "=", "self", ".", "_check_signal", "(", "signal", ")", "self", ".", "signals", "[", "name", "]", "=", "signal" ]
r"""Attach a signal to the graph. Attached signals can be accessed (and modified or deleted) through the :attr:`signals` dictionary. Parameters ---------- signal : array_like A sequence that assigns a value to each vertex. The value of the signal at vertex `i` is ``signal[i]``. name : String Name of the signal used as a key in the :attr:`signals` dictionary. Examples -------- >>> graph = graphs.Sensor(10) >>> signal = np.arange(graph.n_vertices) >>> graph.set_signal(signal, 'mysignal') >>> graph.signals {'mysignal': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}
[ "r", "Attach", "a", "signal", "to", "the", "graph", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L193-L217
train
210,887
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.subgraph
def subgraph(self, vertices): r"""Create a subgraph from a list of vertices. Parameters ---------- vertices : list Vertices to keep. Either a list of indices or an indicator function. Returns ------- subgraph : :class:`Graph` Subgraph. Examples -------- >>> graph = graphs.Graph([ ... [0., 3., 0., 0.], ... [3., 0., 4., 0.], ... [0., 4., 0., 2.], ... [0., 0., 2., 0.], ... ]) >>> graph = graph.subgraph([0, 2, 1]) >>> graph.W.toarray() array([[0., 0., 3.], [0., 0., 4.], [3., 4., 0.]]) """ adjacency = self.W[vertices, :][:, vertices] try: coords = self.coords[vertices] except AttributeError: coords = None graph = Graph(adjacency, self.lap_type, coords, self.plotting) for name, signal in self.signals.items(): graph.set_signal(signal[vertices], name) return graph
python
def subgraph(self, vertices): r"""Create a subgraph from a list of vertices. Parameters ---------- vertices : list Vertices to keep. Either a list of indices or an indicator function. Returns ------- subgraph : :class:`Graph` Subgraph. Examples -------- >>> graph = graphs.Graph([ ... [0., 3., 0., 0.], ... [3., 0., 4., 0.], ... [0., 4., 0., 2.], ... [0., 0., 2., 0.], ... ]) >>> graph = graph.subgraph([0, 2, 1]) >>> graph.W.toarray() array([[0., 0., 3.], [0., 0., 4.], [3., 4., 0.]]) """ adjacency = self.W[vertices, :][:, vertices] try: coords = self.coords[vertices] except AttributeError: coords = None graph = Graph(adjacency, self.lap_type, coords, self.plotting) for name, signal in self.signals.items(): graph.set_signal(signal[vertices], name) return graph
[ "def", "subgraph", "(", "self", ",", "vertices", ")", ":", "adjacency", "=", "self", ".", "W", "[", "vertices", ",", ":", "]", "[", ":", ",", "vertices", "]", "try", ":", "coords", "=", "self", ".", "coords", "[", "vertices", "]", "except", "Attrib...
r"""Create a subgraph from a list of vertices. Parameters ---------- vertices : list Vertices to keep. Either a list of indices or an indicator function. Returns ------- subgraph : :class:`Graph` Subgraph. Examples -------- >>> graph = graphs.Graph([ ... [0., 3., 0., 0.], ... [3., 0., 4., 0.], ... [0., 4., 0., 2.], ... [0., 0., 2., 0.], ... ]) >>> graph = graph.subgraph([0, 2, 1]) >>> graph.W.toarray() array([[0., 0., 3.], [0., 0., 4.], [3., 4., 0.]])
[ "r", "Create", "a", "subgraph", "from", "a", "list", "of", "vertices", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L219-L256
train
210,888
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.extract_components
def extract_components(self): r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weight matrix. If the graph is directed, add into the info parameter the information about the source nodes and the sink nodes. Examples -------- >>> from scipy import sparse >>> W = sparse.rand(10, 10, 0.2) >>> W = utils.symmetrize(W) >>> G = graphs.Graph(W) >>> components = G.extract_components() >>> has_sinks = 'sink' in components[0].info >>> sinks_0 = components[0].info['sink'] if has_sinks else [] """ if self.A.shape[0] != self.A.shape[1]: self.logger.error('Inconsistent shape to extract components. ' 'Square matrix required.') return None if self.is_directed(): raise NotImplementedError('Directed graphs not supported yet.') graphs = [] visited = np.zeros(self.A.shape[0], dtype=bool) # indices = [] # Assigned but never used while not visited.all(): # pick a node not visted yet stack = set(np.nonzero(~visited)[0][[0]]) comp = [] while len(stack): v = stack.pop() if not visited[v]: comp.append(v) visited[v] = True # Add indices of nodes not visited yet and accessible from # v stack.update(set([idx for idx in self.A[v, :].nonzero()[1] if not visited[idx]])) comp = sorted(comp) self.logger.info(('Constructing subgraph for component of ' 'size {}.').format(len(comp))) G = self.subgraph(comp) G.info = {'orig_idx': comp} graphs.append(G) return graphs
python
def extract_components(self): r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weight matrix. If the graph is directed, add into the info parameter the information about the source nodes and the sink nodes. Examples -------- >>> from scipy import sparse >>> W = sparse.rand(10, 10, 0.2) >>> W = utils.symmetrize(W) >>> G = graphs.Graph(W) >>> components = G.extract_components() >>> has_sinks = 'sink' in components[0].info >>> sinks_0 = components[0].info['sink'] if has_sinks else [] """ if self.A.shape[0] != self.A.shape[1]: self.logger.error('Inconsistent shape to extract components. ' 'Square matrix required.') return None if self.is_directed(): raise NotImplementedError('Directed graphs not supported yet.') graphs = [] visited = np.zeros(self.A.shape[0], dtype=bool) # indices = [] # Assigned but never used while not visited.all(): # pick a node not visted yet stack = set(np.nonzero(~visited)[0][[0]]) comp = [] while len(stack): v = stack.pop() if not visited[v]: comp.append(v) visited[v] = True # Add indices of nodes not visited yet and accessible from # v stack.update(set([idx for idx in self.A[v, :].nonzero()[1] if not visited[idx]])) comp = sorted(comp) self.logger.info(('Constructing subgraph for component of ' 'size {}.').format(len(comp))) G = self.subgraph(comp) G.info = {'orig_idx': comp} graphs.append(G) return graphs
[ "def", "extract_components", "(", "self", ")", ":", "if", "self", ".", "A", ".", "shape", "[", "0", "]", "!=", "self", ".", "A", ".", "shape", "[", "1", "]", ":", "self", ".", "logger", ".", "error", "(", "'Inconsistent shape to extract components. '", ...
r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weight matrix. If the graph is directed, add into the info parameter the information about the source nodes and the sink nodes. Examples -------- >>> from scipy import sparse >>> W = sparse.rand(10, 10, 0.2) >>> W = utils.symmetrize(W) >>> G = graphs.Graph(W) >>> components = G.extract_components() >>> has_sinks = 'sink' in components[0].info >>> sinks_0 = components[0].info['sink'] if has_sinks else []
[ "r", "Split", "the", "graph", "into", "connected", "components", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L408-L469
train
210,889
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.compute_laplacian
def compute_laplacian(self, lap_type='combinatorial'): r"""Compute a graph Laplacian. For undirected graphs, the combinatorial Laplacian is defined as .. math:: L = D - W, where :math:`W` is the weighted adjacency matrix and :math:`D` the weighted degree matrix. The normalized Laplacian is defined as .. math:: L = I - D^{-1/2} W D^{-1/2}, where :math:`I` is the identity matrix. For directed graphs, the Laplacians are built from a symmetrized version of the weighted adjacency matrix that is the average of the weighted adjacency matrix and its transpose. As the Laplacian is defined as the divergence of the gradient, it is not affected by the orientation of the edges. For both Laplacians, the diagonal entries corresponding to disconnected nodes (i.e., nodes with degree zero) are set to zero. Once computed, the Laplacian is accessible by the attribute :attr:`L`. Parameters ---------- lap_type : {'combinatorial', 'normalized'} The kind of Laplacian to compute. Default is combinatorial. Examples -------- Combinatorial and normalized Laplacians of an undirected graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 1, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2., -2., 0.], [-2., 3., -1.], [ 0., -1., 1.]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.81649658, 0. ], [-0.81649658, 1. , -0.57735027], [ 0. , -0.57735027, 1. ]]) Combinatorial and normalized Laplacians of a directed graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 0, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2. , -2. , 0. ], [-2. , 2.5, -0.5], [ 0. , -0.5, 0.5]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.89442719, 0. ], [-0.89442719, 1. , -0.4472136 ], [ 0. , -0.4472136 , 1. ]]) The Laplacian is defined as the divergence of the gradient. See :meth:`compute_differential_operator` for details. >>> graph = graphs.Path(20) >>> graph.compute_differential_operator() >>> L = graph.D.dot(graph.D.T) >>> np.all(L.toarray() == graph.L.toarray()) True The Laplacians have a bounded spectrum. >>> G = graphs.Sensor(50) >>> G.compute_laplacian('combinatorial') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2*np.max(G.dw) True >>> G.compute_laplacian('normalized') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2 True """ if lap_type != self.lap_type: # Those attributes are invalidated when the Laplacian is changed. # Alternative: don't allow the user to change the Laplacian. self._lmax = None self._U = None self._e = None self._coherence = None self._D = None self.lap_type = lap_type if not self.is_directed(): W = self.W else: W = utils.symmetrize(self.W, method='average') if lap_type == 'combinatorial': D = sparse.diags(self.dw) self.L = D - W elif lap_type == 'normalized': d = np.zeros(self.n_vertices) disconnected = (self.dw == 0) np.power(self.dw, -0.5, where=~disconnected, out=d) D = sparse.diags(d) self.L = sparse.identity(self.n_vertices) - D * W * D self.L[disconnected, disconnected] = 0 self.L.eliminate_zeros() else: raise ValueError('Unknown Laplacian type {}'.format(lap_type))
python
def compute_laplacian(self, lap_type='combinatorial'): r"""Compute a graph Laplacian. For undirected graphs, the combinatorial Laplacian is defined as .. math:: L = D - W, where :math:`W` is the weighted adjacency matrix and :math:`D` the weighted degree matrix. The normalized Laplacian is defined as .. math:: L = I - D^{-1/2} W D^{-1/2}, where :math:`I` is the identity matrix. For directed graphs, the Laplacians are built from a symmetrized version of the weighted adjacency matrix that is the average of the weighted adjacency matrix and its transpose. As the Laplacian is defined as the divergence of the gradient, it is not affected by the orientation of the edges. For both Laplacians, the diagonal entries corresponding to disconnected nodes (i.e., nodes with degree zero) are set to zero. Once computed, the Laplacian is accessible by the attribute :attr:`L`. Parameters ---------- lap_type : {'combinatorial', 'normalized'} The kind of Laplacian to compute. Default is combinatorial. Examples -------- Combinatorial and normalized Laplacians of an undirected graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 1, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2., -2., 0.], [-2., 3., -1.], [ 0., -1., 1.]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.81649658, 0. ], [-0.81649658, 1. , -0.57735027], [ 0. , -0.57735027, 1. ]]) Combinatorial and normalized Laplacians of a directed graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 0, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2. , -2. , 0. ], [-2. , 2.5, -0.5], [ 0. , -0.5, 0.5]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.89442719, 0. ], [-0.89442719, 1. , -0.4472136 ], [ 0. , -0.4472136 , 1. ]]) The Laplacian is defined as the divergence of the gradient. See :meth:`compute_differential_operator` for details. >>> graph = graphs.Path(20) >>> graph.compute_differential_operator() >>> L = graph.D.dot(graph.D.T) >>> np.all(L.toarray() == graph.L.toarray()) True The Laplacians have a bounded spectrum. >>> G = graphs.Sensor(50) >>> G.compute_laplacian('combinatorial') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2*np.max(G.dw) True >>> G.compute_laplacian('normalized') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2 True """ if lap_type != self.lap_type: # Those attributes are invalidated when the Laplacian is changed. # Alternative: don't allow the user to change the Laplacian. self._lmax = None self._U = None self._e = None self._coherence = None self._D = None self.lap_type = lap_type if not self.is_directed(): W = self.W else: W = utils.symmetrize(self.W, method='average') if lap_type == 'combinatorial': D = sparse.diags(self.dw) self.L = D - W elif lap_type == 'normalized': d = np.zeros(self.n_vertices) disconnected = (self.dw == 0) np.power(self.dw, -0.5, where=~disconnected, out=d) D = sparse.diags(d) self.L = sparse.identity(self.n_vertices) - D * W * D self.L[disconnected, disconnected] = 0 self.L.eliminate_zeros() else: raise ValueError('Unknown Laplacian type {}'.format(lap_type))
[ "def", "compute_laplacian", "(", "self", ",", "lap_type", "=", "'combinatorial'", ")", ":", "if", "lap_type", "!=", "self", ".", "lap_type", ":", "# Those attributes are invalidated when the Laplacian is changed.", "# Alternative: don't allow the user to change the Laplacian.", ...
r"""Compute a graph Laplacian. For undirected graphs, the combinatorial Laplacian is defined as .. math:: L = D - W, where :math:`W` is the weighted adjacency matrix and :math:`D` the weighted degree matrix. The normalized Laplacian is defined as .. math:: L = I - D^{-1/2} W D^{-1/2}, where :math:`I` is the identity matrix. For directed graphs, the Laplacians are built from a symmetrized version of the weighted adjacency matrix that is the average of the weighted adjacency matrix and its transpose. As the Laplacian is defined as the divergence of the gradient, it is not affected by the orientation of the edges. For both Laplacians, the diagonal entries corresponding to disconnected nodes (i.e., nodes with degree zero) are set to zero. Once computed, the Laplacian is accessible by the attribute :attr:`L`. Parameters ---------- lap_type : {'combinatorial', 'normalized'} The kind of Laplacian to compute. Default is combinatorial. Examples -------- Combinatorial and normalized Laplacians of an undirected graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 1, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2., -2., 0.], [-2., 3., -1.], [ 0., -1., 1.]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.81649658, 0. ], [-0.81649658, 1. , -0.57735027], [ 0. , -0.57735027, 1. ]]) Combinatorial and normalized Laplacians of a directed graph. >>> graph = graphs.Graph([ ... [0, 2, 0], ... [2, 0, 1], ... [0, 0, 0], ... ]) >>> graph.compute_laplacian('combinatorial') >>> graph.L.toarray() array([[ 2. , -2. , 0. ], [-2. , 2.5, -0.5], [ 0. , -0.5, 0.5]]) >>> graph.compute_laplacian('normalized') >>> graph.L.toarray() array([[ 1. , -0.89442719, 0. ], [-0.89442719, 1. , -0.4472136 ], [ 0. , -0.4472136 , 1. ]]) The Laplacian is defined as the divergence of the gradient. See :meth:`compute_differential_operator` for details. >>> graph = graphs.Path(20) >>> graph.compute_differential_operator() >>> L = graph.D.dot(graph.D.T) >>> np.all(L.toarray() == graph.L.toarray()) True The Laplacians have a bounded spectrum. >>> G = graphs.Sensor(50) >>> G.compute_laplacian('combinatorial') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2*np.max(G.dw) True >>> G.compute_laplacian('normalized') >>> G.compute_fourier_basis() >>> -1e-10 < G.e[0] < 1e-10 < G.e[-1] < 2 True
[ "r", "Compute", "a", "graph", "Laplacian", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L471-L591
train
210,890
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph._check_signal
def _check_signal(self, s): r"""Check if signal is valid.""" s = np.asanyarray(s) if s.shape[0] != self.n_vertices: raise ValueError('First dimension must be the number of vertices ' 'G.N = {}, got {}.'.format(self.N, s.shape)) return s
python
def _check_signal(self, s): r"""Check if signal is valid.""" s = np.asanyarray(s) if s.shape[0] != self.n_vertices: raise ValueError('First dimension must be the number of vertices ' 'G.N = {}, got {}.'.format(self.N, s.shape)) return s
[ "def", "_check_signal", "(", "self", ",", "s", ")", ":", "s", "=", "np", ".", "asanyarray", "(", "s", ")", "if", "s", ".", "shape", "[", "0", "]", "!=", "self", ".", "n_vertices", ":", "raise", "ValueError", "(", "'First dimension must be the number of v...
r"""Check if signal is valid.
[ "r", "Check", "if", "signal", "is", "valid", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L593-L599
train
210,891
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.dirichlet_energy
def dirichlet_energy(self, x): r"""Compute the Dirichlet energy of a signal defined on the vertices. The Dirichlet energy of a signal :math:`x` is defined as .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] (x[j] - x[i])^2 for the combinatorial Laplacian, and .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] \left( \frac{x[j]}{d[j]} - \frac{x[i]}{d[i]} \right)^2 for the normalized Laplacian, where :math:`d` is the weighted degree :attr:`dw`, :math:`\nabla_\mathcal{G} x = D^\top x` and :math:`D` is the differential operator :attr:`D`. See :meth:`grad` for the definition of the gradient :math:`\nabla_\mathcal{G}`. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- energy : float The Dirichlet energy of the graph signal. See Also -------- grad : compute the gradient of a vertex signal Examples -------- Non-directed graph: >>> graph = graphs.Path(5, directed=False) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 8.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([2., 0., 2., 0.]) Directed graph: >>> graph = graphs.Path(5, directed=True) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 4.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([1.41421356, 0. , 1.41421356, 0. ]) """ x = self._check_signal(x) return x.T.dot(self.L.dot(x))
python
def dirichlet_energy(self, x): r"""Compute the Dirichlet energy of a signal defined on the vertices. The Dirichlet energy of a signal :math:`x` is defined as .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] (x[j] - x[i])^2 for the combinatorial Laplacian, and .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] \left( \frac{x[j]}{d[j]} - \frac{x[i]}{d[i]} \right)^2 for the normalized Laplacian, where :math:`d` is the weighted degree :attr:`dw`, :math:`\nabla_\mathcal{G} x = D^\top x` and :math:`D` is the differential operator :attr:`D`. See :meth:`grad` for the definition of the gradient :math:`\nabla_\mathcal{G}`. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- energy : float The Dirichlet energy of the graph signal. See Also -------- grad : compute the gradient of a vertex signal Examples -------- Non-directed graph: >>> graph = graphs.Path(5, directed=False) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 8.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([2., 0., 2., 0.]) Directed graph: >>> graph = graphs.Path(5, directed=True) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 4.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([1.41421356, 0. , 1.41421356, 0. ]) """ x = self._check_signal(x) return x.T.dot(self.L.dot(x))
[ "def", "dirichlet_energy", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "_check_signal", "(", "x", ")", "return", "x", ".", "T", ".", "dot", "(", "self", ".", "L", ".", "dot", "(", "x", ")", ")" ]
r"""Compute the Dirichlet energy of a signal defined on the vertices. The Dirichlet energy of a signal :math:`x` is defined as .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] (x[j] - x[i])^2 for the combinatorial Laplacian, and .. math:: x^\top L x = \| \nabla_\mathcal{G} x \|_2^2 = \frac12 \sum_{i,j} W[i, j] \left( \frac{x[j]}{d[j]} - \frac{x[i]}{d[i]} \right)^2 for the normalized Laplacian, where :math:`d` is the weighted degree :attr:`dw`, :math:`\nabla_\mathcal{G} x = D^\top x` and :math:`D` is the differential operator :attr:`D`. See :meth:`grad` for the definition of the gradient :math:`\nabla_\mathcal{G}`. Parameters ---------- x : array_like Signal of length :attr:`n_vertices` living on the vertices. Returns ------- energy : float The Dirichlet energy of the graph signal. See Also -------- grad : compute the gradient of a vertex signal Examples -------- Non-directed graph: >>> graph = graphs.Path(5, directed=False) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 8.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([2., 0., 2., 0.]) Directed graph: >>> graph = graphs.Path(5, directed=True) >>> signal = [0, 2, 2, 4, 4] >>> graph.dirichlet_energy(signal) 4.0 >>> # The Dirichlet energy is indeed the squared norm of the gradient. >>> graph.compute_differential_operator() >>> graph.grad(signal) array([1.41421356, 0. , 1.41421356, 0. ])
[ "r", "Compute", "the", "Dirichlet", "energy", "of", "a", "signal", "defined", "on", "the", "vertices", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L601-L661
train
210,892
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.dw
def dw(self): r"""The weighted degree of vertices. For undirected graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \sum_j W[j, i] = \sum_j W[i, j], where :math:`W` is the weighted adjacency matrix :attr:`W`. For directed graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \frac12 (d^\text{in}[i] + d^\text{out}[i]) = \frac12 (\sum_j W[j, i] + \sum_j W[i, j]), i.e., as the average of the in and out degrees. Examples -------- Undirected graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [1, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [1 2 1] >>> print(graph.dw) # Weighted degree. [1 3 2] Directed graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [0, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [0.5 1.5 1. ] >>> print(graph.dw) # Weighted degree. [0.5 2.5 2. ] """ if self._dw is None: if not self.is_directed(): # Shortcut for undirected graphs. self._dw = np.ravel(self.W.sum(axis=0)) else: degree_in = np.ravel(self.W.sum(axis=0)) degree_out = np.ravel(self.W.sum(axis=1)) self._dw = (degree_in + degree_out) / 2 return self._dw
python
def dw(self): r"""The weighted degree of vertices. For undirected graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \sum_j W[j, i] = \sum_j W[i, j], where :math:`W` is the weighted adjacency matrix :attr:`W`. For directed graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \frac12 (d^\text{in}[i] + d^\text{out}[i]) = \frac12 (\sum_j W[j, i] + \sum_j W[i, j]), i.e., as the average of the in and out degrees. Examples -------- Undirected graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [1, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [1 2 1] >>> print(graph.dw) # Weighted degree. [1 3 2] Directed graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [0, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [0.5 1.5 1. ] >>> print(graph.dw) # Weighted degree. [0.5 2.5 2. ] """ if self._dw is None: if not self.is_directed(): # Shortcut for undirected graphs. self._dw = np.ravel(self.W.sum(axis=0)) else: degree_in = np.ravel(self.W.sum(axis=0)) degree_out = np.ravel(self.W.sum(axis=1)) self._dw = (degree_in + degree_out) / 2 return self._dw
[ "def", "dw", "(", "self", ")", ":", "if", "self", ".", "_dw", "is", "None", ":", "if", "not", "self", ".", "is_directed", "(", ")", ":", "# Shortcut for undirected graphs.", "self", ".", "_dw", "=", "np", ".", "ravel", "(", "self", ".", "W", ".", "...
r"""The weighted degree of vertices. For undirected graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \sum_j W[j, i] = \sum_j W[i, j], where :math:`W` is the weighted adjacency matrix :attr:`W`. For directed graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \frac12 (d^\text{in}[i] + d^\text{out}[i]) = \frac12 (\sum_j W[j, i] + \sum_j W[i, j]), i.e., as the average of the in and out degrees. Examples -------- Undirected graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [1, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [1 2 1] >>> print(graph.dw) # Weighted degree. [1 3 2] Directed graph: >>> graph = graphs.Graph([ ... [0, 1, 0], ... [0, 0, 2], ... [0, 2, 0], ... ]) >>> print(graph.d) # Number of neighbors. [0.5 1.5 1. ] >>> print(graph.dw) # Weighted degree. [0.5 2.5 2. ]
[ "r", "The", "weighted", "degree", "of", "vertices", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L741-L795
train
210,893
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.lmax
def lmax(self): r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`. """ if self._lmax is None: self.logger.warning('The largest eigenvalue G.lmax is not ' 'available, we need to estimate it. ' 'Explicitly call G.estimate_lmax() or ' 'G.compute_fourier_basis() ' 'once beforehand to suppress the warning.') self.estimate_lmax() return self._lmax
python
def lmax(self): r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`. """ if self._lmax is None: self.logger.warning('The largest eigenvalue G.lmax is not ' 'available, we need to estimate it. ' 'Explicitly call G.estimate_lmax() or ' 'G.compute_fourier_basis() ' 'once beforehand to suppress the warning.') self.estimate_lmax() return self._lmax
[ "def", "lmax", "(", "self", ")", ":", "if", "self", ".", "_lmax", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "'The largest eigenvalue G.lmax is not '", "'available, we need to estimate it. '", "'Explicitly call G.estimate_lmax() or '", "'G.compute_four...
r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`.
[ "r", "Largest", "eigenvalue", "of", "the", "graph", "Laplacian", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L798-L811
train
210,894
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph._get_upper_bound
def _get_upper_bound(self): r"""Return an upper bound on the eigenvalues of the Laplacian.""" if self.lap_type == 'normalized': return 2 # Equal iff the graph is bipartite. elif self.lap_type == 'combinatorial': bounds = [] # Equal for full graphs. bounds += [self.n_vertices * np.max(self.W)] # Gershgorin circle theorem. Equal for regular bipartite graphs. # Special case of the below bound. bounds += [2 * np.max(self.dw)] # Anderson, Morley, Eigenvalues of the Laplacian of a graph. # Equal for regular bipartite graphs. if self.n_edges > 0: sources, targets, _ = self.get_edge_list() bounds += [np.max(self.dw[sources] + self.dw[targets])] # Merris, A note on Laplacian graph eigenvalues. if not self.is_directed(): W = self.W else: W = utils.symmetrize(self.W, method='average') m = W.dot(self.dw) / self.dw # Mean degree of adjacent vertices. bounds += [np.max(self.dw + m)] # Good review: On upper bounds for Laplacian graph eigenvalues. return min(bounds) else: raise ValueError('Unknown Laplacian type ' '{}'.format(self.lap_type))
python
def _get_upper_bound(self): r"""Return an upper bound on the eigenvalues of the Laplacian.""" if self.lap_type == 'normalized': return 2 # Equal iff the graph is bipartite. elif self.lap_type == 'combinatorial': bounds = [] # Equal for full graphs. bounds += [self.n_vertices * np.max(self.W)] # Gershgorin circle theorem. Equal for regular bipartite graphs. # Special case of the below bound. bounds += [2 * np.max(self.dw)] # Anderson, Morley, Eigenvalues of the Laplacian of a graph. # Equal for regular bipartite graphs. if self.n_edges > 0: sources, targets, _ = self.get_edge_list() bounds += [np.max(self.dw[sources] + self.dw[targets])] # Merris, A note on Laplacian graph eigenvalues. if not self.is_directed(): W = self.W else: W = utils.symmetrize(self.W, method='average') m = W.dot(self.dw) / self.dw # Mean degree of adjacent vertices. bounds += [np.max(self.dw + m)] # Good review: On upper bounds for Laplacian graph eigenvalues. return min(bounds) else: raise ValueError('Unknown Laplacian type ' '{}'.format(self.lap_type))
[ "def", "_get_upper_bound", "(", "self", ")", ":", "if", "self", ".", "lap_type", "==", "'normalized'", ":", "return", "2", "# Equal iff the graph is bipartite.", "elif", "self", ".", "lap_type", "==", "'combinatorial'", ":", "bounds", "=", "[", "]", "# Equal for...
r"""Return an upper bound on the eigenvalues of the Laplacian.
[ "r", "Return", "an", "upper", "bound", "on", "the", "eigenvalues", "of", "the", "Laplacian", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L883-L911
train
210,895
epfl-lts2/pygsp
pygsp/graphs/graph.py
Graph.get_edge_list
def get_edge_list(self): r"""Return an edge list, an alternative representation of the graph. Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i` to :math:`v_j` is associated with the weight :math:`W[i, j]`. For each edge :math:`e_k`, the method returns :math:`(i, j, W[i, j])` as `(sources[k], targets[k], weights[k])`, with :math:`i \in [0, |\mathcal{V}|-1], j \in [0, |\mathcal{V}|-1], k \in [0, |\mathcal{E}|-1]`. Returns ------- sources : vector of int Source node indices. targets : vector of int Target node indices. weights : vector of float Edge weights. Notes ----- The weighted adjacency matrix is the canonical form used in this package to represent a graph as it is the easiest to work with when considering spectral methods. Edge orientation (i.e., which node is the source or the target) is arbitrary for undirected graphs. The implementation uses the upper triangular part of the adjacency matrix, hence :math:`i \leq j \ \forall k`. Examples -------- Edge list of a directed graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 0, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1, 1], [1, 0, 2], [3, 3, 4]) Edge list of an undirected graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 4, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1], [1, 2], [3, 4]) """ if self.is_directed(): W = self.W.tocoo() else: W = sparse.triu(self.W, format='coo') sources = W.row targets = W.col weights = W.data assert self.n_edges == sources.size == targets.size == weights.size return sources, targets, weights
python
def get_edge_list(self): r"""Return an edge list, an alternative representation of the graph. Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i` to :math:`v_j` is associated with the weight :math:`W[i, j]`. For each edge :math:`e_k`, the method returns :math:`(i, j, W[i, j])` as `(sources[k], targets[k], weights[k])`, with :math:`i \in [0, |\mathcal{V}|-1], j \in [0, |\mathcal{V}|-1], k \in [0, |\mathcal{E}|-1]`. Returns ------- sources : vector of int Source node indices. targets : vector of int Target node indices. weights : vector of float Edge weights. Notes ----- The weighted adjacency matrix is the canonical form used in this package to represent a graph as it is the easiest to work with when considering spectral methods. Edge orientation (i.e., which node is the source or the target) is arbitrary for undirected graphs. The implementation uses the upper triangular part of the adjacency matrix, hence :math:`i \leq j \ \forall k`. Examples -------- Edge list of a directed graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 0, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1, 1], [1, 0, 2], [3, 3, 4]) Edge list of an undirected graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 4, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1], [1, 2], [3, 4]) """ if self.is_directed(): W = self.W.tocoo() else: W = sparse.triu(self.W, format='coo') sources = W.row targets = W.col weights = W.data assert self.n_edges == sources.size == targets.size == weights.size return sources, targets, weights
[ "def", "get_edge_list", "(", "self", ")", ":", "if", "self", ".", "is_directed", "(", ")", ":", "W", "=", "self", ".", "W", ".", "tocoo", "(", ")", "else", ":", "W", "=", "sparse", ".", "triu", "(", "self", ".", "W", ",", "format", "=", "'coo'"...
r"""Return an edge list, an alternative representation of the graph. Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i` to :math:`v_j` is associated with the weight :math:`W[i, j]`. For each edge :math:`e_k`, the method returns :math:`(i, j, W[i, j])` as `(sources[k], targets[k], weights[k])`, with :math:`i \in [0, |\mathcal{V}|-1], j \in [0, |\mathcal{V}|-1], k \in [0, |\mathcal{E}|-1]`. Returns ------- sources : vector of int Source node indices. targets : vector of int Target node indices. weights : vector of float Edge weights. Notes ----- The weighted adjacency matrix is the canonical form used in this package to represent a graph as it is the easiest to work with when considering spectral methods. Edge orientation (i.e., which node is the source or the target) is arbitrary for undirected graphs. The implementation uses the upper triangular part of the adjacency matrix, hence :math:`i \leq j \ \forall k`. Examples -------- Edge list of a directed graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 0, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1, 1], [1, 0, 2], [3, 3, 4]) Edge list of an undirected graph. >>> graph = graphs.Graph([ ... [0, 3, 0], ... [3, 0, 4], ... [0, 4, 0], ... ]) >>> sources, targets, weights = graph.get_edge_list() >>> list(sources), list(targets), list(weights) ([0, 1], [1, 2], [3, 4])
[ "r", "Return", "an", "edge", "list", "an", "alternative", "representation", "of", "the", "graph", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L913-L980
train
210,896
epfl-lts2/pygsp
pygsp/optimization.py
prox_tv
def prox_tv(x, gamma, G, A=None, At=None, nu=1, tol=10e-4, maxit=200, use_matrix=True): r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.graphs.Graph.grad`. This function requires the PyUNLocBoX to be executed. This function solves: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \|x\|_{TV}` Parameters ---------- x: int Input signal gamma: ndarray Regularization parameter G: graph object Graphs structure A: lambda function Forward operator, this parameter allows to solve the following problem: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \| A x\|_{TV}` (default = Id) At: lambda function Adjoint operator. (default = Id) nu: float Bound on the norm of the operator (default = 1) tol: float Stops criterion for the loop. The algorithm will stop if : :math:`\frac{n(t) - n(t - 1)} {n(t)} < tol` where :math:`n(t) = f(x) + 0.5 \|x-y\|_2^2` is the objective function at iteration :math:`t` (default = :math:`10e-4`) maxit: int Maximum iteration. (default = 200) use_matrix: bool If a matrix should be used. (default = True) Returns ------- sol: solution Examples -------- """ if A is None: def A(x): return x if At is None: def At(x): return x tight = 0 l1_nu = 2 * G.lmax * nu if use_matrix: def l1_a(x): return G.Diff * A(x) def l1_at(x): return G.Diff * At(D.T * x) else: def l1_a(x): return G.grad(A(x)) def l1_at(x): return G.div(x) functions, _ = _import_pyunlocbox() functions.norm_l1(x, gamma, A=l1_a, At=l1_at, tight=tight, maxit=maxit, verbose=verbose, tol=tol)
python
def prox_tv(x, gamma, G, A=None, At=None, nu=1, tol=10e-4, maxit=200, use_matrix=True): r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.graphs.Graph.grad`. This function requires the PyUNLocBoX to be executed. This function solves: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \|x\|_{TV}` Parameters ---------- x: int Input signal gamma: ndarray Regularization parameter G: graph object Graphs structure A: lambda function Forward operator, this parameter allows to solve the following problem: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \| A x\|_{TV}` (default = Id) At: lambda function Adjoint operator. (default = Id) nu: float Bound on the norm of the operator (default = 1) tol: float Stops criterion for the loop. The algorithm will stop if : :math:`\frac{n(t) - n(t - 1)} {n(t)} < tol` where :math:`n(t) = f(x) + 0.5 \|x-y\|_2^2` is the objective function at iteration :math:`t` (default = :math:`10e-4`) maxit: int Maximum iteration. (default = 200) use_matrix: bool If a matrix should be used. (default = True) Returns ------- sol: solution Examples -------- """ if A is None: def A(x): return x if At is None: def At(x): return x tight = 0 l1_nu = 2 * G.lmax * nu if use_matrix: def l1_a(x): return G.Diff * A(x) def l1_at(x): return G.Diff * At(D.T * x) else: def l1_a(x): return G.grad(A(x)) def l1_at(x): return G.div(x) functions, _ = _import_pyunlocbox() functions.norm_l1(x, gamma, A=l1_a, At=l1_at, tight=tight, maxit=maxit, verbose=verbose, tol=tol)
[ "def", "prox_tv", "(", "x", ",", "gamma", ",", "G", ",", "A", "=", "None", ",", "At", "=", "None", ",", "nu", "=", "1", ",", "tol", "=", "10e-4", ",", "maxit", "=", "200", ",", "use_matrix", "=", "True", ")", ":", "if", "A", "is", "None", "...
r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.graphs.Graph.grad`. This function requires the PyUNLocBoX to be executed. This function solves: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \|x\|_{TV}` Parameters ---------- x: int Input signal gamma: ndarray Regularization parameter G: graph object Graphs structure A: lambda function Forward operator, this parameter allows to solve the following problem: :math:`sol = \min_{z} \frac{1}{2} \|x - z\|_2^2 + \gamma \| A x\|_{TV}` (default = Id) At: lambda function Adjoint operator. (default = Id) nu: float Bound on the norm of the operator (default = 1) tol: float Stops criterion for the loop. The algorithm will stop if : :math:`\frac{n(t) - n(t - 1)} {n(t)} < tol` where :math:`n(t) = f(x) + 0.5 \|x-y\|_2^2` is the objective function at iteration :math:`t` (default = :math:`10e-4`) maxit: int Maximum iteration. (default = 200) use_matrix: bool If a matrix should be used. (default = True) Returns ------- sol: solution Examples --------
[ "r", "Total", "Variation", "proximal", "operator", "for", "graphs", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/optimization.py#L25-L96
train
210,897
epfl-lts2/pygsp
pygsp/graphs/randomregular.py
RandomRegular.is_regular
def is_regular(self): r""" Troubleshoot a given regular graph. """ warn = False msg = 'The given matrix' # check symmetry if np.abs(self.A - self.A.T).sum() > 0: warn = True msg = '{} is not symmetric,'.format(msg) # check parallel edged if self.A.max(axis=None) > 1: warn = True msg = '{} has parallel edges,'.format(msg) # check that d is d-regular if np.min(self.d) != np.max(self.d): warn = True msg = '{} is not d-regular,'.format(msg) # check that g doesn't contain any self-loop if self.A.diagonal().any(): warn = True msg = '{} has self loop.'.format(msg) if warn: self.logger.warning('{}.'.format(msg[:-1]))
python
def is_regular(self): r""" Troubleshoot a given regular graph. """ warn = False msg = 'The given matrix' # check symmetry if np.abs(self.A - self.A.T).sum() > 0: warn = True msg = '{} is not symmetric,'.format(msg) # check parallel edged if self.A.max(axis=None) > 1: warn = True msg = '{} has parallel edges,'.format(msg) # check that d is d-regular if np.min(self.d) != np.max(self.d): warn = True msg = '{} is not d-regular,'.format(msg) # check that g doesn't contain any self-loop if self.A.diagonal().any(): warn = True msg = '{} has self loop.'.format(msg) if warn: self.logger.warning('{}.'.format(msg[:-1]))
[ "def", "is_regular", "(", "self", ")", ":", "warn", "=", "False", "msg", "=", "'The given matrix'", "# check symmetry", "if", "np", ".", "abs", "(", "self", ".", "A", "-", "self", ".", "A", ".", "T", ")", ".", "sum", "(", ")", ">", "0", ":", "war...
r""" Troubleshoot a given regular graph.
[ "r", "Troubleshoot", "a", "given", "regular", "graph", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/randomregular.py#L107-L136
train
210,898
epfl-lts2/pygsp
pygsp/graphs/_io.py
IOMixIn._break_signals
def _break_signals(self): r"""Break N-dimensional signals into N 1D signals.""" for name in list(self.signals.keys()): if self.signals[name].ndim == 2: for i, signal_1d in enumerate(self.signals[name].T): self.signals[name + '_' + str(i)] = signal_1d del self.signals[name]
python
def _break_signals(self): r"""Break N-dimensional signals into N 1D signals.""" for name in list(self.signals.keys()): if self.signals[name].ndim == 2: for i, signal_1d in enumerate(self.signals[name].T): self.signals[name + '_' + str(i)] = signal_1d del self.signals[name]
[ "def", "_break_signals", "(", "self", ")", ":", "for", "name", "in", "list", "(", "self", ".", "signals", ".", "keys", "(", ")", ")", ":", "if", "self", ".", "signals", "[", "name", "]", ".", "ndim", "==", "2", ":", "for", "i", ",", "signal_1d", ...
r"""Break N-dimensional signals into N 1D signals.
[ "r", "Break", "N", "-", "dimensional", "signals", "into", "N", "1D", "signals", "." ]
8ce5bde39206129287375af24fdbcd7edddca8c5
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/_io.py#L29-L35
train
210,899