Exemplo n.º 1
0
def getGeoMag1YVar(geometry, feature, parent):
    geom_pt = geometry.asPoint()
    today = datetime.datetime.now()
    y1 = today + datetime.timedelta(days=365)
    geomag_now = geomag.declination(geom_pt.y(), geom_pt.x())
    geomag_y1 = geomag.declination(geom_pt.y(), geom_pt.x(), time=y1.date())
    return geomag_y1 - geomag_now
Exemplo n.º 2
0
def getNorthAngle(latitude, longitude):
    magDec = gm.declination(latitude, longitude)
    accel_mag = get_accel_mag()
    acceleration = accel_mag["acceleration"]
    magnetic = accel_mag["magnetic"]
    while (acceleration[0]**2 + acceleration[1]**2 + acceleration[2]**2 < 56.25
           or acceleration[0]**2 + acceleration[1]**2 + acceleration[2]**2 >
           156.25):
        accel_mag = get_accel_mag()
        acceleration = accel_mag["acceleration"]
        magnetic = accel_mag["magnetic"]
    if (magnetic[0] != 0):
        magNorth = degrees(atan(magnetic[1] / magnetic[0]))
        if (magnetic[0] < 0):
            magNorth += 180
        if (magNorth < 0):
            magNorth += 360
    else:
        if (magnetic[1] < 0):
            magNorth = 270
        else:
            magNorth = 90

    trueNorth = magNorth + magDec
    if (trueNorth < 0):
        trueNorth += 360
    elif (trueNorth > 360):
        trueNorth -= 360
    return trueNorth
Exemplo n.º 3
0
def mag_var(netCDFfile):

    print(netCDFfile)

    ds = Dataset(netCDFfile, 'a')

    lat = ds.variables['LATITUDE'][:]
    lon = ds.variables['LONGITUDE'][:]
    nom_depth = ds.variables['NOMINAL_DEPTH'][:]

    time = ds.variables['TIME']
    dt = num2date(time[:], units=time.units, calendar=time.calendar)

    len_time = len(dt)
    time_mid = dt[int(len_time/2)]
    date = time_mid.date()  # geomag wants date object not datetime

    dec = geomag.declination(lat, lon, time=date)

    print("calc for ", time_mid, lat, lon, dec)

    ds.setncattr("geomagnetic_varition", dec)
    ds.setncattr("geomagnetic_varition_comment", "calculation for %s at LATITUDE and LONGITUDE using https://pypi.org/project/geomag/" % date)

    ds.close()

    return netCDFfile
Exemplo n.º 4
0
 def updated(self, channel):
     if self.gps_utc - self.last_time > 10:
         self.last_time = self.gps_utc
         self.magnetic_declination = declination(self.gps_lat, self.gps_lng,
                                                 self.gps_altitude)
         self.publish()
         print("Magnetic Declination: %.1f" % (self.magnetic_declination, ))
Exemplo n.º 5
0
def MagDeclin(gLat, gLong):
    declin = geomag.declination(gLat,gLong)
    MagDeclinlination = round(declin,2)
    if MagDeclinlination < 0:
        Cardinal ="W"
    else:
        Cardinal ="E"
    MagDecTxt = str(abs(MagDeclinlination)) + " " + Cardinal
    return(MagDecTxt)
Exemplo n.º 6
0
def unit_vectors(exif_obj):
    """Compute east and north unit vectors given the camera yaw."""
    camera_yaw = exif_obj["camera_yaw"]
    lat, lon = exif_obj["img_lat"], exif_obj["img_lon"]
    declination = geomag.declination(lat, lon)
    camera_yaw += declination  # compensate for magnetic variation
    alpha = camera_yaw * np.pi / 180
    n = [-np.cos(alpha), -np.sin(alpha)]
    e = [-np.sin(alpha), np.cos(alpha)]
    return np.array(n), np.array(e)
Exemplo n.º 7
0
	def updateGui(self):
		if self.hasNewPayloadGps:
			self.parent.ids.station_lat.text = str(self.latDeg)
			self.parent.ids.station_long.text = str(self.lonDeg)
			self.parent.ids.station_alt.text = str(self.altMeters)
			self.parent.ids.station_trueHeading.text = str(self.imuX)
			self.parent.ids.station_time.text = str(self.gpsTime)
			self.magneticVariation = geomag.declination(
				dlat=self.latDeg, dlon=self.lonDeg, h=self.altMeters
			)
			self.hasNewPayloadGps = False
Exemplo n.º 8
0
def calculate_mag_var(position, date):
	if position[0] and position[2] and date:
		try:
			var=float(geomag.declination(position[0], position[2], 0, date))
			var=round(var,1)
			if var >= 0.0:
				mag_var=[var,'E']
			if var < 0.0:
				mag_var=[var*-1,'W']
		except: mag_var=['','']
	else: mag_var=['','']
	return mag_var
Exemplo n.º 9
0
def satellite_finder(params):
    # si la dirección viene definida, se obtiene latitud y longitud via Google API
    if params.address:
        address, lat, lng = google_geocode(params.address)

    # si no hay dirección, lat/lng son obligatorios
    elif params.lat and params.lng:
        address = None
        lat = convert_float('lat', params.lat, -90, 90)
        lng = convert_float('lng', params.lng, -180, 180)
    else:
        raise SatError("Alguno de los parámetros 'address' o 'lat/lng' tiene que estar definido")

    # si la altura no viene definida, se obtiene via Google API
    if params.alt:
        alt = convert_float('alt', params.alt, -500, 9000)
    else:
        alt = google_elevation(lat, lng)

    # obtiene la longitud del satélite (su latitud es cero)
    if params.sat:
        sat = Satellites.get(params.sat.upper(), None)
        if not sat:
            sat = convert_float('sat', params.sat, -180, 180)
    else:
        raise SatError("El parámetro 'sat' tiene que estar definido")

    # obtiene declinación magnética, en grados
    magn = geomag.declination(lat, lng, alt / Foot)

    # cálculo de coordenadas antena (x, y, z)
    lat_rad = math.radians(lat)
    r_ant = radio_elipse(lat_rad, Radio_Ecuat, Radio_Polar) + alt
    coord_ant = r_ant * math.cos(lat_rad), 0, r_ant * math.sin(lat_rad)

    # cálculo de coordenadas satélite (x, y, z)
    lng_rad = math.radians(lng - sat)
    r_sat = Radio_Ecuat + Orbita_Geo
    coord_sat = r_sat * math.cos(lng_rad), r_sat * math.sin(lng_rad), 0

    # cálculo de distancia al satélite, en km
    distance = norma_eucl(coord_ant, coord_sat) / 1000

    # cálculo de azimut y elevacion, en grados
    azimuth = 180 + math.degrees(math.atan2(math.tan(lng_rad), math.sin(lat_rad)))
    alfa = math.sqrt((r_sat * math.cos(lng_rad) - r_ant * math.cos(lat_rad)) ** 2 + r_sat ** 2 * math.sin(
        lng_rad) ** 2 + r_ant ** 2 * math.sin(lat_rad) ** 2)
    elevation = math.degrees(math.asin((r_sat * math.cos(lng_rad) * math.cos(lat_rad) - r_ant) / alfa))

    return OrderedDict([('address', address), ('lat', '%7.4f' % lat), ('lng', '%7.4f' % lng),
                        ('alt', '%5.1f' % alt), ('sat', '%5.1f' % sat), ('distance', '%5.1f' % distance),
                        ('elevation', '%5.2f' % elevation), ('azimuth_true', '%5.2f' % azimuth),
                        ('azimuth_magn', '%5.2f' % (azimuth - magn))])
Exemplo n.º 10
0
 def setHeading(self, heading):
     curtime = time.time()
     if curtime - self.last_mag_update > 60 or self.magnetic_declination is None:
         # update every minute at the most
         if not (self.missing_lat or self.missing_lng):
             self.last_mag_update = curtime
             self.magnetic_declination = declination (self.lat, self.lng, self.altitude)
     md = self.magnetic_declination
     if md is None:
         md = 0
     self.pov.update_heading (heading + md)
     if not self.rendering_prohibited:
         self.pov.render(self)
Exemplo n.º 11
0
 def setHeading(self, heading):
     curtime = time.time()
     if curtime - self.last_mag_update > 60 or self.magnetic_declination is None:
         # update every minute at the most
         if not (self.missing_lat or self.missing_lng):
             self.last_mag_update = curtime
             self.magnetic_declination = declination (self.lat, self.lng, self.altitude)
     md = self.magnetic_declination
     if md is None:
         md = 0
     self.pov.update_heading (heading + md)
     if not self.rendering_prohibited:
         self.pov.render(self)
Exemplo n.º 12
0
    def __init__(self, location, magnetic, accel):
        '''
        sensor is a gyro or magnetic sensor device like HMC5883L
        location is triple (long(°), lat(°), altitude(m))
        '''
        lon = location[0]
        lat = location[1]
        alt = location[2]

        self.magnetic = magnetic
        self.accel = accel
        self.declination = geomag.declination(dlat=lat,
                                              dlon=lon,
                                              h=3.2808399 * alt)
Exemplo n.º 13
0
    def __init__(self, time, seconds, lat, lon, alt, trackingMethod, groundLat, groundLon, groundAlt):
        self.time = time
        self.seconds = seconds
        self.lat = lat
        self.lon = lon
        self.alt = alt
        self.trackingMethod = trackingMethod

        ### Calculate pointing values and distances ###
        distanceToTarget = haversine(groundLat, groundLon, self.lat, self.lon)
        self.bear = bearing(groundLat, groundLon, self.lat, self.lon)
        self.ele = elevationAngle(self.alt, groundAlt, distanceToTarget)
        self.los = losDistance(self.alt, groundAlt, distanceToTarget)
        self.magDec = geomag.declination(
            dlat=self.lat, dlon=self.lon, h=self.alt)
Exemplo n.º 14
0
def calculate_mag_var(position, date):
	if position[0] and position[2] and date:
		try:
			lat=lat_DM_to_DD(position[0])
			if position[1]=='S': lat = lat * -1
			lon=lon_DM_to_DD(position[2])
			if position[3]=='W': lon = lon * -1
			var=float(geomag.declination(lat, lon, 0, date))
			var=round(var,1)
			if var >= 0.0:
				mag_var=[var,'E']
			if var < 0.0:
				mag_var=[var*-1,'W']
		except: mag_var=['','']
	else: mag_var=['','']
	return mag_var
Exemplo n.º 15
0
    def calculate_declination(self):
        baddblsb = self.p.badDblSpinBoxValue

        p = re.compile('\d+\.\d+')
        x = self.decXDblSpinBx.value()
        xok = (int(x) != 0 and p.match(str(x)) is not None)
        self.decXDblSpinBx.setStyleSheet("" if xok else baddblsb)

        y = self.decXDblSpinBx.value()
        yok = (int(y) != 0 and p.match(str(y)) is not None)
        self.decYDblSpinBx.setStyleSheet("" if yok else baddblsb)

        # NOTE: elevation value can be 0; approx. value will increase accuracy
        if not (xok or yok):
            self.clear_declination_values()
            return

        # transform UTM point to WGS 84, lat/lon
        pt = QgsPoint(self.decXDblSpinBx.value(), self.decYDblSpinBx.value())
        wgs84 = QgsCoordinateReferenceSystem(4326)
        # QgsMessageLog.logMessage("wgs84: {0}".format(wgs84.authid()),
        #                          self.tr("Fdt"), QgsMessageLog.INFO)
        mapcrs = self.canvas.mapRenderer().destinationCrs()
        # QgsMessageLog.logMessage("mapcrs: {0}".format(mapcrs.authid()),
        #                          self.tr("Fdt"), QgsMessageLog.INFO)
        xform = QgsCoordinateTransform(mapcrs, wgs84)
        wgspt = xform.transform(pt)
        # QgsMessageLog.logMessage(
        #     "wgspt:\n  {0}\n  {1}".format(wgspt.y(), wgspt.x()),
        #     self.tr("Fdt"), QgsMessageLog.INFO)

        # ensure height is in US feet
        h = self.decElevDblSpnBx.value()
        hinm = self.decElevUnitsCmbBx.currentIndex()  # 0 = ft, 1 = m
        elev = h if not hinm else h * 3.281

        gmdec = geomag.declination(wgspt.y(), wgspt.x(), elev)
        nb = self.calculate_mag_bearing(0, gmdec)
        eb = self.calculate_mag_bearing(90, gmdec)
        sb = self.calculate_mag_bearing(180, gmdec)
        wb = self.calculate_mag_bearing(270, gmdec)

        self.decCurrentDblSpinBox.setValue(gmdec)
        self.decNBearingDblSpnBx.setValue(nb)
        self.decEBearingDblSpnBx.setValue(eb)
        self.decSBearingDblSpnBx.setValue(sb)
        self.decWBearingDblSpnBx.setValue(wb)
Exemplo n.º 16
0
    def __init__(self, time, seconds, lat, lon, alt, trackingMethod, groundLat,
                 groundLon, groundAlt):
        self.time = time
        self.seconds = seconds
        self.lat = lat
        self.lon = lon
        self.alt = alt
        self.trackingMethod = trackingMethod

        ### Calculate pointing values and distances ###
        distanceToTarget = haversine(groundLat, groundLon, self.lat, self.lon)
        self.bear = bearing(groundLat, groundLon, self.lat, self.lon)
        self.ele = elevationAngle(self.alt, groundAlt, distanceToTarget)
        self.los = losDistance(self.alt, groundAlt, distanceToTarget)
        self.magDec = geomag.declination(dlat=self.lat,
                                         dlon=self.lon,
                                         h=self.alt)
Exemplo n.º 17
0
    def getCenterBearing(self, s2):
        """ Acquire a center bearing and a GPS location from the calibration arduino """

        
        
        s2.flushInput()		# Clear the buffer so it can read new info
        
        # Read from GPS module and populate temp_gps[]

        tempLat = temp_gps[1]		# Get ground station latitude
        tempLon = temp_gps[2]		# Get ground station longitude
        tempAlt = temp_gps[3]		# Get ground station altitude
        # Get the offset for the center bearing
        tempoffsetDegrees = temp_arduino[4]
        tempLat = tempLat.split(".")
        # Convert the lat to decimal degrees as a float
        self.groundLat = float(tempLat[0]) + float(tempLat[1]) / 10000000
        tempLon = tempLon.split(".")
        # Convert the lon to decimal degrees as a float
        self.groundLon = float(tempLon[0]) - float(tempLon[1]) / 10000000
        tempAlt = tempAlt.split(".")
        # Get the altitude to the floor(foot)
        self.groundAlt = int(tempAlt[0])
        self.centerBear = float(tempoffsetDegrees)
        declination = float(geomag.declination(
            dlat=self.groundLat, dlon=self.groundLon, h=self.groundAlt))
        self.centerBear = (self.centerBear + declination)
        if self.centerBear > 360:
            self.centerBear -= 360
        elif self.centerBear < 0:
            self.centerBear += 360
        print ("Local Latitude: \t", self.groundLat)
        print ("Local Longitude:\t", self.groundLon)
        print ("Local Altitude: \t", self.groundAlt)
        print ("Offset Degrees: \t", self.centerBear)
        print ("Declination:	\t", declination)
        print ("Offset + Dec:   \t", self.centerBear)
        print ("-------------------------------------------------------")

        self.antennaBear = self.centerBear
        # Lets the program know that the center bearing has been set before
        self.centerBearSet = True
Exemplo n.º 18
0
def calculate_mag_var(position, date):
    if position[0] and position[2] and date:
        try:
            lat = lat_DM_to_DD(position[0])
            if position[1] == "S":
                lat = lat * -1
            lon = lon_DM_to_DD(position[2])
            if position[3] == "W":
                lon = lon * -1
            var = float(geomag.declination(lat, lon, 0, date))
            var = round(var, 1)
            if var >= 0.0:
                mag_var = [var, "E"]
            if var < 0.0:
                mag_var = [var * -1, "W"]
        except:
            mag_var = ["", ""]
    else:
        mag_var = ["", ""]
    return mag_var
Exemplo n.º 19
0
    def calcTiltHeading(self, ax, ay, az):
        fNormAcc = math.sqrt(ax*ax + ay*ay + az*az)
        fSinRoll = ay/fNormAcc
        fCosRoll = math.sqrt(1.0-(fSinRoll * fSinRoll))
        fSinPitch = ax/fNormAcc
        fCosPitch = math.sqrt(1.0-(fSinPitch * fSinPitch))

        fTiltedX = self.m[0]*fCosPitch + self.m[2]*fSinPitch
        fTiltedY = self.m[0]*fSinRoll*fSinPitch + self.m[1]*fCosRoll - self.m[2]*fSinRoll*fCosPitch

        fcosf= fTiltedX / math.sqrt(fTiltedX*fTiltedX+fTiltedY*fTiltedY)
        if fTiltedY>0:
          HeadingValue = math.acos(fcosf)*180/math.pi
        else:
          HeadingValue =360-math.acos(fcosf)*180/math.pi

        import geomag
        HeadingValue -= geomag.declination(37,128)
        if HeadingValue>360:
          HeadingValue=HeadingValue-360

        return HeadingValue
Exemplo n.º 20
0
    def calcTiltHeading(self, ax, ay, az):
        fNormAcc = math.sqrt(ax*ax + ay*ay + az*az)
        fSinRoll = ay/fNormAcc
        fCosRoll = math.sqrt(1.0-(fSinRoll * fSinRoll))
        fSinPitch = ax/fNormAcc
        fCosPitch = math.sqrt(1.0-(fSinPitch * fSinPitch))

        fTiltedX = self.m[0]*fCosPitch + self.m[2]*fSinPitch
        fTiltedY = self.m[0]*fSinRoll*fSinPitch + self.m[1]*fCosRoll - self.m[2]*fSinRoll*fCosPitch

        fcosf= fTiltedX / math.sqrt(fTiltedX*fTiltedX+fTiltedY*fTiltedY)
        if fTiltedY>0:
          HeadingValue = math.acos(fcosf)*180/math.pi
        else:
          HeadingValue =360-math.acos(fcosf)*180/math.pi

        import geomag
        HeadingValue -= geomag.declination(37,128)
        if HeadingValue>360:
          HeadingValue=HeadingValue-360

        return HeadingValue
Exemplo n.º 21
0
    def calcTiltHeading(self):
        fNormAcc = math.sqrt(math.fsum(i * i for i in self.a))
        fSinRoll = self.a[1] / fNormAcc
        fCosRoll = math.sqrt(1.0 - (fSinRoll * fSinRoll))
        fSinPitch = self.a[0] / fNormAcc
        fCosPitch = math.sqrt(1.0 - (fSinPitch * fSinPitch))

        fTiltedX = self.m[0] * fCosPitch + self.m[2] * fSinPitch
        fTiltedY = self.m[0] * fSinRoll * fSinPitch + self.m[1] * fCosRoll - self.m[2] * fSinRoll * fCosPitch

        fcosf = fTiltedX / math.sqrt(fTiltedX * fTiltedX + fTiltedY * fTiltedY)
        if fTiltedY > 0:
            HeadingValue = math.acos(fcosf) * 180 / math.pi
        else:
            HeadingValue = 360 - math.acos(fcosf) * 180 / math.pi

        # HeadingValue -= -8
        HeadingValue -= geomag.declination(37, 128)
        if HeadingValue > 360:
            HeadingValue = HeadingValue - 360

        return HeadingValue
Exemplo n.º 22
0
    def calcTiltHeading(self):
        fNormAcc = math.sqrt(sum(i*i for i in self.a))
        fSinRoll = self.a[1]/fNormAcc
        fCosRoll = math.sqrt(1.0-(fSinRoll * fSinRoll))
        fSinPitch = self.a[0]/fNormAcc
        fCosPitch = math.sqrt(1.0-(fSinPitch * fSinPitch))

        fTiltedX = self.m[0]*fCosPitch + self.m[2]*fSinPitch
        fTiltedY = self.m[0]*fSinRoll*fSinPitch + self.m[1]*fCosRoll - self.m[2]*fSinRoll*fCosPitch

        fcosf= fTiltedX / math.sqrt(fTiltedX*fTiltedX+fTiltedY*fTiltedY)
        if fTiltedY>0:
          HeadingValue = math.acos(fcosf)*180/math.pi
        else:
          HeadingValue =360-math.acos(fcosf)*180/math.pi

        import geomag
        #HeadingValue -= -8
        HeadingValue -= geomag.declination(37,128)
        if HeadingValue>360:
          HeadingValue=HeadingValue-360

        return HeadingValue
Exemplo n.º 23
0
def gprmc(lat, lon):  # Assuming the Land of Oz

    today = datetime.utcnow()

    time = today.strftime("%H%M%S.%f").rstrip('0')
    warning = "A"  # "A" for good, "V" for bad. I'm an optimist.
    latD = dd2dm(lat)
    if lat < 0: latH = "S"
    else: latH = "N"
    lonD = dd2dm(lon)
    if lon < 0: lonH = "W"
    else: lonH = "E"
    speed = "0"  # ?
    course = ""  # ?
    dateUTC = today.strftime("%d%m%y")  # Using UTC time.
    mag = geomag.declination(lat, lon, time=today.date())  # See geomag library
    magD = "E" if mag < 0 else "W"  # West or East declination?
    mag = abs(mag)  # Data stored in magD

    gprmcData = "GPRMC,%s,%s,%s,%s,%s,%s,%s,%s,%s,%f.00,%s" % (
        time,
        warning,
        latD,
        latH,
        lonD,
        lonH,
        speed,
        course,
        dateUTC,
        mag,
        magD,
    )

    check = checksum(gprmcData)
    gprmcFormat = "$%s*%X\r\n" % (gprmcData, check)

    return gprmcFormat
Exemplo n.º 24
0
def gprmc(lat,lon): # Assuming the Land of Oz

    today=datetime.utcnow()

    time= today.strftime("%H%M%S.%f").rstrip('0')
    warning="A" # "A" for good, "V" for bad. I'm an optimist.
    latD=dd2dm(lat)
    if lat<0: latH="S"
    else: latH="N"
    lonD=dd2dm(lon)
    if lon<0: lonH="W"
    else: lonH="E"
    speed="0" # ?
    course="" # ?
    dateUTC=today.strftime("%d%m%y") # Using UTC time.
    mag=geomag.declination(lat,lon,time=today.date() ) # See geomag library
    magD="E" if mag<0 else "W" # West or East declination?
    mag=abs(mag) # Data stored in magD 

    gprmcData="GPRMC,%s,%s,%s,%s,%s,%s,%s,%s,%s,%f.00,%s"%(
            time,
            warning,
            latD,
            latH,
            lonD,
            lonH,
            speed,
            course,
            dateUTC,
            mag,
            magD,
            )

    check=checksum(gprmcData)
    gprmcFormat="$%s*%X\r\n"%(gprmcData,check)

    return gprmcFormat
Exemplo n.º 25
0
def string_notes(system, run=0.0, stationClass = 1):
    """page 5"""

    name, usaf = geo.closestUSAF( geo.zipToCoordinates(system.zipcode), stationClass)
    mintemp = epw.minimum(usaf)
    twopercentTemp = epw.twopercent(usaf)
    ac_rated = 0.0
    dc_rated = 0.0
    for i in system.shape:
        dc_rated += i.array.Pmax
        try:
            if i.phase == 1:
                ac_rated += i.current * i.ac_voltage
            else:
                ac_rated += i.phase * i.current * i.ac_voltage/ 3**.5
        except:
            ac_rated += i.Paco
            pass
    notes = []
    notes.append("%s KW AC RATED" % round(ac_rated/1000.0,2))
    notes.append("%s KW DC RATED" % round(dc_rated/1000.0,2))
    #BUG: This doesn't work for unbalanced 3 phase
    if system.phase == 1:
        Aac = round(ac_rated/i.ac_voltage,1)
    else:
        Aac = round(ac_rated/i.ac_voltage/3**.5,1)
    notes.append( "System AC Output Current: %s A" % Aac)

    notes.append("Nominal AC Voltage: %s V" % i.ac_voltage)
    notes.append("")
    notes.append("Minimum Temperature: %s C" % mintemp)
    notes.append("2 Percent Max Temperature: %s C" % twopercentTemp)
    notes.append("Weather Source: %s %s" % (name, usaf))
    notes.append("")
    di, dp = system.describe()
    aMax = 0
    for i in system.shape:
        if dp.has_key(i.array.panel.model):
            notes.append( "PV Module Ratings @ STC")
            notes.append("Module Make: %s" % i.array.panel.make)
            notes.append("Module Model: %s" % i.array.panel.model)
            notes.append("Quantity: %s" % dp[i.array.panel.model])
            notes.append("Max Power-Point Current (Imp): %s A" % i.array.panel.Impp)
            notes.append("Max Power-Point Voltage (Vmp): %s V" % i.array.panel.Vmpp)
            notes.append("Open-Circuit Voltage (Voc): %s V" % i.array.panel.Voc)
            notes.append("Short-Circuit Current (Isc): %s A" % i.array.panel.Isc)
            notes.append("Maximum Power (Pmax): %s W" % round(i.array.panel.Pmax,1))
            #notes.append("Module Rated Max Voltage: %s V" % i.array.panel.Vrated)

            notes.append("")
            dp.pop(i.array.panel.model)
        if di.has_key(i.model):
            notes.append("Inverter Make: %s" % i.make)
            notes.append("Inverter Model: %s" % i.model)
            notes.append("Quantity: %s" % di[i.model])
            notes.append("Max Power: %s KW" % round(i.Paco/1000.0,1))
            #this is hack... This should be calculated based upon power cores
            if hasattr(i,'current'):
                notes.append("Max AC Current: %s A" % round(i.current,1))
            elif i.ac_voltage == 480:
                notes.append("Max AC Current: %s A" % round(i.Paco*1.0/i.ac_voltage/3**.5,1))
            else:
                notes.append("Max AC Current: %s A" % round(i.Paco*1.0/i.ac_voltage,1))
            #greater than 1 in parallel
            if len(i.array.shape) > 1:
                pass
                notes.append("DC Operating Current: %s A" % \
                        round(i.array.panel.Impp*len(i.array.shape),1))
                notes.append("DC Short Circuit Current: %s A" % \
                        round(i.array.panel.Isc*len(i.array.shape),1))
            #greater than 1 in series
            if max(i.array.shape)> 1:
                notes.append("DC Operating Voltage: %s V" % round(i.array.Vdc(),1))
                notes.append("System Max DC Voltage: %s V" % round(i.array.Vmax(mintemp),1))
                if i.array.Vmax(mintemp) > 600:
                    print "WARNING: Array exceeds 600V DC"
                notes.append("Pnom Ratio: %s" % round((i.array.Pmax/i.Paco),2))
                if (i.array.Vdc(twopercentTemp) *.9) < i.mppt_low:
                    print "WARNING: Array IV Knee drops out of Inverter range"
                if (i.array.Pmax/i.Paco) < 1.1:
                    print "WARNING: Array potentially undersized"
            notes.append("")
            di.pop(i.model)
        if i.array.Vmax(mintemp) > aMax:
            aMax = i.array.Vmax(mintemp)

    notes.append("Array Azimuth: %s Degrees" % system.azimuth)
    notes.append("Array Tilt: %s Degrees" % system.tilt)
    s9 = system.solstice(9)
    s15 = system.solstice(15)
    notes.append("December 21 9:00 AM Sun Azimuth: %s Degrees" % \
            (round(degrees(s9[1]),1)))
    notes.append("December 21 9:00 AM Sun Altitude: %s Degrees" % \
            (round(degrees(s9[0]),1)))
    notes.append("December 21 3:00 PM Sun Azimuth: %s Degrees" % \
            (round(degrees(s15[1]),1)))
    notes.append("December 21 3:00 PM Sun Altitude: %s Degrees" % \
            (round(degrees(s9[0]),1)))
    if 'geomag' in sys.modules:
        notes.append("Magnetic declination: %s Degrees" % \
                round(geomag.declination(dlat=system.place[0],dlon=system.place[1])))
    notes.append("Minimum Row space ratio: %s" % \
            round(system.minRowSpace(1.0),2))
    print "\n".join(notes)

    print ""
    print "Minimum Bundle"
    minC = vd.vd(Aac,5,verbose=False)
    try:
        ee.assemble(minC,Aac,conduit='STEEL')
        if run > 0:
            print "Long Run"
            minC = vd.vd(Aac,run,v=i.ac_voltage,tAmb=15,pf=.95,material='AL',verbose=False)
            ee.assemble(minC,Aac,conduit='PVC')
    except:
        print "Warning: Multiple sets of conductors"
    return notes
Exemplo n.º 26
0
        targetlatDeg = 44.587746
        targetlonDeg = -123.096098
        targetaltMeters = 200
        #lat = input('Enter latitude of target: ')
        #lon = input('Enter longitude of target: ')
        #alt = input('Enter altitude of target: ')
    else:
        target.update()
    tracker.update()

    bearing = ServoControl.bearing(
        tracker.latDeg, tracker.lonDeg, targetlatDeg, targetlonDeg
    )

    if(bearing):
        tracker.imuX = (tracker.imuX + 360)%360
        # print "The tracker heading is ", tracker.imuX
        declination = geomag.declination(
            dlat=tracker.latDeg, dlon=tracker.lonDeg, h=tracker.altMeters
        )
        # print "Magnetic declination is ", declination
        tracker.imuX = (tracker.imuX + declination) % 360
        print "Tracker heading after declination: ", tracker.imuX

        print "The solution bearing is: ", bearing
        solution = (bearing - tracker.imuX + 360) % 360
        print "Tracker needs to move ", solution
        print "In servo, that's ", ServoControl.degToServo(solution)
        print tracker.imuX, tracker.imuMag, tracker.imuSys
        time.sleep(5)
Exemplo n.º 27
0
        sdata = data.decode().split(",")
        if sdata[2] == 'V':
            print("no satellite data available")

#        print("---Parsing GPVTG---")
        tracking_true = sdata[1]
#        tracking_mag = sdata[3]	#Theoretically the GPS might have a lookup table for magnetic declination. If it does this line might work

# if there is no data (for example the gps is not moving) return a crazy large number to indicate that
        if tracking_true == "":
            tracking_true = "32768"
            tracking_mag  = "32768"

# Since our GPS receiver does not have the lookup table for declination, we use the geomag library
        if int(tracking_true) >=0 and int(tracking_true)<=360:
            tracking_mag = tracking_true + geomag.declination(lat/1000000, lon/1000000)

        speed = sdata[5]

        if speed == "":
            speed = "32768"
        if alt == "":
            alt = "15000"

        GPS_data = bytearray([int(float(speed)) & 0xFF, int(float(speed))>>8, int(float(alt)*conv_m2ft) & 0xFF, int(float(alt)*conv_m2ft)>>8, int(float(tracking_true)) & 0xFF, int(float(tracking_true))>>8, int(float(tracking_mag)) & 0xFF, int(float(tracking_mag))>>8])
        msg = can.Message(arbitration_id=100, data=GPS_data, extended_id=False)
        Msg_Ready = True
#        print("Speed: %s, Alt : %s, tracking_true: %s, tracking_mag: %s" %  (speed, alt, tracking_true, tracking_mag))
    if  Msg_Ready:
        try:
            bus.send(msg)
Exemplo n.º 28
0
    else:
        arcpy.AddWarning("Warning: Need to add Planning Point or ICP prior to updating map layout\n")

    unProjCoordSys = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    desc = arcpy.Describe(fc1)
    shapefieldname = desc.ShapeFieldName

    rows1 = arcpy.SearchCursor(fc1, '', unProjCoordSys)
    k = 0
    declin = 0
    for row1 in rows1:
        feat = row1.getValue(shapefieldname)
        pnt = feat.getPart()
        latitude = pnt.Y
        longitude = pnt.X
        declin = geomag.declination(latitude,longitude) + declin
        k+=1
    del rows1
    del row1

    declin_avg = declin / k
    MagDeclinlination = round(declin_avg,2)
    if MagDeclinlination < 0:
        Cardinal ="W"
    else:
        Cardinal ="E"
    MagDecTxt = str(abs(MagDeclinlination)) + " " + Cardinal
    arcpy.AddMessage(MagDecTxt)

    try:  #Update Incident Name and Number with the file name and dataframe name
        IncName = df.name
Exemplo n.º 29
0
def cal_magnetic_declination(course: SailingCourse):
    declination = geomag.declination(course.latitude,
                                     course.longitude,
                                     time=convert_str_to_date(course.date))
    return round(declination)
Exemplo n.º 30
0
		IMUheadingAverage = sum(IMUheadingList)/movingAverageRange
		IMUrollAverage = sum(IMUrollList)/movingAverageRange
		IMUpitchAverage = sum(IMUpitchList)/movingAverageRange

		AMEwindangleAverage = sum(AMEwindangleList)/movingAverageRange

		targetWaypointLatitude = waypointLatitudeList[waypointCounter]
		targetWaypointLongitude = waypointLongitudeList[waypointCounter]

		distanceToWaypoint, bearingToWaypoint = findDistanceandBearing(GPSlatitudeAverage, GPSlongitudeAverage, targetWaypointLatitude, targetWaypointLongitude)
		#if (distanceToWaypoint <= acceptWaypointDistance) and (waypointCounter < numberOfWaypoints - 1):
		if ((cycleCounter % 20) == 0) and (waypointCounter < numberOfWaypoints - 1):
				waypointCounter += 1

		magneticDeclination = geomag.declination(GPSlatitudeAverage, GPSlongitudeAverage)
		IMUheadingCorrected = IMUheadingAverage + magneticDeclination

		headingMode = 0
		if (GPSspeedAverage > 1.5) and ((range(IMUheadingList) <  15) or (range(IMUheadingList) > 345)) and (GPSfix == 1):
			heading = GPSheadingAverage
			headingMode = 1
		else:
			heading = IMUheadingCorrected


		if cycleCounter > 10:
			try:
				print("\n\n")
				print("Time: %s"%(time))
				print("Waypoint\t|\tNumber: %d\tDistance: %d\t\tBearing: %d"%(waypointCounter, distanceToWaypoint, bearingToWaypoint))
Exemplo n.º 31
0
#!/usr/bin/env python3

import socket, json, geomag

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 9999         # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'gps')
    data = s.recv(1024)

jdata = data.decode('utf-8')
obj = json.loads(jdata)
decl = geomag.declination(dlat=obj['lat'], dlon=obj['lon'],h=obj['alt'])
print(decl)
Exemplo n.º 32
0
def string_notes(system, run=0.0):
    """page 5"""
    stationClass = 3
    name, usaf = geo.closestUSAF( geo.zipToCoordinates(system.zipcode), stationClass)
    mintemp = epw.minimum(usaf)
    twopercentTemp = epw.twopercent(usaf)
    ac_rated = 0
    dc_rated = 0
    for i in system.shape:
        dc_rated += i.array.Pmax
        ac_rated += i.Paco
    notes = []
    notes.append("%s KW AC RATED" % round(ac_rated/1000.0,2))
    notes.append("%s KW DC RATED" % round(dc_rated/1000.0,2))
    #BUG: This doesn't work for 3 phase
    if system.phase == 1:
        Aac = round(sum([i.Paco for i in system.shape])/i.ac_voltage,1)
    else:
        Aac = round(sum([i.Paco for i in system.shape])/i.ac_voltage/3**.5,1)
    notes.append( "System AC Output Current: %s A" % Aac)

    notes.append("Nominal AC Voltage: %s V" % i.ac_voltage)
    notes.append("")
    notes.append("Minimum Temperature: %s C" % mintemp)
    notes.append("2 Percent Max Temperature: %s C" % twopercentTemp)
    notes.append("")
    di, dp = system.describe()
    aMax = 0
    for i in system.shape:
        if dp.has_key(i.array.panel.model):
            notes.append( "PV Module Ratings @ STC")
            notes.append("Module Make: %s" % i.array.panel.make)
            notes.append("Module Model: %s" % i.array.panel.model)
            notes.append("Quantity: %s" % dp[i.array.panel.model])
            notes.append("Max Power-Point Current (Imp): %s A" % i.array.panel.Impp)
            notes.append("Max Power-Point Voltage (Vmp): %s V" % i.array.panel.Vmpp)
            notes.append("Open-Circuit Voltage (Voc): %s V" % i.array.panel.Voc)
            notes.append("Short-Circuit Current (Isc): %s A" % i.array.panel.Isc)
            notes.append("Maximum Power (Pmax): %s W" % round(i.array.panel.Pmax,1))
            #notes.append("Module Rated Max Voltage: %s V" % i.array.panel.Vrated)

            notes.append("")
            dp.pop(i.array.panel.model)
        if di.has_key(i.model):
            notes.append("Inverter Make: %s" % i.make)
            notes.append("Inverter Model: %s" % i.model)
            notes.append("Quantity: %s" % di[i.model])
            notes.append("Max Power: %s KW" % round(i.Paco/1000.0,1))
            #this is hack... This should be calculated based upon power cores
            if i.ac_voltage == 480:
                notes.append("Max AC Current: %s A" % round(i.Paco*1.0/i.ac_voltage/3**.5,1))
            else:
                notes.append("Max AC Current: %s A" % round(i.Paco*1.0/i.ac_voltage,1))
            #greater than 1 in parallel
            if len(i.array.shape) > 1:
                pass
                notes.append("DC Operating Current: %s A" % \
                        round(i.array.panel.Impp*len(i.array.shape),1))
                notes.append("DC Short Circuit Current: %s A" % \
                        round(i.array.panel.Isc*len(i.array.shape),1))
            #greater than 1 in series
            if max(i.array.shape)> 1:
                notes.append("DC Operating Voltage: %s V" % round(i.array.Vdc(),1))
                notes.append("System Max DC Voltage: %s V" % round(i.array.Vmax(mintemp),1))
                notes.append("Pnom Ratio: %s" % round((i.array.Pmax/i.Paco),2))
            notes.append("")
            di.pop(i.model)
        if i.array.Vmax(mintemp) > aMax:
            aMax = i.array.Vmax(mintemp)

    notes.append("Array Azimuth: %s Degrees" % system.azimuth)
    notes.append("Array Tilt: %s Degrees" % system.tilt)
    notes.append("December 21 9:00 AM Sun Azimuth: %s Degrees" % \
            int(round(degrees(system.solstice(9)[1]),0)))
    notes.append("December 21 3:00 PM Sun Azimuth: %s Degrees" % \
            int(round(degrees(system.solstice(15)[1]),0)))
    if sys.modules['geomag']:
        notes.append("Magnetic declination: %s Degrees" % \
                round(geomag.declination(dlat=system.place[0],dlon=system.place[1])))
    notes.append("Minimum Row space ratio: %s" % \
            round(system.minRowSpace(1.0),2))
    print "\n".join(notes)

    print ""
    print "Minimum Bundle"
    minC = vd.vd(Aac,5)
    ee.assemble(minC,Aac,conduit='STEEL')
    if run > 0:
        print "Long Run"
        minC = vd.vd(Aac,run,v=i.ac_voltage,tAmb=15,pf=.95,material='AL')
        ee.assemble(minC,Aac,conduit='PVC')
    return notes
def arduinoGround():  #Gather data from arduino mounted on ground station
    global groundAlt, groundLat, groundLon, centerBear, antennaBear, calibrationGoal
    if arduinoAttached:
        s2 = serial.Serial(str(arduinoCOM),
                           baudrate=arduinoBaud,
                           timeout=arduinoTimeout)
        time.sleep(5)
        temp_arduino = "0"
        calibration = 0
        x = 64
        y = 70
        bad = 0
        while (calibration < int(calibrationGoal)):
            temp_arduino = "0"
            s2.flushInput()
            time.sleep(0.05)
            while (temp_arduino[0] != '~'):
                temp_arduino = s2.readline()
                print temp_arduino
                temp_arduino = temp_arduino.split(',')
            try:
                calibration = int(temp_arduino[8]) + int(
                    temp_arduino[7]) + int(temp_arduino[6]) + int(
                        temp_arduino[5])
            finally:
                print "Calibration: ", calibration, " // Goal of ", int(
                    calibrationGoal)
                if (x > 191):
                    x = 64
                    time.sleep(3)
                else:
                    x += 10
                if (y < 70):
                    y = 127
                else:
                    y -= 3
                movePanServo(x)
                moveTiltServo(y)
        moveToCenterPos()
        time.sleep(10)
        temp_arduino = "0"
        s2.flushInput()
        while (temp_arduino[0] != '~'):
            temp_arduino = s2.readline()
            print temp_arduino
            temp_arduino = temp_arduino.split(',')
        print "Requesting Latitude"
        tempLat = temp_arduino[1]
        print tempLat
        print "Requesting Longitude"
        tempLon = temp_arduino[2]
        print tempLon
        print "Requesting Altitude"
        tempAlt = temp_arduino[3]
        tempoffsetDegrees = "0.00"
        print tempAlt
        print "Requesting Orientation"
        tempoffsetDegrees = temp_arduino[4]
        print tempoffsetDegrees
        tempLat = tempLat.split(".")
        groundLat = float(tempLat[0]) + float(tempLat[1]) / 10000000
        tempLon = tempLon.split(".")
        groundLon = float(tempLon[0]) - float(tempLon[1]) / 10000000
        tempAlt = tempAlt.split(".")
        groundAlt = int(tempAlt[0])
        #tempoffsetDegrees = tempoffsetDegrees.split(".")
        centerBear = float(tempoffsetDegrees)
        declination = float(
            geomag.declination(dlat=groundLat, dlon=groundLon, h=groundAlt))
        s2.close()
    else:
        print "Error: Arduino set in Settings as not connected"
    print "Local Latitude: \t", groundLat
    print "Local Longitude:\t", groundLon
    print "Local Altitude: \t", groundAlt
    print "Offset Degrees: \t", centerBear
    print "Declination:    \t", declination
    centerBear = (centerBear + declination)
    if centerBear > 360:
        centerBear = centerBear - 360
    elif centerBear < 0:
        centerBear = centerBear + 360
    print "Offset + Dec:   \t", (centerBear)
    print "-------------------------------------------------------"
    antennaBear = (centerBear)
Exemplo n.º 34
0
def string_notes(system, run=0.0, station_class=3):
    """page 5"""

    name, usaf = geo.closest_usaf(geo.zip_coordinates(system.zipcode), \
            station_class)
    mintemp = eere.minimum(usaf)
    twopercent_temp = eere.twopercent(usaf)
    ac_kva_rated = 0.0
    dc_rated = 0.0
    ac_kw = 0.0
    for i in system.shape:
        dc_rated += i.array.p_max
        try:
            if i.phase == 1:
                ac_kva_rated += i.current * i.ac_voltage
            else:
                ac_kva_rated += i.phase * i.current * i.ac_voltage / 3**.5
        except Exception:
            ac_kva_rated += i.p_aco
        ac_kw += i.p_aco
    notes = []
    notes.append("%s KVA AC RATED" % round(ac_kva_rated / 1000.0, 2))
    notes.append("%s KW AC RATED" % round(ac_kw / 1000.0, 2))
    notes.append("%s KW DC RATED" % round(dc_rated / 1000.0, 2))
    #BUG: This doesn't work for unbalanced 3 phase
    if system.phase == 1:
        a_ac = round(ac_kva_rated / i.ac_voltage, 1)
    else:
        a_ac = round(ac_kva_rated / i.ac_voltage / 3**.5, 1)
    notes.append("System AC Output Current: %s A" % a_ac)

    notes.append("Nominal AC Voltage: %s V" % i.ac_voltage)
    notes.append("")
    notes.append("Minimum Temperature: %s C" % mintemp)
    notes.append("2 Percent Max Temperature: %s C" % twopercent_temp)
    notes.append("Weather Source: %s %s" % (name, usaf))
    notes.append("")
    d_inverters, d_panels = system.describe()
    a_max = 0
    for i in system.shape:
        module_name = i.array.dump()['panel']
        if d_panels.has_key(module_name):
            module = modules.Module(module_name)
            notes.append("PV Module Ratings @ STC")
            notes.append("Module Make: %s" % module.make)
            notes.append("Module Model: %s" % module.model)
            notes.append("Quantity: %s" % d_panels[module_name])
            notes.append("Max Power-Point Current (Imp): %s A" % module.i_mpp)
            notes.append("Max Power-Point Voltage (Vmp): %s V" % module.v_mpp)
            notes.append("Open-Circuit Voltage (Voc): %s V" % module.v_oc)
            notes.append("Short-Circuit Current (Isc): %s A" % module.i_sc)
            notes.append("Maximum Power (Pmax): %s W" % round(module.p_max, 1))

            notes.append("")
            d_panels.pop(module_name)
        if d_inverters.has_key(i.model):
            notes.append("Inverter Make: %s" % i.make)
            notes.append("Inverter Model: %s" % i.model)
            notes.append("Quantity: %s" % d_inverters[i.model])
            notes.append("Max Power: %s KW" % round(i.p_aco / 1000.0, 1))
            #this is hack... This should be calculated based upon power cores
            if hasattr(i, 'current'):
                notes.append("Max AC Current: %s A" % round(i.current, 1))
            elif i.ac_voltage == 480:
                notes.append("Max AC Current: %s A" % \
                        round(i.p_aco*1.0/i.ac_voltage/3**.5, 1))
            else:
                notes.append("Max AC Current: %s A" % \
                        round(i.p_aco*1.0/i.ac_voltage, 1))
            #greater than 1 in parallel
            if i.array.mcount() > 1:
                notes.append("DC Operating Current: %s A" % \
                        round(i.array.i_mpp(), 1))
                notes.append("DC Short Circuit Current: %s A" % \
                        round(i.array.i_sc(), 1))
            #greater than 1 in series
            if i.array.mcount() > 1:
                notes.append("DC Operating Voltage: %s V" % \
                        round(i.array.v_dc(), 1))
                notes.append("System Max DC Voltage: %s V" % \
                        round(i.array.v_max(mintemp), 1))
                if i.array.v_max(mintemp) > 600:
                    logger.warning("WARNING: Array exceeds 600V DC")
                notes.append("Pnom Ratio: %s" % \
                        round((i.array.p_max/i.p_aco), 2))
                if (i.array.v_dc(twopercent_temp) * .9) < i.mppt_low:
                    logger.warning("WARNING: " \
                            "Array IV Knee drops out of Inverter range")
                if (i.array.p_max / i.p_aco) < 1.1:
                    logger.warning("WARNING: Array potentially undersized")
            notes.append("")
            d_inverters.pop(i.model)
        if i.array.v_max(mintemp) > a_max:
            a_max = i.array.v_max(mintemp)

    notes.append("Array Azimuth: %s Degrees" % system.azimuth)
    notes.append("Array Tilt: %s Degrees" % system.tilt)
    sols_9 = system.solstice(9)
    sols_15 = system.solstice(15)
    notes.append("December 21 9:00 AM Sun Azimuth: %s Degrees" % \
            (round(degrees(sols_9[1]), 1)))
    notes.append("December 21 9:00 AM Sun Altitude: %s Degrees" % \
            (round(degrees(sols_9[0]), 1)))
    notes.append("December 21 3:00 PM Sun Azimuth: %s Degrees" % \
            (round(degrees(sols_15[1]), 1)))
    notes.append("December 21 3:00 PM Sun Altitude: %s Degrees" % \
            (round(degrees(sols_9[0]), 1)))
    if 'geomag' in sys.modules:
        notes.append("Magnetic declination: %s Degrees" % \
                round(geomag.declination(dlat=system.place[0], \
                dlon=system.place[1])))
    notes.append("Minimum Row space ratio: %s" % \
            round(system.min_row_space(1.0), 2))
    if __name__ == '__main__':
        print "\n".join(notes)
    else:
        logger.info("Plant Details:\n" + "\n".join(notes))

    print ""
    print "Minimum Bundle"
    min_c = vd.vd(a_ac, 5, verbose=False)
    try:
        ee.assemble(min_c, a_ac, conduit='STEEL')
        if run > 0:
            print "Long Run"
            min_c = vd.vd(a_ac, run, v=i.ac_voltage, t_amb=15, pf=.95, \
                    material='AL', verbose=False)
            ee.assemble(min_c, a_ac, conduit='PVC')
    except:
        print "Warning: Multiple sets of conductors"
    return notes
Exemplo n.º 35
0
 def bearing_true(self, lat, lon, alt=0, date=datetime.date.today()):
     #CB wmm = WorldMagneticModel()
     #CB declination = wmm.calc_mag_field(lat, lon, alt, date).declination
     declination = geomag.declination(lat, lon)  #CB
     return self._bearing + declination
Exemplo n.º 36
0
def get_declination():
    owm = pyowm.OWM(
        '6a4296ddd0988dee8222522a8656542c')  # You MUST provide a valid API key
    latitude = g.lat
    longitude = g.lng

    geolocator = Nominatim()
    location = geolocator.reverse((str(g.lat) + "," + str(g.lng)))
    print('HERE')
    new_location = str(location).split(',')
    print(new_location[3])
    print('HERE')
    #y = str(location).split(",")
    #print(y)

    # need to fix this part
    country = "US"
    city = str(new_location[3])
    cc = city + ',' + country
    # Have a pro subscription? Then use:
    # owm = pyowm.OWM(API_key='your-API-key', subscription_type='pro')

    # Search for current weather in ANYWHERE!

    observation = owm.weather_at_place(cc)
    #observation = owm.weather_at_place(cc)

    #observation = owm.weather_at_place('Seattle, US'))
    observation = owm.weather_at_place(cc)

    w = observation.get_weather()
    print(w)

    # Weather details

    #print(w.get_wind())                  # {'speed': 4.6, 'deg': 330}
    #print(w.get_humidity())              # 87
    #print(w.get_temperature('fahrenheit'))  # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0}

    print(w.get_wind())  # {'speed': 4.6, 'deg': 330}
    print(w.get_humidity())  # 87
    print(w.get_temperature(
        'fahrenheit'))  # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0}

    # Search current weather observations in the surroundings of
    # lat=22.57W, lon=43.12S (Rio de Janeiro, BR)
    observation_list = owm.weather_around_coords(latitude, longitude)
    print(type(observation_list))

    #print(observation_list)
    #w = observation_list.get_weather()
    weather = Weather(Unit.CELSIUS)
    lookup = weather.lookup_by_latlng(latitude, longitude)
    condition = lookup.condition

    #print(condition.text)
    # magnetic declination, temp in celcius
    print(str(geomag.declination(latitude, longitude)))

    return str(city + '\r') + str(latitude) + str(
        longitude) + "Magnetic declination" + str(
            geomag.declination(latitude, longitude)) + str(
                w.get_temperature('fahrenheit')) + "Humidity: " + str(
                    w.get_humidity()) + str(
                        w.get_wind()) + str('             ') + str(
                            condition.text)

    print(condition.text)
    # magnetic declination, temp in celcius
    print(str(geomag.declination(latitude, longitude)))

    return str(condition.text)
Exemplo n.º 37
0
desc = arcpy.Describe(fc1)
shapefieldname = desc.ShapeFieldName

arcpy.AddMessage("Checking for Planning Point\n")
try:
    cPlanPt =arcpy.GetCount_management(fc1)
    if int(cPlanPt.getOutput(0)) > 0:
        rows1 = arcpy.SearchCursor(fc1, '', unProjCoordSys)
        k = 0
        declin = 0
        for row1 in rows1:
            feat = row1.getValue(shapefieldname)
            pnt = feat.getPart()
            latitude = pnt.Y
            longitude = pnt.X
            declin = geomag.declination(latitude,longitude) + declin
            k+=1
        del rows1
        del row1

        declin_avg = declin / k
        MagDeclinlination = round(declin_avg,2)
        if MagDeclinlination < 0:
            Cardinal ="W"
        else:
            Cardinal ="E"
        MagDecTxt = str(abs(MagDeclinlination)) + " " + Cardinal
        arcpy.AddMessage(MagDecTxt)

        try:
            cIncident=arcpy.GetCount_management("Incident_Information")
Exemplo n.º 38
0
def get_mag_decl():
    update_state()
    return geomag.declination(dlat=state['lat'],
                              dlon=state['lon'],
                              h=state['alt'])
Exemplo n.º 39
0
def process_capture(meta,
                    path,
                    write_to_disk=False,
                    guess=False,
                    clockwise=True,
                    macs=None):
    """
    Process a captured data set
    :param meta:            meta dict containing capture results
    :param write_to_disk:   bool designating whether to write to disk
    :param guess:           bool designating whether to return a table of guessed bearings for detected BSSIDs
    :param clockwise:       direction antenna was moving during the capture,
    :param macs:            list of macs to filter on
    :return: (_beacon_count, _results_path):
    """

    module_logger.info("Processing capture (meta: {})".format(str(meta)))

    _beacon_count = 0
    _beacon_failures = 0

    # Correct bearing to compensate for magnetic declination
    #CB _declination = WorldMagneticModel()\
    #CB     .calc_mag_field(float(meta[meta_csv_fieldnames[6]]),
    #CB                     float(meta[meta_csv_fieldnames[7]]),
    #CB                     date=date.fromtimestamp(float(meta["start"])))\
    #CB     .declination
    lat = float(meta[meta_csv_fieldnames[6]])  # CB
    lon = float(meta[meta_csv_fieldnames[7]])  # CB
    start_date = date.fromtimestamp(float(meta["start"]))  # CB
    alt = 0
    _declination = geomag.declination(lat, lon, alt, start_date)  # CB

    # Read results into a DataFrame
    # Build columns
    _default_columns = [
        'capture',
        'pass',
        'duration',
        'hop-rate',
        'timestamp',
        'bssid',
        'ssid',
        'encryption',
        'cipher',
        'auth',
        'ssi',
        'channel',
        'bearing_magnetic',
        'bearing_true',
        'lat',
        'lon',
        'alt',
        'lat_err',
        'lon_error',
        'alt_error',
    ]

    _rows = []
    _pcap = os.path.join(path, meta[meta_csv_fieldnames[16]])

    # Build filter string
    _filter = 'wlan'  #CB: 'wlan[0] == 0x80'
    # Override any provide mac filter list if we have one in the capture metadata
    if meta_csv_fieldnames[19] in meta and meta[meta_csv_fieldnames[19]]:
        macs = [meta[meta_csv_fieldnames[19]]]
    if macs:
        _mac_string = ' and ('
        _mac_strings = ['wlan.bssid == ' + mac for mac in macs]
        _mac_string += ' or '.join(_mac_strings)
        _mac_string += ')'
        _filter += _mac_string

    packets = pyshark.FileCapture(_pcap,
                                  display_filter=_filter,
                                  keep_packets=False,
                                  use_json=True)

    for packet in packets:

        try:
            # Get time, bssid & db from packet
            pbssid = packet.wlan.bssid
            ptime = parser.parse(packet.sniff_timestamp).timestamp()
            pssid = next((tag.ssid for tag in packet.wlan_mgt.tagged.all.tag
                          if hasattr(tag, 'ssid')), None)
            pssi = int(packet.wlan_radio.signal_dbm) if hasattr(
                packet.wlan_radio, 'signal_dbm') else int(
                    packet.radiotap.dbm_antsignal)
            pchannel = next((int(tag.current_channel)
                             for tag in packet.wlan_mgt.tagged.all.tag
                             if hasattr(tag, 'current_channel')), None)
            if not pchannel:
                pchannel = int(packet.wlan_radio.channel) if hasattr(
                    packet.wlan_radio, 'channel') else int(
                        packet.radiotap.channel.freq)

            # Determine AP security, if any https://ccie-or-null.net/2011/06/22/802-11-beacon-frames/
            pencryption = None
            pcipher = None
            pauth = None

            _cipher_tree = None
            _auth_tree = None

            # Parse Security Details
            # Check for MS WPA tag
            _ms_wpa = next(
                (i for i, tag in enumerate(packet.wlan_mgt.tagged.all.tag)
                 if hasattr(tag, 'wfa.ie.wpa.version')), None)
            if _ms_wpa is not None:
                pencryption = "WPA"

                if hasattr(packet.wlan_mgt.tagged.all.tag[_ms_wpa].wfa.ie.wpa,
                           'akms.list'):
                    _auth_tree = packet.wlan_mgt.tagged.all.tag[
                        _ms_wpa].wfa.ie.wpa.akms.list.akms_tree

                if hasattr(packet.wlan_mgt.tagged.all.tag[_ms_wpa].wfa.ie.wpa,
                           'ucs.list'):
                    _cipher_tree = packet.wlan_mgt.tagged.all.tag[
                        _ms_wpa].wfa.ie.wpa.ucs.list.ucs_tree

            # Check for RSN Tag
            _rsn = next(
                (i for i, tag in enumerate(packet.wlan_mgt.tagged.all.tag)
                 if hasattr(tag, 'rsn')), None)
            if _rsn is not None:
                pencryption = "WPA"

                if hasattr(packet.wlan_mgt.tagged.all.tag[_rsn].rsn,
                           'akms.list') and _auth_tree is None:
                    _auth_tree = packet.wlan_mgt.tagged.all.tag[
                        _rsn].rsn.akms.list.akms_tree

                if hasattr(packet.wlan_mgt.tagged.all.tag[_rsn].rsn,
                           'pcs.list') and _cipher_tree is None:
                    _cipher_tree = packet.wlan_mgt.tagged.all.tag[
                        _rsn].rsn.pcs.list.pcs_tree

            # Parse _auth_tree
            if _auth_tree:
                try:
                    _type = _auth_tree.type == '2'
                except AttributeError:
                    _type = next(
                        (_node.type
                         for _node in _auth_tree if hasattr(_node, 'type') and
                         (_node.type == '2' or _node.type == '3')), False)

                if _type == '3':
                    pauth = "FT"
                elif _type == '2':
                    pauth = "PSK"

            # Parse _cipher_tree
            if _cipher_tree:
                _types = []
                try:
                    _types.append(_cipher_tree.type)
                except AttributeError:
                    _types += [
                        _node.type for _node in _cipher_tree
                        if hasattr(_node, 'type')
                    ]

                if _types:
                    _types_str = []
                    for _type in _types:
                        if _type == '4':
                            _types_str.append("CCMP")
                        elif _type == '2':
                            _types_str.append("TKIP")
                    pcipher = "+".join(_types_str)

            if not pencryption:
                # WEP
                pencryption = "WEP" if packet.wlan_mgt.fixed.all.capabilities_tree.has_field(
                    "privacy"
                ) and packet.wlan_mgt.fixed.all.capabilities_tree.privacy == 1 else "Open"
                if pencryption == "WEP":
                    pcipher = "WEP"

        except AttributeError as e:
            module_logger.warning("Failed to parse packet: {}".format(e))
            _beacon_failures += 1
            continue

        # Antenna correlation
        # Compute the timespan for the rotation, and use the relative packet time to determine
        # where in the rotation the packet was captured
        # This is necessary to have a smooth antenna rotation with microstepping
        total_time = float(meta["end"]) - float(meta["start"])
        pdiff = ptime - float(meta["start"])
        if pdiff <= 0:
            pdiff = 0

        cw = 1 if clockwise else -1

        pprogress = pdiff / total_time
        pbearing_magnetic = (cw * pprogress * float(meta["degrees"]) +
                             float(meta["bearing"])) % 360
        pbearing_true = (pbearing_magnetic + _declination) % 360

        _rows.append([
            meta[meta_csv_fieldnames[0]],
            meta[meta_csv_fieldnames[1]],
            meta[meta_csv_fieldnames[4]],
            meta[meta_csv_fieldnames[5]],
            ptime,
            str(pbssid),
            str(pssid),
            pencryption,
            pcipher,
            pauth,
            pssi,
            pchannel,
            pbearing_magnetic,
            pbearing_true,
            meta[meta_csv_fieldnames[6]],
            meta[meta_csv_fieldnames[7]],
            meta[meta_csv_fieldnames[8]],
            meta[meta_csv_fieldnames[9]],
            meta[meta_csv_fieldnames[10]],
            meta[meta_csv_fieldnames[11]],
        ])

        _beacon_count += 1

    _results_df = pd.DataFrame(_rows, columns=_default_columns)
    # Add mw column
    _results_df.loc[:, 'mw'] = dbm_to_mw(_results_df['ssi'])
    module_logger.info("Completed processing {} beacons ({} failures)".format(
        _beacon_count, _beacon_failures))

    # If asked to guess, return list of bssids and a guess as to their bearing
    if guess:
        _columns = [
            'ssid', 'bssid', 'channel', 'security', 'strength', 'method',
            'bearing'
        ]
        _rows = []

        with futures.ProcessPoolExecutor() as executor:

            _guess_processes = {}

            for names, group in _results_df.groupby(['ssid', 'bssid']):
                _channel = group.groupby('channel').count()['capture'].idxmax()
                _encryption = pd.unique(group['encryption'])[0]
                # _cipher = pd.unique(group['cipher'])[0]
                # _auth = pd.unique(group['auth'])[0]
                _strength = group['ssi'].max()
                if not names[0]:
                    names = ('<blank>', names[1])

                _row = [names[0], names[1], _channel, _encryption, _strength]
                _guess_processes[executor.submit(locate.interpolate, group,
                                                 int(meta['degrees']))] = _row

            for future in futures.as_completed(_guess_processes):
                _row = _guess_processes[future]
                _guess, _method = future.result()
                _rows.append(_row + [_method, _guess])

            guess = pd.DataFrame(_rows,
                                 columns=_columns).sort_values('strength',
                                                               ascending=False)

    # If a path is given, write the results to a file
    if write_to_disk:
        _results_path = os.path.join(
            path,
            time.strftime('%Y%m%d-%H-%M-%S') + "-results" + ".csv")
        _results_df.to_csv(_results_path, sep=',', index=False)
        module_logger.info("Wrote results to {}".format(_results_path))
        write_to_disk = _results_path

    return _beacon_count, _results_df, write_to_disk, guess
Exemplo n.º 40
0
def get_tru_heading(raw, lat, lon):
    return raw - geomag.declination(lat,lon)*ephem.degree
Exemplo n.º 41
0
def parseAccelMag(mag, accel, lat, lon):
    """
    Parse the accelerometer and magnetometer, calculating a heading.

    :param mag:     The magetometer sensor object.
    :param accel:   The accelerometer sensor object.
    :param lat:     The current latitude, to use to calculate the magnetic declination.
    :param lon:     The current longitude, to use to calculate the magnetic declination.
    """
    # Set magnetometer offset
    magOffset = [14.699999999999996, 26.55, -5.324999999999999]

    # Get sensor data
    accels = accel.acceleration
    mags = mag.magnetic

    accx = accels[0]
    accy = accels[1]
    accz = accels[2]
    magx = mags[0] + magOffset[0]
    magy = mags[1] + magOffset[1]
    magz = mags[2] + magOffset[2]

    # Convert in terms of g
    g = 9.81
    gx = accx / g
    gy = accy / g
    gz = accz / g

    # Calculate roll and pitch from accel data
    if abs(gx) > 1:
        gx = math.copysign(1, gx)
    pitch = math.asin(-gx)
    checkVal = gy / math.cos(pitch)
    if (abs(checkVal) <= 1.0):
        roll = math.asin(checkVal)
    else:
        roll = 0

    # Calculate compass heading - compensate for tilt, require pitch, roll from accel
    magNorm = math.sqrt(magx**2 + magy**2 + magz**2)
    mxn = magx / magNorm
    myn = magy / magNorm
    mzn = magz / magNorm

    # Project onto x-y plane
    mx2 = (mxn * math.cos(pitch)) + (mzn * math.sin(pitch))
    my2 = (mxn * math.sin(roll) * math.sin(pitch)) + (myn * math.cos(roll)) - (
        mzn * math.sin(roll) * math.cos(pitch))
    mz2 = (-mzn * math.cos(roll) * math.sin(pitch)) + (
        myn * math.sin(roll)) + (mzn * math.cos(roll) * math.cos(pitch))

    # Calc heading
    heading = 0
    if (mx2 > 0 and my2 > 0):
        heading = math.atan(my2 / mx2)
    elif mx2 < 0:
        heading = math.pi + math.atan(my2 / mx2)
    elif (mx2 > 0 and my2 <= 0):
        heading = 2 * math.pi + math.atan(my2 / mx2)
    elif my2 < 0:
        # mx2 == 0
        heading = math.pi / 2.0
    elif my2 > 0:
        # mx2 == 0
        heading = 3 * math.pi / 2.0

    headingMagCompass = (-180.0 * heading / math.pi + 180.0) % 360

    # Adjust for magnetic declination
    currDeclination = geomag.declination(lat, lon)
    headingMagTrue = (heading + currDeclination) % 360

    # Convert pitch and roll to degs
    pitch = math.degrees(pitch)
    roll = math.degrees(roll)

    return accx, accy, accz, magx, magy, magz, pitch, roll, headingMagCompass, headingMagTrue
Exemplo n.º 42
0
    def compute_current_weather(self):
        ts = []
        icaos = []
        lats = []
        lons = []
        alts = []
        temps = []
        vgs = []
        trks = []
        vas = []
        hdgs = []
        magdev = []

        update_acs = self.get_updated_aircraft()

        for icao, ac in list(update_acs.items()):  # only last updated
            # ac = self.acs[icao]
            # print(ac['icao'])

            if ('tpos' not in ac) or ('tv' not in ac) or ('t60' not in ac) or \
                    ('t50' not in ac) or ('gs' not in ac):
                continue

            if (self.t - ac['tpos'] > 5) or (self.t - ac['t60'] > 5) or (self.t - ac['t50'] > 5) or \
                    (self.correction and ac['roll'] > 5):
                continue

            h = ac['alt'] * aero.ft
            vtas = ac['tas'] * aero.kts
            vias = ac['ias'] * aero.kts
            mach = ac['mach']

            if h < 11000:
                p = 101325 * (1 + (-0.0065 * h) / 288.15)**(-9.81 /
                                                            (-0.0065 * 287.05))
            if h >= 11000:  # up to 20000 m
                p = 22632 * np.exp(-(9.81 * (h - 11000) / (287.05 * 216.65)))

            if mach < 0.3:
                temp = vtas**2 * p / (vias**2 * aero.rho0 * aero.R)
                rho = p / (aero.R * temp)
                vtas2 = vias * np.sqrt(aero.rho0 / rho)
            else:
                temp = vtas**2 * aero.T0 / (mach**2 * aero.a0**2)
                vtas2 = mach * aero.a0 * np.sqrt(temp / aero.T0)

            va = vtas if ac['t50'] > ac['t60'] else vtas2

            ts.append(ac['tpos'])
            icaos.append(icao)
            lats.append(ac['lat'])
            lons.append(ac['lon'])
            alts.append(ac['alt'])
            temps.append(temp)
            vgs.append(ac['gs'] * 0.5144)
            trks.append(np.radians(ac['trk']))
            vas.append(va)
            hdgs.append(np.radians(ac['hdg']))
            magdev.append(np.radians(ac['magdev']))

        if GEO_MAG_SUPPORT:
            d_hdgs = []
            for i, hdg in enumerate(hdgs):
                d_hdg = np.radians(
                    geomag.declination(lats[i], lons[i], alts[i]))
                d_hdgs.append(d_hdg)

            hdgs = hdgs - np.array(d_hdgs) + magdev

        vgx = vgs * np.sin(trks)
        vgy = vgs * np.cos(trks)
        vax = vas * np.sin(hdgs)
        vay = vas * np.cos(hdgs)

        wx = vgx - vax
        wy = vgy - vay

        self.weather = OrderedDict()
        self.weather['ts'] = np.array(ts)
        self.weather['icao'] = np.array(icaos)
        self.weather['lat'] = np.array(lats)
        self.weather['lon'] = np.array(lons)
        self.weather['alt'] = np.array(alts)
        self.weather['wx'] = wx
        self.weather['wy'] = wy
        self.weather['temp'] = temps

        # very important to reset the buffer
        self.reset_updated_aircraft()

        # return the new weather dataframe
        df_weather = pd.DataFrame.from_dict(self.weather)
        return df_weather if df_weather.shape[0] > 0 else None
Exemplo n.º 43
0
def updateMapLayout():
    mxd, df = getDataframe()

    dfSpatial_Ref = df.spatialReference.name
    dfSpatial_Type = df.spatialReference.type

    # Get UTM and USNG Zones
    # Get declination from Incident Information

    fc1 = "Plan_Point"
    fc2 = "Incident_Information"
    fc3 = "Assets"

    cPlanPt = arcpy.GetCount_management(fc1)
    cBasePt = arcpy.GetCount_management(fc3)
    if int(cPlanPt.getOutput(0)) > 0:
        cPlanPt = cPlanPt
        intLyr = "1 Incident_Group\Planning Point"
    elif int(cBasePt.getOutput(0)) > 0:
        cPlanPt = cBasePt
        fc1 = fc3
        intLyr = "2 Incident Assets\Assets"
    else:
        arcpy.AddError("Warning: Need to add Planning Point or ICP prior to updating map layout.\n")
        arcpy.AddError("Warning: Map Layout COULD NOT be updated.\n")
        sys.exit(0)

    desc = arcpy.Describe(fc1)

    unProjCoordSys = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    shapefieldname = desc.ShapeFieldName

    #First determine the grid north value
    fld_gNorth = "gNORTH"
    field_type = "FLOAT"
    gNorth_Check(fc1, fld_gNorth, field_type)
    if fc1 == "Assets":
        where0 = '"Asset_Type" = 1'
    else:
        where0 = ""
    rows0 = arcpy.SearchCursor(fc1, where0, unProjCoordSys)
    k = 0.0
    gridNorth = 0.0
    for row0 in rows0:
        gridN = row0.getValue(fld_gNorth)
        arcpy.AddMessage('Grid North: {0}'.format(gridN))
        gridNorth += float(gridN)
        k+=1.0
    del row0
    del rows0
    del k


    rows1 = arcpy.SearchCursor(fc1, where0, unProjCoordSys)
    k = 0
    declin = 0.0
    for row1 in rows1:
        feat = row1.getValue(shapefieldname)
        pnt = feat.getPart()
        latitude = pnt.Y
        longitude = pnt.X
        declin = geomag.declination(latitude,longitude) + declin
        k+=1
    del rows1
    del row1

    gridN = round((gridNorth / k),2)
    if gridN > 0:
        gCard ="W"
    else:
        gCard ="E"
    gNorthTxt = str(abs(gridN)) + " " + gCard

    # Rotate data frame to adjust map layout for True North vs Grid North.
    # Grid North is parallel with the edge of the page.  The "True North" arrow
    # should be rotated to TRUE NORTH.
    try:
        df.rotation = 0.0
        if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "gNorth"):
            gridNorth=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "gNorth")[0]
            gridNorth.text = gNorthTxt
        # Remove field
        dropField=[fld_gNorth]
        arcpy.DeleteField_management(fc1, dropField)
    except:
        pass

    declin_avg = declin / k
    MagDeclinlination = round(declin_avg,2)
    if MagDeclinlination < 0:
        Cardinal ="W"
        bearingTuple=('ADD','SUBTRACT')
    else:
        Cardinal ="E"
        bearingTuple=('SUBTRACT','ADD')
    MagDecTxt = str(abs(MagDeclinlination)) + " " + Cardinal

##    try:  #Update Incident Name and Number with the file name and dataframe name
    IncName = df.name
    IncNumA = mxd.filePath.split("\\")
    IncNum=IncNumA[-1].strip(".mxd")
    arcpy.AddMessage("\nThe Incident Name is " + IncName)
    arcpy.AddMessage("The Incident Number is: " + IncNum + "\n")
    if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MapName"):
        MapName=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MapName")[0]
        MapName.text = " "

    if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "PlanNum"):
        PlanNum=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "PlanNum")[0]
        PlanNum.text = " "

    if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "AssignNum"):
        AssignNum=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "AssignNum")[0]
        AssignNum.text = " "

    fld2 = "Incident_Name"
    fld3 = "Incident_Number"
    cursor = arcpy.UpdateCursor(fc2)
    for row in cursor:
        incidName=row.getValue(fld2)
        if incidName != IncName:
            row.setValue(fld2, IncName)
            row.setValue(fld3, IncNum)
            cursor.updateRow(row)
        del incidName
    del cursor, row
    del IncName, IncNum, fld2, fld3
##    except:
##        arcpy.AddMessage("Error: Update Incident Name and Number manually\n")

    arcpy.AddMessage("The Coordinate System for the dataframe is: " + dfSpatial_Type)
    arcpy.AddMessage("The Datum for the dataframe is: " + dfSpatial_Ref)
    if dfSpatial_Type=='Projected':
        arcpy.AddMessage("Be sure to turn on USNG Grid in Data Frame Properties.\n")

    arcpy.AddMessage("Updating UTM and USNG grid info on map layout")
##    try:
    for llyr in arcpy.mapping.ListLayers(mxd, "*",df):
        if str(llyr.name) == "MRGS_UTM_USNG":
            mapLyr=arcpy.mapping.ListLayers(mxd, "MRGS_UTM_USNG",df)[0]
        elif str(llyr.name) == "MRGSZones_World":
            mapLyr=arcpy.mapping.ListLayers(mxd, "MGRSZones_World",df)[0]
    arcpy.SelectLayerByLocation_management(mapLyr,"INTERSECT", intLyr) #"1 Incident_Group\Planning Point")
    cursor=arcpy.SearchCursor(mapLyr)
    for row in cursor:
        if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "UTMZone"):
            UTMZn=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "UTMZone")[0]
            UTMZn.text = row.getValue("GRID1MIL")
            UTMzone = str(UTMZn.text)
        else:
            UTMzone = ""

        if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "USNGZone"):
            USNGZn=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "USNGZone")[0]
            USNGZn.text = row.getValue("GRID100K")
            USNGzone = str(USNGZn.text)
        else:
            USNGzone =""
        arcpy.AddMessage("UTM Zone is {0} and USNG Grid is {1}".format(UTMzone,USNGzone))
    del cursor
    try:
        del row
    except:
        pass
    del mapLyr
##    except:
##        arcpy.AddMessage("Error: Update USNG Grid and UTM Zone text fields on map layout manually\n")

    arcpy.AddMessage("Grid North correction to True North based on location of IPP or ICP is: {0}".format(gNorthTxt))
    try:
        cIncident=arcpy.GetCount_management("Incident_Information")
        # Get list of fields in Incident Information
        fieldList = arcpy.ListFields(fc2)
        field=[]
        for fld in fieldList:
            field.append(fld.name.encode('ascii','ignore'))

        fld_gNorth = "gNORTH"
        fldType = "STRING"
        checkFields(fc2, fld_gNorth, fldType)

        fld_MagDec = "MagDec"
        fldType = "STRING"
        checkFields(fc2, fld_MagDec, fldType)


        if int(cIncident.getOutput(0)) > 0:
            cursor = arcpy.UpdateCursor(fc2)
            for row in cursor:
                row.setValue(fld_MagDec, MagDecTxt)
                row.setValue(fld_gNorth, gNorthTxt)
                cursor.updateRow(row)
            if arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MagDecl"):
                MagDeclin=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "MagDecl")[0]
                MagDeclin.text = MagDecTxt
                arcpy.AddMessage("Magnetic Declination is {0}\n".format(MagDeclin.text))
                del MagDeclin
            del cursor, row

        else:
            arcpy.AddWarning("No Incident Information provided\n")

        try:
            if arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","bearingConv"):
                bearingConv=arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","bearingConv")[0]
                bcText=bearingConv.text
                # Even though the templates have %s in them, we may have
                # clobbered them in a previous run.  So put 'em back.
                bcText=bcText.replace('ADD','%s')
                bcText=bcText.replace('SUBTRACT','%s')
                bearingConv.text= bcText % bearingTuple
                del bearingConv
        except:
            arcpy.AddMessage("Failed to update bearing conversion text.")
    except:
        arcpy.AddMessage("Error: Update Magnetic Declination Manually\n")

    try:
        fld2 = "MapDatum"
        fld3 = "MapCoord"
        cursor = arcpy.UpdateCursor(fc2)
        for row in cursor:
            row.setValue(fld2, dfSpatial_Ref)
        ##                row.setValue(fld3, dfSpatial_Type)
            if "UTM_ZONE" in field:
                row.setValue("UTM_ZONE", UTMZn.text)
            if "USNG_GRID" in field:
                row.setValue("USNG_GRID", USNGZn.text)
            cursor.updateRow(row)
        del cursor, row
    except:
        arcpy.AddMessage("Error: Update Map Datum and Map Coordinates (Projected/Geogrpahic) Manually\n")

    try:
        del UTMZn
        del USNGZn
    except:
        pass

    del mxd
    del df, dfSpatial_Ref, dfSpatial_Type
    return
Exemplo n.º 44
0
def test_timedistance_v0(dlat, dlng, alt, date, dec):
    assert round(declination(dlat, dlng, alt, date), 2) == dec
    def refresh(self):
        global recievedTime, losLog, bearingLog, elevationLog
        if (useRFD):
            self.updateIncoming(0, 0, rfdTime)
            self.updateIncoming(0, 1, rfdLat)
            self.updateIncoming(0, 2, rfdLon)
            self.updateIncoming(0, 3, round(rfdAlt, 2))
            self.updateIncoming(0, 4, round(rfdEle, 2))
            self.updateIncoming(0, 5, round(rfdBear, 2))
            self.updateIncoming(0, 6, round(rfdLOS, 2))
            self.updateIncoming(
                0, 7,
                round(
                    float(
                        geomag.declination(dlat=rfdLat, dlon=rfdLon,
                                           h=rfdAlt))), 2)
        else:
            #Incoming Data Table
            self.updateIncoming(0, 0, iridiumTime)
            self.updateIncoming(0, 1, iridiumLat)
            self.updateIncoming(0, 2, iridiumLon)
            self.updateIncoming(0, 3, round(iridiumAlt, 2))
            self.updateIncoming(0, 4, round(iridiumEle, 2))
            self.updateIncoming(0, 5, round(iridiumBear, 2))
            self.updateIncoming(0, 6, round(iridiumLOS, 2))
            self.updateIncoming(
                0, 7,
                round(
                    geomag.declination(dlat=iridiumLat,
                                       dlon=iridiumLon,
                                       h=iridiumAlt), 2))

        #Ground Station Data Table (unlikely to change but what the heck)
        self.updateGround(0, 0, groundLat)
        self.updateGround(0, 1, groundLon)
        self.updateGround(0, 2, groundAlt)
        self.updateGround(0, 3, centerBear)
        #Antenna current "intended" position
        self.updateGround(0, 4, trackBearOffset)
        self.updateGround(0, 5, trackTiltOffset)
        self.updateGround(0, 6, antennaBear)
        self.updateGround(0, 7, antennaEle)
        if settingsUpdated:
            testarray = np.array([
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                18, 19, 20, 21, 22, 23
            ])
            testdata = np.array([
                0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4,
                5, 6, 7
            ])
            if len(receivedAlt) > 0:

                # create an axis
                ALTPLOT = self.figure.add_subplot(221)
                LOSPLOT = self.figure.add_subplot(222)
                ELEPLOT = self.figure.add_subplot(223)
                BEARPLOT = self.figure.add_subplot(224)

                # discards the old graph
                ALTPLOT.hold(False)
                LOSPLOT.hold(False)
                ELEPLOT.hold(False)
                BEARPLOT.hold(False)

                # plot data
                ALTPLOT.plot(receivedTime - receivedTime[0], receivedAlt, 'r-')
                ALTPLOT.set_ylabel('Altitude (ft)')
                LOSPLOT.plot(receivedTime - receivedTime[0], losLog, 'g-')
                LOSPLOT.set_ylabel('Line-of-Sight (km)')
                ELEPLOT.plot(receivedTime - receivedTime[0], elevationLog,
                             'b-')
                ELEPLOT.set_ylabel('Elevation Angle')
                BEARPLOT.plot(receivedTime - receivedTime[0], bearingLog, 'y-')
                BEARPLOT.set_ylabel('Bearing Angle')

                # refresh canvas
                self.canvas.draw()
Exemplo n.º 46
0
def updateMapLayout(aprx, df, lyt, mf):
    fc1 = "Planning_Points"
    fc2 = "Incident_Info"
    fc3 = "AssetPts"

    IncidPP = path.join(wrkspc, fc1)
    desc = arcpy.Describe(IncidPP)
    dfSpatial_Ref = desc.spatialReference.name
    dfSpatial_Type = desc.spatialReference.type

    # Get UTM and USNG Zones
    # Get declination from Incident Information

    cPlanPt = arcpy.GetCount_management(fc1)
    cBasePt = arcpy.GetCount_management(fc3)
    if int(cPlanPt.getOutput(0)) > 0:
        cPlanPt = cPlanPt
        intLyr = "Incident\Planning_Points"
    elif int(cBasePt.getOutput(0)) > 0:
        cPlanPt = cBasePt
        fc1 = fc3
        intLyr = "Assets\Assets"
    else:
        arcpy.AddError(
            "Warning: Need to add Planning Point or ICP prior to updating map layout.\n"
        )
        arcpy.AddError("Warning: Map Layout COULD NOT be updated.\n")
        sys.exit(0)

    unProjCoordSys = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    shapefieldname = desc.ShapeFieldName

    # Determine grid North (if applicable) and declination
    fld_gNorth = "gNORTH"
    field_type = "FLOAT"
    if fc1 == "Assets":
        where0 = '"Asset_Type" = 1'
    else:
        where0 = ""

    if dfSpatial_Type == "Projected":
        cMeridian = desc.spatialReference.centralmeridian
    gridConv = []
    deClinat = []
    for row in arcpy.da.SearchCursor(fc1, ["SHAPE@XY"], where0,
                                     unProjCoordSys):
        x, y = row[0]
        if dfSpatial_Type == "Projected":
            gridConv.append(atan(tan(x - cMeridian) + sin(y)))
        else:
            gridConv.append(0.0)
        deClinat.append(declination(y, x))

    # Grid North determination
    gridNorth = mean(gridConv)
    gridN = round(gridNorth, 2)
    if gridN > 0:
        gCard = "W"
    else:
        gCard = "E"
    gNorthTxt = str(abs(gridN)) + " " + gCard
    arcpy.AddMessage('Grid North: {0}'.format(gNorthTxt))

    # Magnetic Declination
    declin = mean(deClinat)
    MagDeclinlination = round(declin, 2)
    if MagDeclinlination < 0:
        Cardinal = "W"
    else:
        Cardinal = "E"
    MagDecTxt = str(abs(MagDeclinlination)) + " " + Cardinal

    # Rotate data frame to adjust map layout for True North vs Grid North.
    # Grid North is parallel with the edge of the page.  The "True North" arrow
    # should be rotated to TRUE NORTH.

    # Rotate the map by grid north - or do I need to rotate to -gridN?
    mf.camera.heading = gridN
    try:
        if lyt.listElements('TEXT_ELEMENT', 'MagDec'):
            magNorth = lyt.listElements('TEXT_ELEMENT', 'MagDec')[0]
            magNorth.text = MagDecTxt
        if lyt.listElements('TEXT_ELEMENT', 'gNorth'):
            gNorth = lyt.listElements('TEXT_ELEMENT', 'gNorth')[0]
            gNorth.text = gNorthTxt
    except:
        pass

##    try:  #Update Incident Name and Number with the file name and dataframe name
    IncidName = " "
    IncNum = " "
    flds = ['IncidName', 'IncidNum']
    with arcpy.da.SearchCursor(fc2, flds) as cursor:
        for row in cursor:
            IncidName = row[0]
            IncNum = row[1]
    arcpy.AddMessage("\nThe Incident Name is " + IncidName)
    arcpy.AddMessage("The Incident Number is: " + IncNum + "\n")
    if lyt.listElements("TEXT_ELEMENT", "MapTitle"):
        MapTitle = lyt.listElements("TEXT_ELEMENT", "MapTitle")[0]
        MapTitle.text = " "

    if lyt.listElements("TEXT_ELEMENT", "RefNum"):
        RefNum = lyt.listElements("TEXT_ELEMENT", "RefNum")[0]
        RefNum.text = " "

    del cursor, row
    del IncidName, IncNum, flds
    ##    except:
    ##        arcpy.AddMessage("Error: Update Incident Name and Number manually\n")

    arcpy.AddMessage(
        "Grid North correction to True North based on location of IPP or ICP is: {0}"
        .format(gNorthTxt))
    #    try:
    cIncident = arcpy.GetCount_management(fc2)
    # Get list of fields in Incident Information
    fieldList = arcpy.ListFields(fc2)
    field = []
    for fld in fieldList:
        field.append(fld.name.encode('ascii', 'ignore'))

    fld2 = "MapDatum"
    fld3 = "MapCoord"

    incdFlds = ["MagDec", "gNorth", "UTM_ZONE", "USNG_GRID",
                "MapDatum"]  #,fld2, fld3]
    if int(cIncident.getOutput(0)) > 0:
        with arcpy.da.UpdateCursor(fc2, incdFlds) as cursor:
            for row in cursor:
                row[0] = MagDecTxt
                row[1] = gNorthTxt
                #                row[2]=UTMZn.text
                #                row[3]=USNGZn.text
                #                row[4]=dfSpatial_Ref
                cursor.updateRow(row)
        del cursor, row
    else:
        arcpy.AddWarning("No Incident Information provided\n")
#    except:
#        arcpy.AddMessage("Error: Update Magnetic Declination Manually\n")
    return
Exemplo n.º 47
0
def string_notes(system, run=0.0, station_class=3):
    """page 5"""

    name, usaf = geo.closest_usaf(geo.zip_coordinates(system.zipcode), \
            station_class)
    mintemp = eere.minimum(usaf)
    twopercent_temp = eere.twopercent(usaf)
    ac_kva_rated = 0.0
    dc_rated = 0.0
    ac_kw = 0.0
    for i in system.shape:
        dc_rated += i.array.p_max
        try:
            if i.phase == 1:
                ac_kva_rated += i.current * i.ac_voltage
            else:
                ac_kva_rated += i.phase * i.current * i.ac_voltage / 3**.5
        except Exception:
            ac_kva_rated += i.p_aco
        ac_kw += i.p_aco
    notes = []
    notes.append("%s KVA AC RATED" % round(ac_kva_rated/1000.0, 2))
    notes.append("%s KW AC RATED" % round(ac_kw/1000.0, 2))
    notes.append("%s KW DC RATED" % round(dc_rated/1000.0, 2))
    #BUG: This doesn't work for unbalanced 3 phase
    if system.phase == 1:
        a_ac = round(ac_kva_rated/i.ac_voltage, 1)
    else:
        a_ac = round(ac_kva_rated/i.ac_voltage/3**.5, 1)
    notes.append("System AC Output Current: %s A" % a_ac)

    notes.append("Nominal AC Voltage: %s V" % i.ac_voltage)
    notes.append("")
    notes.append("Minimum Temperature: %s C" % mintemp)
    notes.append("2 Percent Max Temperature: %s C" % twopercent_temp)
    notes.append("Weather Source: %s %s" % (name, usaf))
    notes.append("")
    d_inverters, d_panels = system.describe()
    a_max = 0
    for i in system.shape:
        module_name = i.array.dump()['panel']
        if d_panels.has_key(module_name):
            module = modules.Module(module_name)
            notes.append("PV Module Ratings @ STC")
            notes.append("Module Make: %s" % module.make)
            notes.append("Module Model: %s" % module.model)
            notes.append("Quantity: %s" % d_panels[module_name])
            notes.append("Max Power-Point Current (Imp): %s A" % module.i_mpp)
            notes.append("Max Power-Point Voltage (Vmp): %s V" % module.v_mpp)
            notes.append("Open-Circuit Voltage (Voc): %s V" % module.v_oc)
            notes.append("Short-Circuit Current (Isc): %s A" % module.i_sc)
            notes.append("Maximum Power (Pmax): %s W" % round(module.p_max, 1))

            notes.append("")
            d_panels.pop(module_name)
        if d_inverters.has_key(i.model):
            notes.append("Inverter Make: %s" % i.make)
            notes.append("Inverter Model: %s" % i.model)
            notes.append("Quantity: %s" % d_inverters[i.model])
            notes.append("Max Power: %s KW" % round(i.p_aco/1000.0, 1))
            #this is hack... This should be calculated based upon power cores
            if hasattr(i, 'current'):
                notes.append("Max AC Current: %s A" % round(i.current, 1))
            elif i.ac_voltage == 480:
                notes.append("Max AC Current: %s A" % \
                        round(i.p_aco*1.0/i.ac_voltage/3**.5, 1))
            else:
                notes.append("Max AC Current: %s A" % \
                        round(i.p_aco*1.0/i.ac_voltage, 1))
            #greater than 1 in parallel
            if i.array.mcount() > 1:
                notes.append("DC Operating Current: %s A" % \
                        round(i.array.i_mpp(), 1))
                notes.append("DC Short Circuit Current: %s A" % \
                        round(i.array.i_sc(), 1))
            #greater than 1 in series
            if i.array.mcount() > 1:
                notes.append("DC Operating Voltage: %s V" % \
                        round(i.array.v_dc(), 1))
                notes.append("System Max DC Voltage: %s V" % \
                        round(i.array.v_max(mintemp), 1))
                if i.array.v_max(mintemp) > 600:
                    logger.warning("WARNING: Array exceeds 600V DC")
                notes.append("Pnom Ratio: %s" % \
                        round((i.array.p_max/i.p_aco), 2))
                if (i.array.v_dc(twopercent_temp) * .9) < i.mppt_low:
                    logger.warning("WARNING: " \
                            "Array IV Knee drops out of Inverter range")
                if (i.array.p_max/i.p_aco) < 1.1:
                    logger.warning("WARNING: Array potentially undersized")
            notes.append("")
            d_inverters.pop(i.model)
        if i.array.v_max(mintemp) > a_max:
            a_max = i.array.v_max(mintemp)

    notes.append("Array Azimuth: %s Degrees" % system.azimuth)
    notes.append("Array Tilt: %s Degrees" % system.tilt)
    sols_9 = system.solstice(9)
    sols_15 = system.solstice(15)
    notes.append("December 21 9:00 AM Sun Azimuth: %s Degrees" % \
            (round(degrees(sols_9[1]), 1)))
    notes.append("December 21 9:00 AM Sun Altitude: %s Degrees" % \
            (round(degrees(sols_9[0]), 1)))
    notes.append("December 21 3:00 PM Sun Azimuth: %s Degrees" % \
            (round(degrees(sols_15[1]), 1)))
    notes.append("December 21 3:00 PM Sun Altitude: %s Degrees" % \
            (round(degrees(sols_9[0]), 1)))
    if 'geomag' in sys.modules:
        notes.append("Magnetic declination: %s Degrees" % \
                round(geomag.declination(dlat=system.place[0], \
                dlon=system.place[1])))
    notes.append("Minimum Row space ratio: %s" % \
            round(system.min_row_space(1.0), 2))
    if __name__ == '__main__':
        print "\n".join(notes)
    else:
        logger.info("Plant Details:\n" + "\n".join(notes))

    print ""
    print "Minimum Bundle"
    min_c = vd.vd(a_ac, 5, verbose=False)
    try:
        ee.assemble(min_c, a_ac, conduit='STEEL')
        if run > 0:
            print "Long Run"
            min_c = vd.vd(a_ac, run, v=i.ac_voltage, t_amb=15, pf=.95, \
                    material='AL', verbose=False)
            ee.assemble(min_c, a_ac, conduit='PVC')
    except:
        print "Warning: Multiple sets of conductors"
    return notes
Exemplo n.º 48
0
def getMagneticDeclination(geometry, feature, parent):
    geom_pt = geometry.asPoint()
    return geomag.declination(geom_pt.y(), geom_pt.x())