def test_updatestate(): gs = HackingState("TestReflectionString", "Il Pentest sta verificando se la stringa è riflessa", False) gs.setAction( Action( "NameRequest", "Invia la richiesta con una testNTT, controlla tutte le pagine per verificare se la stringa è riflessa" )) observation1 = Observation("ReflectionString", "La stringa e' riflessa") observation2 = Observation("NotReflectionString", "La stringa non e' riflessa") newHS = HackingState("TestReflectionType", "Il Pentest sta verificando il tipo di riflessione", False) actionToAnalyze = Action("CheckReflectionType", "Analizza la riflessione dove è avvenuta") newHS.setAction(actionToAnalyze) failState = HackingState("NoXSS", "No xss found", False) gs.addObservationState(observation1, newHS) gs.addObservationState(observation2, failState) hg = HackingGoal("xss", "goal", gs) currentObservation = Observation("ReflectionString", "La stringa e' riflessa") hg.acquireObservation(currentObservation) theActionToDo = hg.suggestAction() assert theActionToDo == actionToAnalyze
def deleteandrestart(self): self.speak("WARNING! You're about to erase all files in {0}".format( self.obs.workingDirectory)) if 'y' in self.input( " are you sure you're okay with this? [y,N]").lower(): if 'y' in self.input(" for realsies? [y,N]").lower(): shutil.rmtree(self.obs.workingDirectory) self.obs = Observation(self.filename)
def test_id(): cat1 = "OBSERVATION_ONE" cat2 = "OBSERVATION_TWO" cat3 = "OBSERVATION_THREE" be2 = BaseElement("secondObservation", "The second observation", cat2) be3 = BaseElement("thirdObservation", "The third observation", cat3) be = BaseElement("firstObservation", "The first observation", cat1) d = { cat1: be, cat3: be3, cat2: be2 } o = Observation(d) idObs = o.getID() assert idObs == "firstObservation|||secondObservation|||thirdObservation"
def putJSONMemory(self, data, attributePool: AttributePool, capsuleByName): for routeData in data: memoryList = [] for memory in routeData["memory"]: inputObs = [] for obs in memory: caps = capsuleByName(obs["name"]) route = caps.getRouteByName(obs["route"]) prob = obs["probability"] attrDict = {} for attr in obs["attributes"]: attrDict[caps.getAttributeByName( attr["attribute"])] = attr["value"] inputObs.append( Observation(caps, route, [], attrDict, prob)) memoryList.append(route.observationFromInputs(inputObs)) currentRoute = self.getRouteByName(routeData["route"]) if currentRoute is None: self.addSemanticRoute(memoryList[0].getInputObservations(), attributePool) memoryList.pop(0) currentRoute.addSavedObservations(memoryList) else: currentRoute.addSavedObservations(memoryList)
def ParseDataToObsList(filename): """ returns a list of observations of the person as in input .csv file, which is filename param """ observationList = [ ] #list of the person observations, each obs contains latitude, longitude, start_time and duration as in input file file = open(filename) #open and reader = csv.reader(file) #read input file of the person next(reader, None) #skip file header try: for e in reader: #e is stored as read line from input in reader #get latitude, longitude, start_time and duration at their corresponding indices of e lat = e[0] lon = e[1] startTime = getDateTimeFromString(e[2]) duration = e[3] #create an object of Observation class using extracted latitude, longitude, start_time and duration obs = Observation(lat, lon, startTime, duration) observationList.append( obs) #and put the object to the observation list except IndexError as error: #index error when processing list print(error) return None except Exception as exception: print(exception) return None return observationList
def __init__(self, obs=None, binsize=100, remake=False, noiseassumedforplotting=0.001, label=''): '''Initialize a transmission spectrum object, using a normal Observation file.''' Talker.__init__(self, line=200) self.remake = remake # load the observation structure for this file if type(obs) == str: self.obs = Observation(obs, nods9=True) else: self.obs = obs # load the self.name = self.obs.name self.binsize = binsize self.label = 'defaultFit' self.maskname = 'defaultMask' self.unit = 10 self.unitstring = 'nm' self.noiseassumedforplotting = noiseassumedforplotting self.loadLCs()
def process(segmentFilename): """ @param segmentFileName The path to the segmentation.data dataset This method takes the segmentation data and turns it into a set of Observations """ with open(segmentFilename, newline='') as file: reader = csv.reader(file) segmentOut = [] lineCount = 0 for line in reader: lineCount += 1 if lineCount <= 5: # first five lines are a header continue segmentOut.append(line) observations = [] for line in segmentOut: label = line[0] features = [] for feature in line[1:]: # all features are continuous features.append(ContinuousFeature(float(feature))) observations.append(Observation(label, features)) return observations
def createObservation(self, header, row): """Create an action from a row :row: the row :returns: the parsed action """ idRow = row[0] observationElements = {} for i in range(len(header)): if CSVObservations.DELIMITER_OBSERVATION in header[i]: # Take all the actions of the category category = header[i] idObservation = row[i] # Get all elements of the category categoryElements = self.actionElements.getElementsByCategory( category) # Get the currect value for that action if idObservation != "": obsInstance = categoryElements.getElement(idObservation) if obsInstance is None: print "WARN: no %s idObservation" % (idObservation) observationElements[category] = obsInstance else: obsInstance = categoryElements.getElement(idObservation) obsInstance = BaseElement.empty(category) observationElements[category] = obsInstance return Observation(observationElements, idRow)
def setup(self): # load in the observation file for this object self.obs = Observation(self.filename) self.display = loupe() #''mosasaurus', # xsize=self.obs.xsize*self.obs.displayscale, # ysize=self.obs.ysize*self.obs.displayscale) # create a night object, associated with this observation self.night = Night(self.obs) # set up the Calibration self.calib = Calibration(self) # create a mask self.mask = Mask(self)
def testEqualityObs(): e1 = BaseElement.empty("TEST") cat1 = "OBSERVATION_ONE" cat2 = "OBSERVATION_TWO" cat3 = "OBSERVATION_THREE" be2 = BaseElement("secondObservation", "The second observation", cat2) be3 = BaseElement("thirdObservation", "The third observation", cat3) be = BaseElement("firstObservation", "The first observation", cat1) d = { cat1: be, cat3: be3, cat2: be2, "TEST": e1 } o = Observation(d) o2 = Observation(d) assert o == o2
def submit_observation(self, direction): totalDistanceSeen = 0 next_pos = self.maze.next_point_in_direction(self.pos, direction) while self.maze.value_at_point(next_pos) == 0: next_pos = self.maze.next_point_in_direction(next_pos, direction) totalDistanceSeen += 1 observation = Observation(self.pos, totalDistanceSeen, direction) self.brain.accept_information(observation) return totalDistanceSeen
def test_withEmptyElements(): e1 = BaseElement.empty("TEST") cat1 = "OBSERVATION_ONE" cat2 = "OBSERVATION_TWO" cat3 = "OBSERVATION_THREE" be2 = BaseElement("secondObservation", "The second observation", cat2) be3 = BaseElement("thirdObservation", "The third observation", cat3) be = BaseElement("firstObservation", "The first observation", cat1) d = { cat1: be, cat3: be3, cat2: be2, "TEST": e1 } o = Observation(d) idObs = o.getID() assert idObs == "firstObservation||||||secondObservation|||thirdObservation"
def parseJSON(self, json_obj): obs_list=[] js_obs=json_obj['observations'] for obs in js_obs: win=np.array(obs['window']) calCentroid_AC=obs['calCentroidAC']/pix_size_AC+5.5 calCentroid_AL=obs['calCentroidAL']/pix_size_AL+8.5 o = Observation(self, obs['id'], np.swapaxes(win,0,1), obs['integrationTime'], obs['transitid'], obs['timestamp'], obs['day'],obs['ACmotion'],obs['ACrate'], calCentroid_AC, calCentroid_AL) obs_list.append(o) return obs_list
def initializeFromObs(self, obs): '''Initialize a spectrum from an observation filename or instance.''' # load the observation structure for this file if type(obs) == str: self.obs = Observation(obs, nods9=True) else: self.obs = obs # keep track of the name and binsize self.name = self.obs.name
def test_displayobservation(): gs = HackingState("TestReflectionString", "Il Pentest sta verificando se la stringa è riflessa", False) gs.setAction( "Invia la richiesta con una testNTT, controlla tutte le pagine per verificare se la stringa è riflessa" ) observation1 = Observation("La stringa e' riflessa") observation2 = Observation("La stringa non e' riflessa") newHS = HackingState("TestReflectionType", "Il Pentest sta verificando il tipo di riflessione", False) failState = HackingState("NoXSS", "No xss found", False) gs.addObservationState(observation1, newHS) gs.addObservationState(observation2, failState) hg = HackingGoal("xss", "goal", gs) avObs = hg.displayCurrentObservations() assert len(avObs) == 2 assert avObs[0] == observation1 assert avObs[1] == observation2
def backwardPass(self, observation: Observation, withBackground: bool): # Observation with only outputs filled takenRoute = observation.getTakenRoute() if takenRoute is None: # TODO: Choose a better route # If no route is specified, we just take the first takenRoute = self._routes[0] outputs = takenRoute.runGFunction( observation.getOutputsList(), isTraining=withBackground) # Attribute - List of Values capsAttrValues = takenRoute.pairInputCapsuleAttributes( outputs) # Capsule - {Attribute - List of Values} obsList = {} for capsule, attrValues in capsAttrValues.items(): obsList[capsule] = [] for index in range(len(list(attrValues.values())[0])): obsList[capsule].append( Observation(capsule, None, [], attrValues, observation.getInputProbability(capsule), index)) observation.addInputObservation(obsList[capsule][-1]) return obsList # Capsule - List of Observations (with only outputs filled)
def show(filename='wasp94_140801.obs', binsize=25, vmin=0.98, vmax=1.02, remake=False): obs = Observation(filename) cube = Cube(obs, remake=remake) cube.makeMeanSpectrum() #cube.loadSpectra() #cube.convolveCube(width=5.0) #cube.shiftCube() cube.makeLCs(binsize=binsize)
def reduce(filename='wasp94_140801.obs'): # generate an observation object obs = Observation(filename) # load the headers for this observation obs.loadHeaders() # create a night object, associated with this observation night = Night(obs) # create an observing log from all the image headers from this night night.obsLog() # set up the calibration calib = Calibration(obs) # loop through the CCD's needed for this observation, and make sure they are stitched #for n in obs.nNeeded: # ccd = CCD(obs,n=n,calib=calib) # ccd.createStitched(visualize=True) mask = Mask(calib) for a in mask.apertures: a.displayStamps(a.images) a.extractAll(remake=True)
def construct_worldstate(self, response): """Construct a world state based upon WS request""" i = 0; worldstate = WorldState() visual_observations = [] holding_object = None; O = Observation() #print "Check response:", response,response[1] for i in range(len(response)): if response[i] == "observation": O = Observation() b = i+1 while (b <len(response)): if response[b] == "observation": if O.name =="visual": if O.props['colour'] !="hand": self.add_observation(worldstate, O) else: self.add_observation(worldstate, O) break elif response[b] == "name": #print "Name:", response[b+1] O.name = response[b+1]; b = b+2 elif response[b] == "Self_flag": #print "Self_flag:", response[b+1] if int(response[b+1]) == 1: O.self_flag = True; b = b+2; continue if int(response[b+1]) == 0: O.self_flag = False; b = b+2; continue else: try: p_value = float(response[b+1]) except: try: p_value = int(response[b+1]) except: p_value = str(response[b+1]) #print "Props value:",response[b], p_value O.set_concrete_var(response[b], p_value); b += 2 if O.name =="visual": if O.colour !="hand": self.add_observation(worldstate, O) else: self.add_observation(worldstate, O) return worldstate
def observationFromInputs(self, inputObservations : list, forcedProbability : float = 1.0): inputs = {} # Attribute - List of Values for obs in inputObservations: newInputs = obs.getOutputs(True) # Attribute - Value for newAttr, newValue in newInputs.items(): if newAttr in inputs: inputs[newAttr].append(newValue) else: inputs[newAttr] = [newValue] outputs = self.runGammaFunction(inputs, False) # TODO: Use actual probability return Observation(self._parentCapsule, self, inputObservations, outputs, min(forcedProbability, 1.0))
def getObservation(self, index: int): if index >= 0: currentIndex = index for route in self._routes: if index < route.getNumObservations(): return route.getObservation(index) currentIndex = currentIndex - route.getNumObservations() if index < len(self._pixelObservations): return self._pixelObservations[index] # Otherwise, Zero Observation zeroDict = {} for attribute in self._attributes.values(): zeroDict[attribute] = 0.0 return Observation(self, None, [], zeroDict, 0.0)
def fit(filename='wasp94_140801.obs', binsize=25, remake=False): obs = Observation(filename, nods9=True) cube = Cube(obs) if remake: cube.makeLCs(binsize=binsize) cube.loadLCs(binsize=binsize) tm = fitTLC.TM(e=0.0, a_over_rs=0.055 * 1.496e13 / 1.45 / 6.96e10, b=0.17, u1=0.1, u2=0.1, rp_over_rs=np.sqrt(0.01197), w=np.pi / 2.0, period=3.9501907, t0=2456416.40138) for lc in cube.lcs: tlc = fitTLC.TLC(lc.lc['bjd'], lc.lc['raw_counts']) tm.plot(tlc) return cube
def process(abaloneFilename): """ @param abaloneFileName The path to the abalone.data dataset This method takes the abalone data and turns it into a set of Observations """ with open(abaloneFilename, newline='') as file: reader = csv.reader(file) carOut = [] for line in reader: className = line[-1] features = [] for index, feature in enumerate(line[:-1]): if index == 0: features.append(CategoricalFeature(feature)) else: features.append(ContinuousFeature(float(feature))) carOut.append(Observation(className, features)) return (carOut)
def predict(self, observations: dict, external: list): newObservations = {} for caps, obsList in observations.items(): newObservations[caps] = [] for receiverObs in obsList: effects = [] for senderObs in [ x for senderObsList in observations.values() for x in senderObsList ]: if senderObs != receiverObs: triplet, distance = RelationTriplet.generate( senderObs, receiverObs, self._capsuleNetwork.getAttributePool(), self._capsuleNetwork) effects.append( self._neuralNetPhiR.forwardPass(triplet)) aggregated = self.aggregate(effects, external, receiverObs) result = self._neuralNetPhiO.forwardPass(aggregated) attributes = RelationTriplet.mapAttributes( self._capsuleNetwork.getAttributePool(), caps, result) accelerations = RelationTriplet.mapAttributes( self._capsuleNetwork.getAttributePool(), caps, result, HyperParameters.MaximumAttributeCount) newObs = Observation(caps, receiverObs.getTakenRoute(), receiverObs.getInputObservations(), attributes, receiverObs.getProbability()) newObs.linkPreviousObservation(receiverObs) for attr, accel in accelerations.items(): accelerations[attr] = ( (accel * 2.0) - 1.0) * HyperParameters.AccelerationScale newObs.setAccelerations(accelerations) newObservations[caps].append(newObs) return newObservations
def putJSON(self, data): # Only needs to load semantic capsules and data semCaps = {} for layerData in data["semanticLayers"]: for capsData in layerData["semanticCapsules"]: capsName = capsData["name"] obsList = [] # First Route saved/loaded independently, as it is required to create the # Capsule. for obsData in capsData["firstRouteObservations"]: obsCaps = self.getCapsuleByName(obsData["name"]) obsRoute = obsCaps.getRouteByName(obsData["route"]) obsProb = obsData["probability"] attrDict = {} for attrData in obsData["attributes"]: attrDict[obsCaps.getAttributeByName( attrData["attribute"])] = attrData["value"] obsList.append( Observation(obsCaps, obsRoute, [], attrDict, obsProb)) semCaps[capsName] = self.addSemanticCapsule( capsName, obsList, 0) # Adding remaining memory if "remainingMemory" in capsData: semCaps[capsName].putJSONMemory( capsData["remainingMemory"], self._attributePool, lambda name: self.getCapsuleByName(name)) if "metaLearner" in data: self._metaLearner.putJSON(data["metaLearner"]) return semCaps # List of Semantic Capsules
def producePrimitiveObservations(self, observation: Observation): if observation.getCapsule() not in self._primitiveCapsules: outputObsList = [] if not observation.getInputObservations(): newObsDict = observation.getCapsule().backwardPass( observation, False) observation.clearInputObservations() for newObsList in newObsDict.values(): for newObs in newObsList: outputObsList = outputObsList + self.producePrimitiveObservations( newObs) else: for newObs in observation.getInputObservations(): outputObsList = outputObsList + self.producePrimitiveObservations( newObs) return outputObsList # List of Observations for Primitive Capsules else: return [observation ] # List of Observation for this Primitive Capsules
def add(self, caller=None): """Adds an observation to the target world state from the GUI. Used for constructing targets for chains.""" otype = self.builder.get_object("cmbObservation").get_active_text() o = Observation() o.name = otype properties = o.get_properties() dlg = None """if otype == "Stack": dlg = self.builder.get_object("msgProperty") dlg.set_transient_for(self.requestWin) dlg.set_property("text", "Number of objects:") dlg.run() objs = int(self.builder.get_object("entProperty").get_text()) for i in range(0, objs): self.builder.get_object("entProperty").set_text("") self.builder.get_object("entProperty").grab_focus() dlg.set_property("text", "Object %d:" % i) dlg.run() value = self.builder.get_object("entProperty").get_text() o.set_concrete_var("object%d"%i, value) else:""" dlg = self.builder.get_object("msgProperty") dlg.set_transient_for(self.requestWin) dlg.set_property("text", "Enter properties and values") dlg.run() value = self.builder.get_object("entProperty").get_text() self.builder.get_object("entProperty").set_text("") self.builder.get_object("entProperty").grab_focus() value = value.split(); m = 0 while m<len(value): #print "M & values:", m, value[m], value[m+1] o.set_concrete_var(value[m], value[m+1]) m = m+2 if dlg: dlg.hide() self.requestState.add_observation(o) self.requestTxt.set_text("Current state to request:\n\n%s" % self.requestState.to_string()) self.showBtn.set_sensitive(True) self.executeBtn.set_sensitive(True)
def __init__(self): Observation.__init__(self) self.schema = None self.schema_var = None self.successful_var = None self.successful = False
def generate(senderObservation: Observation, receiverObservation: Observation, attributePool: AttributePool, capsNet: CapsuleNetwork): senderOutputs = senderObservation.getOutputs() receiverOutputs = receiverObservation.getOutputs() senderVelocities = senderObservation.getVelocities( HyperParameters.TimeStep) receiverVelocities = receiverObservation.getVelocities( HyperParameters.TimeStep) # Triplet Format: # Sender -- Symbol | Attributes | Velocities | Static/Dynamic | Rigid/Elastic # Receiver -- Symbol | Attributes | Velocities | Static/Dynamic | Rigid/Elastic # Relation -- Distance | Degrees-Of-Freedom | Sender Normal | Receiver Normal totalObjectEntries = (HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 2 * HyperParameters.DegreesOfFreedom) triplet = [0.0] * RelationTriplet.tripletLength() # Symbols if senderObservation.getCapsule().getOrderID( ) < HyperParameters.MaximumSymbolCount: triplet[senderObservation.getCapsule().getOrderID()] = 1.0 if receiverObservation.getCapsule().getOrderID( ) < HyperParameters.MaximumSymbolCount: triplet[totalObjectEntries + receiverObservation.getCapsule().getOrderID()] = 1.0 # Attributes / Velocities for i in range(HyperParameters.MaximumAttributeCount): triplet[HyperParameters.MaximumSymbolCount + HyperParameters.MaximumAttributeCount + i] = 0.5 triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + HyperParameters.MaximumAttributeCount + i] = 0.5 for outputAttribute, outputValue in senderOutputs.items(): pos = attributePool.getAttributeOrder(outputAttribute) if pos > -1: triplet[HyperParameters.MaximumSymbolCount + pos] = outputValue triplet[HyperParameters.MaximumSymbolCount + HyperParameters.MaximumAttributeCount + pos] = (senderVelocities[outputAttribute] + 1.0) * 0.5 for outputAttribute, outputValue in receiverOutputs.items(): pos = attributePool.getAttributeOrder(outputAttribute) if pos > -1: triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + pos] = outputValue triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + HyperParameters.MaximumAttributeCount + pos] = (receiverVelocities[outputAttribute] + 1.0) * 0.5 DQA, DSA = senderObservation.getCapsule().getPhysicalProperties() DQB, DSB = receiverObservation.getCapsule().getPhysicalProperties() # Static / Dynamic triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount] = DQA[0] triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 1] = DQA[1] triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 2] = DQA[2] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount] = DQB[0] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 1] = DQB[1] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 2] = DQB[2] # Rigid / Elastic triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 3] = DSA[0] triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 4] = DSA[1] triplet[HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 5] = DSA[2] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 3] = DSB[0] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 4] = DSB[1] triplet[totalObjectEntries + HyperParameters.MaximumSymbolCount + 2 * HyperParameters.MaximumAttributeCount + 5] = DSB[2] # Distance dist, norm1, norm2 = capsNet.distance(senderObservation, receiverObservation) triplet[2 * totalObjectEntries] = dist # Degrees-Of-Freedom # TODO: triplet[2 * totalObjectEntries + 1] = 1.0 triplet[2 * totalObjectEntries + 2] = 1.0 triplet[2 * totalObjectEntries + 3] = 1.0 # Normal: for i in range(HyperParameters.Dimensions): triplet[2 * totalObjectEntries + 1 + HyperParameters.DegreesOfFreedom + i] = (norm1[i] + 1.0) * 0.5 triplet[2 * totalObjectEntries + 1 + HyperParameters.DegreesOfFreedom + HyperParameters.Dimensions + i] = (norm2[i] + 1.0) * 0.5 return triplet, dist
def generateInteractionSequence(self, capsNet: CapsuleNetwork, width: int, height: int, folder: str, idname: str): # Generate Images in the folder with name id + "." + sequence_index + file_format # 0 = No Interaction # 1 = Newtonian Collision interType = random.randint(0, 1) # 0 = Image Before # 1 = Image at Interaction # 2 = Image After positionA = [None, None, None] positionB = [None, None, None] positionA[1] = np.array( [0.5, 0.5]) #np.array([random.random(), random.random()]) # TODO: Assuming Circles for now massA = random.random() * 0.2 + 0.1 massB = random.random() * 0.2 + 0.1 intA = random.random() intB = random.random() strA = min(random.random(), (0.333333 - massA) * 10.0) strB = min(random.random(), (0.333333 - massB) * 10.0) rotA = random.random() rotB = random.random() awayDir = np.array([random.random() - 0.5, random.random() - 0.5]) awayDir = awayDir / np.linalg.norm(awayDir) velMod = 0.5 if 1 == 1: #interType == 10: # No Interaction maxDist = random.random() awayVec = awayDir * ((massA + massB + (strA + strB) * 0.1) * 0.5 + maxDist + 0.02) positionB[1] = positionA[1] + awayVec # Velocities velA = np.array([random.random() - 0.5, random.random() - 0.5]) * min( maxDist, velMod * random.random()) velB = np.array([random.random() - 0.5, random.random() - 0.5]) * min( maxDist, velMod * random.random()) positionA[0] = positionA[1] - velA positionA[2] = positionA[1] + velA positionB[0] = positionB[1] - velB positionB[2] = positionB[1] + velB elif interType == 1: # Interaction awayVec = awayDir * ((massA + massB + (strA + strB) * 0.1) * 0.5) positionB[1] = positionA[1] + awayVec # Velocities velA = np.array([random.random() - 0.5, random.random() - 0.5 ]) * velMod * random.random() velB = np.array([random.random() - 0.5, random.random() - 0.5 ]) * velMod * random.random() if np.dot(velA, velB) < 0: # Flying away from each other -> Reverse one Velocity velA = -velA if (np.dot(velA, awayDir) < 0 and np.dot(velB, awayDir) < 0 and np.linalg.norm(velB) < np.linalg.norm(velA)) or \ (np.dot(velA, awayDir) > 0 and np.dot(velB, awayDir) > 0 and np.linalg.norm(velA) < np.linalg.norm(velB)): # A Flying away from B and B flying towards A (or B Flying away from A and A flying towards B) # Only collide if B (A) is faster than A (B), thus we switch velocities velTemp = velA velA = velB velB = velTemp positionA[0] = positionA[1] - velA positionB[0] = positionB[1] - velB tempB = np.dot((velB - velA), awayVec) / (math.pow( np.linalg.norm(awayVec), 2.0)) resultVelB = velB - (2 * massA / (massA + massB)) * tempB * awayVec tempA = np.dot((velA - velB), -awayVec) / (math.pow( np.linalg.norm(awayVec), 2.0)) resultVelA = velA - (2 * massB / (massA + massB)) * tempA * (-awayVec) positionA[2] = positionA[1] + resultVelA positionB[2] = positionB[1] + resultVelB attributesA = [None, None, None] attributesB = [None, None, None] for i in range(3): attributesA[i] = np.zeros(HyperParameters.MaximumAttributeCount) attributesB[i] = np.zeros(HyperParameters.MaximumAttributeCount) attributesA[i][self._xPosOffset] = positionA[i][0] attributesA[i][self._yPosOffset] = positionA[i][1] attributesA[i][self._sizeOffset] = massA attributesA[i][self._intOffset] = intA attributesA[i][self._strOffset] = strA attributesA[i][self._rotOffset] = rotA attributesA[i][self._arOffset] = 1.0 attributesB[i][self._xPosOffset] = positionB[i][0] attributesB[i][self._yPosOffset] = positionB[i][1] attributesB[i][self._sizeOffset] = massB attributesB[i][self._intOffset] = intB attributesB[i][self._strOffset] = strB attributesB[i][self._rotOffset] = rotB attributesB[i][self._arOffset] = 1.0 # Render Images and Save circCaps = capsNet.getCapsuleByName("TestPrimitives.Circle") for i in range(3): attrDictA = {} for j in range(len(attributesA[i])): attrDictA[circCaps.getAttributeByName( self._attributePool.getAttributeNameByOrder( j))] = attributesA[i][j] attrDictB = {} for j in range(len(attributesB[i])): attrDictB[circCaps.getAttributeByName( self._attributePool.getAttributeNameByOrder( j))] = attributesB[i][j] observationA = Observation(circCaps, circCaps._routes[0], [], attrDictA, 1.0) observationB = Observation(circCaps, circCaps._routes[0], [], attrDictB, 1.0) obs = {circCaps: [observationA, observationB]} imageReal, ignore1, ignore2 = capsNet.generateImage( width, height, obs) pixels = [0.0] * (width * height * 3) for yy in range(height): for xx in range(width): pixels[(yy * width + xx) * 3] = imageReal[(yy * width + xx) * 4] pixels[(yy * width + xx) * 3 + 1] = imageReal[(yy * width + xx) * 4] pixels[(yy * width + xx) * 3 + 2] = imageReal[(yy * width + xx) * 4] scipy.misc.imsave(folder + idname + "." + str(i) + ".png", np.reshape(pixels, [height, width, 3])) return
save_path=prm["save_path"], path_Z0_2018=None, path_Z0_2019=None, path_to_file_npy=prm["path_to_file_npy"], verbose=prm["verbose"], load_z0=False, save=False) # BDclim BDclim = Observation(prm["BDclim_stations_path"], prm["BDclim_data_path"], begin=prm["begin"], end=prm["end"], select_date_time_serie=prm["select_date_time_serie"], path_vallot=prm["path_vallot"], path_saint_sorlin=prm["path_saint_sorlin"], path_argentiere=prm["path_argentiere"], path_Dome_Lac_Blanc=prm["path_Dome_Lac_Blanc"], path_Col_du_Lac_Blanc=prm["path_Col_du_Lac_Blanc"], path_Muzelle_Lac_Blanc=prm["path_Muzelle_Lac_Blanc"], path_Col_de_Porte=prm["path_Col_de_Porte"], path_Col_du_Lautaret=prm["path_Col_du_Lautaret"], GPU=prm["GPU"]) if not(prm["GPU"]): number_of_neighbors = 4 BDclim.update_stations_with_KNN_from_NWP(number_of_neighbors, AROME) BDclim.update_stations_with_KNN_from_MNT_using_cKDTree(IGN) del AROME """