def color(self, u, v=None): r""" Return the color of an edge. INPUT: If ``v`` is ``None``, then ``u`` is consider to be an edge. Otherwise, ``uv`` is taken as the edge. EXAMPLES:: sage: from flexrilog import FlexRiGraph sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3)) sage: delta = G.NAC_colorings()[0] sage: delta.color(0,3) 'red' sage: delta.color([2,4]) 'blue' sage: delta.color(1,2) Traceback (most recent call last): ... ValueError: There is no edge [1, 2] """ if not v is None: if not self._graph.has_edge(u, v): raise exceptions.ValueError('There is no edge ' + str([u, v])) return 'red' if Set([u, v]) in self._red_edges else 'blue' else: if not self._graph.has_edge(u[0], u[1]): raise exceptions.ValueError('There is no edge ' + str([u[0], u[1]])) return 'red' if Set([u[0], u[1]]) in self._red_edges else 'blue'
def is_blue(self, u, v=None): r""" Return if the edge is blue. INPUT: If ``v`` is ``None``, then ``u`` is consider to be an edge. Otherwise, ``uv`` is taken as the edge. EXAMPLES:: sage: from flexrilog import FlexRiGraph sage: G = FlexRiGraph(graphs.CompleteBipartiteGraph(3,3)) sage: delta = G.NAC_colorings()[0] sage: delta.is_blue(2,4) True sage: delta.is_blue([0,4]) False sage: delta.is_blue(1,2) Traceback (most recent call last): ... ValueError: There is no edge [1, 2] """ if v: if not self._graph.has_edge(u, v): raise exceptions.ValueError('There is no edge ' + str([u, v])) return Set([u, v]) in self._blue_edges else: if not self._graph.has_edge(u[0], u[1]): raise exceptions.ValueError('There is no edge ' + str([u[0], u[1]])) return Set([u[0], u[1]]) in self._blue_edges
def __init__(self, R=None, t=None): if (R is None): raise exceptions.ValueError('Rotation matrix must be defined.') if (t is None): raise exceptions.ValueError('Translation vector must be defined') self.R = np.array(R) self.t = np.array(t) self.t = self.t.reshape(3, 1)
def tag_of_enclosing_csquare(lon, lat, resol): ## Identify enclosing csquare tag for point (lon, lat) at resolution resol degrees # @param lon : longitude[deg] of target point # @param lat : latitude[deg] of target point # @param resol : resolution[deg] desired c-square # @return : c-square tag corresponding to input # =============================================================================== # resol must be a standard step: 10, 5, 1, 0.5, 0.1, .... # handle boundary cases # =============================================================================== if not -180 < lon < 180: raise exceptions.ValueError("range error: lon = %f " % lon) if not -90 < lat < 90: raise exceptions.ValueError("range error: lat = %f " % lat) # # identify global WMO quadrant and tag # if lon>0: if lat>0: wmo_quadrant = 1 else: wmo_quadrant = 3 else: if lat>0: wmo_quadrant = 7 else: wmo_quadrant = 5 # --- fold to NE quadrant lon = abs(lon)/10 lat = abs(lat)/10 ilon = int(lon) ilat = int(lat) this_resol = 10.0 # avoid integer division below tag = "%1d%1d%02d" % (wmo_quadrant, ilat, ilon) # include leading zeros from lon designator # # csquare quadrant labelling is different from WMO # while this_resol/resol > 1.001: lon = 10*(lon-ilon) # reap next lon digit lat = 10*(lat-ilat) # reap next lat digit csq_quadrant = 1 if lon>5: csq_quadrant += 1 if lat>5: csq_quadrant += 2 ilon = int(lon) ilat = int(lat) tag = tag + ":%1d%1d%1d" % (csq_quadrant, ilat, ilon) this_resol /= 10. # corresponding to current tag if this_resol/resol < 0.201: # last step was half division tag = tag[:-2] # drop last two digits to back up half step return tag
def evaluate_expression(strexp, track, globals, locals): # Evaluate conditions in strexp. tmpl = '' # Resultant template string. conditions = [] # Condition stack. i = 0 while i < len(strexp): if strexp.startswith('##', i): tmpl += '#' i += 2 elif strexp.startswith('#if{', i): begin = i + 4 end = strexp.find('}', begin) if begin <= end: b = eval(strexp[begin:end], globals, locals) conditions.append(b) i = end + 1 else: raise exceptions.ValueError("'}' is missing (pos = %d)\n%s" % (i, strexp)) elif strexp.startswith('#elif{', i): conditions.pop() begin = i + 6 end = strexp.find('}', begin) if begin <= end: b = eval(strexp[begin:end], globals, locals) conditions.append(b) i = end + 1 else: raise exceptions.ValueError("'}' is missing (pos = %d)\n%s" % (i, strexp)) elif strexp.startswith('#else', i): if not conditions: raise exceptions.ValueError( "Corresponding #if is missing (pos = %d)\n%s" % (i, strexp)) i += 5 b = conditions.pop() condidions.append(not b) elif strexp.startswith('#endif', i): if not conditions: raise exceptions.ValueError( "Corresponding #if is missing (pos = %d)\n%s" % (i, strexp)) i += 6 b = conditions.pop() elif not conditions or conditions[-1]: tmpl += strexp[i] i += 1 else: i += 1 return string.Template(tmpl).substitute(track)
def unproject(self, data): """ Projects the data back to the input space. :param data: Data to unproject. :type data: numpy array [num data point, data dimension] :return: Projected data. :rtype: numpy array [num data point, data dimension] """ if self.input_dim != data.shape[1]: raise ex.ValueError("Wrong data dimensionality.") if not self.trained: raise ex.ValueError("Train model first!") return data * self.standard_deviation + self.mean
def __init__(self, db_file_path): if not db_file_path: raise exceptions.ValueError("db_file_path") if not os.path.exists(db_file_path): raise exceptions.OSError("db_file_path") if not db_file_path.endswith('.db'): raise exceptions.ValueError("db_file_path") self.db_file_path = db_file_path self.zone = os.path.basename(db_file_path)[:-3] self._load_zone()
def __init__(self, G, coloring, name=None, check=True): from flexible_rigid_graph import FlexRiGraph if type(G) == FlexRiGraph or 'FlexRiGraph' in str( type(G)) or isinstance(G, FlexRiGraph): self._graph = G else: raise exceptions.TypeError('The graph G must be FlexRiGraph.') if type(coloring) in [list, Set] and len(coloring) == 2: self._red_edges = Set([Set(e) for e in coloring[0]]) self._blue_edges = Set([Set(e) for e in coloring[1]]) elif type(coloring) == dict: self._red_edges = Set( [Set(e) for e in coloring if coloring[e] == 'red']) self._blue_edges = Set( [Set(e) for e in coloring if coloring[e] == 'blue']) elif type(coloring) == NACcoloring or isinstance( coloring, NACcoloring) or 'NACcoloring' in str(type(coloring)): self._red_edges = copy(coloring._red_edges) self._blue_edges = copy(coloring._blue_edges) else: raise exceptions.TypeError( 'The coloring must be a dict, list consisting of two lists or an instance of NACcoloring.' ) self._check_edges() self._name = name if check and not self.is_NAC_coloring(): raise exceptions.ValueError('The coloring is not a NAC-coloring.')
def __init__(self, argv=[], rpcmethod='thrift', callback=None, blockingcallback=None): if len(argv) > 1: host = argv[1] else: host = None if len(argv) > 2: port = argv[2] else: port = None self.client = None from gnuradio.ctrlport.RPCConnection import RPCMethods if RPCMethods.has_key(rpcmethod): from gnuradio.ctrlport.RPCConnectionThrift import RPCConnectionThrift if rpcmethod == 'thrift': #print("making RPCConnectionThrift") self.client = RPCConnectionThrift(host, port) #print("made %s" % self.client) #print("making callback call") if not callback is None: callback(self.client) #print("making blockingcallback call") if not blockingcallback is None: blockingcallback() else: print("Unsupported RPC method: ", rpcmethod) raise exceptions.ValueError()
def dihedrals(self, by_type): if not hasattr(self, "topology_data"): raise exc.ValueError("Topology file doesn't contain any data.") self.dihedrals = [] topology_dihedrals_list = topology_data[ "DIHEDRALS_INC_HYDROGEN"] + topology_data[ "DIHEDRALS_WITHOUT_HYDROGEN"] if by_type is True: while topology_dihedrals_list: atom_1 = old_div(topology_dihedrals_list.pop(0), 3) atom_2 = old_div(topology_dihedrals_list.pop(0), 3) atom_3 = old_div(topology_dihedrals_list.pop(0), 3) atom_4 = old_div(topology_dihedrals_list.pop(0), 3) bond_type = topology_dihedrals_list.pop(0) self.dihedrals.append( (atom_1, atom_2, atom_3, atom_4, bond_type)) else: while topology_dihedrals_list: atom_1 = old_div(topology_dihedrals_list.pop(0), 3) atom_2 = old_div(topology_dihedrals_list.pop(0), 3) atom_3 = old_div(topology_dihedrals_list.pop(0), 3) atom_4 = old_div(topology_dihedrals_list.pop(0), 3) bond_type = topology_dihedrals_list.pop(0) self.dihedrals.append((atom_1, atom_2, atom_3, atom_4)) return self.dihedrals
def _edges_with_same_length(self): tmp = {} for u, v in self._graph.edges(labels=False): s = self._parametrization[u] - self._parametrization[v] l = s.inner_product(s) if self._par_type == 'rational' and not l in self._field.constant_field(): raise exceptions.ValueError('The edge ' + str((u, v)) + ' does not have constant length.') if self._par_type == 'symbolic': l = l.simplify_full() if not l.simplify_full().is_constant(): raise exceptions.ValueError('The edge ' + str((u, v)) + ' does not have constant length.') if tmp.has_key(l): tmp[l].append([u, v]) else: tmp[l] = [[u, v]] self._same_lengths = tmp.values()
def Deltoid(cls, par_type='rational'): r""" Return a deltoid motion. """ if par_type == 'rational': FF = FunctionField(QQ, 't') t = FF.gen() C = { _sage_const_0 : vector((_sage_const_0 , _sage_const_0 )), _sage_const_1 : vector((_sage_const_1 , _sage_const_0 )), _sage_const_2 : vector((_sage_const_4 *(t**_sage_const_2 - _sage_const_2 )/(t**_sage_const_2 + _sage_const_4 ), _sage_const_12 *t/(t**_sage_const_2 + _sage_const_4 ))), _sage_const_3 : vector(((t**_sage_const_4 - _sage_const_13 *t**_sage_const_2 + _sage_const_4 )/(t**_sage_const_4 + _sage_const_5 *t**_sage_const_2 + _sage_const_4 ), _sage_const_6 *(t**_sage_const_3 - _sage_const_2 *t)/(t**_sage_const_4 + _sage_const_5 *t**_sage_const_2 + _sage_const_4 ))) } G = FlexRiGraph([[0, 1], [1, 2], [2, 3], [0, 3]]) return GraphMotion.ParametricMotion(G, C, 'rational', sampling_type='tan', check=False) elif par_type == 'symbolic': t = var('t') C = { _sage_const_0 : vector((_sage_const_0 , _sage_const_0 )), _sage_const_1 : vector((_sage_const_1 , _sage_const_0 )), _sage_const_2 : vector((_sage_const_4 *(t**_sage_const_2 - _sage_const_2 )/(t**_sage_const_2 + _sage_const_4 ), _sage_const_12 *t/(t**_sage_const_2 + _sage_const_4 ))), _sage_const_3 : vector(((t**_sage_const_4 - _sage_const_13 *t**_sage_const_2 + _sage_const_4 )/(t**_sage_const_4 + _sage_const_5 *t**_sage_const_2 + _sage_const_4 ), _sage_const_6 *(t**_sage_const_3 - _sage_const_2 *t)/(t**_sage_const_4 + _sage_const_5 *t**_sage_const_2 + _sage_const_4 ))) } G = FlexRiGraph([[0, 1], [1, 2], [2, 3], [0, 3]]) return ParametricGraphMotion.ParametricMotion(G, C, 'symbolic', sampling_type='tan', check=False) else: raise exceptions.ValueError('Deltoid with par_type ' + str(par_type) + ' is not supported.')
def __init__(self, dirPath, obsNames=None, create=False, refDirPath=None, name=None, ppExePath=None, ppOutputFile=None, studyConfig=None, # options for creating new study update=False, # options for updating existing study verbose=False, parameters={}): """ Create an instance of HadCM3 class. Default behaviour is to read from dirPath and prohibit updates. :param dirPath -- path to directory where model simulation exists or is to be created :param create (optional with default False). If True create new directory and populate it. Afterwards the ModelSimulation will be readOnly. These options should be specified when creating a new study otherwise they are optional and ignored :param refDirPath -- reference directory. Copy all files from here into dirPath :param name -- name of the model simulation. If not provided will be taken from dirPath :param ppExePath -- path to post proessing executable :param ppOutputFile -- output file for post processing executable :param obsNames -- list of observations to be readin. (see readObs()) :param studyConfig -- written into directory. :param parameters -- a dict on pandas series specifying hte parameter values :param update -- allow updates to the simulation information. :param verbose -- provide verbose output. (See individual methods). Default is False. :returns initialised object. """ # no parameters should be provided unless create or update provided if len(parameters) >0 and not (create or update): raise exceptions.ValueError("Provided parameters but not specified create or update") # call superclass init super(EddieModel, self).__init__(dirPath, obsNames=obsNames, create=create, refDirPath=refDirPath, name=name, ppExePath=ppExePath, ppOutputFile=ppOutputFile, parameters=parameters, # options for creating new study update=update, # options for updating existing study verbose=verbose) if studyConfig is not None: studyConfig.save(filename=os.path.join(self.dirPath,"config.json")) # write study configuration for fakemodel.
def readNameList(self, params, fail=False, verbose=False): """ Read parameter value from registered namelist :param fail: If True fail if param not found :param verbose (Optional -- default False). Provide verbose information. :param params -- a list of parameters. :example self.readNameList(['RHCRIT', 'VF1']) :return:An OrderedDict with the values indexed by the param names """ result = collections.OrderedDict() for param in params: # have it as meta function? if param in self._metaFn: # have a meta funcion -- takes priority. result[param] = self.readMetaNameList(param, verbose=verbose) elif param in self._convNameList: # in the conversion index nlValue = self.readNameListVar(self._convNameList[param], verbose=verbose) if len(nlValue) != 1: raise exceptions.ValueError("Should only have one key") for k in nlValue.keys( ): # in this case shoudl only have one key and we don't want it as a list result[param] = nlValue[k] # just want the value and as single param SHOULD return elif fail: # not found it and want to fail raise exceptions.KeyError("Param %s not found" % param) else: pass return result # return the result.
def __init__(self, model, data=None): """ The constructor initializes the CD trainer with a given model and data. :param model: The model to sample from. :type model: Valid model class. :param data: Data for initialization, only has effect if the centered gradient is used. :type data: numpy array [num. samples x input dim] """ # Store model variable self.model = model # Create the Gibbs-sampler self.sampler = sampler.GibbsSampler(model) # Count the number of parameters parameters = self.model.get_parameters() self.num_parameters = len(parameters) self.hidden_offsets = 0.5 * numx.ones((1, self.model.output_dim)) if data is not None: if self.model.input_dim != data.shape[1]: raise ex.ValueError("Data dimension and model input dimension have to be equal!") self.visible_offsets = data.mean(axis=0).reshape(1, data.shape[1]) else: self.visible_offsets = 0.5 * numx.ones((1, self.model.input_dim)) # Storage variables for the gradients self.parameter_updates = [] for i in range(self.num_parameters): self.parameter_updates.append(numx.zeros(( parameters[i].shape[0], parameters[i].shape[1]), dtype=model.dtype))
def file_chunker(file_handler, chunk_count, chunk_index): """Access a chunk of a file @param: file_handler - the file object @param: chunk_count - the number of section to divide this file into @param: chunk_index - the index of the chunk to read from @yield: lines of the chunk identified by the chunk_index """ if 1 > chunk_count: raise exceptions.ValueError("Chunk count must be > 0 ") if chunk_index > chunk_count: raise exceptions.IndexError("Chunk index out of bound") # seek to the end of file file_handler.seek(0, 2) file_size = file_handler.tell() # in case file is too small chunk_size = max(1, file_size // chunk_count) chunk_start = chunk_index * chunk_size chunk_end = chunk_start + chunk_size # Set the file position at the start of the first line in the chunk if chunk_start == 0: file_handler.seek(0) else: file_handler.seek(chunk_start - 1) file_handler.readline() # Start yielding line within the chunk identified by the chunk index while file_handler.tell() < chunk_end: line = file_handler.readline() if not line: # End of file, readline() include new line character for blank line break # Next line yield line.strip()
def getcamera(band, camera=None): """ If camera is None, define the camera for the given unique band. If camera is a string, reformat it for use as a key to the dicts. :param band: :param camera: :return: """ import exceptions magsys = 'AB' band = band.upper() if camera is None: if band in ZPTDICT[magsys]['ACSWFC'] and band in ZPTDICT[magsys][ 'WFC3UVIS']: raise exceptions.ValueError( "you must specify a camera for filter %s" % band) elif band in ZPTDICT[magsys]['ACSWFC']: camera = 'ACSWFC' elif band in ZPTDICT[magsys]['WFC3IR']: camera = 'WFC3IR' elif band in ZPTDICT[magsys]['WFC3UVIS']: camera = 'WFC3UVIS' else: camera = camera.upper().translate(None, '_-+/ ') if camera.startswith('ACS'): camera = 'ACSWFC' elif camera.endswith('IR'): camera = 'WFC3IR' elif camera.endswith('UVIS'): camera = 'WFC3UVIS' return (camera)
def __init__(self, model): """ Initializes the sampler with the model. :param model: The model to sample from. :type model: Valid model class like BinaryBinary-RBM. """ # Set the model if not hasattr(model, 'probability_h_given_v'): raise ex.ValueError("The model needs to implement the function probability_h_given_v!") if not hasattr(model, 'probability_v_given_h'): raise ex.ValueError("The model needs to implement the function probability_v_given_h!") if not hasattr(model, 'sample_h'): raise ex.ValueError("The model needs to implement the function sample_h!") if not hasattr(model, 'sample_v'): raise ex.ValueError("The model needs to implement the function sample_v!") self.model = model
def n(self, wl_nm, axis="mix"): """ Axis specifies crystal axis, either o, e, or mix. If mix, class instances value for theta sets mixing angle (0 = pure ordinary). Following experimental results from Willer, Blanke, Schade 'Difference frequency generation in AgGaSe2: sellmeier and temperature-dispersion equations', use rational-exponent Sellmeier from Roberts (1996) """ wl_um = wl_nm * 1.0e-3 no = np.sqrt(self.Ao + self.Bo / (np.power(wl_um, self.ao) - self.Co) + self.Fo / (np.power(wl_um, self.bo) - self.Go) + self.Jo / (np.power(wl_um, self.co) - self.Ko) + self.Do / (1. - self.Eo / np.power(wl_um, self.do))) ne = np.sqrt(self.Ae + self.Be / (np.power(wl_um, self.ae) - self.Ce) + self.Fe / (np.power(wl_um, self.be) - self.Ge) + self.Je / (np.power(wl_um, self.ce) - self.Ke) + self.De / (1. - self.Ee / np.power(wl_um, self.de))) if axis == 'mix': return 1.0 / np.sqrt( np.sin(self.theta)**2 / ne**2 + np.cos(self.theta)**2 / no**2) elif axis == 'o': return no elif axis == 'e': return ne raise exceptions.ValueError("Axis was ", str(axis), "; must be 'mix', 'o', or 'e'")
def ang2vec(theta, phi): """ang2vec : convert angles to 3D position vector Parameters ---------- theta : float, scalar or arry-like colatitude in radians measured southward from north pole (in [0,pi]). phi : float, scalar or array-like longitude in radians measured eastward (in [0, 2*pi]). Returns ------- vec : float, array if theta and phi are vectors, the result is a 2D array with a vector per row otherwise, it is a 1D array of shape (3,) See Also -------- vec2ang, rotator.dir2vec, rotator.vec2dir """ if npy.any(theta < 0) or npy.any(theta > npy.pi): raise exceptions.ValueError('THETA is out of range [0,pi]') sintheta = npy.sin(theta) return npy.array([sintheta*npy.cos(phi), sintheta*npy.sin(phi), npy.cos(theta)]).T
def train(self, data, iterations=1000, convergence=0.0, status=False): """ Training the model (full batch). :param data: data for training. :type data: numpy array [num data point, data dimension] :param iterations: Number of iterations :type iterations: int :param convergence: If the angle (in degrees) between filters of two updates is less than the given value, \ training is terminated. :type convergence: double :param status: If true the progress is printed to the console. :type status: bool """ if self.input_dim != data.shape[1]: raise ex.ValueError("Wrong data dimensionality.") # Random init self.projection_matrix = numx.random.randn(data.shape[1], data.shape[1]) projection_matrix_old = numx.copy(self.projection_matrix) for epoch in range(0, iterations): # One iteration hyptan = 1.0 - 2.0 / ( numx.exp(2.0 * numx.dot(data, self.projection_matrix)) + 1.0) self.projection_matrix = ( numx.dot(data.T, hyptan) / data.shape[0] - numx.array( numx.dot(numx.ones( (data.shape[1], 1) ), numx.matrix(numx.mean(1.0 - hyptan**2.0, axis=0)))) * self.projection_matrix) tmp = numx.linalg.inv( numx.dot(self.projection_matrix.T, self.projection_matrix)) ew, ev = numx.linalg.eig(tmp) self.projection_matrix = numx.dot( self.projection_matrix, numx.real(numx.dot(numx.dot(ev, numx.diag(ew)**0.5), ev.T))) angle = numx.mean( numx.diagonal( npext.angle_between_vectors(projection_matrix_old.T, self.projection_matrix.T, True))) if angle < convergence or 180.0 - angle < convergence: break projection_matrix_old = numx.copy(self.projection_matrix) if status is True: import pydeep.misc.measuring as mea mea.print_progress(epoch, iterations, True) # Set results self.mean = numx.zeros((1, data.shape[1])) self.unprojection_matrix = self.projection_matrix.T self.trained = True
def __init__(self, input): ## constructor for class CSquareList # @param input : designation[ | designation [ | designation [ ... ]]] (see below) # =========================================================================== # input is either a parsable string or list of CSquares # If string, instantiate list of CSquare corresponding to string pattern # input string may contain wildcards ("*" or "***") and reference multiple # c-squares (separated by "|") as described in format specification # # Parse input string as follows: # input = designation[ | designation [ | designation [ ... ]]] # designation = tag | tag\* | tag\*\*\* # # List order is left-to-right, with wildcards expanded in reproducable order # set by loops below. Do not check for duplicates nor resolution consistency # =========================================================================== if isinstance(input, basestring): for designation in input.split("|"): if designation[-4:] == ":***": # all subsquares of level above basetag = designation[:-4] for ix in range(10): for iy in range(10): csq_quadrant = 1 if ix>4: csq_quadrant += 1 if iy>4: csq_quadrant += 2 tag = basetag + (":%d%d%d" % (csq_quadrant,iy,ix)) self.append(CSquare(tag)) elif designation[-2:] == ":*": # append corresponding 4 half-squares basetag = designation[:-2] for csq_quadrant in range(1,5): tag = basetag + (":%d" % csq_quadrant) self.append(CSquare(tag)) else: # assume it is a primitive tag self.append(CSquare(designation)) else: if not hasattr(input, "__len__"): raise exceptions.ValueError("CSquareList instantiation: input not a sequence") for i,member in enumerate(input): # validate all members in list if not isinstance(member, CSquare): raise exceptions.ValueError("CSquareList instantiation: element %d is not CSquare instance" % i) self.append(member)
def get_reflection(self): r1 = self.get_t1_reflection() r2 = self.get_t2_reflection() if (r1 != r2): print "\nWARNING: Crystals not matched (c1='%s', c2='%s')\n" % ( r1, r2) raise exceptions.ValueError("Invalid Crystal Arrangement") return r1
def __init__(self, *args): ## constructor for class CSquare: # @param args : eiter a primitive C-Square tag (precedence) or a (lon[deg],lat[deg],resolution[deg]) of an enclosed point # =========================================================================== # args is eiter a primitive C-Square tag (precedence) or a (lon,lat,resolution) tuple # corresponding to a point enclosed by the desired C-Square # =========================================================================== if isinstance(args[0], basestring): if len(args)>1: raise exceptions.ValueError("CSquare instantiation: expect no args beyond tag" ) self.bbx, self.resolution = tag2bbox(args[0]) self.id = args[0] else: if len(args) != 3: raise exceptions.ValueError("CSquare instantiation: expect args (lon,lat,resolution)") self.id = tag_of_enclosing_csquare(*args) self.bbx, self.resolution = tag2bbox(self.id)
def getState(next_waypoint, light): for state in State.AVAILABLE_STATES: if state.next_waypoint == next_waypoint and state.light == light: return state # State not found raise exceptions.ValueError( 'State not found: next_waypoint {}, light {}'.format( next_waypoint, light))
def edge_lengths(self): r""" Return the dictionary of edge lengths. """ res = {} for u, v in self._graph.edges(labels=False): s = self._parametrization[u] - self._parametrization[v] l = s.inner_product(s) if self._par_type == 'rational': if not l in self._field.constant_field(): raise exceptions.ValueError('The edge ' + str((u, v)) + ' does not have constant length.') l = self._field.constant_field()(l) elif self._par_type == 'symbolic': l = l.simplify_full() if not l.simplify_full().is_constant(): raise exceptions.ValueError('The edge ' + str((u, v)) + ' does not have constant length.') res[(u, v)] = sqrt(l) return res
def __init__(self, model, num_samples, num_chains=3, betas=None): """ Initializes the sampler with the model. :param model: The model to sample from. :type model: Valid model Class. :param num_samples: The number of samples to generate. .. Note:: Optimal performance (ATLAS,MKL) is achieved if the number of samples equals the \ batchsize. :type num_samples: :param num_chains: The number of Markov chains. :type num_chains: int :param betas: Array of inverse temperatures to sample from, its dimensionality needs to equal the number of \ chains or if None is given the inverse temperatures are initialized linearly from 0.0 to 1.0 \ in 'num_chains' steps. :type betas: int, None """ if not model._fast_PT: raise ex.NotImplementedError("Only more efficient for Binary RBMs") # Check and set the model if not hasattr(model, 'probability_h_given_v'): raise ex.ValueError("The model needs to implement the function probability_h_given_v!") if not hasattr(model, 'probability_v_given_h'): raise ex.ValueError("The model needs to implement the function probability_v_given_h!") if not hasattr(model, 'sample_h'): raise ex.ValueError("The model needs to implement the function sample_h!") if not hasattr(model, 'sample_v'): raise ex.ValueError("The model needs to implement the function sample_v!") if not hasattr(model, 'energy'): raise ex.ValueError("The model needs to implement the function energy!") if not hasattr(model, 'input_dim'): raise ex.ValueError("The model needs to implement the parameter input_dim!") self.model = model # Initialize persistent Markov chains to Gaussian random samples. self.num_samples = num_samples self.chains = model.sample_v(numx.random.randn(num_chains * self.num_samples, model.input_dim) * 0.01) # Sets the beta values self.num_betas = num_chains if betas is None: self.betas = numx.linspace(0.0, 1.0, num_chains).reshape(num_chains, 1) else: self.betas = self.betas.reshape(numx.array(betas).shape[0], 1) if self.betas.shape[0] != num_chains: raise ex.ValueError("The number of betas and Markov chains must be equivalent!") # Repeat betas batchsize times self.betas = numx.tile(self.betas.T, self.num_samples).T.reshape(num_chains * self.num_samples, 1) # Indices of the chains on temperature beta = 1.0 self.select_indices = numx.arange(self.num_betas - 1, self.num_samples * self.num_betas, self.num_betas)
def addChild(self, bitfield): if (self.__length < (bitfield.position() + len(bitfield))): raise (exceptions.ValueError('Bitfield \'%s\' is out of bounds.' % (name))) bitfield.__parent = self self.__children[bitfield.name()] = bitfield
def calculate_overlap(self, A, B): """ calculate overlap integral between fields A and B. A & B must be integers between 0-2 (0 = pump, 1 = signal, 3 = idler.)""" if (type(A) is not int) or (type(B) is not int): e = exceptions.TypeError('A & B must both be integers.') raise e if A < 0 or A > 3 or B < 0 or B > 3: e = exceptions.ValueError('A & B must be in range [0,3].') raise e return (self.waists[A] + self.waists[B]) / 2.0
def value(self, v=None): if (self.__parent is None): current_value = self.__value else: current_value = self.__parent.value() mask = self.__createMask() if (v is None): return ((current_value & mask) >> self.__position) if (type(v) == types.StringType): for item in self.__cipher.items(): if (item[1] == v): v = item[0] break if (type(v) == types.StringType): raise exceptions.ValueError(v + ' is an unknown symbol.') if (v > long(mask)): raise exceptions.ValueError( 'Value exceeds length of this bit field.') new_value = (current_value & ~mask) | (v << self.__position) if (self.__parent is None): self.__value = new_value else: self.__parent.value(new_value) return (self)