INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Converts the text category to a tasks. Category instance.
def parse_category(self, item, field_name, source_name): """ Converts the text category to a tasks.Category instance. """ # Get and checks for the corresponding slug slug = category_map.get(self.get_value(item, source_name), None) if not slug: return None # Load the category instance try: return Category.objects.get(slug=slug) except Category.DoesNotExist: pass
Converts the date in the format: Thu 03.
def parse_date(self, item, field_name, source_name): """ Converts the date in the format: Thu 03. As only the day is provided, tries to find the best match based on the current date, considering that dates are on the past. """ # Get the current date now = datetime.now().date() # Get the date from the source val = self.get_value(item, source_name) week_day, day = val.split() day = int(day) # If the current date is minor than the item date # go back one month if now.day < day: if now.month == 1: now = now.replace(month=12, year=now.year-1) else: now = now.replace(month=now.month-1) # Finally, replace the source day in the current date # and return now = now.replace(day=day) return now
Parse numeric fields.
def parse_totals(self, item, field_name, source_name): """ Parse numeric fields. """ val = self.get_value(item, source_name) try: return int(val) except: return 0
Iterator of the list of items in the XML source.
def get_items(self): """ Iterator of the list of items in the XML source. """ # Use `iterparse`, it's more efficient, specially for big files for event, item in ElementTree.iterparse(self.source): if item.tag == self.item_tag_name: yield item # Releases the item from memory item.clear()
This method receives an item from the source and a source name and returns the text content for the source_name node.
def get_value(self, item, source_name): """ This method receives an item from the source and a source name, and returns the text content for the `source_name` node. """ return force_text(smart_str(item.findtext(source_name))).strip()
Saves an error in the error list.
def save_error(self, data, exception_info): """ Saves an error in the error list. """ # TODO: what to do with errors? Let it flow? Write to a log file? self.errors.append({'data': data, 'exception': ''.join(format_exception(*exception_info)), })
Parses all data from the source saving model instances.
def parse(self): """ Parses all data from the source, saving model instances. """ # Checks if the source is loaded if not self.loaded: self.load(self.source) for item in self.get_items(): # Parse the fields from the source into a dict data = self.parse_item(item) # Get the instance from the DB, or a new one instance = self.get_instance(data) # Feed instance with data self.feed_instance(data, instance) # Try to save the instance or keep the error try: self.save_item(item, data, instance) except Exception as e: self.save_error(data, sys.exc_info()) # Unload the source self.unload()
Receives an item and returns a dictionary of field values.
def parse_item(self, item): """ Receives an item and returns a dictionary of field values. """ # Create a dictionary from values for each field parsed_data = {} for field_name in self.fields: # A field-name may be mapped to another identifier on the source, # it could be a XML path or a CSV column name / position. # Defaults to the field-name itself. source_name = self.field_map.get(field_name, field_name) # Uses a custom method "parse_%(field_name)" # or get the value from the item parse = getattr(self, 'parse_%s' % field_name, None) if parse: value = parse(item, field_name, source_name) else: value = self.get_value(item, source_name) # Add the value to the parsed data parsed_data[field_name] = value return parsed_data
Get an item from the database or an empty one if not found.
def get_instance(self, data): """ Get an item from the database or an empty one if not found. """ # Get unique fields unique_fields = self.unique_fields # If there are no unique fields option, all items are new if not unique_fields: return self.model() # Build the filter filter = dict([(f, data[f]) for f in unique_fields]) # Get the instance from the DB or use a new instance try: instance = self.model._default_manager.get(**filter) except self.model.DoesNotExist: return self.model() return instance
Feeds a model instance using parsed data ( usually from parse_item ).
def feed_instance(self, data, instance): """ Feeds a model instance using parsed data (usually from `parse_item`). """ for prop, val in data.items(): setattr(instance, prop, val) return instance
Saves a model instance to the database.
def save_item(self, item, data, instance, commit=True): """ Saves a model instance to the database. """ if commit: instance.save() return instance
Downloads a HTTP resource from url and save to dest. Capable of dealing with Gzip compressed content.
def download_file(url, dest): """ Downloads a HTTP resource from `url` and save to `dest`. Capable of dealing with Gzip compressed content. """ # Create the HTTP request request = urllib2.Request(url) # Add the header to accept gzip encoding request.add_header('Accept-encoding', 'gzip') # Open the request opener = urllib2.build_opener() response = opener.open(request) # Retrieve data data = response.read() # If the data is compressed, put the data in a stream and decompress if response.headers.get('content-encoding', '') == 'gzip': stream = StringIO.StringIO(data) gzipper = gzip.GzipFile(fileobj=stream) data = gzipper.read() # Write to a file f = open(dest, 'wb') f.write(data) f.close()
Opens the source file.
def load(self, source): """ Opens the source file. """ self.source = open(self.source, 'rb') self.loaded = True
Iterator to read the rows of the CSV file.
def get_items(self): """ Iterator to read the rows of the CSV file. """ # Get the csv reader reader = csv.reader(self.source) # Get the headers from the first line headers = reader.next() # Read each line yielding a dictionary mapping # the column headers to the row values for row in reader: # Skip empty rows if not row: continue yield dict(zip(headers, row))
This method receives an item from the source and a source name and returns the text content for the source_name node.
def get_value(self, item, source_name): """ This method receives an item from the source and a source name, and returns the text content for the `source_name` node. """ val = item.get(source_name.encode('utf-8'), None) if val is not None: val = convert_string(val) return val
Return value of variable set in the package where said variable is named in the Python meta format __<meta_name > __.
def get_package_meta(meta_name): """Return value of variable set in the package where said variable is named in the Python meta format `__<meta_name>__`. """ regex = "__{0}__ = ['\"]([^'\"]+)['\"]".format(meta_name) return re.search(regex, package_file).group(1)
Raises ValueError if this sandbox instance is currently running.
def allow_network_access(self, value: bool): """ Raises ValueError if this sandbox instance is currently running. """ if self._is_running: raise ValueError( "Cannot change network access settings on a running sandbox") self._allow_network_access = value
Runs a command inside the sandbox and returns the results.
def run_command(self, args: List[str], max_num_processes: int=None, max_stack_size: int=None, max_virtual_memory: int=None, as_root: bool=False, stdin: FileIO=None, timeout: int=None, check: bool=False, truncate_stdout: int=None, truncate_stderr: int=None) -> 'CompletedCommand': """ Runs a command inside the sandbox and returns the results. :param args: A list of strings that specify which command should be run inside the sandbox. :param max_num_processes: The maximum number of processes the command is allowed to spawn. :param max_stack_size: The maximum stack size, in bytes, allowed for the command. :param max_virtual_memory: The maximum amount of memory, in bytes, allowed for the command. :param as_root: Whether to run the command as a root user. :param stdin: A file object to be redirected as input to the command's stdin. If this is None, /dev/null is sent to the command's stdin. :param timeout: The time limit for the command. :param check: Causes CalledProcessError to be raised if the command exits nonzero or times out. :param truncate_stdout: When not None, stdout from the command will be truncated after this many bytes. :param truncate_stderr: When not None, stderr from the command will be truncated after this many bytes. """ cmd = ['docker', 'exec', '-i', self.name, 'cmd_runner.py'] if stdin is None: cmd.append('--stdin_devnull') if max_num_processes is not None: cmd += ['--max_num_processes', str(max_num_processes)] if max_stack_size is not None: cmd += ['--max_stack_size', str(max_stack_size)] if max_virtual_memory is not None: cmd += ['--max_virtual_memory', str(max_virtual_memory)] if timeout is not None: cmd += ['--timeout', str(timeout)] if truncate_stdout is not None: cmd += ['--truncate_stdout', str(truncate_stdout)] if truncate_stderr is not None: cmd += ['--truncate_stderr', str(truncate_stderr)] if not as_root: cmd += ['--linux_user_id', str(self._linux_uid)] cmd += args if self.debug: print('running: {}'.format(cmd), flush=True) with tempfile.TemporaryFile() as f: try: subprocess.run(cmd, stdin=stdin, stdout=f, stderr=subprocess.PIPE, check=True) f.seek(0) json_len = int(f.readline().decode().rstrip()) results_json = json.loads(f.read(json_len).decode()) stdout_len = int(f.readline().decode().rstrip()) stdout = tempfile.NamedTemporaryFile() stdout.write(f.read(stdout_len)) stdout.seek(0) stderr_len = int(f.readline().decode().rstrip()) stderr = tempfile.NamedTemporaryFile() stderr.write(f.read(stderr_len)) stderr.seek(0) result = CompletedCommand(return_code=results_json['return_code'], timed_out=results_json['timed_out'], stdout=stdout, stderr=stderr, stdout_truncated=results_json['stdout_truncated'], stderr_truncated=results_json['stderr_truncated']) if (result.return_code != 0 or results_json['timed_out']) and check: raise subprocess.CalledProcessError( result.return_code, cmd, output=result.stdout, stderr=result.stderr) return result except subprocess.CalledProcessError as e: f.seek(0) print(f.read()) print(e.stderr) raise
Copies the specified files into the working directory of this sandbox. The filenames specified can be absolute paths or relative paths to the current working directory.
def add_files(self, *filenames: str, owner: str=SANDBOX_USERNAME, read_only: bool=False): """ Copies the specified files into the working directory of this sandbox. The filenames specified can be absolute paths or relative paths to the current working directory. :param owner: The name of a user who should be granted ownership of the newly added files. Must be either autograder_sandbox.SANDBOX_USERNAME or 'root', otherwise ValueError will be raised. :param read_only: If true, the new files' permissions will be set to read-only. """ if owner != SANDBOX_USERNAME and owner != 'root': raise ValueError('Invalid value for parameter "owner": {}'.format(owner)) with tempfile.TemporaryFile() as f, \ tarfile.TarFile(fileobj=f, mode='w') as tar_file: for filename in filenames: tar_file.add(filename, arcname=os.path.basename(filename)) f.seek(0) subprocess.check_call( ['docker', 'cp', '-', self.name + ':' + SANDBOX_WORKING_DIR_NAME], stdin=f) file_basenames = [os.path.basename(filename) for filename in filenames] if owner == SANDBOX_USERNAME: self._chown_files(file_basenames) if read_only: chmod_cmd = ['chmod', '444'] + file_basenames self.run_command(chmod_cmd, as_root=True)
Copies the specified file into the working directory of this sandbox and renames it to new_filename.
def add_and_rename_file(self, filename: str, new_filename: str) -> None: """ Copies the specified file into the working directory of this sandbox and renames it to new_filename. """ dest = os.path.join( self.name + ':' + SANDBOX_WORKING_DIR_NAME, new_filename) subprocess.check_call(['docker', 'cp', filename, dest]) self._chown_files([new_filename])
Return a list of all enrollments for the passed course_id.
def get_enrollments_for_course(self, course_id, params={}): """ Return a list of all enrollments for the passed course_id. https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.index """ url = COURSES_API.format(course_id) + "/enrollments" enrollments = [] for datum in self._get_paged_resource(url, params=params): enrollments.append(CanvasEnrollment(data=datum)) return enrollments
Return a list of all enrollments for the passed course sis id.
def get_enrollments_for_course_by_sis_id(self, sis_course_id, params={}): """ Return a list of all enrollments for the passed course sis id. """ return self.get_enrollments_for_course( self._sis_id(sis_course_id, sis_field="course"), params)
Return a list of all enrollments for the passed section_id.
def get_enrollments_for_section(self, section_id, params={}): """ Return a list of all enrollments for the passed section_id. https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.index """ url = SECTIONS_API.format(section_id) + "/enrollments" enrollments = [] for datum in self._get_paged_resource(url, params=params): enrollments.append(CanvasEnrollment(data=datum)) return enrollments
Return a list of all enrollments for the passed section sis id.
def get_enrollments_for_section_by_sis_id(self, sis_section_id, params={}): """ Return a list of all enrollments for the passed section sis id. """ return self.get_enrollments_for_section( self._sis_id(sis_section_id, sis_field="section"), params)
Return a list of enrollments for the passed user regid.
def get_enrollments_for_regid(self, regid, params={}, include_courses=True): """ Return a list of enrollments for the passed user regid. https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.index """ sis_user_id = self._sis_id(regid, sis_field="user") url = USERS_API.format(sis_user_id) + "/enrollments" courses = Courses() if include_courses else None enrollments = [] for datum in self._get_paged_resource(url, params=params): enrollment = CanvasEnrollment(data=datum) if include_courses: course_id = datum["course_id"] course = courses.get_course(course_id) if course.sis_course_id is not None: enrollment.course = course # the following 3 lines are not removed # to be backward compatible. enrollment.course_url = course.course_url enrollment.course_name = course.name enrollment.sis_course_id = course.sis_course_id else: enrollment.course_url = re.sub( r'/users/\d+$', '', enrollment.html_url) enrollments.append(enrollment) return enrollments
Enroll a user into a course.
def enroll_user(self, course_id, user_id, enrollment_type, params=None): """ Enroll a user into a course. https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.create """ url = COURSES_API.format(course_id) + "/enrollments" if not params: params = {} params["user_id"] = user_id params["type"] = enrollment_type data = self._post_resource(url, {"enrollment": params}) return CanvasEnrollment(data=data)
Calculates the foundation capacity according Vesics ( 1975 ) #Gunaratne Manjriker. 2006. Spread Footings: Analysis and Design. Ref: http:// geo. cv. nctu. edu. tw/ foundation/ download/ BearingCapacityOfFoundations. pdf
def capacity_vesics_1975(sl, fd, h_l=0, h_b=0, vertical_load=1, slope=0, base_tilt=0, verbose=0, gwl=1e6, **kwargs): """ Calculates the foundation capacity according Vesics(1975) #Gunaratne, Manjriker. 2006. "Spread Footings: Analysis and Design." Ref: http://geo.cv.nctu.edu.tw/foundation/download/ BearingCapacityOfFoundations.pdf :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param slope: ground slope :param base_tilt: The slope of the underside of the foundation :param verbose: verbosity :return: ultimate bearing stress """ if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) area_foundation = fd.length * fd.width c_a = 0.6 - 1.0 * sl.cohesion horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2) fd.nq_factor = ((np.tan(np.pi / 4 + sl.phi_r / 2)) ** 2 * np.exp(np.pi * np.tan(sl.phi_r))) if sl.phi_r == 0: fd.nc_factor = 5.14 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) fd.ng_factor = 2.0 * (fd.nq_factor + 1) * np.tan(sl.phi_r) # shape factors: s_c = 1.0 + fd.nq_factor / fd.nc_factor * fd.width / fd.length s_q = 1 + fd.width / fd.length * np.tan(sl.phi_r) s_g = max(1.0 - 0.4 * fd.width / fd.length, 0.6) # add limit of 0.6 based on Vesic # depth factors: if fd.depth / fd.width > 1: k = np.arctan(fd.depth / fd.width) else: k = fd.depth / fd.width d_c = 1 + 0.4 * k d_q = 1 + 2 * np.tan(sl.phi_r) * (1 - np.sin(sl.phi_r)) ** 2 * k d_g = 1.0 # load inclination factors m__b = (2.0 + fd.width / fd.length) / (1 + fd.width / fd.length) m_l = (2.0 + fd.length / fd.width) / (1 + fd.length / fd.width) m = np.sqrt(m__b ** 2 + m_l ** 2) if sl.phi_r == 0: i_q = 1.0 i_g = 1.0 else: i_q = (1.0 - horizontal_load / (vertical_load + area_foundation * c_a / np.tan(sl.phi_r))) ** m i_g = (1.0 - horizontal_load / (vertical_load + area_foundation * c_a / np.tan(sl.phi_r))) ** (m + 1) i_c = i_q - (1 - i_q) / (fd.nq_factor - 1) check_i_c = 1 - m * horizontal_load / (area_foundation * c_a * fd.nc_factor) if abs(check_i_c - i_c) / i_c > 0.001: raise DesignError # ground slope factors: if sl.phi_r == 0: # g_c = slope / 5.14 g_c = i_q else: g_c = i_q - (1 - i_q) / (5.14 * np.tan(sl.phi_r)) g_q = (1.0 - np.tan(slope)) ** 2 g_g = g_q # tilted base factors if sl.phi_r == 0: b_c = g_c else: b_c = 1 - 2 * base_tilt / (5.14 * np.tan(sl.phi_r)) b_q = (1.0 - base_tilt * np.tan(sl.phi_r)) ** 2 b_g = b_q # stress at footing base: if gwl == 0: q_d = sl.unit_eff_weight * fd.depth unit_weight = sl.unit_bouy_weight elif gwl > 0 and gwl < fd.depth: q_d = (sl.unit_dry_weight * gwl) + (sl.unit_bouy_weight * (fd.depth - gwl)) unit_weight = sl.unit_bouy_weight elif gwl >= fd.depth and gwl <= fd.depth + fd.width: sl.average_unit_bouy_weight = sl.unit_bouy_weight + ( ((gwl - fd.depth) / fd.width) * (sl.unit_dry_weight - sl.unit_bouy_weight)) q_d = sl.unit_dry_weight * fd.depth unit_weight = sl.average_unit_bouy_weight elif gwl > fd.depth + fd.width: q_d = sl.unit_dry_weight * fd.depth unit_weight = sl.unit_dry_weight if verbose: log("Nc: ", fd.nc_factor) log("N_qV: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("d_c: ", d_c) log("d_q: ", d_q) log("d_g: ", d_g) log("i_c: ", i_c) log("i_q: ", i_q) log("i_g: ", i_g) log("g_c: ", g_c) log("g_q: ", g_q) log("g_g: ", g_g) log("b_c: ", b_c) log("b_q: ", b_q) log("b_g: ", b_g) log("q_d: ", q_d) # Capacity fd.q_ult = (sl.cohesion * fd.nc_factor * s_c * d_c * i_c * g_c * b_c + q_d * fd.nq_factor * s_q * d_q * i_q * g_q * b_q + 0.5 * fd.width * unit_weight * fd.ng_factor * s_g * d_g * i_g * g_g * b_g) if verbose: log("qult: ", fd.q_ult) return fd.q_ult
Calculates the foundation capacity according Terzaghi ( 1943 ) Ref: http:// geo. cv. nctu. edu. tw/ foundation/ download/ BearingCapacityOfFoundations. pdf
def capacity_terzaghi_1943(sl, fd, round_footing=False, verbose=0, **kwargs): """ Calculates the foundation capacity according Terzaghi (1943) Ref: http://geo.cv.nctu.edu.tw/foundation/ download/BearingCapacityOfFoundations.pdf :param sl: Soil object :param fd: Foundation object :param round_footing: if True, then foundation is round :param verbose: verbosity :return: ultimate bearing stress Note: the shape factor of 1.3 is used for aspect ratio > 6 """ if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) a02 = ((np.exp(np.pi * (0.75 - sl.phi / 360) * np.tan(sl.phi_r))) ** 2) a0_check = (np.exp((270 - sl.phi) / 180 * np.pi * np.tan(sl.phi_r))) if (a02 - a0_check) / a02 > 0.001: raise DesignError fd.nq_factor = (a02 / (2 * (np.cos((45 + sl.phi / 2) * np.pi / 180)) ** 2)) fd.ng_factor = (2 * (fd.nq_factor + 1) * np.tan(sl.phi_r) / (1 + 0.4 * np.sin(4 * sl.phi_r))) if sl.phi_r == 0: fd.nc_factor = 5.7 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) # shape factors: if round_footing: s_c = 1.3 s_g = 0.6 elif fd.length / fd.width < 5: s_c = 1.3 s_g = 0.8 else: s_c = 1.0 s_g = 1.0 s_q = 1.0 # stress at footing base: q_d = sl.unit_dry_weight * fd.depth # Capacity fd.q_ult = (sl.cohesion * fd.nc_factor * s_c + q_d * fd.nq_factor * s_q + 0.5 * fd.width * sl.unit_dry_weight * fd.ng_factor * s_g) if verbose: log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("qult: ", fd.q_ult) return fd.q_ult
Calculates the foundation capacity according Hansen ( 1970 ) Ref: http:// bestengineeringprojects. com/ civil - projects/ hansens - bearing - capacity - theory/
def capacity_hansen_1970(sl, fd, h_l=0, h_b=0, vertical_load=1, slope=0, base_tilt=0, verbose=0, **kwargs): """ Calculates the foundation capacity according Hansen (1970) Ref: http://bestengineeringprojects.com/civil-projects/ hansens-bearing-capacity-theory/ :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param slope: ground slope :param base_tilt: The slope of the underside of the foundation :param verbose: verbosity :return: ultimate bearing stress """ if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) area_foundation = fd.length * fd.width horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2) c_a = 0.6 - 1.0 * sl.cohesion fd.nq_factor = ((np.tan(np.pi / 4 + sl.phi_r / 2)) ** 2 * np.exp(np.pi * np.tan(sl.phi_r))) if sl.phi_r == 0: fd.nc_factor = 5.14 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) fd.ng_factor = 1.5 * (fd.nq_factor - 1) * np.tan(sl.phi_r) # shape factors if sl.phi_r == 0: s_c = 0.2 * fd.width / fd.length else: s_c = 1.0 + fd.nq_factor / fd.nc_factor * fd.width / fd.length s_q = 1.0 + fd.width / fd.length * np.sin(sl.phi_r) s_g = 1.0 - 0.4 * fd.width / fd.length # depth factors: if fd.depth / fd.width > 1: k = np.arctan(fd.depth / fd.width) else: k = fd.depth / fd.width d_c = 1 + 0.4 * k if sl.phi == 0: d_c = 0.4 * k d_q = 1 + 2 * np.tan(sl.phi_r) * (1 - np.sin(sl.phi_r)) ** 2 * k d_g = 1.0 # incline load factors: if sl.phi_r == 0: i_q = 1.0 i_c = 0.5 - 0.5 * np.sqrt(1 - horizontal_load / area_foundation * c_a) i_g = 1.0 else: i_q = ((1.0 - 0.5 * horizontal_load / (vertical_load + area_foundation * c_a / np.tan(sl.phi_r))) ** 5) i_c = i_q - (1 - i_q) / (fd.nq_factor - 1) i_g = ((1 - (0.7 * horizontal_load) / (vertical_load + area_foundation * c_a / np.tan(sl.phi_r))) ** 5) # slope factors: if sl.phi_r == 0: g_c = (slope / np.pi * 180) / 147 else: g_c = 1.0 - (slope / np.pi * 180) / 147 g_q = 1 - 0.5 * np.tan(slope) ** 5 g_g = g_q # base tilt factors: if sl.phi_r == 0: b_c = (base_tilt / np.pi * 180) / 147 else: b_c = 1.0 - (base_tilt / np.pi * 180) / 147 b_q = (np.exp(-0.0349 * (base_tilt / np.pi * 180) * np.tan(sl.phi_r))) b_g = (np.exp(-0.0471 * (base_tilt / np.pi * 180) * np.tan(sl.phi_r))) if verbose: log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("d_c: ", d_c) log("d_q: ", d_q) log("d_g: ", d_g) log("i_c: ", i_c) log("i_q: ", i_q) log("i_g: ", i_g) log("g_c: ", g_c) log("g_q: ", g_q) log("g_g: ", g_g) log("b_c: ", b_c) log("b_q: ", b_q) log("b_g: ", b_g) # stress at footing base: q_d = sl.unit_dry_weight * fd.depth # Capacity if sl.phi_r == 0: fd.q_ult = (sl.cohesion * fd.nc_factor * (1 + s_c + d_c - i_c - g_c - b_c) + q_d) else: fd.q_ult = (sl.cohesion * fd.nc_factor * s_c * d_c * i_c * g_c * b_c + q_d * fd.nq_factor * s_q * d_q * i_q * g_q * b_q + 0.5 * fd.width * sl.unit_dry_weight * fd.ng_factor * s_g * d_g * i_g * g_g * b_g)
Calculates the foundation capacity according Meyerhoff ( 1963 ) http:// www. engs - comp. com/ meyerhof/ index. shtml
def capacity_meyerhof_1963(sl, fd, gwl=1e6, h_l=0, h_b=0, vertical_load=1, verbose=0, **kwargs): """ Calculates the foundation capacity according Meyerhoff (1963) http://www.engs-comp.com/meyerhof/index.shtml :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param verbose: verbosity :return: ultimate bearing stress """ if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2) fd.nq_factor = ((np.tan(np.pi / 4 + sl.phi_r / 2)) ** 2 * np.exp(np.pi * np.tan(sl.phi_r))) if sl.phi_r == 0: fd.nc_factor = 5.14 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) fd.ng_factor = (fd.nq_factor - 1) * np.tan(1.4 * sl.phi_r) if verbose: log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) kp = (np.tan(np.pi / 4 + sl.phi_r / 2)) ** 2 # shape factors s_c = 1 + 0.2 * kp * fd.width / fd.length if sl.phi > 10: s_q = 1.0 + 0.1 * kp * fd.width / fd.length else: s_q = 1.0 s_g = s_q # depth factors d_c = 1 + 0.2 * np.sqrt(kp) * fd.depth / fd.width if sl.phi > 10: d_q = 1 + 0.1 * np.sqrt(kp) * fd.depth / fd.width else: d_q = 1.0 d_g = d_q # inclination factors: theta_load = np.arctan(horizontal_load / vertical_load) i_c = (1 - theta_load / (np.pi * 0.5)) ** 2 i_q = i_c if sl.phi > 0: i_g = (1 - theta_load / sl.phi_r) ** 2 else: i_g = 0 # stress at footing base: if gwl == 0: q_d = sl.unit_bouy_weight * fd.depth unit_weight = sl.unit_bouy_weight elif gwl > 0 and gwl < fd.depth: q_d = (sl.unit_dry_weight * gwl) + (sl.unit_bouy_weight * (fd.depth - gwl)) unit_weight = sl.unit_bouy_weight elif gwl >= fd.depth and gwl <= fd.depth + fd.width: sl.average_unit_bouy_weight = sl.unit_bouy_weight + ( ((gwl - fd.depth) / fd.width) * (sl.unit_dry_weight - sl.unit_bouy_weight)) q_d = sl.unit_dry_weight * fd.depth unit_weight = sl.average_unit_bouy_weight elif gwl > fd.depth + fd.width: q_d = sl.unit_dry_weight * fd.depth unit_weight = sl.unit_dry_weight if verbose: log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("d_c: ", d_c) log("d_q: ", d_q) log("d_g: ", d_g) log("i_c: ", i_c) log("i_q: ", i_q) log("i_g: ", i_g) log("q_d: ", q_d) # Capacity fd.q_ult = (sl.cohesion * fd.nc_factor * s_c * d_c * i_c + q_d * fd.nq_factor * s_q * d_q * i_q + 0.5 * fd.width * unit_weight * fd.ng_factor * s_g * d_g * i_g) return fd.q_ult
calculates the capacity according to Appendix B verification method 4 of the NZ building code
def capacity_nzs_vm4_2011(sl, fd, h_l=0, h_b=0, vertical_load=1, slope=0, verbose=0, **kwargs): """ calculates the capacity according to Appendix B verification method 4 of the NZ building code :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param slope: ground slope :param verbose: verbosity :return: ultimate bearing stress """ # Need to make adjustments if sand has DR<40% or # clay has liquidity indices greater than 0.7 if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2) h_eff_b = kwargs.get("h_eff_b", 0) h_eff_l = kwargs.get("h_eff_l", 0) loc_v_l = kwargs.get("loc_v_l", fd.length / 2) loc_v_b = kwargs.get("loc_v_b", fd.width / 2) ecc_b = h_b * h_eff_b / vertical_load ecc_l = h_l * h_eff_l / vertical_load width_eff = min(fd.width, 2 * (loc_v_b + ecc_b), 2 * (fd.width - loc_v_b - ecc_b)) length_eff = min(fd.length, 2 * (loc_v_l + ecc_l), 2 * (fd.length - loc_v_l - ecc_l)) area_foundation = length_eff * width_eff # check para 3.4.1 if width_eff / 2 < fd.width / 6: raise DesignError("failed on eccentricity") # LOAD FACTORS: fd.nq_factor = ((np.tan(np.pi / 4 + sl.phi_r / 2)) ** 2 * np.exp(np.pi * np.tan(sl.phi_r))) if sl.phi_r == 0: fd.nc_factor = 5.14 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) fd.ng_factor = 2.0 * (fd.nq_factor - 1) * np.tan(sl.phi_r) # shape factors: s_c = 1.0 + fd.nq_factor / fd.nc_factor * width_eff / length_eff s_q = 1 + width_eff / length_eff * np.tan(sl.phi_r) s_g = max(1.0 - 0.4 * width_eff / length_eff, 0.6) # add limit of 0.6 based on Vesics # depth factors: if fd.depth / width_eff > 1: k = np.arctan(fd.depth / width_eff) else: k = fd.depth / width_eff if sl.phi_r == 0: d_c = 1 + 0.4 * k d_q = 1.0 else: d_q = (1 + 2 * np.tan(sl.phi_r) * (1 - np.sin(sl.phi_r)) ** 2 * k) d_c = d_q - (1 - d_q) / (fd.nq_factor * np.tan(sl.phi_r)) d_g = 1.0 # load inclination factors: if sl.phi_r == 0: i_c = 0.5 * (1 + np.sqrt(1 - horizontal_load / (area_foundation * sl.cohesion))) i_q = 1.0 i_g = 1.0 else: if h_b == 0: i_q = 1 - horizontal_load / (vertical_load + area_foundation * sl.cohesion / np.tan(sl.phi_r)) i_g = i_q elif h_b > 0 and h_l == 0: i_q = ((1 - 0.7 * horizontal_load / (vertical_load + area_foundation * sl.cohesion / np.tan(sl.phi_r))) ** 3) i_g = ((1 - horizontal_load / (vertical_load + area_foundation * sl.cohesion / np.tan(sl.phi_r))) ** 3) else: raise DesignError("not setup for bi-directional loading") i_c = (i_q * fd.nq_factor - 1) / (fd.nq_factor - 1) # ground slope factors: g_c = 1 - slope * (1.0 - fd.depth / (2 * width_eff)) / 150 g_q = (1 - np.tan(slope * (1 - fd.depth / (2 * width_eff)))) ** 2 g_g = g_q # stress at footing base: q_d = sl.unit_dry_weight * fd.depth if verbose: log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("H: ", horizontal_load) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("d_c: ", d_c) log("d_q: ", d_q) log("d_g: ", d_g) log("i_c: ", i_c) log("i_q: ", i_q) log("i_g: ", i_g) log("g_c: ", g_c) log("g_q: ", g_q) log("g_g: ", g_g) # Capacity fd.q_ult = (sl.cohesion * fd.nc_factor * s_c * d_c * i_c * g_c + q_d * fd.nq_factor * s_q * d_q * i_q * g_q + 0.5 * width_eff * sl.unit_dry_weight * fd.ng_factor * s_g * d_g * i_g * g_g) if verbose: log("q_ult: ", fd.q_ult) return fd.q_ult
calculates the capacity according to THe Engineering of Foundations textbook by Salgado
def capacity_salgado_2008(sl, fd, h_l=0, h_b=0, vertical_load=1, verbose=0, **kwargs): """ calculates the capacity according to THe Engineering of Foundations textbook by Salgado ISBN: 0072500581 :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param verbose: verbosity :return: ultimate bearing stress """ # Need to make adjustments if sand has DR<40% or # clay has liquidity indices greater than 0.7 if not kwargs.get("disable_requires", False): models.check_required(sl, ["phi_r", "cohesion", "unit_dry_weight"]) models.check_required(fd, ["length", "width", "depth"]) h_eff_b = kwargs.get("h_eff_b", 0) h_eff_l = kwargs.get("h_eff_l", 0) loc_v_l = kwargs.get("loc_v_l", fd.length / 2) loc_v_b = kwargs.get("loc_v_b", fd.width / 2) ecc_b = h_b * h_eff_b / vertical_load ecc_l = h_l * h_eff_l / vertical_load width_eff = min(fd.width, 2 * (loc_v_b + ecc_b), 2 * (fd.width - loc_v_b - ecc_b)) length_eff = min(fd.length, 2 * (loc_v_l + ecc_l), 2 * (fd.length - loc_v_l - ecc_l)) # check para 3.4.1 if width_eff / 2 < fd.width / 6: DesignError("failed on eccentricity") # LOAD FACTORS: fd.nq_factor = np.exp(np.pi * np.tan(sl.phi_r)) * (1 + np.sin(sl.phi_r)) / (1 - np.sin(sl.phi_r)) fd.ng_factor = 1.5 * (fd.nq_factor - 1) * np.tan(sl.phi_r) # fd.ng_factor = (fd.nq_factor - 1) * np.tan(1.32 * sl.phi_r) if sl.phi_r == 0: fd.nc_factor = 5.14 else: fd.nc_factor = (fd.nq_factor - 1) / np.tan(sl.phi_r) # shape factors: s_q = 1 + (width_eff / length_eff) * np.tan(sl.phi_r) s_g = max(1 - 0.4 * width_eff / length_eff, 0.6) s_c = 1.0 # depth factors: d_q = 1 + 2 * np.tan(sl.phi_r) * (1 - np.sin(sl.phi_r)) ** 2 * fd.depth / width_eff d_g = 1.0 d_c = 1.0 # stress at footing base: q_d = sl.unit_dry_weight * fd.depth if verbose: log("width_eff: ", width_eff) log("length_eff: ", length_eff) log("Nc: ", fd.nc_factor) log("Nq: ", fd.nq_factor) log("Ng: ", fd.ng_factor) log("s_c: ", s_c) log("s_q: ", s_q) log("s_g: ", s_g) log("d_c: ", d_c) log("d_q: ", d_q) log("d_g: ", d_g) log("q_d: ", q_d) # Capacity fd.q_ult = (sl.cohesion * fd.nc_factor * s_c * d_c + q_d * fd.nq_factor * s_q * d_q + 0.5 * width_eff * sl.unit_dry_weight * fd.ng_factor * s_g * d_g) if verbose: log("qult: ", fd.q_ult) return fd.q_ult
Determine the size of a footing given an aspect ratio and a load: param sl: Soil object: param vertical_load: The applied load to the foundation: param fos: The target factor of safety: param length_to_width: The desired length to width ratio of the foundation: param verbose: verbosity: return: a Foundation object
def size_footing_for_capacity(sl, vertical_load, fos=1.0, length_to_width=1.0, verbose=0, **kwargs): """ Determine the size of a footing given an aspect ratio and a load :param sl: Soil object :param vertical_load: The applied load to the foundation :param fos: The target factor of safety :param length_to_width: The desired length to width ratio of the foundation :param verbose: verbosity :return: a Foundation object """ method = kwargs.get("method", 'vesics') depth_to_width = kwargs.get("depth_to_width", 0) depth = kwargs.get("depth", 0) use_depth_to_width = 0 if not depth: use_depth_to_width = 1 # Find approximate size fd = models.FoundationRaft() fd.width = .5 # start with B=1.0m for i in range(50): fd.length = length_to_width * fd.width if use_depth_to_width: fd.depth = depth_to_width * fd.width capacity_method_selector(sl, fd, method) q = fd.q_ult bearing_capacity = q * fd.length * fd.width fs_actual = bearing_capacity / vertical_load if fs_actual < fos: # Need to increase foundation sizes fd.width += 0.5 else: if verbose: log("fs_actual: ", fs_actual) log("fd.width: ", fd.width) break # at this stage the current size should be too big width_array = [] fs_array = [] for j in range(11): width_array.append(fd.width) fd.length = length_to_width * fd.width if use_depth_to_width: fd.depth = depth_to_width * fd.width capacity_method_selector(sl, fd, method) q = fd.q_ult capacity = q * fd.length * fd.width fs_array.append(capacity / vertical_load) fd.width = fd.width - 0.5 / 10 # search the array until FS satisfied: if verbose: log("reqFS: ", fos) log("width array: \n", width_array) log("FS array: \n", fs_array) for fs in range(len(fs_array)): if fs_array[fs] < fos: fd.width = width_array[fs - 1] fd.length = length_to_width * fd.width if use_depth_to_width: fd.depth = depth_to_width * fd.width capacity_method_selector(sl, fd, method) break if fs == len(fs_array) - 1: DesignError("No suitable foundation sizes could be determined!") return fd
Calculates the bearing capacity of a foundation on soil using the specified method.: param sl: Soil Object: param fd: Foundation Object: param method: Method: param kwargs:: return:
def capacity_method_selector(sl, fd, method, **kwargs): """ Calculates the bearing capacity of a foundation on soil using the specified method. :param sl: Soil Object :param fd: Foundation Object :param method: Method :param kwargs: :return: """ if method == 'vesics': capacity_vesics_1975(sl, fd, **kwargs) elif method == 'nzs': capacity_nzs_vm4_2011(sl, fd, **kwargs) elif method == 'terzaghi': capacity_terzaghi_1943(sl, fd, **kwargs) elif method == 'hansen': capacity_hansen_1970(sl, fd, **kwargs) elif method == 'meyerhoff': capacity_meyerhof_1963(sl, fd, **kwargs) elif method == 'salgado': capacity_salgado_2008(sl, fd, **kwargs)
Calculates the two - layered foundation capacity according Meyerhof and Hanna ( 1978 )
def deprecated_capacity_meyerhof_and_hanna_1978(sl_0, sl_1, h0, fd, verbose=0): """ Calculates the two-layered foundation capacity according Meyerhof and Hanna (1978) :param sl_0: Top Soil object :param sl_1: Base Soil object :param h0: Height of top soil layer :param fd: Foundation object :param h_l: Horizontal load parallel to length :param h_b: Horizontal load parallel to width :param vertical_load: Vertical load :param verbose: verbosity :return: ultimate bearing stress """ # UNFINISHED, this code is copied from the Meyerhoff method # horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2) sl_0.nq_factor_0 = ( (np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_0.phi)))) if sl_0.phi == 0: sl_0.nc_factor_0 = 5.14 else: sl_0.nc_factor_0 = (sl_0.nq_factor_0 - 1) / np.tan(np.deg2rad(sl_0.phi)) sl_0.ng_factor_0 = (sl_0.nq_factor_0 - 1) * np.tan(1.4 * np.deg2rad(sl_0.phi)) sl_1.nq_factor_1 = ( (np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_1.phi)))) if sl_1.phi == 0: sl_1.nc_factor_1 = 5.14 else: sl_1.nc_factor_1 = (sl_1.nq_factor_1 - 1) / np.tan(np.deg2rad(sl_1.phi)) sl_1.ng_factor_1 = (sl_1.nq_factor_1 - 1) * np.tan(1.4 * np.deg2rad(sl_1.phi)) if verbose: log("Nc: ", sl_1.nc_factor_1) log("Nq: ", sl_1.nq_factor_1) log("Ng: ", sl_1.ng_factor_1) sl_0.kp_0 = (np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2 sl_1.kp_1 = (np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2 # shape factors # s_c = 1 + 0.2 * kp * fd.width / fd.length if sl_0.phi >= 10: sl_0.s_c_0 = 1 + 0.2 * sl_0.kp_0 * (fd.width / fd.length) sl_0.s_q_0 = 1.0 + 0.1 * sl_0.kp_0 * (fd.width / fd.length) else: sl_0.s_c_0 = 1 + 0.2 * (fd.width / fd.length) sl_0.s_q_0 = 1.0 sl_0.s_g_0 = sl_0.s_q_0 if sl_1.phi >= 10: sl_1.s_c_1 = 1 + 0.2 * sl_1.kp_1 * (fd.width / fd.length) sl_1.s_q_1 = 1.0 + 0.1 * sl_1.kp_1 * (fd.width / fd.length) else: sl_1.s_c_1 = 1 + 0.2 * (fd.width / fd.length) sl_1.s_q_1 = 1.0 sl_1.s_g_1 = sl_1.s_q_1 """ # depth factors d_c = 1 + 0.2 * np.sqrt(kp) * fd.depth / fd.width if sl_0.phi > 10: d_q = 1 + 0.1 * np.sqrt(kp) * fd.depth / fd.width else: d_q = 1.0 d_g = d_q # inclination factors: theta_load = np.arctan(horizontal_load / vertical_load) i_c = (1 - theta_load / (np.pi * 0.5)) ** 2 i_q = i_c if sl_0.phi > 0: i_g = (1 - theta_load / sl_0.phi_r) ** 2 else: i_g = 0 """ # stress at footing base: # q_d = sl_0.unit_dry_weight_0 * fd.depth # ks sl_0.q_0 = (sl_0.cohesion * sl_0.nc_factor_0) + (0.5 * sl_0.unit_dry_weight * fd.width * sl_0.ng_factor_0) sl_1.q_1 = (sl_1.cohesion * sl_1.nc_factor_1) + (0.5 * sl_1.unit_dry_weight * fd.width * sl_1.ng_factor_1) q1_q0 = sl_1.q_1 / sl_0.q_0 x_0 = np.array([0, 20.08, 22.42, 25.08, 27.58, 30.08, 32.58, 34.92, 37.83, 40.00, 42.67, 45.00, 47.00, 49.75]) y_0 = np.array([0.93, 0.93, 0.93, 0.93, 1.01, 1.17, 1.32, 1.56, 1.87, 2.26, 2.72, 3.35, 3.81, 4.82]) x_2 = np.array([0, 20.08, 22.50, 25.08, 27.58, 30.08, 32.50, 35.00, 37.67, 40.17, 42.67, 45.00, 47.50, 50.00]) y_2 = np.array([1.55, 1.55, 1.71, 1.86, 2.10, 2.33, 2.72, 3.11, 3.81, 4.43, 5.28, 6.14, 7.46, 9.24]) x_4 = np.array([0, 20.00, 22.51, 25.10, 27.69, 30.11, 32.45, 35.04, 37.88, 40.14, 42.65, 45.07, 47.33, 50.08]) y_4 = np.array([2.49, 2.49, 2.64, 2.87, 3.34, 3.81, 4.43, 5.20, 6.29, 7.38, 9.01, 11.11, 14.29, 19.34]) x_10 = np.array([0, 20.00, 22.50, 25.08, 28.00, 30.00, 32.50, 34.92, 37.50, 40.17, 42.42, 45.00, 47.17, 50.08]) y_10 = np.array([3.27, 3.27, 3.74, 4.44, 5.37, 6.07, 7.16, 8.33, 10.04, 12.30, 15.95, 21.17, 27.47, 40.00]) x_int = sl_0.phi if sl_0.phi < 1: fd.ks = 0 else: if q1_q0 == 0: fd.ks = np.interp(x_int, x_0, y_0) elif q1_q0 == 0.2: fd.ks = np.interp(x_int, x_2, y_2) elif q1_q0 == 0.4: fd.ks = np.interp(x_int, x_4, y_4) elif q1_q0 == 1.0: fd.ks = np.interp(x_int, x_10, y_10) elif 0 < q1_q0 < 0.2: ks_1 = np.interp(x_int, x_0, y_0) ks_2 = np.interp(x_int, x_2, y_2) fd.ks = (((ks_2 - ks_1) * q1_q0) / 0.2) + ks_1 elif 0.2 < q1_q0 < 0.4: ks_1 = np.interp(x_int, x_2, y_2) ks_2 = np.interp(x_int, x_4, y_4) fd.ks = (((ks_2 - ks_1) * (q1_q0 - 0.2)) / 0.2) + ks_1 elif 0.4 < q1_q0 < 1.0: ks_1 = np.interp(x_int, x_4, y_4) ks_2 = np.interp(x_int, x_10, y_10) fd.ks = (((ks_2 - ks_1) * (q1_q0 - 0.4)) / 0.6) + ks_1 else: raise DesignError("Cannot compute 'ks', bearing ratio out-of-range (q1_q0 = %.3f) required: 0-1." % q1_q0) # ca if sl_0.cohesion == 0: c1_c0 = 0 else: c1_c0 = sl_1.cohesion / sl_0.cohesion x = np.array([0.000, 0.082, 0.206, 0.298, 0.404, 0.509, 0.598, 0.685, 0.772]) y = np.array([0.627, 0.700, 0.794, 0.855, 0.912, 0.948, 0.968, 0.983, 0.997]) ca_c0 = np.interp(c1_c0, x, y) fd.ca = ca_c0 * sl_0.cohesion # Capacity a = 1 # ???? s = 1 # ???? r = 1 + (fd.width / fd.length) q_b1 = (sl_1.cohesion * sl_1.nc_factor_1 * sl_1.s_c_1) q_b2 = (sl_0.unit_dry_weight * h0 * sl_1.nq_factor_1 * sl_1.s_q_1) q_b3 = (sl_1.unit_dry_weight * fd.width * sl_1.ng_factor_1 * sl_1.s_g_1 / 2) fd.q_b = q_b1 + q_b2 + q_b3 fd.q_ult4 = (r * (2 * fd.ca * (h0 - fd.depth) / fd.width) * a) fd.q_ult5 = r * (sl_0.unit_dry_weight * ((h0 - fd.depth) ** 2)) * (1 + (2 * fd.depth / (h0 - fd.depth))) * ( fd.ks * np.tan(np.deg2rad(sl_0.phi)) / fd.width) * s fd.q_ult6 = (sl_0.unit_dry_weight * (h0 - fd.depth)) fd.q_ult = fd.q_b + fd.q_ult4 + fd.q_ult5 - fd.q_ult6 # maximum value (qu <= qt) q_t1 = (sl_0.cohesion * sl_0.nc_factor_0 * sl_0.s_c_0) q_t2 = (sl_0.unit_dry_weight * fd.depth * sl_0.nq_factor_0 * sl_0.s_q_0) q_t3 = (sl_0.unit_dry_weight * fd.width * sl_0.ng_factor_0 * sl_0.s_g_0 / 2) fd.q_t = q_t1 + q_t2 + q_t3 if fd.q_ult > fd.q_t: fd.q_ult = fd.q_t return fd.q_ult
Calculates the two - layered foundation capacity according Meyerhof and Hanna ( 1978 )
def capacity_meyerhof_and_hanna_1978(sl_0, sl_1, h0, fd, gwl=1e6, verbose=0): """ Calculates the two-layered foundation capacity according Meyerhof and Hanna (1978) :param sl_0: Top Soil object :param sl_1: Base Soil object :param h0: Height of top soil layer :param fd: Foundation object :param wtl: water table level :param verbose: verbosity :return: ultimate bearing stress """ sp = sm.SoilProfile() sp.add_layer(0, sl_0) sp.add_layer(h0, sl_1) sp.gwl = gwl return capacity_sp_meyerhof_and_hanna_1978(sp, fd)
Calculates the two - layered foundation capacity according Meyerhof and Hanna ( 1978 )
def capacity_sp_meyerhof_and_hanna_1978(sp, fd, verbose=0): """ Calculates the two-layered foundation capacity according Meyerhof and Hanna (1978) :param sp: Soil profile object :param fd: Foundation object :param wtl: water table level :param verbose: verbosity :return: ultimate bearing stress """ assert isinstance(sp, sm.SoilProfile) sl_0 = sp.layer(1) sl_1 = sp.layer(2) h0 = sp.layer_depth(2) gwl = sp.gwl sl_0.nq_factor_0 = ( (np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_0.phi)))) if sl_0.phi == 0: sl_0.nc_factor_0 = 5.14 else: sl_0.nc_factor_0 = (sl_0.nq_factor_0 - 1) / np.tan(np.deg2rad(sl_0.phi)) sl_0.ng_factor_0 = (sl_0.nq_factor_0 - 1) * np.tan(1.4 * np.deg2rad(sl_0.phi)) sl_1.nq_factor_1 = ( (np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_1.phi)))) if sl_1.phi == 0: sl_1.nc_factor_1 = 5.14 else: sl_1.nc_factor_1 = (sl_1.nq_factor_1 - 1) / np.tan(np.deg2rad(sl_1.phi)) sl_1.ng_factor_1 = (sl_1.nq_factor_1 - 1) * np.tan(1.4 * np.deg2rad(sl_1.phi)) if verbose: log("Nc: ", sl_1.nc_factor_1) log("Nq: ", sl_1.nq_factor_1) log("Ng: ", sl_1.ng_factor_1) sl_0.kp_0 = (np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2 sl_1.kp_1 = (np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2 # shape factors if sl_0.phi >= 10: sl_0.s_c_0 = 1 + 0.2 * sl_0.kp_0 * (fd.width / fd.length) sl_0.s_q_0 = 1.0 + 0.1 * sl_0.kp_0 * (fd.width / fd.length) else: sl_0.s_c_0 = 1 + 0.2 * (fd.width / fd.length) sl_0.s_q_0 = 1.0 sl_0.s_g_0 = sl_0.s_q_0 if sl_1.phi >= 10: sl_1.s_c_1 = 1 + 0.2 * sl_1.kp_1 * (fd.width / fd.length) sl_1.s_q_1 = 1.0 + 0.1 * sl_1.kp_1 * (fd.width / fd.length) else: sl_1.s_c_1 = 1 + 0.2 * (fd.width / fd.length) sl_1.s_q_1 = 1.0 sl_1.s_g_1 = sl_1.s_q_1 # Note: this method explicitly accounts for the foundation depth, so there are no depth factors # TODO: inclination factors, see doi.org/10.1139/t78-060 # Capacity a = 1 # assumed to be one but can range between 1.1 and 1.27 for square footings according to Das (1999) Ch 4 s = 1 r = 1 + (fd.width / fd.length) # put the same things before that condition # effective weight not in the soil object if gwl == 0: # case 1: GWL at surface q_at_interface = sl_0.unit_bouy_weight * h0 unit_eff_weight_0_at_fd_depth = sl_0.unit_bouy_weight unit_eff_weight_0_at_interface = sl_0.unit_bouy_weight unit_eff_weight_1_below_foundation = sl_1.unit_bouy_weight elif 0 < gwl <= fd.depth: # Case 2: GWL at between foundation depth and surface q_at_interface = (sl_0.unit_dry_weight * gwl) + (sl_0.unit_bouy_weight * (h0 - gwl)) q_d = (sl_0.unit_dry_weight * gwl) + (sl_0.unit_bouy_weight * (fd.depth - gwl)) unit_eff_weight_0_at_fd_depth = q_d / fd.depth unit_eff_weight_0_at_interface = sl_0.unit_bouy_weight unit_eff_weight_1_below_foundation = sl_1.unit_bouy_weight elif fd.depth < gwl <= fd.width + fd.depth: if gwl < h0: # Case 3: GWL at between foundation depth and foundation depth plus width, and GWL < layer 1 depth average_unit_bouy_weight = sl_0.unit_bouy_weight + ( ((gwl - fd.depth) / fd.width) * (sl_0.unit_dry_weight - sl_0.unit_bouy_weight)) q_at_interface = (sl_0.unit_dry_weight * gwl) + (sl_0.unit_bouy_weight * (h0 - gwl)) unit_eff_weight_0_at_fd_depth = sl_0.unit_dry_weight unit_eff_weight_0_at_interface = average_unit_bouy_weight unit_eff_weight_1_below_foundation = sl_1.unit_bouy_weight else: # Case 4: GWL at between foundation depth and foundation depth plus width, and GWL > layer 1 depth average_unit_bouy_weight = sl_1.unit_bouy_weight + ( ((gwl - h0) / fd.width) * (sl_1.unit_dry_weight - sl_1.unit_bouy_weight)) q_at_interface = sl_0.unit_dry_weight * h0 unit_eff_weight_0_at_fd_depth = sl_0.unit_dry_weight unit_eff_weight_0_at_interface = sl_0.unit_dry_weight unit_eff_weight_1_below_foundation = average_unit_bouy_weight elif gwl > fd.depth + fd.width: # Case 5: GWL beyond foundation depth plus width q_at_interface = sl_0.unit_dry_weight * h0 unit_eff_weight_0_at_fd_depth = sl_0.unit_dry_weight unit_eff_weight_0_at_interface = sl_0.unit_dry_weight unit_eff_weight_1_below_foundation = sl_1.unit_dry_weight else: raise ValueError("Could not interpret inputs") # never reached # maximum value (qu <= qt) q_ult6 = q_at_interface - unit_eff_weight_0_at_fd_depth * fd.depth q_0 = (sl_0.cohesion * sl_0.nc_factor_0) + (0.5 * unit_eff_weight_0_at_interface * fd.width * sl_0.ng_factor_0) q_b2 = (q_at_interface * sl_1.nq_factor_1 * sl_1.s_q_1) q_1 = (sl_1.cohesion * sl_1.nc_factor_1) + (0.5 * unit_eff_weight_1_below_foundation * fd.width * sl_1.ng_factor_1) q_b3 = (unit_eff_weight_1_below_foundation * fd.width * sl_1.ng_factor_1 * sl_1.s_g_1 / 2) q_ult5 = r * (unit_eff_weight_0_at_interface * ((h0 - fd.depth) ** 2)) * (1 + (2 * fd.depth / (h0 - fd.depth))) * ( np.tan(np.deg2rad(sl_0.phi)) / fd.width) * s q_t2 = (unit_eff_weight_0_at_fd_depth * fd.depth * sl_0.nq_factor_0 * sl_0.s_q_0) q_t3 = (unit_eff_weight_0_at_interface * fd.width * sl_0.ng_factor_0 * sl_0.s_g_0 / 2) # qb q_b1 = (sl_1.cohesion * sl_1.nc_factor_1 * sl_1.s_c_1) q_b = q_b1 + q_b2 + q_b3 q1_q0 = q_1 / q_0 # calculate the ca factor # if sl_0.cohesion == 0: # c1_c0 = 0 # else: # c1_c0 = sl_1.cohesion / sl_0.cohesion x = np.array([0.000, 0.082, 0.206, 0.298, 0.404, 0.509, 0.598, 0.685, 0.772]) y = np.array([0.627, 0.700, 0.794, 0.855, 0.912, 0.948, 0.968, 0.983, 0.997]) # raise Warning("ca should be interpolated using q1/q2 not cohesion, see Figure 4 in MH1978") ca_c0 = np.interp(q1_q0, x, y) ca = ca_c0 * sl_0.cohesion # ks x_0 = np.array([0, 20.08, 22.42, 25.08, 27.58, 30.08, 32.58, 34.92, 37.83, 40.00, 42.67, 45.00, 47.00, 49.75]) y_0 = np.array([0.93, 0.93, 0.93, 0.93, 1.01, 1.17, 1.32, 1.56, 1.87, 2.26, 2.72, 3.35, 3.81, 4.82]) x_2 = np.array([0, 20.08, 22.50, 25.08, 27.58, 30.08, 32.50, 35.00, 37.67, 40.17, 42.67, 45.00, 47.50, 50.00]) y_2 = np.array([1.55, 1.55, 1.71, 1.86, 2.10, 2.33, 2.72, 3.11, 3.81, 4.43, 5.28, 6.14, 7.46, 9.24]) x_4 = np.array([0, 20.00, 22.51, 25.10, 27.69, 30.11, 32.45, 35.04, 37.88, 40.14, 42.65, 45.07, 47.33, 50.08]) y_4 = np.array([2.49, 2.49, 2.64, 2.87, 3.34, 3.81, 4.43, 5.20, 6.29, 7.38, 9.01, 11.11, 14.29, 19.34]) x_10 = np.array([0, 20.00, 22.50, 25.08, 28.00, 30.00, 32.50, 34.92, 37.50, 40.17, 42.42, 45.00, 47.17, 50.08]) y_10 = np.array([3.27, 3.27, 3.74, 4.44, 5.37, 6.07, 7.16, 8.33, 10.04, 12.30, 15.95, 21.17, 27.47, 40.00]) x_int = sl_0.phi if sl_0.phi < 1: fd.ks = 0 else: if q1_q0 == 0: fd.ks = np.interp(x_int, x_0, y_0) elif q1_q0 == 0.2: fd.ks = np.interp(x_int, x_2, y_2) elif q1_q0 == 0.4: fd.ks = np.interp(x_int, x_4, y_4) elif q1_q0 == 1.0: fd.ks = np.interp(x_int, x_10, y_10) elif 0 < q1_q0 < 0.2: ks_1 = np.interp(x_int, x_0, y_0) ks_2 = np.interp(x_int, x_2, y_2) fd.ks = (((ks_2 - ks_1) * q1_q0) / 0.2) + ks_1 elif 0.2 < q1_q0 < 0.4: ks_1 = np.interp(x_int, x_2, y_2) ks_2 = np.interp(x_int, x_4, y_4) fd.ks = (((ks_2 - ks_1) * (q1_q0 - 0.2)) / 0.2) + ks_1 elif 0.4 < q1_q0 < 1.0: ks_1 = np.interp(x_int, x_4, y_4) ks_2 = np.interp(x_int, x_10, y_10) fd.ks = (((ks_2 - ks_1) * (q1_q0 - 0.4)) / 0.6) + ks_1 else: raise DesignError( "Cannot compute 'ks', bearing ratio out-of-range (q1_q0 = %.3f) required: 0-1." % q1_q0) # qu q_ult4 = (r * (2 * ca * (h0 - fd.depth) / fd.width) * a) q_ult5_ks = q_ult5 * fd.ks q_ult = q_b + q_ult4 + q_ult5_ks - q_ult6 q_t1 = (sl_0.cohesion * sl_0.nc_factor_0 * sl_0.s_c_0) q_t = q_t1 + q_t2 + q_t3 if q_ult > q_t: if h0 > fd.width/2: fd.q_ult = q_t else: vert_eff_stress_interface = sp.vertical_effective_stress(h0) vert_eff_stress_lowest = sp.vertical_effective_stress(fd.width+fd.depth) average_eff_stress = (vert_eff_stress_interface + vert_eff_stress_lowest) / 2 c_2_eff = sl_1.cohesion + average_eff_stress * np.tan(np.radians(sl_1.phi)) if sl_0.cohesion > c_2_eff: fd.q_ult = q_t else: # vd = {} # vd[1] =[1, 1, 1, 1, 1] # vd[0.667] = [1, 1.033, 1.064, 1.088, 1.109] # vd[0.5] = [1, 1.056, 1.107, 1.152, 1.193] # vd[0.333] = [1, 1.088, 1.167, 1.241, 1.311] # vd[0.25] = [1, 1.107, 1.208, 1.302, 1.389] # vd[0.2] = [1, 1.121, 1.235, 1.342, 1.444] # vd[0.1] = [1, 1.154, 1.302, 1.446, 1.584] h_over_b = (h0 - fd.depth)/fd.width c1_over_c2 =sl_0.cohesion/c_2_eff c_1_over_c_2 = [0.1, 0.2, 0.25, 0.333, 0.5, 0.667, 1.] m_1 = [1.584, 1.444, 1.389, 1.311, 1.193, 1.109, 1.] m_125 = [1.446, 1.342, 1.302, 1.241, 1.152, 1.088, 1.] m_167 = [1.302, 1.235, 1.208, 1.167, 1.107, 1.064, 1.] m_25 = [1.154, 1.121, 1.107, 1.088, 1.056, 1.033, 1.] m_5 = [1, 1, 1, 1, 1, 1, 1] if h_over_b == 0.1: m = np.interp(c1_over_c2, c_1_over_c_2, m_1) elif h_over_b == 0.125: m = np.interp(c1_over_c2, c_1_over_c_2, m_125) elif h_over_b == 0.167: m = np.interp(c1_over_c2, c_1_over_c_2, m_167) elif h_over_b == 0.250: m = np.interp(c1_over_c2, c_1_over_c_2, m_25) elif h_over_b >= 0.5: m = np.interp(c1_over_c2, c_1_over_c_2, m_5) elif 0.1 < h_over_b < 0.125: m_a = np.interp(c1_over_c2, c_1_over_c_2, m_1) m_b = np.interp(c1_over_c2, c_1_over_c_2, m_125) m = np.interp(h_over_b, [0.1,0.125], [m_a,m_b]) elif 0.125 < h_over_b < 0.167: m_a = np.interp(c1_over_c2, c_1_over_c_2, m_125) m_b = np.interp(c1_over_c2, c_1_over_c_2, m_167) m = np.interp(h_over_b, [0.125, 0.167], [m_a, m_b]) elif 0.167 < h_over_b < 0.25: m_a = np.interp(c1_over_c2, c_1_over_c_2, m_167) m_b = np.interp(c1_over_c2, c_1_over_c_2, m_25) m = np.interp(h_over_b, [0.167, 0.250], [m_a, m_b]) elif 0.25 < h_over_b < 0.5: m_a = np.interp(c1_over_c2, c_1_over_c_2, m_25) m_b = np.interp(c1_over_c2, c_1_over_c_2, m_5) m = np.interp(h_over_b, [0.250, 0.500], [m_a, m_b]) fd.q_ult = (sl_0.cohesion * m * sl_0.nc_factor_0) + (unit_eff_weight_0_at_fd_depth * fd.depth) else: fd.q_ult = q_ult return fd.q_ult
List the roles for an account for the passed Canvas account ID.
def get_roles_in_account(self, account_id, params={}): """ List the roles for an account, for the passed Canvas account ID. https://canvas.instructure.com/doc/api/roles.html#method.role_overrides.api_index """ url = ACCOUNTS_API.format(account_id) + "/roles" roles = [] for datum in self._get_resource(url, params=params): roles.append(CanvasRole(data=datum)) return roles
List the roles for an account for the passed account SIS ID.
def get_roles_by_account_sis_id(self, account_sis_id, params={}): """ List the roles for an account, for the passed account SIS ID. """ return self.get_roles_in_account(self._sis_id(account_sis_id, sis_field="account"), params)
List all course roles available to an account for the passed Canvas account ID including course roles inherited from parent accounts.
def get_effective_course_roles_in_account(self, account_id): """ List all course roles available to an account, for the passed Canvas account ID, including course roles inherited from parent accounts. """ course_roles = [] params = {"show_inherited": "1"} for role in self.get_roles_in_account(account_id, params): if role.base_role_type != "AccountMembership": course_roles.append(role) return course_roles
Get information about a single role for the passed Canvas account ID.
def get_role(self, account_id, role_id): """ Get information about a single role, for the passed Canvas account ID. https://canvas.instructure.com/doc/api/roles.html#method.role_overrides.show """ url = ACCOUNTS_API.format(account_id) + "/roles/{}".format(role_id) return CanvasRole(data=self._get_resource(url))
Get information about a single role for the passed account SIS ID.
def get_role_by_account_sis_id(self, account_sis_id, role_id): """ Get information about a single role, for the passed account SIS ID. """ return self.get_role(self._sis_id(account_sis_id, sis_field="account"), role_id)
Return course resource for given canvas course id.
def get_course(self, course_id, params={}): """ Return course resource for given canvas course id. https://canvas.instructure.com/doc/api/courses.html#method.courses.show """ include = params.get("include", []) if "term" not in include: include.append("term") params["include"] = include url = COURSES_API.format(course_id) return CanvasCourse(data=self._get_resource(url, params=params))
Return course resource for given sis id.
def get_course_by_sis_id(self, sis_course_id, params={}): """ Return course resource for given sis id. """ return self.get_course(self._sis_id(sis_course_id, sis_field="course"), params)
Returns a list of courses for the passed account ID.
def get_courses_in_account(self, account_id, params={}): """ Returns a list of courses for the passed account ID. https://canvas.instructure.com/doc/api/accounts.html#method.accounts.courses_api """ if "published" in params: params["published"] = "true" if params["published"] else "" url = ACCOUNTS_API.format(account_id) + "/courses" courses = [] for data in self._get_paged_resource(url, params=params): courses.append(CanvasCourse(data=data)) return courses
Return a list of courses for the passed account SIS ID.
def get_courses_in_account_by_sis_id(self, sis_account_id, params={}): """ Return a list of courses for the passed account SIS ID. """ return self.get_courses_in_account( self._sis_id(sis_account_id, sis_field="account"), params)
Return a list of published courses for the passed account ID.
def get_published_courses_in_account(self, account_id, params={}): """ Return a list of published courses for the passed account ID. """ params["published"] = True return self.get_courses_in_account(account_id, params)
Return a list of published courses for the passed account SIS ID.
def get_published_courses_in_account_by_sis_id(self, sis_account_id, params={}): """ Return a list of published courses for the passed account SIS ID. """ return self.get_published_courses_in_account( self._sis_id(sis_account_id, sis_field="account"), params)
Return a list of courses for the passed regid.
def get_courses_for_regid(self, regid, params={}): """ Return a list of courses for the passed regid. https://canvas.instructure.com/doc/api/courses.html#method.courses.index """ self._as_user = regid data = self._get_resource("/api/v1/courses", params=params) self._as_user = None courses = [] for datum in data: if "sis_course_id" in datum: courses.append(CanvasCourse(data=datum)) else: courses.append(self.get_course(datum["id"], params)) return courses
Create a canvas course with the given subaccount id and course name.
def create_course(self, account_id, course_name): """ Create a canvas course with the given subaccount id and course name. https://canvas.instructure.com/doc/api/courses.html#method.courses.create """ url = ACCOUNTS_API.format(account_id) + "/courses" body = {"course": {"name": course_name}} return CanvasCourse(data=self._post_resource(url, body))
Updates the SIS ID for the course identified by the passed course ID.
def update_sis_id(self, course_id, sis_course_id): """ Updates the SIS ID for the course identified by the passed course ID. https://canvas.instructure.com/doc/api/courses.html#method.courses.update """ url = COURSES_API.format(course_id) body = {"course": {"sis_course_id": sis_course_id}} return CanvasCourse(data=self._put_resource(url, body))
Returns participation data for the given account_id and term_id.
def get_activity_by_account(self, account_id, term_id): """ Returns participation data for the given account_id and term_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.department_participation """ url = ("/api/v1/accounts/sis_account_id:%s/analytics/" "terms/sis_term_id:%s/activity.json") % (account_id, term_id) return self._get_resource(url)
Returns grade data for the given account_id and term_id.
def get_grades_by_account(self, account_id, term_id): """ Returns grade data for the given account_id and term_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.department_grades """ url = ("/api/v1/accounts/sis_account_id:%s/analytics/" "terms/sis_term_id:%s/grades.json") % (account_id, term_id) return self._get_resource(url)
Returns statistics for the given account_id and term_id.
def get_statistics_by_account(self, account_id, term_id): """ Returns statistics for the given account_id and term_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.department_statistics """ url = ("/api/v1/accounts/sis_account_id:%s/analytics/" "terms/sis_term_id:%s/statistics.json") % (account_id, term_id) return self._get_resource(url)
Returns participation data for the given sis_course_id.
def get_activity_by_sis_course_id(self, sis_course_id): """ Returns participation data for the given sis_course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_participation """ url = "/api/v1/courses/%s/analytics/activity.json" % ( self._sis_id(sis_course_id, sis_field="course")) return self._get_resource(url)
Returns assignment data for the given course_id.
def get_assignments_by_sis_course_id(self, sis_course_id): """ Returns assignment data for the given course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_assignments """ url = "/api/v1/courses/%s/analytics/assignments.json" % ( self._sis_id(sis_course_id, sis_field="course")) return self._get_resource(url)
Returns per - student data for the given course_id.
def get_student_summaries_by_sis_course_id(self, sis_course_id): """ Returns per-student data for the given course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_student_summaries """ url = "/api/v1/courses/%s/analytics/student_summaries.json" % ( self._sis_id(sis_course_id, sis_field="course")) return self._get_resource(url)
Returns student activity data for the given user_id and course_id.
def get_student_activity_for_sis_course_id_and_sis_user_id( self, sis_user_id, sis_course_id): """ Returns student activity data for the given user_id and course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_participation """ url = ("/api/v1/courses/%s/analytics/users/" "sis_user_id:%s/activity.json") % ( self._sis_id(sis_course_id, sis_field="course"), sis_user_id) return self._get_resource(url)
Returns student assignment data for the given user_id and course_id.
def get_student_assignments_for_sis_course_id_and_sis_user_id( self, sis_user_id, sis_course_id): """ Returns student assignment data for the given user_id and course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments """ url = ("/api/v1/courses/%s/analytics/" "users/sis_user_id:%s/assignments.json") % ( self._sis_id(sis_course_id, sis_field="course"), sis_user_id) return self._get_resource(url)
Returns student assignment data for the given user_id and course_id.
def get_student_assignments_for_sis_course_id_and_canvas_user_id( self, sis_course_id, user_id): """ Returns student assignment data for the given user_id and course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments """ url = "/api/v1/courses/%s/analytics/users/%s/assignments.json" % ( self._sis_id(sis_course_id, sis_field="course"), user_id) return self._get_resource(url)
Returns student messaging data for the given user_id and course_id.
def get_student_messaging_for_sis_course_id_and_sis_user_id( self, sis_user_id, sis_course_id): """ Returns student messaging data for the given user_id and course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_messaging """ url = ("/api/v1/courses/%s/analytics/" "users/sis_user_id:%s/communication.json") % ( self._sis_id(sis_course_id, sis_field="course"), sis_user_id) return self._get_resource(url)
https:// canvas. instructure. com/ doc/ api/ submissions. html#method. submissions_api. index
def get_submissions_by_course_and_assignment( self, course_id, assignment_id, params={}): """ https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.index """ url = COURSES_API.format(course_id) url += "/assignments/{}/submissions".format(assignment_id) submissions = [] for data in self._get_paged_resource(url, params=params): submissions.append(Submission(data=data)) return submissions
List submissions for multiple assignments by course/ section sis id and optionally student
def get_submissions_multiple_assignments_by_sis_id( self, is_section, sis_id, students=None, assignments=None, **params): """ List submissions for multiple assignments by course/section sis id and optionally student https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.for_students """ if is_section: return self.get_submissions_multiple_assignments( is_section, self._sis_id(sis_id, 'section'), students, assignments, **params) else: return self.get_submissions_multiple_assignments( is_section, self._sis_id(sis_id, 'course'), students, assignments, **params)
List submissions for multiple assignments by course/ section id and optionally student
def get_submissions_multiple_assignments( self, is_section, course_id, students=None, assignments=None, **params): """ List submissions for multiple assignments by course/section id and optionally student https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.for_students """ api = SECTIONS_API if is_section else COURSES_API if students is not None: params['student_ids'] = students if assignments is not None: params['assignment_ids'] = assignments url = api.format(course_id) + "/students/submissions" data = self._get_paged_resource(url, params=params) submissions = [] for submission in data: submissions.append(Submission(data=submission)) return submissions
Rotation stiffness of foundation.: param fd: Foundation object: param sl: Soil Object.: param axis: The axis which it should be computed around: return:
def rotational_stiffness(sl, fd, axis="length", a0=0.0, **kwargs): """ Rotation stiffness of foundation. :param fd: Foundation object :param sl: Soil Object. :param axis: The axis which it should be computed around :return: """ if not kwargs.get("disable_requires", False): gf.models.check_required(sl, ["g_mod", "poissons_ratio"]) gf.models.check_required(fd, ["length", "width", "depth"]) if fd.depth > 0.0: pass l = fd.length * 0.5 b = fd.width * 0.5 v = sl.poissons_ratio if axis == "length": i_bx = fd.i_ll k_rx = 1 - 0.2 * a0 k_f_0 = (sl.g_mod / (1 - v) * i_bx ** 0.75 * (l / b) ** 0.25 * (2.4 + 0.5 * (b / l))) * k_rx else: i_by = fd.i_ww k_ry = 1 - 0.3 * a0 k_f_0 = (sl.g_mod / (1 - v) * i_by ** 0.75 * (3 * (l / b) ** 0.15)) * k_ry return k_f_0
Return external tools for the passed canvas account id.
def get_external_tools_in_account(self, account_id, params={}): """ Return external tools for the passed canvas account id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url = ACCOUNTS_API.format(account_id) + "/external_tools" external_tools = [] for data in self._get_paged_resource(url, params=params): external_tools.append(data) return external_tools
Return external tools for the passed canvas course id.
def get_external_tools_in_course(self, course_id, params={}): """ Return external tools for the passed canvas course id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url = COURSES_API.format(course_id) + "/external_tools" external_tools = [] for data in self._get_paged_resource(url, params=params): external_tools.append(data) return external_tools
Create an external tool using the passed json_data.
def _create_external_tool(self, context, context_id, json_data): """ Create an external tool using the passed json_data. context is either COURSES_API or ACCOUNTS_API. context_id is the Canvas course_id or account_id, depending on context. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.create """ url = context.format(context_id) + "/external_tools" return self._post_resource(url, body=json_data)
Update the external tool identified by external_tool_id with the passed json data.
def _update_external_tool(self, context, context_id, external_tool_id, json_data): """ Update the external tool identified by external_tool_id with the passed json data. context is either COURSES_API or ACCOUNTS_API. context_id is the course_id or account_id, depending on context https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.update """ url = context.format(context_id) + "/external_tools/{}".format( external_tool_id) return self._put_resource(url, body=json_data)
Delete the external tool identified by external_tool_id.
def _delete_external_tool(self, context, context_id, external_tool_id): """ Delete the external tool identified by external_tool_id. context is either COURSES_API or ACCOUNTS_API. context_id is the course_id or account_id, depending on context https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.destroy """ url = context.format(context_id) + "/external_tools/{}".format( external_tool_id) response = self._delete_resource(url) return True
Get a sessionless launch url for an external tool.
def _get_sessionless_launch_url(self, context, context_id, tool_id): """ Get a sessionless launch url for an external tool. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.generate_sessionless_launch """ url = context.format(context_id) + "/external_tools/sessionless_launch" params = {"id": tool_id} return self._get_resource(url, params)
Get a sessionless launch url for an external tool.
def get_sessionless_launch_url_from_account_sis_id( self, tool_id, account_sis_id): """ Get a sessionless launch url for an external tool. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.generate_sessionless_launch """ return self.get_sessionless_launch_url_from_account( tool_id, self._sis_id(account_sis_id, "account"))
Get a sessionless launch url for an external tool.
def get_sessionless_launch_url_from_course_sis_id( self, tool_id, course_sis_id): """ Get a sessionless launch url for an external tool. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.generate_sessionless_launch """ return self.get_sessionless_launch_url_from_course( tool_id, self._sis_id(course_sis_id, "course"))
Can define a Foundation Object from dimensions.: param length: Foundation length: param width: Foundation width: param depth: Foundation depth: param height: Foundation height: return: A Foundation object
def create_foundation(length, width, depth=0.0, height=0.0): """ Can define a Foundation Object from dimensions. :param length: Foundation length :param width: Foundation width :param depth: Foundation depth :param height: Foundation height :return: A Foundation object """ a_foundation = FoundationRaft() a_foundation.length = length a_foundation.width = width a_foundation.depth = depth a_foundation.height = height return a_foundation
Can define a Soil object.: param phi: Internal friction angle: param cohesion: Cohesion of soil: param unit_dry_weight: The dry unit weight of the soil.: param pw: specific weight of water: return: A Soil object.
def create_soil(phi=0.0, cohesion=0.0, unit_dry_weight=0.0, pw=9800): """ Can define a Soil object. :param phi: Internal friction angle :param cohesion: Cohesion of soil :param unit_dry_weight: The dry unit weight of the soil. :param pw: specific weight of water :return: A Soil object. """ soil = Soil(pw=pw) soil.phi = phi soil.cohesion = cohesion soil.unit_dry_weight = unit_dry_weight return soil
Check if a parameter is available on an object
def check_required(obj, required_parameters): """ Check if a parameter is available on an object :param obj: Object :param required_parameters: list of parameters :return: """ for parameter in required_parameters: if not hasattr(obj, parameter) or getattr(obj, parameter) is None: raise DesignError("parameter '%s' must be set for '%s' object." % (parameter, obj.base_type))
Returns user profile data.
def get_user(self, user_id): """ Returns user profile data. https://canvas.instructure.com/doc/api/users.html#method.profile.settings """ url = USERS_API.format(user_id) + "/profile" return CanvasUser(data=self._get_resource(url))
Returns a list of users for the given course id.
def get_users_for_course(self, course_id, params={}): """ Returns a list of users for the given course id. """ url = COURSES_API.format(course_id) + "/users" data = self._get_paged_resource(url, params=params) users = [] for datum in data: users.append(CanvasUser(data=datum)) return users
Returns a list of users for the given sis course id.
def get_users_for_sis_course_id(self, sis_course_id, params={}): """ Returns a list of users for the given sis course id. """ return self.get_users_for_course( self._sis_id(sis_course_id, sis_field="course"), params)
Create and return a new user and pseudonym for an account.
def create_user(self, user, account_id=None): """ Create and return a new user and pseudonym for an account. https://canvas.instructure.com/doc/api/users.html#method.users.create """ if account_id is None: account_id = self._canvas_account_id if account_id is None: raise MissingAccountID() url = ACCOUNTS_API.format(account_id) + "/users" data = self._post_resource(url, user.post_data()) return CanvasUser(data=data)
Return a user s logins for the given user_id.
def get_user_logins(self, user_id, params={}): """ Return a user's logins for the given user_id. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.index """ url = USERS_API.format(user_id) + "/logins" data = self._get_paged_resource(url, params=params) logins = [] for login_data in data: logins.append(Login(data=login_data)) return logins
Update an existing login for a user in the given account.
def update_user_login(self, login, account_id=None): """ Update an existing login for a user in the given account. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.update """ if account_id is None: account_id = self._canvas_account_id if account_id is None: raise MissingAccountID login_id = login.login_id url = ACCOUNTS_API.format(account_id) + "/logins/{}".format(login_id) data = self._put_resource(url, login.put_data()) return Login(data=data)
return url path to next page of paginated data
def _next_page(self, response): """ return url path to next page of paginated data """ for link in response.getheader("link", "").split(","): try: (url, rel) = link.split(";") if "next" in rel: return url.lstrip("<").rstrip(">") except Exception: return
Canvas GET method on a full url. Return representation of the requested resource chasing pagination links to coalesce resources if indicated.
def _get_resource_url(self, url, auto_page, data_key): """ Canvas GET method on a full url. Return representation of the requested resource, chasing pagination links to coalesce resources if indicated. """ headers = {'Accept': 'application/json', 'Connection': 'keep-alive'} response = DAO.getURL(url, headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) data = json.loads(response.data) self.next_page_url = self._next_page(response) if auto_page and self.next_page_url: if isinstance(data, list): data.extend(self._get_resource_url(self.next_page_url, True, data_key)) elif isinstance(data, dict) and data_key is not None: data[data_key].extend(self._get_resource_url( self.next_page_url, True, data_key)[data_key]) return data
Canvas GET method. Return representation of the requested paged resource either the requested page or chase pagination links to coalesce resources.
def _get_paged_resource(self, url, params=None, data_key=None): """ Canvas GET method. Return representation of the requested paged resource, either the requested page, or chase pagination links to coalesce resources. """ if not params: params = {} self._set_as_user(params) auto_page = not ('page' in params or 'per_page' in params) if 'per_page' not in params and self._per_page != DEFAULT_PAGINATION: params["per_page"] = self._per_page full_url = url + self._params(params) return self._get_resource_url(full_url, auto_page, data_key)
Canvas GET method. Return representation of the requested resource.
def _get_resource(self, url, params=None, data_key=None): """ Canvas GET method. Return representation of the requested resource. """ if not params: params = {} self._set_as_user(params) full_url = url + self._params(params) return self._get_resource_url(full_url, True, data_key)
Canvas PUT method.
def _put_resource(self, url, body): """ Canvas PUT method. """ params = {} self._set_as_user(params) headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Connection': 'keep-alive'} url = url + self._params(params) response = DAO.putURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
Canvas POST method.
def _post_resource(self, url, body): """ Canvas POST method. """ params = {} self._set_as_user(params) headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'Connection': 'keep-alive'} url = url + self._params(params) response = DAO.postURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
Canvas DELETE method.
def _delete_resource(self, url): """ Canvas DELETE method. """ params = {} self._set_as_user(params) headers = {'Accept': 'application/json', 'Connection': 'keep-alive'} url = url + self._params(params) response = DAO.deleteURL(url, headers) if not (response.status == 200 or response.status == 204): raise DataFailureException(url, response.status, response.data) return response
Return a list of the admins in the account.
def get_admins(self, account_id, params={}): """ Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index """ url = ADMINS_API.format(account_id) admins = [] for data in self._get_paged_resource(url, params=params): admins.append(CanvasAdmin(data=data)) return admins
Flag an existing user as an admin within the account.
def create_admin(self, account_id, user_id, role): """ Flag an existing user as an admin within the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.create """ url = ADMINS_API.format(account_id) body = {"user_id": unquote(str(user_id)), "role": role, "send_confirmation": False} return CanvasAdmin(data=self._post_resource(url, body))
Flag an existing user as an admin within the account sis id.
def create_admin_by_sis_id(self, sis_account_id, user_id, role): """ Flag an existing user as an admin within the account sis id. """ return self.create_admin(self._sis_id(sis_account_id), user_id, role)
Remove an account admin role from a user.
def delete_admin(self, account_id, user_id, role): """ Remove an account admin role from a user. https://canvas.instructure.com/doc/api/admins.html#method.admins.destroy """ url = ADMINS_API.format(account_id) + "/{}?role={}".format( user_id, quote(role)) response = self._delete_resource(url) return True
Remove an account admin role from a user for the account sis id.
def delete_admin_by_sis_id(self, sis_account_id, user_id, role): """ Remove an account admin role from a user for the account sis id. """ return self.delete_admin(self._sis_id(sis_account_id), user_id, role)
List the grading standards available to a course https:// canvas. instructure. com/ doc/ api/ grading_standards. html#method. grading_standards_api. context_index
def get_grading_standards_for_course(self, course_id): """ List the grading standards available to a course https://canvas.instructure.com/doc/api/grading_standards.html#method.grading_standards_api.context_index """ url = COURSES_API.format(course_id) + "/grading_standards" standards = [] for data in self._get_resource(url): standards.append(GradingStandard(data=data)) return standards
Create a new grading standard for the passed course.
def create_grading_standard_for_course(self, course_id, name, grading_scheme, creator): """ Create a new grading standard for the passed course. https://canvas.instructure.com/doc/api/grading_standards.html#method.grading_standards_api.create """ url = COURSES_API.format(course_id) + "/grading_standards" body = { "title": name, "grading_scheme_entry": grading_scheme, "as_user_id": creator } return GradingStandard(data=self._post_resource(url, body))
Return section resource for given canvas section id.
def get_section(self, section_id, params={}): """ Return section resource for given canvas section id. https://canvas.instructure.com/doc/api/sections.html#method.sections.show """ url = SECTIONS_API.format(section_id) return CanvasSection(data=self._get_resource(url, params=params))
Return section resource for given sis id.
def get_section_by_sis_id(self, sis_section_id, params={}): """ Return section resource for given sis id. """ return self.get_section( self._sis_id(sis_section_id, sis_field="section"), params)
Return list of sections for the passed course ID.
def get_sections_in_course(self, course_id, params={}): """ Return list of sections for the passed course ID. https://canvas.instructure.com/doc/api/sections.html#method.sections.index """ url = COURSES_API.format(course_id) + "/sections" sections = [] for data in self._get_paged_resource(url, params=params): sections.append(CanvasSection(data=data)) return sections
Return list of sections for the passed course SIS ID.
def get_sections_in_course_by_sis_id(self, sis_course_id, params={}): """ Return list of sections for the passed course SIS ID. """ return self.get_sections_in_course( self._sis_id(sis_course_id, sis_field="course"), params)