idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
54,000 | def get_position ( self , utc_time , normalize = True ) : kep = self . _sgdp4 . propagate ( utc_time ) pos , vel = kep2xyz ( kep ) if normalize : pos /= XKMPER vel /= XKMPER * XMNPDA / SECDAY return pos , vel | Get the cartesian position and velocity from the satellite . |
54,001 | def compute_pixels ( orb , sgeom , times , rpy = ( 0.0 , 0.0 , 0.0 ) ) : if isinstance ( orb , ( list , tuple ) ) : tle1 , tle2 = orb orb = Orbital ( "mysatellite" , line1 = tle1 , line2 = tle2 ) pos , vel = orb . get_position ( times , normalize = False ) vectors = sgeom . vectors ( pos , vel , * rpy ) centre = - pos a__ = 6378.137 b__ = 6356.752314245 radius = np . array ( [ [ 1 / a__ , 1 / a__ , 1 / b__ ] ] ) . T shape = vectors . shape xr_ = vectors . reshape ( [ 3 , - 1 ] ) * radius cr_ = centre . reshape ( [ 3 , - 1 ] ) * radius ldotc = np . einsum ( "ij,ij->j" , xr_ , cr_ ) lsq = np . einsum ( "ij,ij->j" , xr_ , xr_ ) csq = np . einsum ( "ij,ij->j" , cr_ , cr_ ) d1_ = ( ldotc - np . sqrt ( ldotc ** 2 - csq * lsq + lsq ) ) / lsq return vectors * d1_ . reshape ( shape [ 1 : ] ) - centre | Compute cartesian coordinates of the pixels in instrument scan . |
54,002 | def vectors ( self , pos , vel , roll = 0.0 , pitch = 0.0 , yaw = 0.0 ) : nadir = subpoint ( - pos ) nadir /= vnorm ( nadir ) x = vel / vnorm ( vel ) y = np . cross ( nadir , vel , 0 , 0 , 0 ) y /= vnorm ( y ) x_rotated = qrotate ( nadir , x , self . fovs [ 0 ] + roll ) xy_rotated = qrotate ( x_rotated , y , self . fovs [ 1 ] + pitch ) return qrotate ( xy_rotated , nadir , yaw ) | Get unit vectors pointing to the different pixels . |
54,003 | def avhrr ( scans_nb , scan_points , scan_angle = 55.37 , frequency = 1 / 6.0 , apply_offset = True ) : avhrr_inst = np . vstack ( ( ( scan_points / 1023.5 - 1 ) * np . deg2rad ( - scan_angle ) , np . zeros ( ( len ( scan_points ) , ) ) ) ) avhrr_inst = np . tile ( avhrr_inst [ : , np . newaxis , : ] , [ 1 , np . int ( scans_nb ) , 1 ] ) times = np . tile ( scan_points * 0.000025 , [ np . int ( scans_nb ) , 1 ] ) if apply_offset : offset = np . arange ( np . int ( scans_nb ) ) * frequency times += np . expand_dims ( offset , 1 ) return ScanGeometry ( avhrr_inst , times ) | Definition of the avhrr instrument . |
54,004 | def avhrr_gac ( scan_times , scan_points , scan_angle = 55.37 , frequency = 0.5 ) : try : offset = np . array ( [ ( t - scan_times [ 0 ] ) . seconds + ( t - scan_times [ 0 ] ) . microseconds / 1000000.0 for t in scan_times ] ) except TypeError : offset = np . arange ( scan_times ) * frequency scans_nb = len ( offset ) avhrr_inst = np . vstack ( ( ( scan_points / 1023.5 - 1 ) * np . deg2rad ( - scan_angle ) , np . zeros ( ( len ( scan_points ) , ) ) ) ) avhrr_inst = np . tile ( avhrr_inst [ : , np . newaxis , : ] , [ 1 , np . int ( scans_nb ) , 1 ] ) times = ( np . tile ( scan_points * 0.000025 , [ scans_nb , 1 ] ) + np . expand_dims ( offset , 1 ) ) return ScanGeometry ( avhrr_inst , times ) | Definition of the avhrr instrument gac version |
54,005 | def olci ( scans_nb , scan_points = None ) : if scan_points is None : scan_len = 4000 scan_points = np . arange ( 4000 ) else : scan_len = len ( scan_points ) scan_angle_west = 46.5 scan_angle_east = - 22.1 scanline_angles = np . linspace ( np . deg2rad ( scan_angle_west ) , np . deg2rad ( scan_angle_east ) , scan_len ) inst = np . vstack ( ( scanline_angles , np . zeros ( scan_len , ) ) ) inst = np . tile ( inst [ : , np . newaxis , : ] , [ 1 , np . int ( scans_nb ) , 1 ] ) times = np . tile ( np . zeros_like ( scanline_angles ) , [ np . int ( scans_nb ) , 1 ] ) return ScanGeometry ( inst , times ) | Definition of the OLCI instrument . |
54,006 | def ascat ( scan_nb , scan_points = None ) : if scan_points is None : scan_len = 42 scan_points = np . arange ( 42 ) else : scan_len = len ( scan_points ) scan_angle_inner = - 25.0 scan_angle_outer = - 53.0 scan_rate = 3.74747474747 if scan_len < 2 : raise ValueError ( "Need at least two scan points!" ) sampling_interval = scan_rate / float ( np . max ( scan_points ) + 1 ) scanline_angles_one = np . linspace ( - np . deg2rad ( scan_angle_outer ) , - np . deg2rad ( scan_angle_inner ) , 21 ) scanline_angles_two = np . linspace ( np . deg2rad ( scan_angle_inner ) , np . deg2rad ( scan_angle_outer ) , 21 ) scan_angles = np . concatenate ( [ scanline_angles_one , scanline_angles_two ] ) [ scan_points ] inst = np . vstack ( ( scan_angles , np . zeros ( scan_len * 1 , ) ) ) inst = np . tile ( inst [ : , np . newaxis , : ] , [ 1 , np . int ( scan_nb ) , 1 ] ) offset = np . arange ( scan_nb ) * scan_rate times = ( np . tile ( scan_points * sampling_interval , [ np . int ( scan_nb ) , 1 ] ) + np . expand_dims ( offset , 1 ) ) return ScanGeometry ( inst , times ) | ASCAT make two scans one to the left and one to the right of the sub - satellite track . |
54,007 | def read ( platform , tle_file = None , line1 = None , line2 = None ) : return Tle ( platform , tle_file = tle_file , line1 = line1 , line2 = line2 ) | Read TLE for platform from tle_file |
54,008 | def fetch ( destination ) : with io . open ( destination , mode = "w" , encoding = "utf-8" ) as dest : for url in TLE_URLS : response = urlopen ( url ) dest . write ( response . read ( ) . decode ( "utf-8" ) ) | Fetch TLE from internet and save it to destination . |
54,009 | def _checksum ( self ) : for line in [ self . _line1 , self . _line2 ] : check = 0 for char in line [ : - 1 ] : if char . isdigit ( ) : check += int ( char ) if char == "-" : check += 1 if ( check % 10 ) != int ( line [ - 1 ] ) : raise ChecksumError ( self . _platform + " " + line ) | Performs the checksum for the current TLE . |
54,010 | def _read_tle ( self ) : if self . _line1 is not None and self . _line2 is not None : tle = self . _line1 . strip ( ) + "\n" + self . _line2 . strip ( ) else : def _open ( filename ) : return io . open ( filename , 'rb' ) if self . _tle_file : urls = ( self . _tle_file , ) open_func = _open elif "TLES" in os . environ : urls = ( max ( glob . glob ( os . environ [ "TLES" ] ) , key = os . path . getctime ) , ) LOGGER . debug ( "Reading TLE from %s" , urls [ 0 ] ) open_func = _open else : LOGGER . debug ( "Fetch TLE from the internet." ) urls = TLE_URLS open_func = urlopen tle = "" designator = "1 " + SATELLITES . get ( self . _platform , '' ) for url in urls : fid = open_func ( url ) for l_0 in fid : l_0 = l_0 . decode ( 'utf-8' ) if l_0 . strip ( ) == self . _platform : l_1 = next ( fid ) . decode ( 'utf-8' ) l_2 = next ( fid ) . decode ( 'utf-8' ) tle = l_1 . strip ( ) + "\n" + l_2 . strip ( ) break if ( self . _platform in SATELLITES and l_0 . strip ( ) . startswith ( designator ) ) : l_1 = l_0 l_2 = next ( fid ) . decode ( 'utf-8' ) tle = l_1 . strip ( ) + "\n" + l_2 . strip ( ) LOGGER . debug ( "Found platform %s, ID: %s" , self . _platform , SATELLITES [ self . _platform ] ) break fid . close ( ) if tle : break if not tle : raise KeyError ( "Found no TLE entry for '%s'" % self . _platform ) self . _line1 , self . _line2 = tle . split ( '\n' ) | Read TLE data . |
54,011 | def _parse_tle ( self ) : def _read_tle_decimal ( rep ) : if rep [ 0 ] in [ "-" , " " , "+" ] : digits = rep [ 1 : - 2 ] . strip ( ) val = rep [ 0 ] + "." + digits + "e" + rep [ - 2 : ] else : digits = rep [ : - 2 ] . strip ( ) val = "." + digits + "e" + rep [ - 2 : ] return float ( val ) self . satnumber = self . _line1 [ 2 : 7 ] self . classification = self . _line1 [ 7 ] self . id_launch_year = self . _line1 [ 9 : 11 ] self . id_launch_number = self . _line1 [ 11 : 14 ] self . id_launch_piece = self . _line1 [ 14 : 17 ] self . epoch_year = self . _line1 [ 18 : 20 ] self . epoch_day = float ( self . _line1 [ 20 : 32 ] ) self . epoch = np . datetime64 ( datetime . datetime . strptime ( self . epoch_year , "%y" ) + datetime . timedelta ( days = self . epoch_day - 1 ) , 'us' ) self . mean_motion_derivative = float ( self . _line1 [ 33 : 43 ] ) self . mean_motion_sec_derivative = _read_tle_decimal ( self . _line1 [ 44 : 52 ] ) self . bstar = _read_tle_decimal ( self . _line1 [ 53 : 61 ] ) try : self . ephemeris_type = int ( self . _line1 [ 62 ] ) except ValueError : self . ephemeris_type = 0 self . element_number = int ( self . _line1 [ 64 : 68 ] ) self . inclination = float ( self . _line2 [ 8 : 16 ] ) self . right_ascension = float ( self . _line2 [ 17 : 25 ] ) self . excentricity = int ( self . _line2 [ 26 : 33 ] ) * 10 ** - 7 self . arg_perigee = float ( self . _line2 [ 34 : 42 ] ) self . mean_anomaly = float ( self . _line2 [ 43 : 51 ] ) self . mean_motion = float ( self . _line2 [ 52 : 63 ] ) self . orbit = int ( self . _line2 [ 63 : 68 ] ) | Parse values from TLE data . |
54,012 | def build_system_components ( device_type , os_id , navigator_id ) : if os_id == 'win' : platform_version = choice ( OS_PLATFORM [ 'win' ] ) cpu = choice ( OS_CPU [ 'win' ] ) if cpu : platform = '%s; %s' % ( platform_version , cpu ) else : platform = platform_version res = { 'platform_version' : platform_version , 'platform' : platform , 'ua_platform' : platform , 'oscpu' : platform , } elif os_id == 'linux' : cpu = choice ( OS_CPU [ 'linux' ] ) platform_version = choice ( OS_PLATFORM [ 'linux' ] ) platform = '%s %s' % ( platform_version , cpu ) res = { 'platform_version' : platform_version , 'platform' : platform , 'ua_platform' : platform , 'oscpu' : 'Linux %s' % cpu , } elif os_id == 'mac' : cpu = choice ( OS_CPU [ 'mac' ] ) platform_version = choice ( OS_PLATFORM [ 'mac' ] ) platform = platform_version if navigator_id == 'chrome' : platform = fix_chrome_mac_platform ( platform ) res = { 'platform_version' : platform_version , 'platform' : 'MacIntel' , 'ua_platform' : platform , 'oscpu' : 'Intel Mac OS X %s' % platform . split ( ' ' ) [ - 1 ] , } elif os_id == 'android' : assert navigator_id in ( 'firefox' , 'chrome' ) assert device_type in ( 'smartphone' , 'tablet' ) platform_version = choice ( OS_PLATFORM [ 'android' ] ) if navigator_id == 'firefox' : if device_type == 'smartphone' : ua_platform = '%s; Mobile' % platform_version elif device_type == 'tablet' : ua_platform = '%s; Tablet' % platform_version elif navigator_id == 'chrome' : device_id = choice ( SMARTPHONE_DEV_IDS ) ua_platform = 'Linux; %s; %s' % ( platform_version , device_id ) oscpu = 'Linux %s' % choice ( OS_CPU [ 'android' ] ) res = { 'platform_version' : platform_version , 'ua_platform' : ua_platform , 'platform' : oscpu , 'oscpu' : oscpu , } return res | For given os_id build random platform and oscpu components |
54,013 | def build_app_components ( os_id , navigator_id ) : if navigator_id == 'firefox' : build_version , build_id = get_firefox_build ( ) if os_id in ( 'win' , 'linux' , 'mac' ) : geckotrail = '20100101' else : geckotrail = build_version res = { 'name' : 'Netscape' , 'product_sub' : '20100101' , 'vendor' : '' , 'build_version' : build_version , 'build_id' : build_id , 'geckotrail' : geckotrail , } elif navigator_id == 'chrome' : res = { 'name' : 'Netscape' , 'product_sub' : '20030107' , 'vendor' : 'Google Inc.' , 'build_version' : get_chrome_build ( ) , 'build_id' : None , } elif navigator_id == 'ie' : num_ver , build_version , trident_version = get_ie_build ( ) if num_ver >= 11 : app_name = 'Netscape' else : app_name = 'Microsoft Internet Explorer' res = { 'name' : app_name , 'product_sub' : None , 'vendor' : '' , 'build_version' : build_version , 'build_id' : None , 'trident_version' : trident_version , } return res | For given navigator_id build app features |
54,014 | def get_option_choices ( opt_name , opt_value , default_value , all_choices ) : choices = [ ] if isinstance ( opt_value , six . string_types ) : choices = [ opt_value ] elif isinstance ( opt_value , ( list , tuple ) ) : choices = list ( opt_value ) elif opt_value is None : choices = default_value else : raise InvalidOption ( 'Option %s has invalid' ' value: %s' % ( opt_name , opt_value ) ) if 'all' in choices : choices = all_choices for item in choices : if item not in all_choices : raise InvalidOption ( 'Choices of option %s contains invalid' ' item: %s' % ( opt_name , item ) ) return choices | Generate possible choices for the option opt_name limited to opt_value value with default value as default_value |
54,015 | def generate_navigator ( os = None , navigator = None , platform = None , device_type = None ) : if platform is not None : os = platform warn ( 'The `platform` option is deprecated.' ' Use `os` option instead.' , stacklevel = 3 ) device_type , os_id , navigator_id = ( pick_config_ids ( device_type , os , navigator ) ) system = build_system_components ( device_type , os_id , navigator_id ) app = build_app_components ( os_id , navigator_id ) ua_template = choose_ua_template ( device_type , navigator_id , app ) user_agent = ua_template . format ( system = system , app = app ) app_version = build_navigator_app_version ( os_id , navigator_id , system [ 'platform_version' ] , user_agent ) return { 'os_id' : os_id , 'navigator_id' : navigator_id , 'platform' : system [ 'platform' ] , 'oscpu' : system [ 'oscpu' ] , 'build_version' : app [ 'build_version' ] , 'build_id' : app [ 'build_id' ] , 'app_version' : app_version , 'app_name' : app [ 'name' ] , 'app_code_name' : 'Mozilla' , 'product' : 'Gecko' , 'product_sub' : app [ 'product_sub' ] , 'vendor' : app [ 'vendor' ] , 'vendor_sub' : '' , 'user_agent' : user_agent , } | Generates web navigator s config |
54,016 | def generate_user_agent ( os = None , navigator = None , platform = None , device_type = None ) : return generate_navigator ( os = os , navigator = navigator , platform = platform , device_type = device_type ) [ 'user_agent' ] | Generates HTTP User - Agent header |
54,017 | def generate_navigator_js ( os = None , navigator = None , platform = None , device_type = None ) : config = generate_navigator ( os = os , navigator = navigator , platform = platform , device_type = device_type ) return { 'appCodeName' : config [ 'app_code_name' ] , 'appName' : config [ 'app_name' ] , 'appVersion' : config [ 'app_version' ] , 'platform' : config [ 'platform' ] , 'userAgent' : config [ 'user_agent' ] , 'oscpu' : config [ 'oscpu' ] , 'product' : config [ 'product' ] , 'productSub' : config [ 'product_sub' ] , 'vendor' : config [ 'vendor' ] , 'vendorSub' : config [ 'vendor_sub' ] , 'buildID' : config [ 'build_id' ] , } | Generates web navigator s config with keys corresponding to keys of windows . navigator JavaScript object . |
54,018 | def more_data ( pipe_out ) : r , _ , _ = select . select ( [ pipe_out ] , [ ] , [ ] , 0 ) return bool ( r ) | Check if there is more data left on the pipe |
54,019 | def read_pipe ( pipe_out ) : out = b'' while more_data ( pipe_out ) : out += os . read ( pipe_out , 1024 ) return out . decode ( 'utf-8' ) | Read data on a pipe |
54,020 | def role ( self ) : try : self . _role = c_char ( self . lib . iperf_get_test_role ( self . _test ) ) . value . decode ( 'utf-8' ) except TypeError : self . _role = c_char ( chr ( self . lib . iperf_get_test_role ( self . _test ) ) ) . value . decode ( 'utf-8' ) return self . _role | The iperf3 instance role |
54,021 | def bind_address ( self ) : result = c_char_p ( self . lib . iperf_get_test_bind_address ( self . _test ) ) . value if result : self . _bind_address = result . decode ( 'utf-8' ) else : self . _bind_address = '*' return self . _bind_address | The bind address the iperf3 instance will listen on |
54,022 | def port ( self ) : self . _port = self . lib . iperf_get_test_server_port ( self . _test ) return self . _port | The port the iperf3 server is listening on |
54,023 | def json_output ( self ) : enabled = self . lib . iperf_get_test_json_output ( self . _test ) if enabled : self . _json_output = True else : self . _json_output = False return self . _json_output | Toggles json output of libiperf |
54,024 | def verbose ( self ) : enabled = self . lib . iperf_get_verbose ( self . _test ) if enabled : self . _verbose = True else : self . _verbose = False return self . _verbose | Toggles verbose output for the iperf3 instance |
54,025 | def iperf_version ( self ) : VersionType = c_char * 30 return VersionType . in_dll ( self . lib , "version" ) . value . decode ( 'utf-8' ) | Returns the version of the libiperf library |
54,026 | def _error_to_string ( self , error_id ) : strerror = self . lib . iperf_strerror strerror . restype = c_char_p return strerror ( error_id ) . decode ( 'utf-8' ) | Returns an error string from libiperf |
54,027 | def server_hostname ( self ) : result = c_char_p ( self . lib . iperf_get_test_server_hostname ( self . _test ) ) . value if result : self . _server_hostname = result . decode ( 'utf-8' ) else : self . _server_hostname = None return self . _server_hostname | The server hostname to connect to . |
54,028 | def protocol ( self ) : proto_id = self . lib . iperf_get_test_protocol_id ( self . _test ) if proto_id == SOCK_STREAM : self . _protocol = 'tcp' elif proto_id == SOCK_DGRAM : self . _protocol = 'udp' return self . _protocol | The iperf3 instance protocol |
54,029 | def omit ( self ) : self . _omit = self . lib . iperf_get_test_omit ( self . _test ) return self . _omit | The test startup duration to omit in seconds . |
54,030 | def duration ( self ) : self . _duration = self . lib . iperf_get_test_duration ( self . _test ) return self . _duration | The test duration in seconds . |
54,031 | def blksize ( self ) : self . _blksize = self . lib . iperf_get_test_blksize ( self . _test ) return self . _blksize | The test blksize . |
54,032 | def num_streams ( self ) : self . _num_streams = self . lib . iperf_get_test_num_streams ( self . _test ) return self . _num_streams | The number of streams to use . |
54,033 | def reverse ( self ) : enabled = self . lib . iperf_get_test_reverse ( self . _test ) if enabled : self . _reverse = True else : self . _reverse = False return self . _reverse | Toggles direction of test |
54,034 | def run ( self ) : if self . json_output : output_to_pipe ( self . _pipe_in ) error = self . lib . iperf_run_client ( self . _test ) if not self . iperf_version . startswith ( 'iperf 3.1' ) : data = read_pipe ( self . _pipe_out ) if data . startswith ( 'Control connection' ) : data = '{' + data . split ( '{' , 1 ) [ 1 ] else : data = c_char_p ( self . lib . iperf_get_test_json_output_string ( self . _test ) ) . value if data : data = data . decode ( 'utf-8' ) output_to_screen ( self . _stdout_fd , self . _stderr_fd ) if not data or error : data = '{"error": "%s"}' % self . _error_to_string ( self . _errno ) return TestResult ( data ) | Run the current test client . |
54,035 | def run ( self ) : def _run_in_thread ( self , data_queue ) : output_to_pipe ( self . _pipe_in ) error = self . lib . iperf_run_server ( self . _test ) output_to_screen ( self . _stdout_fd , self . _stderr_fd ) data = read_pipe ( self . _pipe_out ) if not data or error : data = '{"error": "%s"}' % self . _error_to_string ( self . _errno ) self . lib . iperf_reset_test ( self . _test ) data_queue . put ( data ) if self . json_output : data_queue = Queue ( ) t = threading . Thread ( target = _run_in_thread , args = [ self , data_queue ] ) t . daemon = True t . start ( ) while t . is_alive ( ) : t . join ( .1 ) return TestResult ( data_queue . get ( ) ) else : self . lib . iperf_run_server ( self . _test ) self . lib . iperf_reset_test ( self . _test ) return None | Run the iperf3 server instance . |
54,036 | def subplots ( nrows = 1 , ncols = 1 , sharex = False , sharey = False , squeeze = True , subplot_kw = None , hemisphere = 'lower' , projection = 'equal_area' , ** fig_kw ) : import matplotlib . pyplot as plt if projection in [ 'equal_area' , 'equal_angle' ] : projection += '_stereonet' if subplot_kw == None : subplot_kw = { } subplot_kw [ 'projection' ] = projection return plt . subplots ( nrows , ncols , sharex = sharex , sharey = sharey , squeeze = squeeze , subplot_kw = subplot_kw , ** fig_kw ) | Identical to matplotlib . pyplot . subplots except that this will default to producing equal - area stereonet axes . |
54,037 | def tangent_lineation_plot ( ax , strikes , dips , rakes ) : rake_x , rake_y = mplstereonet . rake ( strikes , dips , rakes ) mag = np . hypot ( rake_x , rake_y ) u , v = - rake_x / mag , - rake_y / mag pole_x , pole_y = mplstereonet . pole ( strikes , dips ) arrows = ax . quiver ( pole_x , pole_y , u , v , width = 1 , headwidth = 4 , units = 'dots' , pivot = 'middle' ) return arrows | Makes a tangent lineation plot for normal faults with the given strikes dips and rakes . |
54,038 | def load ( ) : datadir = os . path . dirname ( __file__ ) filename = os . path . join ( datadir , 'angelier_data.txt' ) data = [ ] with open ( filename , 'r' ) as infile : for line in infile : if line . startswith ( '#' ) : continue strike , dip , rake = line . strip ( ) . split ( ) if rake [ - 1 ] . isalpha ( ) : strike , dip , rake = mplstereonet . parse_rake ( strike , dip , rake ) else : strike , dip = mplstereonet . parse_strike_dip ( strike , dip ) azimuth = float ( rake ) rake = mplstereonet . azimuth2rake ( strike , dip , azimuth ) data . append ( [ strike , dip , rake ] ) strike , dip , rake = zip ( * data ) return strike , dip , rake | Read data from a text file on disk . |
54,039 | def _exponential_kamb ( cos_dist , sigma = 3 ) : n = float ( cos_dist . size ) f = 2 * ( 1.0 + n / sigma ** 2 ) count = np . exp ( f * ( cos_dist - 1 ) ) units = np . sqrt ( n * ( f / 2.0 - 1 ) / f ** 2 ) return count , units | Kernel function from Vollmer for exponential smoothing . |
54,040 | def _linear_inverse_kamb ( cos_dist , sigma = 3 ) : n = float ( cos_dist . size ) radius = _kamb_radius ( n , sigma ) f = 2 / ( 1 - radius ) cos_dist = cos_dist [ cos_dist >= radius ] count = ( f * ( cos_dist - radius ) ) return count , _kamb_units ( n , radius ) | Kernel function from Vollmer for linear smoothing . |
54,041 | def _get_core_transform ( self , resolution ) : return self . _base_transform ( self . _center_longitude , self . _center_latitude , resolution ) | The projection for the stereonet as a matplotlib transform . This is primarily called by LambertAxes . _set_lim_and_transforms . |
54,042 | def _get_affine_transform ( self ) : xscale = yscale = self . _scale return Affine2D ( ) . rotate ( np . radians ( self . rotation ) ) . scale ( 0.5 / xscale , 0.5 / yscale ) . translate ( 0.5 , 0.5 ) | The affine portion of the base transform . This is called by LambertAxes . _set_lim_and_transforms . |
54,043 | def _set_lim_and_transforms ( self ) : LambertAxes . _set_lim_and_transforms ( self ) yaxis_stretch = Affine2D ( ) . scale ( 4 * self . horizon , 1.0 ) yaxis_stretch = yaxis_stretch . translate ( - self . horizon , 0.0 ) yaxis_space = Affine2D ( ) . scale ( 1.0 , 1.1 ) self . _yaxis_transform = yaxis_stretch + self . transData yaxis_text_base = yaxis_stretch + self . transProjection + ( yaxis_space + self . transAffine + self . transAxes ) self . _yaxis_text1_transform = yaxis_text_base + Affine2D ( ) . translate ( - 8.0 , 0.0 ) self . _yaxis_text2_transform = yaxis_text_base + Affine2D ( ) . translate ( 8.0 , 0.0 ) | Setup the key transforms for the axes . |
54,044 | def set_longitude_grid ( self , degrees ) : number = ( 360.0 / degrees ) + 1 locs = np . linspace ( - np . pi , np . pi , number , True ) [ 1 : ] locs [ - 1 ] -= 0.01 self . xaxis . set_major_locator ( FixedLocator ( locs ) ) self . _logitude_degrees = degrees self . xaxis . set_major_formatter ( self . ThetaFormatter ( degrees ) ) | Set the number of degrees between each longitude grid . |
54,045 | def set_rotation ( self , rotation ) : self . _rotation = np . radians ( rotation ) self . _polar . set_theta_offset ( self . _rotation + np . pi / 2.0 ) self . transData . invalidate ( ) self . transAxes . invalidate ( ) self . _set_lim_and_transforms ( ) | Set the rotation of the stereonet in degrees clockwise from North . |
54,046 | def format_coord ( self , x , y ) : p , b = stereonet_math . geographic2plunge_bearing ( x , y ) s , d = stereonet_math . geographic2pole ( x , y ) pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0' . format ( p [ 0 ] , b [ 0 ] ) sd = u'S/D={:03.0f}\u00b0/{:0.0f}\u00b0' . format ( s [ 0 ] , d [ 0 ] ) return u'{}, {}' . format ( pb , sd ) | Format displayed coordinates during mouseover of axes . |
54,047 | def grid ( self , b = None , which = 'major' , axis = 'both' , kind = 'arbitrary' , center = None , ** kwargs ) : grid_on = self . _gridOn Axes . grid ( self , False ) if kind == 'polar' : center = 0 , 0 if self . _overlay_axes is not None : self . _overlay_axes . remove ( ) self . _overlay_axes = None if not b and b is not None : return if b is None : if grid_on : return if center is None or np . allclose ( center , ( np . pi / 2 , 0 ) ) : return Axes . grid ( self , b , which , axis , ** kwargs ) self . _add_overlay ( center ) self . _overlay_axes . grid ( True , which , axis , ** kwargs ) self . _gridOn = True | Usage is identical to a normal axes grid except for the kind and center kwargs . kind = polar will add a polar overlay . |
54,048 | def _polar ( self ) : try : return self . _hidden_polar_axes except AttributeError : fig = self . get_figure ( ) self . _hidden_polar_axes = fig . add_axes ( self . get_position ( True ) , frameon = False , projection = 'polar' ) self . _hidden_polar_axes . format_coord = self . _polar_format_coord return self . _hidden_polar_axes | The hidden polar axis used for azimuth labels . |
54,049 | def set_azimuth_ticklabels ( self , labels , fontdict = None , ** kwargs ) : return self . _polar . set_xticklabels ( labels , fontdict , ** kwargs ) | Sets the labels for the azimuthal ticks . |
54,050 | def plane ( self , strike , dip , * args , ** kwargs ) : segments = kwargs . pop ( 'segments' , 100 ) center = self . _center_latitude , self . _center_longitude lon , lat = stereonet_math . plane ( strike , dip , segments , center ) return self . plot ( lon , lat , * args , ** kwargs ) | Plot lines representing planes on the axes . Additional arguments and keyword arguments are passed on to ax . plot . |
54,051 | def pole ( self , strike , dip , * args , ** kwargs ) : lon , lat = stereonet_math . pole ( strike , dip ) args , kwargs = self . _point_plot_defaults ( args , kwargs ) return self . plot ( lon , lat , * args , ** kwargs ) | Plot points representing poles to planes on the axes . Additional arguments and keyword arguments are passed on to ax . plot . |
54,052 | def rake ( self , strike , dip , rake_angle , * args , ** kwargs ) : lon , lat = stereonet_math . rake ( strike , dip , rake_angle ) args , kwargs = self . _point_plot_defaults ( args , kwargs ) return self . plot ( lon , lat , * args , ** kwargs ) | Plot points representing lineations along planes on the axes . Additional arguments and keyword arguments are passed on to plot . |
54,053 | def line ( self , plunge , bearing , * args , ** kwargs ) : lon , lat = stereonet_math . line ( plunge , bearing ) args , kwargs = self . _point_plot_defaults ( args , kwargs ) return self . plot ( [ lon ] , [ lat ] , * args , ** kwargs ) | Plot points representing linear features on the axes . Additional arguments and keyword arguments are passed on to plot . |
54,054 | def _point_plot_defaults ( self , args , kwargs ) : if args : return args , kwargs if 'ls' not in kwargs and 'linestyle' not in kwargs : kwargs [ 'linestyle' ] = 'none' if 'marker' not in kwargs : kwargs [ 'marker' ] = 'o' return args , kwargs | To avoid confusion for new users this ensures that scattered points are plotted by by plot instead of points joined by a line . |
54,055 | def _contour_helper ( self , args , kwargs ) : contour_kwargs = { } contour_kwargs [ 'measurement' ] = kwargs . pop ( 'measurement' , 'poles' ) contour_kwargs [ 'method' ] = kwargs . pop ( 'method' , 'exponential_kamb' ) contour_kwargs [ 'sigma' ] = kwargs . pop ( 'sigma' , 3 ) contour_kwargs [ 'gridsize' ] = kwargs . pop ( 'gridsize' , 100 ) contour_kwargs [ 'weights' ] = kwargs . pop ( 'weights' , None ) lon , lat , totals = contouring . density_grid ( * args , ** contour_kwargs ) return lon , lat , totals , kwargs | Unify defaults and common functionality of density_contour and density_contourf . |
54,056 | def basic ( ) : fig , ax = mplstereonet . subplots ( ) strike , dip = 315 , 30 ax . plane ( strike , dip , color = 'lightblue' ) ax . pole ( strike , dip , color = 'green' , markersize = 15 ) ax . rake ( strike , dip , 40 , marker = '*' , markersize = 20 , color = 'green' ) fig . subplots_adjust ( top = 0.8 ) return ax | Set up a basic stereonet and plot the same data each time . |
54,057 | def setup_figure ( ) : fig , axes = mplstereonet . subplots ( ncols = 2 , figsize = ( 20 , 10 ) ) for ax in axes : ax . grid ( ls = '-' ) ax . set_longitude_grid_ends ( 90 ) return fig , axes | Setup the figure and axes |
54,058 | def stereonet_projection_explanation ( ax ) : ax . set_title ( 'Dip and Azimuth' , y = 1.1 , size = 18 ) ax . set_azimuth_ticks ( range ( 0 , 360 , 10 ) ) fmt = ax . yaxis . get_major_formatter ( ) labels = [ fmt ( item ) for item in ax . get_azimuth_ticks ( ) ] labels [ 0 ] = 'North' labels [ 9 ] = 'East' labels [ 18 ] = 'South' labels [ 27 ] = 'West' ax . set_azimuth_ticklabels ( labels ) ax . xaxis . set_tick_params ( label1On = True ) labels = list ( range ( 10 , 100 , 10 ) ) + list ( range ( 80 , 0 , - 10 ) ) ax . set_xticks ( np . radians ( np . arange ( - 80 , 90 , 10 ) ) ) ax . set_xticklabels ( [ fmt ( np . radians ( item ) ) for item in labels ] ) ax . set_xlabel ( 'Dip or Plunge' ) xlabel_halo ( ax ) return ax | Example to explain azimuth and dip on a lower - hemisphere stereonet . |
54,059 | def native_projection_explanation ( ax ) : ax . set_title ( 'Longitude and Latitude' , size = 18 , y = 1.1 ) ax . set_azimuth_ticklabels ( [ ] ) ax . set_xticks ( np . radians ( np . arange ( - 80 , 90 , 10 ) ) ) ax . tick_params ( label1On = True ) ax . set_xlabel ( 'Longitude' ) xlabel_halo ( ax ) return ax | Example showing how the native longitude and latitude relate to the stereonet projection . |
54,060 | def xlabel_halo ( ax ) : import matplotlib . patheffects as effects for tick in ax . get_xticklabels ( ) + [ ax . xaxis . label ] : tick . set_path_effects ( [ effects . withStroke ( linewidth = 4 , foreground = 'w' ) ] ) | Add a white halo around the xlabels . |
54,061 | def parse_strike_dip ( strike , dip ) : strike = parse_azimuth ( strike ) dip , direction = split_trailing_letters ( dip ) if direction is not None : expected_direc = strike + 90 if opposite_end ( expected_direc , direction ) : strike += 180 if strike > 360 : strike -= 360 return strike , dip | Parses strings of strike and dip and returns strike and dip measurements following the right - hand - rule . |
54,062 | def parse_plunge_bearing ( plunge , bearing ) : bearing = parse_azimuth ( bearing ) plunge , direction = split_trailing_letters ( plunge ) if direction is not None : if opposite_end ( bearing , direction ) : bearing += 180 if plunge < 0 : bearing += 180 plunge = - plunge if plunge > 90 : bearing += 180 plunge = 180 - plunge if bearing > 360 : bearing -= 360 return plunge , bearing | Parses strings of plunge and bearing and returns a consistent plunge and bearing measurement as floats . Plunge angles returned by this function will always be between 0 and 90 . |
54,063 | def dip_direction2strike ( azimuth ) : azimuth = parse_azimuth ( azimuth ) strike = azimuth - 90 if strike < 0 : strike += 360 return strike | Converts a planar measurment of dip direction using the dip - azimuth convention into a strike using the right - hand - rule . |
54,064 | def parse_azimuth ( azimuth ) : try : azimuth = float ( azimuth ) except ValueError : if not azimuth [ 0 ] . isalpha ( ) : raise ValueError ( 'Ambiguous azimuth: {}' . format ( azimuth ) ) azimuth = parse_quadrant_measurement ( azimuth ) return azimuth | Parses an azimuth measurement in azimuth or quadrant format . |
54,065 | def parse_quadrant_measurement ( quad_azimuth ) : def rotation_direction ( first , second ) : return np . cross ( _azimuth2vec ( first ) , _azimuth2vec ( second ) ) quad_azimuth = quad_azimuth . strip ( ) try : first_dir = quadrantletter_to_azimuth ( quad_azimuth [ 0 ] . upper ( ) ) sec_dir = quadrantletter_to_azimuth ( quad_azimuth [ - 1 ] . upper ( ) ) except KeyError : raise ValueError ( '{} is not a valid azimuth' . format ( quad_azimuth ) ) angle = float ( quad_azimuth [ 1 : - 1 ] ) direc = rotation_direction ( first_dir , sec_dir ) azi = first_dir + direc * angle if abs ( direc ) < 0.9 : raise ValueError ( '{} is not a valid azimuth' . format ( quad_azimuth ) ) if azi < 0 : azi += 360 elif azi > 360 : azi -= 360 return azi | Parses a quadrant measurement of the form AxxB where A and B are cardinal directions and xx is an angle measured relative to those directions . |
54,066 | def inverted ( self ) : inverse_type = globals ( ) [ self . _inverse_type ] return inverse_type ( self . _center_longitude , self . _center_latitude , self . _resolution ) | Return the inverse of the transform . |
54,067 | def cart2sph ( x , y , z ) : r = np . sqrt ( x ** 2 + y ** 2 + z ** 2 ) lat = np . arcsin ( z / r ) lon = np . arctan2 ( y , x ) return lon , lat | Converts cartesian coordinates x y z into a longitude and latitude . x = 0 y = 0 z = 0 is assumed to correspond to the center of the globe . Returns lon and lat in radians . |
54,068 | def plane ( strike , dip , segments = 100 , center = ( 0 , 0 ) ) : lon0 , lat0 = center strikes , dips = np . atleast_1d ( strike , dip ) lons = np . zeros ( ( segments , strikes . size ) , dtype = np . float ) lats = lons . copy ( ) for i , ( strike , dip ) in enumerate ( zip ( strikes , dips ) ) : dip = 90 - dip lon = dip * np . ones ( segments ) lat = np . linspace ( - 90 , 90 , segments ) lon , lat = _rotate ( lon , lat , strike ) if lat0 != 0 or lon0 != 0 : dist = angular_distance ( [ lon , lat ] , [ lon0 , lat0 ] , False ) mask = dist > ( np . pi / 2 ) lon [ mask ] , lat [ mask ] = antipode ( lon [ mask ] , lat [ mask ] ) change = np . diff ( mask . astype ( int ) ) ind = np . flatnonzero ( change ) + 1 lat = np . hstack ( np . split ( lat , ind ) [ : : - 1 ] ) lon = np . hstack ( np . split ( lon , ind ) [ : : - 1 ] ) lons [ : , i ] = lon lats [ : , i ] = lat return lons , lats | Calculates the longitude and latitude of segments points along the stereonet projection of each plane with a given strike and dip in degrees . Returns points for one hemisphere only . |
54,069 | def mean_vector ( lons , lats ) : xyz = sph2cart ( lons , lats ) xyz = np . vstack ( xyz ) . T mean_vec = xyz . mean ( axis = 0 ) r_value = np . linalg . norm ( mean_vec ) mean_vec = cart2sph ( * mean_vec ) return mean_vec , r_value | Returns the resultant vector from a series of longitudes and latitudes |
54,070 | def azimuth2rake ( strike , dip , azimuth ) : plunge , bearing = plane_intersection ( strike , dip , azimuth , 90 ) rake = project_onto_plane ( strike , dip , plunge , bearing ) return rake | Projects an azimuth of a linear feature onto a plane as a rake angle . |
54,071 | def xyz2stereonet ( x , y , z ) : x , y , z = np . atleast_1d ( x , y , z ) return cart2sph ( - z , x , y ) | Converts x y z in _world_ cartesian coordinates into lower - hemisphere stereonet coordinates . |
54,072 | def stereonet2xyz ( lon , lat ) : lon , lat = np . atleast_1d ( lon , lat ) x , y , z = sph2cart ( lon , lat ) return y , z , - x | Converts a sequence of longitudes and latitudes from a lower - hemisphere stereonet into _world_ x y z coordinates . |
54,073 | def _repole ( lon , lat , center ) : vec3 = sph2cart ( * center ) vec3 = np . squeeze ( vec3 ) if not np . allclose ( vec3 , [ 0 , 0 , 1 ] ) : vec1 = np . cross ( vec3 , [ 0 , 0 , 1 ] ) else : vec1 = np . cross ( vec3 , [ 1 , 0 , 0 ] ) vec2 = np . cross ( vec3 , vec1 ) vecs = [ item / np . linalg . norm ( item ) for item in [ vec1 , vec2 , vec3 ] ] basis = np . column_stack ( vecs ) xyz = sph2cart ( lon , lat ) xyz = np . column_stack ( xyz ) prime = xyz . dot ( np . linalg . inv ( basis ) ) lon , lat = cart2sph ( * prime . T ) return lon [ : , None ] , lat [ : , None ] | Reproject data such that center is the north pole . Returns lon lat in the new rotated reference frame . |
54,074 | def _sd_of_eigenvector ( data , vec , measurement = 'poles' , bidirectional = True ) : lon , lat = _convert_measurements ( data , measurement ) vals , vecs = cov_eig ( lon , lat , bidirectional ) x , y , z = vecs [ : , vec ] s , d = stereonet_math . geographic2pole ( * stereonet_math . cart2sph ( x , y , z ) ) return s [ 0 ] , d [ 0 ] | Unifies fit_pole and fit_girdle . |
54,075 | def find_mean_vector ( * args , ** kwargs ) : lon , lat = _convert_measurements ( args , kwargs . get ( 'measurement' , 'lines' ) ) vector , r_value = stereonet_math . mean_vector ( lon , lat ) plunge , bearing = stereonet_math . geographic2plunge_bearing ( * vector ) return ( plunge [ 0 ] , bearing [ 0 ] ) , r_value | Returns the mean vector for a set of measurments . By default this expects the input to be plunges and bearings but the type of input can be controlled through the measurement kwarg . |
54,076 | def find_fisher_stats ( * args , ** kwargs ) : lon , lat = _convert_measurements ( args , kwargs . get ( 'measurement' , 'lines' ) ) conf = kwargs . get ( 'conf' , 95 ) center , stats = stereonet_math . fisher_stats ( lon , lat , conf ) plunge , bearing = stereonet_math . geographic2plunge_bearing ( * center ) mean_vector = ( plunge [ 0 ] , bearing [ 0 ] ) return mean_vector , stats | Returns the mean vector and summary statistics for a set of measurements . By default this expects the input to be plunges and bearings but the type of input can be controlled through the measurement kwarg . |
54,077 | def kmeans ( * args , ** kwargs ) : lon , lat = _convert_measurements ( args , kwargs . get ( 'measurement' , 'poles' ) ) num = kwargs . get ( 'num' , 2 ) bidirectional = kwargs . get ( 'bidirectional' , True ) tolerance = kwargs . get ( 'tolerance' , 1e-5 ) points = lon , lat dist = lambda x : stereonet_math . angular_distance ( x , points , bidirectional ) center_lon = np . random . choice ( lon , num ) center_lat = np . random . choice ( lat , num ) centers = np . column_stack ( [ center_lon , center_lat ] ) while True : dists = np . array ( [ dist ( item ) for item in centers ] ) . T closest = dists . argmin ( axis = 1 ) new_centers = [ ] for i in range ( num ) : mask = mask = closest == i _ , vecs = cov_eig ( lon [ mask ] , lat [ mask ] , bidirectional ) new_centers . append ( stereonet_math . cart2sph ( * vecs [ : , - 1 ] ) ) if np . allclose ( centers , new_centers , atol = tolerance ) : break else : centers = new_centers return centers | Find centers of multi - modal clusters of data using a kmeans approach modified for spherical measurements . |
54,078 | def _dispose ( self ) : self . close ( ) conn_params = self . get_connection_params ( ) key = db_pool . _serialize ( ** conn_params ) try : pool = db_pool . pools [ key ] except KeyError : pass else : pool . dispose ( ) del db_pool . pools [ key ] | Dispose of the pool for this instance closing all connections . |
54,079 | def calc_fc_size ( img_height , img_width ) : height , width = img_height , img_width for _ in range ( 5 ) : height , width = _get_conv_outsize ( ( height , width ) , 4 , 2 , 1 ) conv_out_layers = 512 return conv_out_layers , height , width | Calculates shape of data after encoding . |
54,080 | def calc_im_size ( img_height , img_width ) : height , width = img_height , img_width for _ in range ( 5 ) : height , width = _get_deconv_outsize ( ( height , width ) , 4 , 2 , 1 ) return height , width | Calculates shape of data after decoding . |
54,081 | def get_paths ( directory ) : fnames = [ os . path . join ( directory , f ) for f in os . listdir ( directory ) if os . path . isfile ( os . path . join ( directory , f ) ) and not f . startswith ( '.' ) ] return fnames | Gets all the paths of non - hidden files in a directory and returns a list of those paths . |
54,082 | def inverse_transform ( self , data , test = False ) : if not type ( data ) == Variable : if len ( data . shape ) < 2 : data = data [ np . newaxis ] if len ( data . shape ) != 2 : raise TypeError ( "Invalid dimensions for latent data. Dim = %s.\ Must be a 2d array." % str ( data . shape ) ) data = Variable ( data ) else : if len ( data . data . shape ) < 2 : data . data = data . data [ np . newaxis ] if len ( data . data . shape ) != 2 : raise TypeError ( "Invalid dimensions for latent data. Dim = %s.\ Must be a 2d array." % str ( data . data . shape ) ) assert data . data . shape [ - 1 ] == self . latent_width , "Latent shape %d != %d" % ( data . data . shape [ - 1 ] , self . latent_width ) if self . flag_gpu : data . to_gpu ( ) out = self . model . decode ( data , test = test ) out . to_cpu ( ) if self . mode == 'linear' : final = out . data else : final = out . data . transpose ( 0 , 2 , 3 , 1 ) return final | Transform latent vectors into images . |
54,083 | def load_images ( self , filepaths ) : def read ( fname ) : im = Image . open ( fname ) im = np . float32 ( im ) return im / 255. x_all = np . array ( [ read ( fname ) for fname in tqdm . tqdm ( filepaths ) ] ) x_all = x_all . astype ( 'float32' ) if self . mode == 'convolution' : x_all = x_all . transpose ( 0 , 3 , 1 , 2 ) print ( "Image Files Loaded!" ) return x_all | Load in image files from list of paths . |
54,084 | def fit ( self , img_data , save_freq = - 1 , pic_freq = - 1 , n_epochs = 100 , batch_size = 50 , weight_decay = True , model_path = './VAE_training_model/' , img_path = './VAE_training_images/' , img_out_width = 10 ) : width = img_out_width self . opt . setup ( self . model ) if weight_decay : self . opt . add_hook ( chainer . optimizer . WeightDecay ( 0.00001 ) ) n_data = img_data . shape [ 0 ] batch_iter = list ( range ( 0 , n_data , batch_size ) ) n_batches = len ( batch_iter ) save_counter = 0 for epoch in range ( 1 , n_epochs + 1 ) : print ( 'epoch: %i' % epoch ) t1 = time . time ( ) indexes = np . random . permutation ( n_data ) last_loss_kl = 0. last_loss_rec = 0. count = 0 for i in tqdm . tqdm ( batch_iter ) : x_batch = Variable ( img_data [ indexes [ i : i + batch_size ] ] ) if self . flag_gpu : x_batch . to_gpu ( ) out , kl_loss , rec_loss = self . model . forward ( x_batch ) total_loss = rec_loss + kl_loss * self . kl_ratio self . opt . zero_grads ( ) total_loss . backward ( ) self . opt . update ( ) last_loss_kl += kl_loss . data last_loss_rec += rec_loss . data plot_pics = Variable ( img_data [ indexes [ : width ] ] ) count += 1 if pic_freq > 0 : assert type ( pic_freq ) == int , "pic_freq must be an integer." if count % pic_freq == 0 : fig = self . _plot_img ( plot_pics , img_path = img_path , epoch = epoch ) display ( fig ) if save_freq > 0 : save_counter += 1 assert type ( save_freq ) == int , "save_freq must be an integer." if epoch % save_freq == 0 : name = "vae_epoch%s" % str ( epoch ) if save_counter == 1 : save_meta = True else : save_meta = False self . save ( model_path , name , save_meta = save_meta ) fig = self . _plot_img ( plot_pics , img_path = img_path , epoch = epoch , batch = n_batches , save = True ) msg = "rec_loss = {0} , kl_loss = {1}" print ( msg . format ( last_loss_rec / n_batches , last_loss_kl / n_batches ) ) t_diff = time . time ( ) - t1 print ( "time: %f\n\n" % t_diff ) | Fit the VAE model to the image data . |
54,085 | def transform ( self , data , test = False ) : if not type ( data ) == Variable : if len ( data . shape ) < 4 : data = data [ np . newaxis ] if len ( data . shape ) != 4 : raise TypeError ( "Invalid dimensions for image data. Dim = %s.\ Must be 4d array." % str ( data . shape ) ) if data . shape [ 1 ] != self . color_channels : if data . shape [ - 1 ] == self . color_channels : data = data . transpose ( 0 , 3 , 1 , 2 ) else : raise TypeError ( "Invalid dimensions for image data. Dim = %s" % str ( data . shape ) ) data = Variable ( data ) else : if len ( data . data . shape ) < 4 : data . data = data . data [ np . newaxis ] if len ( data . data . shape ) != 4 : raise TypeError ( "Invalid dimensions for image data. Dim = %s.\ Must be 4d array." % str ( data . data . shape ) ) if data . data . shape [ 1 ] != self . color_channels : if data . data . shape [ - 1 ] == self . color_channels : data . data = data . data . transpose ( 0 , 3 , 1 , 2 ) else : raise TypeError ( "Invalid dimensions for image data. Dim = %s" % str ( data . shape ) ) if self . flag_gpu : data . to_gpu ( ) z = self . _encode ( data , test = test ) [ 0 ] z . to_cpu ( ) return z . data | Transform image data to latent space . |
54,086 | def polynomial_sign ( poly_surface , degree ) : r corner_indices = ( 0 , degree , - 1 ) sub_polys = [ poly_surface ] signs = set ( ) for _ in six . moves . xrange ( _MAX_POLY_SUBDIVISIONS ) : undecided = [ ] for poly in sub_polys : signs . update ( _SIGN ( poly [ 0 , corner_indices ] ) . astype ( int ) ) if np . all ( poly == 0.0 ) : signs . add ( 0 ) elif np . all ( poly > 0.0 ) : signs . add ( 1 ) elif np . all ( poly < 0.0 ) : signs . add ( - 1 ) else : undecided . append ( poly ) if len ( signs ) > 1 : return 0 sub_polys = functools . reduce ( operator . add , [ subdivide_nodes ( poly , degree ) for poly in undecided ] , ( ) , ) if not sub_polys : break if sub_polys : raise ValueError ( "Did not reach a conclusion after max subdivisions" , _MAX_POLY_SUBDIVISIONS , ) else : return signs . pop ( ) | r Determine the sign of a polynomial on the reference triangle . |
54,087 | def quadratic_jacobian_polynomial ( nodes ) : r jac_parts = _helpers . matrix_product ( nodes , _QUADRATIC_JACOBIAN_HELPER ) jac_at_nodes = np . empty ( ( 1 , 6 ) , order = "F" ) jac_at_nodes [ 0 , 0 ] = two_by_two_det ( jac_parts [ : , : 2 ] ) jac_at_nodes [ 0 , 1 ] = two_by_two_det ( jac_parts [ : , 2 : 4 ] ) jac_at_nodes [ 0 , 2 ] = two_by_two_det ( jac_parts [ : , 4 : 6 ] ) jac_at_nodes [ 0 , 3 ] = two_by_two_det ( jac_parts [ : , 6 : 8 ] ) jac_at_nodes [ 0 , 4 ] = two_by_two_det ( jac_parts [ : , 8 : 10 ] ) jac_at_nodes [ 0 , 5 ] = two_by_two_det ( jac_parts [ : , 10 : ] ) bernstein = _helpers . matrix_product ( jac_at_nodes , _QUADRATIC_TO_BERNSTEIN ) return bernstein | r Compute the Jacobian determinant of a quadratic surface . |
54,088 | def cubic_jacobian_polynomial ( nodes ) : r jac_parts = _helpers . matrix_product ( nodes , _CUBIC_JACOBIAN_HELPER ) jac_at_nodes = np . empty ( ( 1 , 15 ) , order = "F" ) jac_at_nodes [ 0 , 0 ] = two_by_two_det ( jac_parts [ : , : 2 ] ) jac_at_nodes [ 0 , 1 ] = two_by_two_det ( jac_parts [ : , 2 : 4 ] ) jac_at_nodes [ 0 , 2 ] = two_by_two_det ( jac_parts [ : , 4 : 6 ] ) jac_at_nodes [ 0 , 3 ] = two_by_two_det ( jac_parts [ : , 6 : 8 ] ) jac_at_nodes [ 0 , 4 ] = two_by_two_det ( jac_parts [ : , 8 : 10 ] ) jac_at_nodes [ 0 , 5 ] = two_by_two_det ( jac_parts [ : , 10 : 12 ] ) jac_at_nodes [ 0 , 6 ] = two_by_two_det ( jac_parts [ : , 12 : 14 ] ) jac_at_nodes [ 0 , 7 ] = two_by_two_det ( jac_parts [ : , 14 : 16 ] ) jac_at_nodes [ 0 , 8 ] = two_by_two_det ( jac_parts [ : , 16 : 18 ] ) jac_at_nodes [ 0 , 9 ] = two_by_two_det ( jac_parts [ : , 18 : 20 ] ) jac_at_nodes [ 0 , 10 ] = two_by_two_det ( jac_parts [ : , 20 : 22 ] ) jac_at_nodes [ 0 , 11 ] = two_by_two_det ( jac_parts [ : , 22 : 24 ] ) jac_at_nodes [ 0 , 12 ] = two_by_two_det ( jac_parts [ : , 24 : 26 ] ) jac_at_nodes [ 0 , 13 ] = two_by_two_det ( jac_parts [ : , 26 : 28 ] ) jac_at_nodes [ 0 , 14 ] = two_by_two_det ( jac_parts [ : , 28 : ] ) bernstein = _helpers . matrix_product ( jac_at_nodes , _QUARTIC_TO_BERNSTEIN ) bernstein /= _QUARTIC_BERNSTEIN_FACTOR return bernstein | r Compute the Jacobian determinant of a cubic surface . |
54,089 | def _de_casteljau_one_round ( nodes , degree , lambda1 , lambda2 , lambda3 ) : r dimension , num_nodes = nodes . shape num_new_nodes = num_nodes - degree - 1 new_nodes = np . empty ( ( dimension , num_new_nodes ) , order = "F" ) index = 0 parent_i1 = 0 parent_i2 = 1 parent_i3 = degree + 1 for k in six . moves . xrange ( degree ) : for unused_j in six . moves . xrange ( degree - k ) : new_nodes [ : , index ] = ( lambda1 * nodes [ : , parent_i1 ] + lambda2 * nodes [ : , parent_i2 ] + lambda3 * nodes [ : , parent_i3 ] ) parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 parent_i1 += 1 parent_i2 += 1 return new_nodes | r Performs one round of the de Casteljau algorithm for surfaces . |
54,090 | def make_transform ( degree , weights_a , weights_b , weights_c ) : num_nodes = ( ( degree + 1 ) * ( degree + 2 ) ) // 2 id_mat = np . eye ( num_nodes , order = "F" ) transform = { 0 : de_casteljau_one_round ( id_mat , degree , * weights_a ) , 1 : de_casteljau_one_round ( id_mat , degree , * weights_b ) , 2 : de_casteljau_one_round ( id_mat , degree , * weights_c ) , } return transform | Compute matrices corresponding to the de Casteljau algorithm . |
54,091 | def reduced_to_matrix ( shape , degree , vals_by_weight ) : r result = np . empty ( shape , order = "F" ) index = 0 for k in six . moves . xrange ( degree + 1 ) : for j in six . moves . xrange ( degree + 1 - k ) : i = degree - j - k key = ( 0 , ) * i + ( 1 , ) * j + ( 2 , ) * k result [ : , index ] = vals_by_weight [ key ] [ : , 0 ] index += 1 return result | r Converts a reduced values dictionary into a matrix . |
54,092 | def _specialize_surface ( nodes , degree , weights_a , weights_b , weights_c ) : partial_vals = { ( 0 , ) : de_casteljau_one_round ( nodes , degree , * weights_a ) , ( 1 , ) : de_casteljau_one_round ( nodes , degree , * weights_b ) , ( 2 , ) : de_casteljau_one_round ( nodes , degree , * weights_c ) , } for reduced_deg in six . moves . xrange ( degree - 1 , 0 , - 1 ) : new_partial = { } transform = make_transform ( reduced_deg , weights_a , weights_b , weights_c ) for key , sub_nodes in six . iteritems ( partial_vals ) : for next_id in six . moves . xrange ( key [ - 1 ] , 2 + 1 ) : new_key = key + ( next_id , ) new_partial [ new_key ] = _helpers . matrix_product ( sub_nodes , transform [ next_id ] ) partial_vals = new_partial return reduced_to_matrix ( nodes . shape , degree , partial_vals ) | Specialize a surface to a reparameterization |
54,093 | def _subdivide_nodes ( nodes , degree ) : if degree == 1 : nodes_a = _helpers . matrix_product ( nodes , LINEAR_SUBDIVIDE_A ) nodes_b = _helpers . matrix_product ( nodes , LINEAR_SUBDIVIDE_B ) nodes_c = _helpers . matrix_product ( nodes , LINEAR_SUBDIVIDE_C ) nodes_d = _helpers . matrix_product ( nodes , LINEAR_SUBDIVIDE_D ) elif degree == 2 : nodes_a = _helpers . matrix_product ( nodes , QUADRATIC_SUBDIVIDE_A ) nodes_b = _helpers . matrix_product ( nodes , QUADRATIC_SUBDIVIDE_B ) nodes_c = _helpers . matrix_product ( nodes , QUADRATIC_SUBDIVIDE_C ) nodes_d = _helpers . matrix_product ( nodes , QUADRATIC_SUBDIVIDE_D ) elif degree == 3 : nodes_a = _helpers . matrix_product ( nodes , CUBIC_SUBDIVIDE_A ) nodes_b = _helpers . matrix_product ( nodes , CUBIC_SUBDIVIDE_B ) nodes_c = _helpers . matrix_product ( nodes , CUBIC_SUBDIVIDE_C ) nodes_d = _helpers . matrix_product ( nodes , CUBIC_SUBDIVIDE_D ) elif degree == 4 : nodes_a = _helpers . matrix_product ( nodes , QUARTIC_SUBDIVIDE_A ) nodes_b = _helpers . matrix_product ( nodes , QUARTIC_SUBDIVIDE_B ) nodes_c = _helpers . matrix_product ( nodes , QUARTIC_SUBDIVIDE_C ) nodes_d = _helpers . matrix_product ( nodes , QUARTIC_SUBDIVIDE_D ) else : nodes_a = specialize_surface ( nodes , degree , _WEIGHTS_SUBDIVIDE0 , _WEIGHTS_SUBDIVIDE1 , _WEIGHTS_SUBDIVIDE2 , ) nodes_b = specialize_surface ( nodes , degree , _WEIGHTS_SUBDIVIDE3 , _WEIGHTS_SUBDIVIDE2 , _WEIGHTS_SUBDIVIDE1 , ) nodes_c = specialize_surface ( nodes , degree , _WEIGHTS_SUBDIVIDE1 , _WEIGHTS_SUBDIVIDE4 , _WEIGHTS_SUBDIVIDE3 , ) nodes_d = specialize_surface ( nodes , degree , _WEIGHTS_SUBDIVIDE2 , _WEIGHTS_SUBDIVIDE3 , _WEIGHTS_SUBDIVIDE5 , ) return nodes_a , nodes_b , nodes_c , nodes_d | Subdivide a surface into four sub - surfaces . |
54,094 | def ignored_double_corner ( intersection , tangent_s , tangent_t , edge_nodes1 , edge_nodes2 ) : prev_index = ( intersection . index_first - 1 ) % 3 prev_edge = edge_nodes1 [ prev_index ] alt_tangent_s = _curve_helpers . evaluate_hodograph ( 1.0 , prev_edge ) cross_prod1 = _helpers . cross_product ( tangent_s . ravel ( order = "F" ) , tangent_t . ravel ( order = "F" ) ) if cross_prod1 >= 0.0 : cross_prod2 = _helpers . cross_product ( alt_tangent_s . ravel ( order = "F" ) , tangent_t . ravel ( order = "F" ) ) if cross_prod2 >= 0.0 : return False prev_index = ( intersection . index_second - 1 ) % 3 prev_edge = edge_nodes2 [ prev_index ] alt_tangent_t = _curve_helpers . evaluate_hodograph ( 1.0 , prev_edge ) alt_tangent_t *= - 1.0 cross_prod3 = _helpers . cross_product ( tangent_s . ravel ( order = "F" ) , alt_tangent_t . ravel ( order = "F" ) ) if cross_prod3 >= 0.0 : cross_prod4 = _helpers . cross_product ( alt_tangent_s . ravel ( order = "F" ) , alt_tangent_t . ravel ( order = "F" ) ) if cross_prod4 >= 0.0 : return False return cross_prod1 > 0.0 or cross_prod3 < 0.0 | Check if an intersection is an ignored double corner . |
54,095 | def ignored_corner ( intersection , tangent_s , tangent_t , edge_nodes1 , edge_nodes2 ) : if intersection . s == 0.0 : if intersection . t == 0.0 : return ignored_double_corner ( intersection , tangent_s , tangent_t , edge_nodes1 , edge_nodes2 ) else : prev_index = ( intersection . index_first - 1 ) % 3 prev_edge = edge_nodes1 [ prev_index ] return ignored_edge_corner ( tangent_t , tangent_s , prev_edge ) elif intersection . t == 0.0 : prev_index = ( intersection . index_second - 1 ) % 3 prev_edge = edge_nodes2 [ prev_index ] return ignored_edge_corner ( tangent_s , tangent_t , prev_edge ) else : return False | Check if an intersection is an ignored corner . |
54,096 | def classify_intersection ( intersection , edge_nodes1 , edge_nodes2 ) : r if intersection . s == 1.0 or intersection . t == 1.0 : raise ValueError ( "Intersection occurs at the end of an edge" , "s" , intersection . s , "t" , intersection . t , ) nodes1 = edge_nodes1 [ intersection . index_first ] tangent1 = _curve_helpers . evaluate_hodograph ( intersection . s , nodes1 ) nodes2 = edge_nodes2 [ intersection . index_second ] tangent2 = _curve_helpers . evaluate_hodograph ( intersection . t , nodes2 ) if ignored_corner ( intersection , tangent1 , tangent2 , edge_nodes1 , edge_nodes2 ) : return CLASSIFICATION_T . IGNORED_CORNER cross_prod = _helpers . cross_product ( tangent1 . ravel ( order = "F" ) , tangent2 . ravel ( order = "F" ) ) if cross_prod < - ALMOST_TANGENT : return CLASSIFICATION_T . FIRST elif cross_prod > ALMOST_TANGENT : return CLASSIFICATION_T . SECOND else : return classify_tangent_intersection ( intersection , nodes1 , tangent1 , nodes2 , tangent2 ) | r Determine which curve is on the inside of the intersection . |
54,097 | def handle_ends ( index1 , s , index2 , t ) : edge_end = False if s == 1.0 : s = 0.0 index1 = ( index1 + 1 ) % 3 edge_end = True if t == 1.0 : t = 0.0 index2 = ( index2 + 1 ) % 3 edge_end = True is_corner = s == 0.0 or t == 0.0 return edge_end , is_corner , ( index1 , s , index2 , t ) | Updates intersection parameters if it is on the end of an edge . |
54,098 | def to_front ( intersection , intersections , unused ) : if intersection . s == 1.0 : next_index = ( intersection . index_first + 1 ) % 3 for other_int in intersections : if other_int . s == 0.0 and other_int . index_first == next_index : if other_int in unused : unused . remove ( other_int ) return other_int return _intersection_helpers . Intersection ( next_index , 0.0 , None , None , interior_curve = CLASSIFICATION_T . FIRST ) elif intersection . t == 1.0 : next_index = ( intersection . index_second + 1 ) % 3 for other_int in intersections : if other_int . t == 0.0 and other_int . index_second == next_index : if other_int in unused : unused . remove ( other_int ) return other_int return _intersection_helpers . Intersection ( None , None , next_index , 0.0 , interior_curve = CLASSIFICATION_T . SECOND ) else : return intersection | Rotates a node to the front . |
54,099 | def get_next ( intersection , intersections , unused ) : result = None if is_first ( intersection . interior_curve ) : result = get_next_first ( intersection , intersections ) elif is_second ( intersection . interior_curve ) : result = get_next_second ( intersection , intersections ) elif intersection . interior_curve == CLASSIFICATION_T . COINCIDENT : result = get_next_coincident ( intersection , intersections ) else : raise ValueError ( 'Cannot get next node if not starting from "FIRST", ' '"TANGENT_FIRST", "SECOND", "TANGENT_SECOND" or "COINCIDENT".' ) if result in unused : unused . remove ( result ) return result | Gets the next node along a given edge . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.